26#include "table/strings.h"
33#if defined(WITH_LIBLZMA)
80 WindowClass::Textfile, WindowClass::None,
89 this->parent = parent;
92void TextfileWindow::ConstructWindow()
103 this->
hscroll->SetStepSize(10);
114 auto it = this->GetIteratorFromPosition(this->
vscroll->GetPosition());
147static const std::regex
_markdown_link_regex{
"\\[(.+?)\\]\\((.+?)\\)", std::regex_constants::ECMAScript | std::regex_constants::optimize};
188 for (
char c : line) {
191 if (c ==
'#')
continue;
192 if (c ==
' ')
continue;
198 if (c ==
' ' || c ==
'-')
continue;
209 }
else if (c ==
' ' || c ==
'-') {
226 std::string::const_iterator last_match_end = line.
text.cbegin();
227 std::string fixed_line;
231 while (matcher != std::sregex_iterator()) {
232 std::smatch match = *matcher;
234 Hyperlink &link = this->
links.emplace_back(line_index, 0, 0, match[2].str());
240 link_colour = SCC_GREEN;
243 link_colour = SCC_LTBLUE;
246 link_colour = SCC_LTBROWN;
250 link_colour = SCC_CONTROL_END;
254 if (link_colour != SCC_CONTROL_END) {
256 builder += std::string_view(last_match_end, match[0].first);
257 link.
begin = fixed_line.length();
258 builder.
PutUtf8(SCC_PUSH_COLOUR);
260 builder += match[1].str();
261 link.
end = fixed_line.length();
262 builder.
PutUtf8(SCC_POP_COLOUR);
263 last_match_end = match[0].second;
269 if (last_match_end == line.
text.cbegin())
return;
272 fixed_line += std::string(last_match_end, line.
text.cend());
275 line.
text = std::move(fixed_line);
285 if (this->
links.empty())
return nullptr;
290 int visible_line = 0;
291 auto it = std::ranges::find_if(this->
lines, [&visible_line, clicked_row](
const Line &l) {
293 return (visible_line - l.
num_lines) <= clicked_row && visible_line > clicked_row;
295 if (it == this->
lines.cend())
return nullptr;
297 size_t line_index = it - this->
lines.cbegin();
298 size_t subline = clicked_row - (visible_line - it->num_lines);
299 Debug(
Facility::Misc,
Severity::Info,
"TextfileWindow check hyperlink: clicked_row={}, line_index={}, line.top={}, subline={}", clicked_row, line_index, visible_line - it->num_lines, subline);
302 std::vector<const Hyperlink *> found_links;
303 for (
const auto &link : this->
links) {
304 if (link.line == line_index) found_links.push_back(&link);
306 if (found_links.empty())
return nullptr;
309 const Line &line = this->
lines[line_index];
311 assert(subline < layout.size());
313 if (char_index < 0)
return nullptr;
317 for (
const Hyperlink *link : found_links) {
319 if (
static_cast<size_t>(char_index) >= link->begin &&
static_cast<size_t>(char_index) < link->end) {
335 this->
history.erase(this->
history.begin() + this->history_pos + 1, this->history.end());
358 if (delta == 0)
return;
359 if (delta < 0 &&
static_cast<int>(this->
history_pos) < -delta)
return;
386 this->ScrollToLine(it->line);
415 if (!newfile.starts_with(
"./"))
return;
418 std::string newpath = this->
filepath;
419 size_t pos = newpath.find_last_of(PATHSEPCHAR);
420 if (pos == std::string::npos) {
423 newpath.erase(pos + 1);
427 size_t anchor_pos = newfile.find_first_of(
'#');
429 if (anchor_pos != std::string::npos) {
430 anchor = newfile.substr(anchor_pos);
431 newfile.erase(anchor_pos);
438 newfile = newfile.substr(2);
439 if (PATHSEPCHAR !=
'/') {
440 for (
char &c : newfile) {
441 if (c ==
'/') c = PATHSEPCHAR;
446 newpath = newpath + newfile;
454 this->
filename = newpath.substr(newpath.find_last_of(PATHSEP) + 1);
461 if (anchor.empty() || line != 0) {
462 this->ScrollToLine(line);
466 this->ScrollToLine(anchor_dest->line);
469 this->ScrollToLine(0);
488 for (
size_t line_index = 0; line_index < this->
lines.size(); ++line_index) {
495 if (!line.
text.empty() && line.
text[0] ==
'#') {
496 this->
jumplist.push_back(line_index);
513 for (
size_t line : this->
jumplist) {
551 if (link ==
nullptr)
return false;
582 int pos = this->
vscroll->GetPosition();
583 int cap = this->
vscroll->GetCapacity();
585 for (
auto &line : this->
lines) {
587 cur_line += line.num_lines;
588 if (cur_line <= pos)
continue;
589 if (
top > pos + cap)
break;
591 int y_offset = (
top - pos) * line_height;
592 if (line.wrapped_width != 0) {
606 this->UpdateVisibleIterators();
616 for (
auto &line : this->
lines) {
619 line.wrapped_width = 0;
627 if (!gui_scope)
return;
637 this->ScrollToLine(index);
640extern bool CanContinueRealtimeTick();
648 bool wrapped = this->IsTextWrapped();
656 int old_lines = line.num_lines;
658 if (line.wrapped_width != window_width) {
660 line.wrapped_width = window_width;
663 if (line.max_width == -1) {
668 line.wrapped_width = 0;
672 this->
num_lines += (line.num_lines - old_lines);
675 if (this->
visible_first > it) pos += (line.num_lines - old_lines);
680 if (!CanContinueRealtimeTick())
break;
683 if (this->
vscroll->SetPosition(pos)) dirty =
true;
690 auto r = this->ContinueReflow();
697 this->UpdateVisibleIterators();
704void TextfileWindow::UpdateVisibleIterators()
711 this->visible_last = std::ranges::next(this->
visible_first, cap + 1, std::end(this->
lines));
718 this->UpdateVisibleIterators();
722std::vector<TextfileWindow::Line>::iterator TextfileWindow::GetIteratorFromPosition(
int pos)
724 for (
auto it = std::begin(this->
lines); it != std::end(this->
lines); ++it) {
725 pos -= it->num_lines;
726 if (pos <= 0)
return it;
728 return std::end(this->
lines);
731void TextfileWindow::ScrollToLine(
size_t line)
735 for (
auto it = std::begin(this->
lines); it != std::end(this->
lines) && line > 0; --line, ++it) {
736 newpos += it->num_lines;
739 this->UpdateVisibleIterators();
744bool TextfileWindow::IsTextWrapped()
const
766#if defined(WITH_ZLIB)
776static std::vector<char>
Gunzip(std::span<char> input)
778 static const int BLOCKSIZE = 8192;
779 std::vector<char> output;
782 z.next_in =
reinterpret_cast<Bytef *
>(input.data());
783 z.avail_in =
static_cast<uInt
>(input.size());
786 int res = inflateInit2(&z, 15 + 32);
788 while (res == Z_OK || (res == Z_BUF_ERROR && z.avail_out == 0)) {
791 z.avail_out += BLOCKSIZE;
792 output.resize(output.size() + BLOCKSIZE);
793 z.next_out =
reinterpret_cast<Bytef *
>(output.data() + output.size() - z.avail_out);
794 res = inflate(&z, Z_FINISH);
798 if (res != Z_STREAM_END)
return {};
800 output.resize(output.size() - z.avail_out);
805#if defined(WITH_LIBLZMA)
815static std::vector<char>
Xunzip(std::span<char> input)
817 static const int BLOCKSIZE = 8192;
818 std::vector<char> output;
820 lzma_stream z = LZMA_STREAM_INIT;
821 z.next_in =
reinterpret_cast<uint8_t *
>(input.data());
822 z.avail_in = input.size();
824 int res = lzma_auto_decoder(&z, UINT64_MAX, LZMA_CONCATENATED);
826 while (res == LZMA_OK || (res == LZMA_BUF_ERROR && z.avail_out == 0)) {
829 z.avail_out += BLOCKSIZE;
830 output.resize(output.size() + BLOCKSIZE);
831 z.next_out =
reinterpret_cast<uint8_t *
>(output.data() + output.size() - z.avail_out);
832 res = lzma_code(&z, LZMA_FINISH);
836 if (res != LZMA_STREAM_END)
return {};
838 output.resize(output.size() - z.avail_out);
856 if (textfile.empty())
return;
860 auto handle =
FioFOpenFile(textfile,
"rb", dir, &filesize);
861 if (!handle.has_value())
return;
863 if (filesize == 0)
return;
865 std::vector<char> buf;
866 buf.resize(filesize);
867 size_t read = fread(buf.data(), 1, buf.size(), *handle);
869 if (read != buf.size())
return;
871#if defined(WITH_ZLIB)
873 if (textfile.ends_with(
".gz")) buf =
Gunzip(buf);
876#if defined(WITH_LIBLZMA)
878 if (textfile.ends_with(
".xz")) buf =
Xunzip(buf);
881 if (buf.empty())
return;
883 std::string_view sv_buf(buf.data(), buf.size());
886 if (sv_buf.starts_with(
"\ufeff")) sv_buf.remove_prefix(3);
911 std::string_view p(text);
912 auto next = p.find_first_of(
'\n');
913 while (next != std::string_view::npos) {
914 this->
lines.emplace_back(p.substr(0, next));
915 p.remove_prefix(next + 1);
917 next = p.find_first_of(
'\n');
919 this->
lines.emplace_back(p);
948 std::string_view prefix = prefixes[type];
950 if (filename.empty())
return std::nullopt;
952 auto slash = filename.find_last_of(PATHSEPCHAR);
953 if (slash == std::string::npos)
return std::nullopt;
955 std::string_view base_path = filename.substr(0, slash + 1);
957 static const std::initializer_list<const std::string_view> extensions{
960#if defined(WITH_ZLIB)
964#if defined(WITH_LIBLZMA)
970 for (
auto &extension : extensions) {
977 file_path = fmt::format(
"{}{}.{}", base_path, prefix, extension);
Class for backupping variables and making sure they are restored later.
void PutUtf8(char32_t c)
Append UTF-8 char.
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.
Compose data into a growing std::string.
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(facility, severity, format_string,...)
Output a line of debugging information.
@ Misc
Misc message facility.
@ Info
Info, information you might care about.
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
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.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
bool FioCheckFileExists(std::string_view filename, Subdirectory subdir)
Check whether the given file exists.
Functions for standard in/out file operations.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
@ None
A path without any base directory.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
bool DrawStringMultiLineWithClipping(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw a multiline string, possibly over multiple lines, if the region is within the current display cl...
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.
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
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.
@ Monospace
Index of the monospaced font in the font tables.
@ Checker
Draw only every second pixel, used for greying-out.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
#define Point
Macro that prevents name conflicts between included headers.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
static constexpr PixelColour PC_WHITE
White palette colour.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
bool StrEndsWithIgnoreCase(std::string_view str, std::string_view suffix)
Check whether the given string ends with the given suffix, ignoring case.
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Compose strings from textual and binary data.
Functions related to low-level strings.
@ ReplaceWithQuestionMark
Replace the unknown/bad bits with question marks.
@ AllowNewline
Allow newlines; replaces '\r ' with ' ' during processing.
@ ReplaceTabCrNlWithSpace
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
void CheckForMissingGlyphs(FontSizes fontsizes, 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.
std::string_view GetCurrentLanguageIsoCode()
Get the ISO language code of the currently loaded language.
TextDirection _current_text_dir
Text direction of the currently selected language.
@ TD_RTL
Text is written right-to-left by default.
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.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Data about how and where to blit pixels.
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
int Width() const
Get width of Rect.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect WithHeight(int height, bool end=false) const
Copy Rect and set its height.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
size_t end
Character position on line the link end.
size_t begin
Character position on line the link begins.
std::string destination
Destination for the link.
int num_lines
Number of visual lines for this line.
std::string text
Contents of the line.
Scrollbar * hscroll
Horizontal scrollbar.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
LineIterator visible_first
Iterator to first visible element.
LineIterator visible_last
Iterator to last visible element.
void Reset() override
Reset the search, i.e.
void OnX2Click(Point pt, WidgetID widget) override
A click with the X2 mouse button has been made on the window.
ReflowIterator reflow_iter
Current iterator for reflow.
uint search_iterator
Iterator for the font check search.
void SetupScrollbars()
Set scrollbars to the right lengths.
void AppendHistory(const std::string &filepath)
Append the new location to the history, so the user can go back.
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.
ReflowIterator reflow_end
End iterator for reflow.
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.
void OnScrollbarScroll(WidgetID widget) override
Notify window that a scrollbar position has been updated.
TextfileType file_type
Type of textfile to view.
size_t num_lines
Number of lines of text, taking account of wrapping.
void AfterLoadMarkdown()
Post-processing of markdown files.
FontSize DefaultSize() override
Get the default (font) size of the string.
void OnX1Click(Point pt, WidgetID widget) override
A click with the X1 mouse button has been made on the window.
void OnInit() override
Notification that the nested widget tree gets initialized.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnRealtimeTick(uint delta_ms) override
Called periodically.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
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 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.
void ReflowContent()
Reset the reflow process to start on the next UI tick.
@ VisibleReflowed
Visible content has been reflowed.
@ None
Nothing has been reflowed.
@ Reflowed
Content has been reflowed.
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.
int max_width
Maximum length of unwrapped text line.
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).
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
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 top
y position of top edge of the window
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.
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 WindowDesc _textfile_desc(WindowPosition::Center, "textfile", 630, 460, WindowClass::Textfile, WindowClass::None, {}, _nested_textfile_widgets)
Window definition for the textfile window.
static constexpr std::initializer_list< 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 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.
std::optional< std::string > GetTextfile(TextfileType type, Subdirectory dir, std::string_view filename)
Search a textfile file next to the given content.
GUI functions related to textfiles.
TextfileType
Additional text files accompanying Tar archives.
@ ContentEnd
This marker is used to generate the above three buttons in sequence by various of places in the code.
@ Center
Center the window.