26#include "table/strings.h"
33#if defined(WITH_LIBLZMA)
91void TextfileWindow::ConstructWindow()
113 for (
auto &line : this->
lines) {
120 for (
auto &line : this->
lines) {
130uint TextfileWindow::GetContentHeight()
132 if (this->
lines.empty())
return 0;
133 return this->
lines.back().bottom;
143 size.width = std::max(200u, size.width);
167static const std::regex
_markdown_link_regex{
"\\[(.+?)\\]\\((.+?)\\)", std::regex_constants::ECMAScript | std::regex_constants::optimize};
208 for (
char c : line) {
211 if (c ==
'#')
continue;
212 if (c ==
' ')
continue;
218 if (c ==
' ' || c ==
'-')
continue;
229 }
else if (c ==
' ' || c ==
'-') {
251 while (
matcher != std::sregex_iterator()) {
256 link.destination = match[2].str();
257 this->
links.push_back(link);
280 this->
links.back().begin = fixed_line.length();
284 this->
links.back().end = fixed_line.length();
308 if (this->
links.empty())
return nullptr;
315 auto it = std::ranges::find_if(this->
lines, [clicked_row](
const Line &l) {
return l.
top <= clicked_row && l.
bottom > clicked_row; });
316 if (it == this->
lines.cend())
return nullptr;
317 line_index = it - this->
lines.cbegin();
318 subline = clicked_row - it->top;
319 Debug(
misc, 4,
"TextfileWindow check hyperlink: clicked_row={}, line_index={}, line.top={}, subline={}", clicked_row,
line_index, it->top,
subline);
327 for (
const auto &link : this->
links) {
342 Debug(
misc, 4,
"Checking link from char {} to {}", link->begin, link->end);
343 if (
static_cast<size_t>(
char_index) >= link->begin &&
static_cast<size_t>(
char_index) < link->end) {
344 Debug(
misc, 4,
"Returning link with destination: {}", link->destination);
382 if (delta == 0)
return;
383 if (delta < 0 &&
static_cast<int>(this->
history_pos) < -delta)
return;
410 this->ScrollToLine(it->line);
439 if (!
newfile.starts_with(
"./"))
return;
443 size_t pos =
newpath.find_last_of(PATHSEPCHAR);
444 if (pos == std::string::npos) {
463 if (PATHSEPCHAR !=
'/') {
465 if (c ==
'/') c = PATHSEPCHAR;
485 if (anchor.empty() || line != 0) {
486 this->ScrollToLine(line);
493 this->ScrollToLine(0);
519 if (!line.
text.empty() && line.
text[0] ==
'#') {
537 for (
size_t line : this->
jumplist) {
565 if (link ==
nullptr)
return false;
583 fr =
fr.Translate(-
fr.left, -
fr.top);
591 for (
auto &line : this->
lines) {
592 if (line.bottom < pos)
continue;
593 if (line.top > pos + cap)
break;
595 int y_offset = (line.top - pos) * line_height;
623 this->ScrollToLine(index);
626void TextfileWindow::ScrollToLine(
size_t line)
631 newpos = this->
lines[line].top;
633 newpos =
static_cast<int>(line);
663#if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
669#if defined(WITH_ZLIB)
679static std::vector<char>
Gunzip(std::span<char> input)
681 static const int BLOCKSIZE = 8192;
682 std::vector<char> output;
685 memset(&z, 0,
sizeof(z));
686 z.next_in =
reinterpret_cast<Bytef *
>(input.data());
687 z.avail_in =
static_cast<uInt
>(input.size());
690 int res = inflateInit2(&z, 15 + 32);
692 while (res == Z_OK || (res == Z_BUF_ERROR && z.avail_out == 0)) {
695 z.avail_out += BLOCKSIZE;
696 output.resize(output.size() + BLOCKSIZE);
697 z.next_out =
reinterpret_cast<Bytef *
>(output.data() + output.size() - z.avail_out);
698 res = inflate(&z, Z_FINISH);
702 if (res != Z_STREAM_END)
return {};
704 output.resize(output.size() - z.avail_out);
709#if defined(WITH_LIBLZMA)
719static std::vector<char>
Xunzip(std::span<char> input)
721 static const int BLOCKSIZE = 8192;
722 std::vector<char> output;
724 lzma_stream z = LZMA_STREAM_INIT;
725 z.next_in =
reinterpret_cast<uint8_t *
>(input.data());
726 z.avail_in = input.size();
728 int res = lzma_auto_decoder(&z, UINT64_MAX, LZMA_CONCATENATED);
730 while (res == LZMA_OK || (res == LZMA_BUF_ERROR && z.avail_out == 0)) {
733 z.avail_out += BLOCKSIZE;
734 output.resize(output.size() + BLOCKSIZE);
735 z.next_out =
reinterpret_cast<uint8_t *
>(output.data() + output.size() - z.avail_out);
736 res = lzma_code(&z, LZMA_FINISH);
740 if (res != LZMA_STREAM_END)
return {};
742 output.resize(output.size() - z.avail_out);
758 if (textfile.empty())
return;
763 if (!handle.has_value())
return;
765 if (filesize == 0)
return;
767 std::vector<char> buf;
768 buf.resize(filesize);
769 size_t read =
fread(buf.data(), 1, buf.size(), *handle);
771 if (read != buf.size())
return;
773#if defined(WITH_ZLIB)
778#if defined(WITH_LIBLZMA)
783 if (buf.empty())
return;
785 std::string_view
sv_buf(buf.data(), buf.size());
788 if (
sv_buf.starts_with(
"\ufeff"))
sv_buf.remove_prefix(3);
813 std::string_view p(text);
815 auto next = p.find_first_of(
'\n');
816 while (next != std::string_view::npos) {
817 this->
lines.emplace_back(row, p.substr(0, next));
818 p.remove_prefix(next + 1);
821 next = p.find_first_of(
'\n');
823 this->
lines.emplace_back(row, p);
827 for (
auto &line : this->
lines) {
849 static const char *
const prefixes[] = {
854 static_assert(
lengthof(prefixes) == TFT_CONTENT_END);
857 if (type >= TFT_CONTENT_END)
return std::nullopt;
859 std::string_view prefix = prefixes[type];
861 if (filename.empty())
return std::nullopt;
863 auto slash = filename.find_last_of(PATHSEPCHAR);
864 if (slash == std::string::npos)
return std::nullopt;
866 std::string_view base_path(filename.data(), slash + 1);
868 static const std::initializer_list<std::string_view> extensions{
871#if defined(WITH_ZLIB)
875#if defined(WITH_LIBLZMA)
881 for (
auto &extension : extensions) {
888 file_path = fmt::format(
"{}{}.{}", base_path, prefix, extension);
Class for backupping variables and making sure they are restored later.
The layouter performs all the layout work.
ptrdiff_t GetCharAtPosition(int x, size_t line_index) const
Get the character that is at a pixel position in the first line of the layouted text.
Control codes that are embedded in the translation strings.
StringControlCode
List of string control codes used for string formatting, displaying, and by strgen to generate the la...
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, bool instant_close, bool persist)
Show a drop down list.
Functions related to the drop down widget.
Types related to the drop down widget.
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
std::optional< FileHandle > FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Functions for Standard In/Out file operations.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
@ NO_DIRECTORY
A path without any base directory.
fluid_settings_t * settings
FluidSynth settings handle.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Functions to read fonts from files and cache them.
int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Functions related to the gfx engine.
Functions related to laying out the texts.
Types related to the graphics and/or input devices.
FontSize
Available font sizes.
@ FS_MONO
Index of the monospaced font in the font tables.
@ SA_TOP
Top align the text.
@ SA_LEFT
Left align the text.
void SetDirty() const
Mark entire window as dirty (in need of re-paint)
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
bool StrEndsWithIgnoreCase(std::string_view str, const std::string_view suffix)
Check whether the given string ends with the given suffix, ignoring case.
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
Functions related to low-level strings.
@ SVS_REPLACE_TAB_CR_NL_WITH_SPACE
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
@ SVS_ALLOW_NEWLINE
Allow newlines; replaces '\r ' with ' ' during processing.
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
const char * GetCurrentLanguageIsoCode()
Get the ISO language code of the currently loaded language.
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Dimensions (a width and height) of a rectangle in 2D.
Data about how and where to blit pixels.
Settings for the four different fonts.
Coordinates of a point in 2D.
constexpr uint Horizontal() const
Get total horizontal padding of RectPadding.
constexpr uint Vertical() const
Get total vertical padding of RectPadding.
Specification of a rectangle with absolute coordinates of all edges.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
size_t line
Which line the link is on.
std::string destination
Destination for the link.
int bottom
Bottom scroll position in visual lines.
int top
Top scroll position in visual lines.
std::string text
Contents of the line.
Scrollbar * hscroll
Horizontal scrollbar.
uint ReflowContent()
Get the total height of the content displayed in this window, if wrapping is disabled.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void Reset() override
Reset the search, i.e.
uint search_iterator
Iterator for the font check search.
void AppendHistory(const std::string &filepath)
Append the new location to the history, so the user can go back.
void OnDropdownSelect(WidgetID widget, int index) override
A dropdown option associated to this window has been selected.
bool Monospace() override
Whether to search for a monospace font or not.
const Hyperlink * GetHyperlink(Point pt) const
Get the hyperlink at the given position.
void NavigateToFile(std::string newfile, size_t line)
Navigate to the requested file.
std::optional< std::string_view > NextString() override
Get the next string to search through.
std::vector< Line > lines
#text, split into lines in a table with lines.
void LoadText(std::string_view buf)
Load a text into the textfile viewer.
bool OnTooltip(Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
Event to display a custom tooltip.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void UpdateHistoryScrollpos()
Update the scroll position to the current, so we can restore there if we go back.
virtual void AfterLoadText()
Post-processing after the text is loaded.
std::string filepath
Full path to the filename.
TextfileType file_type
Type of textfile to view.
void AfterLoadMarkdown()
Post-processing of markdown files.
void SetupScrollbars(bool force_reflow)
Set scrollbars to the right lengths.
FontSize DefaultSize() override
Get the default (font) size of the string.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
size_t history_pos
Position in browsing history (for forward movement).
std::vector< Hyperlink > link_anchors
Anchor names of headings that can be linked to.
void SetFontNames(FontCacheSettings *settings, const char *font_name, const void *os_data) override
Set the right font names.
void NavigateHistory(int delta)
Navigate through the history, either forward or backward.
virtual void OnHyperlinkClick(const Hyperlink &link)
Handle the clicking on a hyperlink.
std::vector< HistoryEntry > history
Browsing history in this window.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
std::vector< Hyperlink > links
Clickable links in lines.
uint max_length
Maximum length of unwrapped text line.
std::string filename
Filename of the textfile.
Scrollbar * vscroll
Vertical scrollbar.
virtual void LoadTextfile(const std::string &textfile, Subdirectory dir)
Loads the textfile text from file and setup lines.
void OnResize() override
Called after the window got resized.
std::vector< size_t > jumplist
Table of contents list, line numbers.
void FindHyperlinksInMarkdown(Line &line, size_t line_index)
Find any hyperlinks in a given line.
High level window description.
Data structure for an opened window.
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing)
ResizeInfo resize
Resize information.
void DisableWidget(WidgetID widget_index)
Sets a widget to disabled.
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
void EnableWidget(WidgetID widget_index)
Sets a widget to Enabled.
int GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height=-1) const
Compute the row of a widget that a user clicked in.
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
int height
Height of the window (number of pixels down in y direction)
void ToggleWidgetLoweredState(WidgetID widget_index)
Invert the lowered/raised status of a widget.
HyperlinkType
Types of link we support in markdown files.
@ File
Link to a local file.
@ Internal
Internal link, or "anchor" in HTML language.
@ Web
Link to an external website.
static constexpr NWidgetPart _nested_textfile_widgets[]
Widgets for the textfile window.
static std::vector< char > Gunzip(std::span< char > input)
Do an in-memory gunzip operation.
static std::vector< char > Xunzip(std::span< char > input)
Do an in-memory xunzip operation.
static WindowDesc _textfile_desc(WDP_CENTER, "textfile", 630, 460, WC_TEXTFILE, WC_NONE, {}, _nested_textfile_widgets)
Window definition for the textfile window.
std::optional< std::string > GetTextfile(TextfileType type, Subdirectory dir, const std::string &filename)
Search a textfile file next to the given content.
static HyperlinkType ClassifyHyperlink(const std::string &destination, bool trusted)
Classify the type of hyperlink the destination describes.
static const std::regex _markdown_link_regex
Regular expression that searches for Markdown links.
static std::string MakeAnchorSlug(const std::string &line)
Create a valid slug for the anchor.
GUI functions related to textfiles.
TextfileType
Additional text files accompanying Tar archives.
@ WDP_CENTER
Center the window.
@ WC_NONE
No window, redirects to WC_MAIN_WINDOW.
@ WC_TEXTFILE
textfile; Window numbers: