OpenTTD Source 20261112-master-gbcbec5e63f
textfile_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "core/backup_type.hpp"
12#include "fileio_func.h"
13#include "gfx_type.h"
14#include "gfx_func.h"
15#include "string_func.h"
17#include "textfile_gui.h"
18#include "dropdown_type.h"
19#include "dropdown_func.h"
20#include "gfx_layout.h"
21#include "debug.h"
22#include "openttd.h"
23
24#include "widgets/misc_widget.h"
25
26#include "table/strings.h"
27#include "table/control_codes.h"
28
29#if defined(WITH_ZLIB)
30#include <zlib.h>
31#endif
32
33#if defined(WITH_LIBLZMA)
34#include <lzma.h>
35#endif
36
37#include <regex>
38
39#include "safeguards.h"
40
42static constexpr std::initializer_list<NWidgetPart> _nested_textfile_widgets = {
47 NWidget(WWT_CAPTION, Colours::Mauve, WID_TF_CAPTION), SetToolTip(STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
48 NWidget(WWT_TEXTBTN, Colours::Mauve, WID_TF_WRAPTEXT), SetStringTip(STR_TEXTFILE_WRAP_TEXT, STR_TEXTFILE_WRAP_TEXT_TOOLTIP),
54 /* As this widget can be toggled, it needs to be a multiplier of FontSize::Monospace. So add a spacer that ensures this. */
57 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
58 NWidget(WWT_DROPDOWN, Colours::Mauve, WID_TF_JUMPLIST), SetStringTip(STR_TEXTFILE_JUMPLIST, STR_TEXTFILE_JUMPLIST_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
59 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
75};
76
79 WindowPosition::Center, "textfile", 630, 460,
80 WindowClass::Textfile, WindowClass::None,
81 {},
83);
84
85TextfileWindow::TextfileWindow(Window *parent, TextfileType file_type) : Window(_textfile_desc), file_type(file_type)
86{
87 /* Init of nested tree is deferred.
88 * TextfileWindow::ConstructWindow must be called by the inheriting window. */
89 this->parent = parent;
90}
91
92void TextfileWindow::ConstructWindow()
93{
94 this->CreateNestedTree();
97 this->GetWidget<NWidgetCore>(WID_TF_CAPTION)->SetStringTip(STR_TEXTFILE_README_CAPTION + to_underlying(this->file_type), STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
99 this->FinishInitNested(this->file_type);
100
103 this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
104}
105
110{
111 /* Minimum number of lines that will be flowed. */
112 if (this->num_lines == 0) this->num_lines = std::size(this->lines);
113
114 auto it = this->GetIteratorFromPosition(this->vscroll->GetPosition());
115
116 auto adapter = AlternatingView{this->lines, it};
117 this->reflow_iter = adapter.begin();
118 this->reflow_end = adapter.end();
119}
120
121/* virtual */ void TextfileWindow::UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize)
122{
123 switch (widget) {
125 resize.width = GetCharacterHeight(FontSize::Monospace); // Width is not available here as the font may not be loaded yet.
126 fill.height = resize.height = GetCharacterHeight(FontSize::Monospace);
127
128 size.height = 4 * resize.height + WidgetDimensions::scaled.frametext.Vertical(); // At least 4 lines are visible.
129 size.width = std::max(200u, size.width); // At least 200 pixels wide.
130 break;
131 }
132}
133
136{
137 this->vscroll->SetCount(this->num_lines);
138 this->hscroll->SetCount(this->IsTextWrapped() ? 0 : CeilDiv(this->max_width, this->resize.step_width));
139
142 this->SetWidgetDisabledState(WID_TF_HSCROLLBAR, this->IsTextWrapped());
143}
144
145
147static const std::regex _markdown_link_regex{"\\[(.+?)\\]\\((.+?)\\)", std::regex_constants::ECMAScript | std::regex_constants::optimize};
148
150enum class HyperlinkType : uint8_t {
155};
156
164static HyperlinkType ClassifyHyperlink(const std::string &destination, bool trusted)
165{
166 if (destination.empty()) return HyperlinkType::Unknown;
167 if (destination.starts_with("#")) return HyperlinkType::Internal;
168
169 /* Only allow external / internal links for sources we trust. */
170 if (!trusted) return HyperlinkType::Unknown;
171
172 if (destination.starts_with("http://")) return HyperlinkType::Web;
173 if (destination.starts_with("https://")) return HyperlinkType::Web;
174 if (destination.starts_with("./")) return HyperlinkType::File;
176}
177
184static std::string MakeAnchorSlug(const std::string &line)
185{
186 std::string r = "#";
187 uint state = 0;
188 for (char c : line) {
189 if (state == 0) {
190 /* State 0: Skip leading hashmarks and spaces. */
191 if (c == '#') continue;
192 if (c == ' ') continue;
193 state = 1;
194 }
195 if (state == 2) {
196 /* State 2: Wait for a non-space/dash character.
197 * When found, output a dash and that character. */
198 if (c == ' ' || c == '-') continue;
199 r += '-';
200 state = 1;
201 }
202 if (state == 1) {
203 /* State 1: Normal text.
204 * Lowercase alphanumerics,
205 * spaces and dashes become dashes,
206 * everything else is removed. */
207 if (isalnum(c)) {
208 r += tolower(c);
209 } else if (c == ' ' || c == '-') {
210 state = 2;
211 }
212 }
213 }
214
215 return r;
216}
217
224void TextfileWindow::FindHyperlinksInMarkdown(Line &line, size_t line_index)
225{
226 std::string::const_iterator last_match_end = line.text.cbegin();
227 std::string fixed_line;
228 StringBuilder builder(fixed_line);
229
230 std::sregex_iterator matcher{ line.text.cbegin(), line.text.cend(), _markdown_link_regex};
231 while (matcher != std::sregex_iterator()) {
232 std::smatch match = *matcher;
233
234 Hyperlink &link = this->links.emplace_back(line_index, 0, 0, match[2].str());
235
236 HyperlinkType link_type = ClassifyHyperlink(link.destination, this->trusted);
237 StringControlCode link_colour;
238 switch (link_type) {
240 link_colour = SCC_GREEN;
241 break;
243 link_colour = SCC_LTBLUE;
244 break;
246 link_colour = SCC_LTBROWN;
247 break;
248 default:
249 /* Don't make other link types fancy as they aren't handled (yet). */
250 link_colour = SCC_CONTROL_END;
251 break;
252 }
253
254 if (link_colour != SCC_CONTROL_END) {
255 /* Format the link to look like a link. */
256 builder += std::string_view(last_match_end, match[0].first);
257 link.begin = fixed_line.length();
258 builder.PutUtf8(SCC_PUSH_COLOUR);
259 builder.PutUtf8(link_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;
264 }
265
266 /* Find next link. */
267 ++matcher;
268 }
269 if (last_match_end == line.text.cbegin()) return; // nothing found
270
271 /* Add remaining text on line. */
272 fixed_line += std::string(last_match_end, line.text.cend());
273
274 /* Overwrite original line text with "fixed" line text. */
275 line.text = std::move(fixed_line);
276}
277
284{
285 if (this->links.empty()) return nullptr;
286
287 /* Which line was clicked. */
289
290 int visible_line = 0;
291 auto it = std::ranges::find_if(this->lines, [&visible_line, clicked_row](const Line &l) {
292 visible_line += l.num_lines;
293 return (visible_line - l.num_lines) <= clicked_row && visible_line > clicked_row;
294 });
295 if (it == this->lines.cend()) return nullptr;
296
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);
300
301 /* Find hyperlinks in this line. */
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);
305 }
306 if (found_links.empty()) return nullptr;
307
308 /* Build line layout to figure out character position that was clicked. */
309 const Line &line = this->lines[line_index];
310 Layouter layout(line.text, line.wrapped_width == 0 ? INT32_MAX : line.wrapped_width, FontSize::Monospace);
311 assert(subline < layout.size());
312 ptrdiff_t char_index = layout.GetCharAtPosition(pt.x - WidgetDimensions::scaled.frametext.left, subline);
313 if (char_index < 0) return nullptr;
314 Debug(Facility::Misc, Severity::Info, "TextfileWindow check hyperlink click: line={}, subline={}, char_index={}", line_index, subline, char_index);
315
316 /* Found character index in line, check if any links are at that position. */
317 for (const Hyperlink *link : found_links) {
318 Debug(Facility::Misc, Severity::Info, "Checking link from char {} to {}", link->begin, link->end);
319 if (static_cast<size_t>(char_index) >= link->begin && static_cast<size_t>(char_index) < link->end) {
320 Debug(Facility::Misc, Severity::Info, "Returning link with destination: {}", link->destination);
321 return link;
322 }
323 }
324
325 return nullptr;
326}
327
334{
335 this->history.erase(this->history.begin() + this->history_pos + 1, this->history.end());
337 this->history.emplace_back(filepath, 0);
340 this->history_pos = this->history.size() - 1;
341}
342
350
357{
358 if (delta == 0) return;
359 if (delta < 0 && static_cast<int>(this->history_pos) < -delta) return;
360 if (delta > 0 && this->history_pos + delta >= this->history.size()) return;
361
363 this->history_pos += delta;
364
365 if (this->history[this->history_pos].filepath != this->filepath) {
366 this->filepath = this->history[this->history_pos].filepath;
367 this->filename = this->filepath.substr(this->filepath.find_last_of(PATHSEP) + 1);
369 }
370
371 this->SetWidgetDisabledState(WID_TF_NAVFORWARD, this->history_pos + 1 >= this->history.size());
373 this->GetScrollbar(WID_TF_VSCROLLBAR)->SetPosition(this->history[this->history_pos].scrollpos);
375 this->SetDirty();
376}
377
378/* virtual */ void TextfileWindow::OnHyperlinkClick(const Hyperlink &link)
379{
380 switch (ClassifyHyperlink(link.destination, this->trusted)) {
382 {
383 auto it = std::ranges::find(this->link_anchors, link.destination, &Hyperlink::destination);
384 if (it != this->link_anchors.cend()) {
385 this->AppendHistory(this->filepath);
386 this->ScrollToLine(it->line);
388 }
389 break;
390 }
391
393 OpenBrowser(link.destination);
394 break;
395
397 this->NavigateToFile(link.destination, 0);
398 break;
399
400 default:
401 /* Do nothing */
402 break;
403 }
404}
405
412void TextfileWindow::NavigateToFile(std::string newfile, size_t line)
413{
414 /* Double-check that the file link begins with ./ as a relative path. */
415 if (!newfile.starts_with("./")) return;
416
417 /* Get the path portion of the current file path. */
418 std::string newpath = this->filepath;
419 size_t pos = newpath.find_last_of(PATHSEPCHAR);
420 if (pos == std::string::npos) {
421 newpath.clear();
422 } else {
423 newpath.erase(pos + 1);
424 }
425
426 /* Check and remove for anchor in link. Do this before we find the filename, as people might have a / after the hash. */
427 size_t anchor_pos = newfile.find_first_of('#');
428 std::string anchor;
429 if (anchor_pos != std::string::npos) {
430 anchor = newfile.substr(anchor_pos);
431 newfile.erase(anchor_pos);
432 }
433
434 /* Now the anchor is gone, check if this is a markdown or textfile. */
435 if (!StrEndsWithIgnoreCase(newfile, ".md") && !StrEndsWithIgnoreCase(newfile, ".txt")) return;
436
437 /* Convert link destination to acceptable local filename (replace forward slashes with correct path separator). */
438 newfile = newfile.substr(2);
439 if (PATHSEPCHAR != '/') {
440 for (char &c : newfile) {
441 if (c == '/') c = PATHSEPCHAR;
442 }
443 }
444
445 /* Paste the two together and check file exists. */
446 newpath = newpath + newfile;
447 if (!FioCheckFileExists(newpath, Subdirectory::None)) return;
448
449 /* Update history. */
450 this->AppendHistory(newpath);
451
452 /* Load the new file. */
453 this->filepath = newpath;
454 this->filename = newpath.substr(newpath.find_last_of(PATHSEP) + 1);
455
457
460
461 if (anchor.empty() || line != 0) {
462 this->ScrollToLine(line);
463 } else {
464 auto anchor_dest = std::ranges::find(this->link_anchors, anchor, &Hyperlink::destination);
465 if (anchor_dest != this->link_anchors.cend()) {
466 this->ScrollToLine(anchor_dest->line);
468 } else {
469 this->ScrollToLine(0);
470 }
471 }
472}
473
475{
476 this->link_anchors.clear();
477
478 if (StrEndsWithIgnoreCase(this->filename, ".md")) this->AfterLoadMarkdown();
479
480 if (this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(this->jumplist.empty() ? SZSP_HORIZONTAL : 0)) this->ReInit();
481}
482
487{
488 for (size_t line_index = 0; line_index < this->lines.size(); ++line_index) {
489 Line &line = this->lines[line_index];
490
491 /* Find and mark all hyperlinks in the line. */
492 this->FindHyperlinksInMarkdown(line, line_index);
493
494 /* All lines beginning with # are headings. */
495 if (!line.text.empty() && line.text[0] == '#') {
496 this->jumplist.push_back(line_index);
497 this->lines[line_index].colour = TextColour::Gold;
498 this->link_anchors.emplace_back(line_index, 0, 0, MakeAnchorSlug(line.text));
499 }
500 }
501}
502
503/* virtual */ void TextfileWindow::OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count)
504{
505 switch (widget) {
506 case WID_TF_WRAPTEXT:
508 this->InvalidateData();
509 break;
510
511 case WID_TF_JUMPLIST: {
512 DropDownList list;
513 for (size_t line : this->jumplist) {
514 list.push_back(MakeDropDownListStringItem(GetString(STR_TEXTFILE_JUMPLIST_ITEM, this->lines[line].text), (int)line));
515 }
516 ShowDropDownList(this, std::move(list), -1, widget);
517 break;
518 }
519
520 case WID_TF_NAVBACK:
521 this->NavigateHistory(-1);
522 break;
523
525 this->NavigateHistory(+1);
526 break;
527
528 case WID_TF_BACKGROUND: {
529 const Hyperlink *link = this->GetHyperlink(pt);
530 if (link != nullptr) this->OnHyperlinkClick(*link);
531 break;
532 }
533 }
534}
535
536/* virtual */ void TextfileWindow::OnX1Click([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget)
537{
538 this->NavigateHistory(-1);
539}
540
541/* virtual */ void TextfileWindow::OnX2Click([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget)
542{
543 this->NavigateHistory(1);
544}
545
546/* virtual */ bool TextfileWindow::OnTooltip([[maybe_unused]] Point pt, WidgetID widget, TooltipCloseCondition close_cond)
547{
548 if (widget != WID_TF_BACKGROUND) return false;
549
550 const Hyperlink *link = this->GetHyperlink(pt);
551 if (link == nullptr) return false;
552
553 GuiShowTooltips(this, GetEncodedString(STR_JUST_RAW_STRING, link->destination), close_cond);
554
555 return true;
556}
557
558/* virtual */ void TextfileWindow::DrawWidget(const Rect &r, WidgetID widget) const
559{
560 if (widget == WID_TF_CAPTION && std::size(this->lines) > 0 && this->reflow_iter != this->reflow_end) {
561 /* Draw a progress bar in the caption. */
562 Rect fr = r.Shrink(WidgetDimensions::scaled.captiontext).WithHeight(WidgetDimensions::scaled.vsep_normal, true);
563 size_t remaining = std::distance(this->reflow_iter, this->reflow_end);
564 fr = fr.WithWidth(static_cast<int>(remaining * fr.Width() / std::size(this->lines)), _current_text_dir != TD_RTL);
566 }
567
568 if (widget != WID_TF_BACKGROUND) return;
569
570 Rect fr = r.Shrink(WidgetDimensions::scaled.frametext);
571
572 DrawPixelInfo new_dpi;
573 if (!FillDrawPixelInfo(&new_dpi, fr)) return;
574 AutoRestoreBackup dpi_backup(_cur_dpi, &new_dpi);
575
576 /* Draw content (now coordinates given to DrawString* are local to the new clipping region). */
577 fr = fr.Translate(-fr.left, -fr.top);
578 int line_height = GetCharacterHeight(FontSize::Monospace);
579
580 if (!this->IsTextWrapped()) fr = ScrollRect(fr, *this->hscroll, this->resize.step_width);
581
582 int pos = this->vscroll->GetPosition();
583 int cap = this->vscroll->GetCapacity();
584 int cur_line = 0;
585 for (auto &line : this->lines) {
586 int top = cur_line;
587 cur_line += line.num_lines;
588 if (cur_line <= pos) continue;
589 if (top > pos + cap) break;
590
591 int y_offset = (top - pos) * line_height;
592 if (line.wrapped_width != 0) {
593 Rect tr = fr.WithWidth(line.wrapped_width, _current_text_dir == TD_RTL);
594 DrawStringMultiLineWithClipping(tr.left, tr.right, y_offset, y_offset + line.num_lines * line_height, line.text, line.colour, {AlignmentH::Start, AlignmentV::Top}, false, FontSize::Monospace);
595 } else {
596 DrawString(fr.left, fr.right, y_offset, line.text, line.colour, {AlignmentH::Start, AlignmentV::Top}, false, FontSize::Monospace);
597 }
598 }
599}
600
601/* virtual */ void TextfileWindow::OnResize()
602{
603 this->vscroll->SetCapacityFromWidget(this, WID_TF_BACKGROUND, WidgetDimensions::scaled.frametext.Vertical());
604 this->hscroll->SetCapacityFromWidget(this, WID_TF_BACKGROUND, WidgetDimensions::scaled.framerect.Horizontal());
605
606 this->UpdateVisibleIterators();
607 this->ReflowContent();
608 this->SetupScrollbars();
609}
610
611/* virtual */ void TextfileWindow::OnInit()
612{
613 /* If font has changed we need to recalculate the maximum width. */
614 this->num_lines = 0;
615 this->max_width = 0;
616 for (auto &line : this->lines) {
617 line.max_width = -1;
618 line.num_lines = 1;
619 line.wrapped_width = 0;
620 }
621
622 this->ReflowContent();
623}
624
625/* virtual */ void TextfileWindow::OnInvalidateData([[maybe_unused]] int data, [[maybe_unused]] bool gui_scope)
626{
627 if (!gui_scope) return;
628
629 this->ReflowContent();
630 this->SetupScrollbars();
631}
632
633void TextfileWindow::OnDropdownSelect(WidgetID widget, int index, int)
634{
635 if (widget != WID_TF_JUMPLIST) return;
636
637 this->ScrollToLine(index);
638}
639
640extern bool CanContinueRealtimeTick();
641
642TextfileWindow::ReflowState TextfileWindow::ContinueReflow()
643{
644 if (this->reflow_iter == this->reflow_end) return ReflowState::None;
645
646 int window_width = this->GetWidget<NWidgetCore>(WID_TF_BACKGROUND)->current_x - WidgetDimensions::scaled.frametext.Horizontal();
647
648 bool wrapped = this->IsTextWrapped();
649 bool dirty = false;
650 int pos = this->vscroll->GetPosition();
651
652 for (/* nothing */; this->reflow_iter != this->reflow_end; ++this->reflow_iter) {
653 auto it = this->reflow_iter.Base();
654 Line &line = *it;
655
656 int old_lines = line.num_lines;
657 if (wrapped) {
658 if (line.wrapped_width != window_width) {
659 line.num_lines = GetStringHeight(line.text, window_width, FontSize::Monospace) / GetCharacterHeight(FontSize::Monospace);
660 line.wrapped_width = window_width;
661 }
662 } else {
663 if (line.max_width == -1) {
664 line.max_width = GetStringBoundingBox(line.text, FontSize::Monospace).width;
665 this->max_width = std::max(this->max_width, line.max_width);
666 }
667 line.num_lines = 1;
668 line.wrapped_width = 0;
669 }
670
671 /* Adjust the total number of lines. */
672 this->num_lines += (line.num_lines - old_lines);
673
674 /* Maintain scroll position. */
675 if (this->visible_first > it) pos += (line.num_lines - old_lines);
676
677 /* Mark dirty if visible range is touched. */
678 if (it >= this->visible_first && it <= this->visible_last) dirty = true;
679
680 if (!CanContinueRealtimeTick()) break;
681 }
682
683 if (this->vscroll->SetPosition(pos)) dirty = true;
684
686}
687
689{
690 auto r = this->ContinueReflow();
691 if (r == ReflowState::None) return;
692
693 this->SetupScrollbars();
694
697 this->UpdateVisibleIterators();
698 }
699
700 /* Caption is always dirty. */
702}
703
704void TextfileWindow::UpdateVisibleIterators()
705{
706 int pos = this->vscroll->GetPosition();
707 int cap = this->vscroll->GetCapacity();
708 this->visible_first = this->GetIteratorFromPosition(pos);
709
710 /* The last visible iterator ignores line wrapping so that it does not need to change when line heights change. */
711 this->visible_last = std::ranges::next(this->visible_first, cap + 1, std::end(this->lines));
712}
713
715{
716 if (widget != WID_TF_VSCROLLBAR) return;
717
718 this->UpdateVisibleIterators();
719 this->ReflowContent();
720}
721
722std::vector<TextfileWindow::Line>::iterator TextfileWindow::GetIteratorFromPosition(int pos)
723{
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;
727 }
728 return std::end(this->lines);
729}
730
731void TextfileWindow::ScrollToLine(size_t line)
732{
733 Scrollbar *sb = this->GetScrollbar(WID_TF_VSCROLLBAR);
734 int newpos = 0;
735 for (auto it = std::begin(this->lines); it != std::end(this->lines) && line > 0; --line, ++it) {
736 newpos += it->num_lines;
737 }
738 sb->SetPosition(std::min(newpos, sb->GetCount() - sb->GetCapacity()));
739 this->UpdateVisibleIterators();
740 this->ReflowContent();
741 this->SetDirty();
742}
743
744bool TextfileWindow::IsTextWrapped() const
745{
746 return this->IsWidgetLowered(WID_TF_WRAPTEXT);
747}
748
749/* virtual */ void TextfileWindow::Reset()
750{
751 this->search_iterator = 0;
752}
753
755{
756 return FontSize::Monospace;
757}
758
759/* virtual */ std::optional<std::string_view> TextfileWindow::NextString()
760{
761 if (this->search_iterator >= this->lines.size()) return std::nullopt;
762
763 return this->lines[this->search_iterator++].text;
764}
765
766#if defined(WITH_ZLIB)
767
776static std::vector<char> Gunzip(std::span<char> input)
777{
778 static const int BLOCKSIZE = 8192;
779 std::vector<char> output;
780
781 z_stream z{};
782 z.next_in = reinterpret_cast<Bytef *>(input.data());
783 z.avail_in = static_cast<uInt>(input.size());
784
785 /* window size = 15, add 32 to enable gzip or zlib header processing */
786 int res = inflateInit2(&z, 15 + 32);
787 /* Z_BUF_ERROR just means we need more space */
788 while (res == Z_OK || (res == Z_BUF_ERROR && z.avail_out == 0)) {
789 /* When we get here, we're either just starting, or
790 * inflate is out of output space - allocate more */
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);
795 }
796
797 inflateEnd(&z);
798 if (res != Z_STREAM_END) return {};
799
800 output.resize(output.size() - z.avail_out);
801 return output;
802}
803#endif
804
805#if defined(WITH_LIBLZMA)
806
815static std::vector<char> Xunzip(std::span<char> input)
816{
817 static const int BLOCKSIZE = 8192;
818 std::vector<char> output;
819
820 lzma_stream z = LZMA_STREAM_INIT;
821 z.next_in = reinterpret_cast<uint8_t *>(input.data());
822 z.avail_in = input.size();
823
824 int res = lzma_auto_decoder(&z, UINT64_MAX, LZMA_CONCATENATED);
825 /* Z_BUF_ERROR just means we need more space */
826 while (res == LZMA_OK || (res == LZMA_BUF_ERROR && z.avail_out == 0)) {
827 /* When we get here, we're either just starting, or
828 * inflate is out of output space - allocate more */
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);
833 }
834
835 lzma_end(&z);
836 if (res != LZMA_STREAM_END) return {};
837
838 output.resize(output.size() - z.avail_out);
839 return output;
840}
841#endif
842
843
849/* virtual */ void TextfileWindow::LoadTextfile(const std::string &textfile, Subdirectory dir)
850{
851 this->lines.clear();
852 this->jumplist.clear();
853
854 if (this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(SZSP_HORIZONTAL)) this->ReInit();
855
856 if (textfile.empty()) return;
857
858 /* Get text from file */
859 size_t filesize;
860 auto handle = FioFOpenFile(textfile, "rb", dir, &filesize);
861 if (!handle.has_value()) return;
862 /* Early return on empty files. */
863 if (filesize == 0) return;
864
865 std::vector<char> buf;
866 buf.resize(filesize);
867 size_t read = fread(buf.data(), 1, buf.size(), *handle);
868
869 if (read != buf.size()) return;
870
871#if defined(WITH_ZLIB)
872 /* In-place gunzip */
873 if (textfile.ends_with(".gz")) buf = Gunzip(buf);
874#endif
875
876#if defined(WITH_LIBLZMA)
877 /* In-place xunzip */
878 if (textfile.ends_with(".xz")) buf = Xunzip(buf);
879#endif
880
881 if (buf.empty()) return;
882
883 std::string_view sv_buf(buf.data(), buf.size());
884
885 /* Check for the byte-order-mark, and skip it if needed. */
886 if (sv_buf.starts_with("\ufeff")) sv_buf.remove_prefix(3);
887
888 /* Update the filename. */
889 this->filepath = textfile;
890 this->filename = this->filepath.substr(this->filepath.find_last_of(PATHSEP) + 1);
891 /* If it's the first file being loaded, add to history. */
892 if (this->history.empty()) this->history.emplace_back(this->filepath, 0);
893
894 /* Process the loaded text into lines, and do any further parsing needed. */
895 this->LoadText(sv_buf);
896}
897
905void TextfileWindow::LoadText(std::string_view buf)
906{
908 this->lines.clear();
909
910 /* Split the string on newlines. */
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);
916
917 next = p.find_first_of('\n');
918 }
919 this->lines.emplace_back(p);
920
921 this->AfterLoadText();
922 this->ReflowContent();
923
925
926 /* The font may have changed when searching for glyphs, so ensure widget sizes are updated just in case. */
927 this->ReInit();
928}
929
937std::optional<std::string> GetTextfile(TextfileType type, Subdirectory dir, std::string_view filename)
938{
940 "readme",
941 "changelog",
942 "license",
943 };
944
945 /* Only the generic text file types allowed for this function */
946 if (type >= TextfileType::ContentEnd) return std::nullopt;
947
948 std::string_view prefix = prefixes[type];
949
950 if (filename.empty()) return std::nullopt;
951
952 auto slash = filename.find_last_of(PATHSEPCHAR);
953 if (slash == std::string::npos) return std::nullopt;
954
955 std::string_view base_path = filename.substr(0, slash + 1);
956
957 static const std::initializer_list<const std::string_view> extensions{
958 "txt",
959 "md",
960#if defined(WITH_ZLIB)
961 "txt.gz",
962 "md.gz",
963#endif
964#if defined(WITH_LIBLZMA)
965 "txt.xz",
966 "md.xz",
967#endif
968 };
969
970 for (auto &extension : extensions) {
971 std::string file_path = fmt::format("{}{}_{}.{}", base_path, prefix, GetCurrentLanguageIsoCode(), extension);
972 if (FioCheckFileExists(file_path, dir)) return file_path;
973
974 file_path = fmt::format("{}{}_{:.2s}.{}", base_path, prefix, GetCurrentLanguageIsoCode(), extension);
975 if (FioCheckFileExists(file_path, dir)) return file_path;
976
977 file_path = fmt::format("{}{}.{}", base_path, prefix, extension);
978 if (FioCheckFileExists(file_path, dir)) return file_path;
979 }
980 return std::nullopt;
981}
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.
Definition gfx_layout.h:266
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.
size_type GetCapacity() const
Gets the number of visible elements of the scrollbar.
bool SetPosition(size_type position)
Sets the position of the first visible element.
size_type GetCount() const
Gets the number of elements in the list.
size_type GetPosition() const
Gets the position of the first visible element in the list.
Compose data into a growing std::string.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
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.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Info
Info, information you might care about.
Definition debug_type.h:19
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
Definition dropdown.cpp:49
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.
Definition dropdown.cpp:591
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).
Definition enum_type.hpp:21
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.
Definition fileio.cpp:248
bool FioCheckFileExists(std::string_view filename, Subdirectory subdir)
Check whether the given file exists.
Definition fileio.cpp:122
Functions for standard in/out file operations.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:87
@ None
A path without any base directory.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
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...
Definition gfx.cpp:867
int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Definition gfx.cpp:711
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
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.
Definition gfx.cpp:111
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.
Definition gfx.cpp:663
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition gfx.cpp:1567
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.
Definition gfx_type.h:248
@ Monospace
Index of the monospaced font in the font tables.
Definition gfx_type.h:252
@ Mauve
Mauve.
Definition gfx_type.h:295
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Gold
Gold colour.
Definition gfx_type.h:320
@ Checker
Draw only every second pixel, used for greying-out.
Definition gfx_type.h:393
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FontSize::Normal)
Widget part function for setting the minimal text lines.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetArrowWidgetTypeTip(ArrowWidgetType widget_type, StringID tip={})
Widget part function for setting the arrow widget type and tooltip.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
#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.
Definition misc_gui.cpp:690
Types related to the misc widgets.
@ WID_TF_JUMPLIST
List to jump around the file.
Definition misc_widget.h:57
@ WID_TF_BACKGROUND
Panel to draw the textfile on.
Definition misc_widget.h:59
@ WID_TF_NAVBACK
Navigate back button.
Definition misc_widget.h:54
@ WID_TF_WRAPTEXT
Whether or not to wrap the text.
Definition misc_widget.h:56
@ WID_TF_NAVFORWARD
Navigate forward button.
Definition misc_widget.h:55
@ WID_TF_CAPTION
The caption of the window.
Definition misc_widget.h:53
@ WID_TF_SEL_JUMPLIST
Selection to display the jump list or not.
Definition misc_widget.h:58
@ WID_TF_HSCROLLBAR
Horizontal scrollbar to scroll through the textfile left-to-right.
Definition misc_widget.h:61
@ WID_TF_VSCROLLBAR
Vertical scrollbar to scroll through the textfile up-and-down.
Definition misc_widget.h:60
Some generic types.
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.
Definition string.cpp:298
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
Compose strings from textual and binary data.
Functions related to low-level strings.
@ ReplaceWithQuestionMark
Replace the unknown/bad bits with question marks.
Definition string_type.h:45
@ AllowNewline
Allow newlines; replaces '\r ' with ' ' during processing.
Definition string_type.h:46
@ ReplaceTabCrNlWithSpace
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
Definition string_type.h:53
void CheckForMissingGlyphs(FontSizes fontsizes, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition strings.cpp:2381
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
std::string_view GetCurrentLanguageIsoCode()
Get the ISO language code of the currently loaded language.
Definition strings.cpp:2298
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
@ 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...
T y
Y coordinate.
T x
X coordinate.
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.
Definition gfx_type.h:157
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.
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.
Definition window_gui.h:171
Data structure for an opened window.
Definition window_gui.h:272
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void DisableWidget(WidgetID widget_index)
Sets a widget to disabled.
Definition window_gui.h:390
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
void EnableWidget(WidgetID widget_index)
Sets a widget to Enabled.
Definition window_gui.h:399
int top
y position of top edge of the window
Definition window_gui.h:309
int GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height=-1) const
Compute the row of a widget that a user clicked in.
Definition window.cpp:218
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.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
void ToggleWidgetLoweredState(WidgetID widget_index)
Invert the lowered/raised status of a widget.
Definition window_gui.h:449
HyperlinkType
Types of link we support in markdown files.
@ File
Link to a local file.
@ Unknown
Unknown link.
@ 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.
Rect ScrollRect(Rect r, const Scrollbar &sb, int resize_step)
Apply 'scroll' to a rect to be drawn in.
Definition widget.cpp:2565
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
@ NWID_SPACER
Invisible widget that takes some space.
Definition widget_type.h:70
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ NWID_HSCROLLBAR
Horizontal scrollbar.
Definition widget_type.h:75
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ Decrease
Arrow to the left or in case of RTL to the right.
Definition widget_type.h:20
@ Increase
Arrow to the right or in case of RTL to the left.
Definition widget_type.h:21
TooltipCloseCondition
Definition window_gui.h:262
@ Center
Center the window.
Definition window_gui.h:146
int WidgetID
Widget ID.
Definition window_type.h:21