OpenTTD Source: src/textfile_gui.cpp Source File

OpenTTD Source 14.0-beta1

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 <http://www.gnu.org/licenses/>.
6 */
7
10 #include "stdafx.h"
11 #include "core/backup_type.hpp"
12 #include "fileio_func.h"
13 #include "fontcache.h"
14 #include "gfx_type.h"
15 #include "gfx_func.h"
16 #include "string_func.h"
17 #include "textfile_gui.h"
18 #include "widgets/dropdown_type.h"
19 #include "gfx_layout.h"
20 #include "debug.h"
21 #include "openttd.h"
22
23 #include "widgets/misc_widget.h"
24
25 #include "table/strings.h"
26 #include "table/control_codes.h"
27
28 #if defined(WITH_ZLIB)
29 #include <zlib.h>
30 #endif
31
32 #if defined(WITH_LIBLZMA)
33 #include <lzma.h>
34 #endif
35
36 #include <regex>
37
38 #include "safeguards.h"
39
41 static constexpr NWidgetPart _nested_textfile_widgets[] = {
42 NWidget(NWID_HORIZONTAL),
43 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
44 NWidget(WWT_PUSHARROWBTN, COLOUR_MAUVE, WID_TF_NAVBACK), SetFill(0, 1), SetMinimalSize(15, 1), SetDataTip(AWV_DECREASE, STR_TEXTFILE_NAVBACK_TOOLTIP),
45 NWidget(WWT_PUSHARROWBTN, COLOUR_MAUVE, WID_TF_NAVFORWARD), SetFill(0, 1), SetMinimalSize(15, 1), SetDataTip(AWV_INCREASE, STR_TEXTFILE_NAVFORWARD_TOOLTIP),
46 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_TF_CAPTION), SetDataTip(STR_NULL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
47 NWidget(WWT_TEXTBTN, COLOUR_MAUVE, WID_TF_WRAPTEXT), SetDataTip(STR_TEXTFILE_WRAP_TEXT, STR_TEXTFILE_WRAP_TEXT_TOOLTIP),
48 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
49 EndContainer(),
50 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_TF_SEL_JUMPLIST),
51 NWidget(WWT_PANEL, COLOUR_MAUVE),
52 NWidget(NWID_HORIZONTAL), SetPIP(WidgetDimensions::unscaled.frametext.left, 0, WidgetDimensions::unscaled.frametext.right),
53 /* As this widget can be toggled, it needs to be a multiplier of FS_MONO. So add a spacer that ensures this. */
54 NWidget(NWID_SPACER), SetMinimalSize(1, 0), SetMinimalTextLines(2, 0, FS_MONO),
55 NWidget(NWID_VERTICAL),
56 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
57 NWidget(WWT_DROPDOWN, COLOUR_MAUVE, WID_TF_JUMPLIST), SetDataTip(STR_TEXTFILE_JUMPLIST, STR_TEXTFILE_JUMPLIST_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
58 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
59 EndContainer(),
60 EndContainer(),
61 EndContainer(),
62 EndContainer(),
63 NWidget(NWID_HORIZONTAL),
64 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_TF_BACKGROUND), SetMinimalSize(200, 125), SetResize(1, 12), SetScrollbar(WID_TF_VSCROLLBAR),
65 EndContainer(),
66 NWidget(NWID_VERTICAL),
67 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_TF_VSCROLLBAR),
68 EndContainer(),
69 EndContainer(),
70 NWidget(NWID_HORIZONTAL),
71 NWidget(NWID_HSCROLLBAR, COLOUR_MAUVE, WID_TF_HSCROLLBAR),
72 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
73 EndContainer(),
74 };
75
77 static WindowDesc _textfile_desc(__FILE__, __LINE__,
78 WDP_CENTER, "textfile", 630, 460,
79 WC_TEXTFILE, WC_NONE,
80 0,
81 std::begin(_nested_textfile_widgets), std::end(_nested_textfile_widgets)
82 );
83
84 TextfileWindow::TextfileWindow(TextfileType file_type) : Window(&_textfile_desc), file_type(file_type)
85 {
86 /* Init of nested tree is deferred.
87 * TextfileWindow::ConstructWindow must be called by the inheriting window. */
88 }
89
90 void TextfileWindow::ConstructWindow()
91 {
92 this->CreateNestedTree();
93 this->vscroll = this->GetScrollbar(WID_TF_VSCROLLBAR);
94 this->hscroll = this->GetScrollbar(WID_TF_HSCROLLBAR);
95 this->GetWidget<NWidgetCore>(WID_TF_CAPTION)->SetDataTip(STR_TEXTFILE_README_CAPTION + this->file_type, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
96 this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(SZSP_HORIZONTAL);
97 this->FinishInitNested(this->file_type);
98
99 this->DisableWidget(WID_TF_NAVBACK);
100 this->DisableWidget(WID_TF_NAVFORWARD);
101 this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
102 }
103
108 uint TextfileWindow::ReflowContent()
109 {
110 uint height = 0;
111 if (!IsWidgetLowered(WID_TF_WRAPTEXT)) {
112 for (auto &line : this->lines) {
113 line.top = height;
114 height++;
115 line.bottom = height;
116 }
117 } else {
118 int max_width = this->GetWidget<NWidgetCore>(WID_TF_BACKGROUND)->current_x - WidgetDimensions::scaled.frametext.Horizontal();
119 for (auto &line : this->lines) {
120 line.top = height;
121 height += GetStringHeight(line.text, max_width, FS_MONO) / GetCharacterHeight(FS_MONO);
122 line.bottom = height;
123 }
124 }
125
126 return height;
127 }
128
129 uint TextfileWindow::GetContentHeight()
130 {
131 if (this->lines.empty()) return 0;
132 return this->lines.back().bottom;
133 }
134
135 /* virtual */ void TextfileWindow::UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize)
136 {
137 switch (widget) {
138 case WID_TF_BACKGROUND:
139 resize->height = GetCharacterHeight(FS_MONO);
140
141 size->height = 4 * resize->height + WidgetDimensions::scaled.frametext.Vertical(); // At least 4 lines are visible.
142 size->width = std::max(200u, size->width); // At least 200 pixels wide.
143 break;
144 }
145 }
146
148 void TextfileWindow::SetupScrollbars(bool force_reflow)
149 {
150 if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
151 /* Reflow is mandatory if text wrapping is on */
152 uint height = this->ReflowContent();
153 this->vscroll->SetCount(ClampTo<uint16_t>(height));
154 this->hscroll->SetCount(0);
155 } else {
156 uint height = force_reflow ? this->ReflowContent() : this->GetContentHeight();
157 this->vscroll->SetCount(ClampTo<uint16_t>(height));
158 this->hscroll->SetCount(this->max_length + WidgetDimensions::scaled.frametext.Horizontal());
159 }
160
161 this->SetWidgetDisabledState(WID_TF_HSCROLLBAR, IsWidgetLowered(WID_TF_WRAPTEXT));
162 }
163
164
166 static const std::regex _markdown_link_regex{"\\[(.+?)\\]\\((.+?)\\)", std::regex_constants::ECMAScript | std::regex_constants::optimize};
167
169 enum class HyperlinkType {
170 Internal,
171 Web,
172 File,
173 Unknown,
174 };
175
183 static HyperlinkType ClassifyHyperlink(const std::string &destination, bool trusted)
184 {
185 if (destination.empty()) return HyperlinkType::Unknown;
186 if (destination.starts_with("#")) return HyperlinkType::Internal;
187
188 /* Only allow external / internal links for sources we trust. */
189 if (!trusted) return HyperlinkType::Unknown;
190
191 if (destination.starts_with("http://")) return HyperlinkType::Web;
192 if (destination.starts_with("https://")) return HyperlinkType::Web;
193 if (destination.starts_with("./")) return HyperlinkType::File;
194 return HyperlinkType::Unknown;
195 }
196
203 static std::string MakeAnchorSlug(const std::string &line)
204 {
205 std::string r = "#";
206 uint state = 0;
207 for (char c : line) {
208 if (state == 0) {
209 /* State 0: Skip leading hashmarks and spaces. */
210 if (c == '#') continue;
211 if (c == ' ') continue;
212 state = 1;
213 }
214 if (state == 2) {
215 /* State 2: Wait for a non-space/dash character.
216 * When found, output a dash and that character. */
217 if (c == ' ' || c == '-') continue;
218 r += '-';
219 state = 1;
220 }
221 if (state == 1) {
222 /* State 1: Normal text.
223 * Lowercase alphanumerics,
224 * spaces and dashes become dashes,
225 * everything else is removed. */
226 if (isalnum(c)) {
227 r += tolower(c);
228 } else if (c == ' ' || c == '-') {
229 state = 2;
230 }
231 }
232 }
233
234 return r;
235 }
236
243 void TextfileWindow::FindHyperlinksInMarkdown(Line &line, size_t line_index)
244 {
245 std::string::const_iterator last_match_end = line.text.cbegin();
246 std::string fixed_line;
247 char ccbuf[5];
248
249 std::sregex_iterator matcher{ line.text.cbegin(), line.text.cend(), _markdown_link_regex};
250 while (matcher != std::sregex_iterator()) {
251 std::smatch match = *matcher;
252
253 Hyperlink link;
254 link.line = line_index;
255 link.destination = match[2].str();
256 this->links.push_back(link);
257
258 HyperlinkType link_type = ClassifyHyperlink(link.destination, this->trusted);
259 StringControlCode link_colour;
260 switch (link_type) {
261 case HyperlinkType::Internal:
262 link_colour = SCC_GREEN;
263 break;
264 case HyperlinkType::Web:
265 link_colour = SCC_LTBLUE;
266 break;
267 case HyperlinkType::File:
268 link_colour = SCC_LTBROWN;
269 break;
270 default:
271 /* Don't make other link types fancy as they aren't handled (yet). */
272 link_colour = SCC_CONTROL_END;
273 break;
274 }
275
276 if (link_colour != SCC_CONTROL_END) {
277 /* Format the link to look like a link. */
278 fixed_line += std::string(last_match_end, match[0].first);
279 this->links.back().begin = fixed_line.length();
280 fixed_line += std::string(ccbuf, Utf8Encode(ccbuf, SCC_PUSH_COLOUR));
281 fixed_line += std::string(ccbuf, Utf8Encode(ccbuf, link_colour));
282 fixed_line += match[1].str();
283 this->links.back().end = fixed_line.length();
284 fixed_line += std::string(ccbuf, Utf8Encode(ccbuf, SCC_POP_COLOUR));
285 last_match_end = match[0].second;
286 }
287
288 /* Find next link. */
289 ++matcher;
290 }
291 if (last_match_end == line.text.cbegin()) return; // nothing found
292
293 /* Add remaining text on line. */
294 fixed_line += std::string(last_match_end, line.text.cend());
295
296 /* Overwrite original line text with "fixed" line text. */
297 line.text = fixed_line;
298 }
299
305 void TextfileWindow::CheckHyperlinkClick(Point pt)
306 {
307 if (this->links.empty()) return;
308
309 /* Which line was clicked. */
310 const int clicked_row = this->GetRowFromWidget(pt.y, WID_TF_BACKGROUND, WidgetDimensions::scaled.frametext.top, GetCharacterHeight(FS_MONO)) + this->GetScrollbar(WID_TF_VSCROLLBAR)->GetPosition();
311 size_t line_index;
312 size_t subline;
313 if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
314 auto it = std::find_if(std::begin(this->lines), std::end(this->lines), [clicked_row](const Line &l) { return l.top <= clicked_row && l.bottom > clicked_row; });
315 if (it == this->lines.cend()) return;
316 line_index = it - this->lines.cbegin();
317 subline = clicked_row - it->top;
318 Debug(misc, 4, "TextfileWindow check hyperlink: clicked_row={}, line_index={}, line.top={}, subline={}", clicked_row, line_index, it->top, subline);
319 } else {
320 line_index = clicked_row / GetCharacterHeight(FS_MONO);
321 subline = 0;
322 }
323
324 /* Find hyperlinks in this line. */
325 std::vector<Hyperlink> found_links;
326 for (const auto &link : this->links) {
327 if (link.line == line_index) found_links.push_back(link);
328 }
329 if (found_links.empty()) return;
330
331 /* Build line layout to figure out character position that was clicked. */
332 uint window_width = IsWidgetLowered(WID_TF_WRAPTEXT) ? this->GetWidget<NWidgetCore>(WID_TF_BACKGROUND)->current_x - WidgetDimensions::scaled.frametext.Horizontal() : INT_MAX;
333 Layouter layout(this->lines[line_index].text, window_width, this->lines[line_index].colour, FS_MONO);
334 assert(subline < layout.size());
335 ptrdiff_t char_index = layout.GetCharAtPosition(pt.x - WidgetDimensions::scaled.frametext.left, subline);
336 if (char_index < 0) return;
337 Debug(misc, 4, "TextfileWindow check hyperlink click: line={}, subline={}, char_index={}", line_index, subline, (int)char_index);
338
339 /* Found character index in line, check if any links are at that position. */
340 for (const auto &link : found_links) {
341 Debug(misc, 4, "Checking link from char {} to {}", link.begin, link.end);
342 if ((size_t)char_index >= link.begin && (size_t)char_index < link.end) {
343 Debug(misc, 4, "Activating link with destination: {}", link.destination);
344 this->OnHyperlinkClick(link);
345 return;
346 }
347 }
348 }
349
355 void TextfileWindow::AppendHistory(const std::string &filepath)
356 {
357 this->history.erase(this->history.begin() + this->history_pos + 1, this->history.end());
358 this->UpdateHistoryScrollpos();
359 this->history.push_back(HistoryEntry{ filepath, 0 });
360 this->EnableWidget(WID_TF_NAVBACK);
361 this->DisableWidget(WID_TF_NAVFORWARD);
362 this->history_pos = this->history.size() - 1;
363 }
364
368 void TextfileWindow::UpdateHistoryScrollpos()
369 {
370 this->history[this->history_pos].scrollpos = this->GetScrollbar(WID_TF_VSCROLLBAR)->GetPosition();
371 }
372
378 void TextfileWindow::NavigateHistory(int delta)
379 {
380 if (delta == 0) return;
381 if (delta < 0 && static_cast<int>(this->history_pos) < -delta) return;
382 if (delta > 0 && this->history_pos + delta >= this->history.size()) return;
383
384 this->UpdateHistoryScrollpos();
385 this->history_pos += delta;
386
387 if (this->history[this->history_pos].filepath != this->filepath) {
388 this->filepath = this->history[this->history_pos].filepath;
389 this->filename = this->filepath.substr(this->filepath.find_last_of(PATHSEP) + 1);
390 this->LoadTextfile(this->filepath, NO_DIRECTORY);
391 }
392
393 this->SetWidgetDisabledState(WID_TF_NAVFORWARD, this->history_pos + 1 >= this->history.size());
394 this->SetWidgetDisabledState(WID_TF_NAVBACK, this->history_pos == 0);
395 this->GetScrollbar(WID_TF_VSCROLLBAR)->SetPosition(this->history[this->history_pos].scrollpos);
396 this->GetScrollbar(WID_TF_HSCROLLBAR)->SetPosition(0);
397 this->SetDirty();
398 }
399
400 /* virtual */ void TextfileWindow::OnHyperlinkClick(const Hyperlink &link)
401 {
402 switch (ClassifyHyperlink(link.destination, this->trusted)) {
403 case HyperlinkType::Internal:
404 {
405 auto it = std::find_if(this->link_anchors.cbegin(), this->link_anchors.cend(), [&](const Hyperlink &other) { return link.destination == other.destination; });
406 if (it != this->link_anchors.cend()) {
407 this->AppendHistory(this->filepath);
408 this->ScrollToLine(it->line);
409 this->UpdateHistoryScrollpos();
410 }
411 break;
412 }
413
414 case HyperlinkType::Web:
415 OpenBrowser(link.destination);
416 break;
417
418 case HyperlinkType::File:
419 this->NavigateToFile(link.destination, 0);
420 break;
421
422 default:
423 /* Do nothing */
424 break;
425 }
426 }
427
434 void TextfileWindow::NavigateToFile(std::string newfile, size_t line)
435 {
436 /* Double-check that the file link begins with ./ as a relative path. */
437 if (!newfile.starts_with("./")) return;
438
439 /* Get the path portion of the current file path. */
440 std::string newpath = this->filepath;
441 size_t pos = newpath.find_last_of(PATHSEPCHAR);
442 if (pos == std::string::npos) {
443 newpath.clear();
444 } else {
445 newpath.erase(pos + 1);
446 }
447
448 /* Check and remove for anchor in link. Do this before we find the filename, as people might have a / after the hash. */
449 size_t anchor_pos = newfile.find_first_of('#');
450 std::string anchor;
451 if (anchor_pos != std::string::npos) {
452 anchor = newfile.substr(anchor_pos);
453 newfile.erase(anchor_pos);
454 }
455
456 /* Now the anchor is gone, check if this is a markdown or textfile. */
457 if (!StrEndsWithIgnoreCase(newfile, ".md") && !StrEndsWithIgnoreCase(newfile, ".txt")) return;
458
459 /* Convert link destination to acceptable local filename (replace forward slashes with correct path separator). */
460 newfile = newfile.substr(2);
461 if (PATHSEPCHAR != '/') {
462 for (char &c : newfile) {
463 if (c == '/') c = PATHSEPCHAR;
464 }
465 }
466
467 /* Paste the two together and check file exists. */
468 newpath = newpath + newfile;
469 if (!FioCheckFileExists(newpath, NO_DIRECTORY)) return;
470
471 /* Update history. */
472 this->AppendHistory(newpath);
473
474 /* Load the new file. */
475 this->filepath = newpath;
476 this->filename = newpath.substr(newpath.find_last_of(PATHSEP) + 1);
477
478 this->LoadTextfile(this->filepath, NO_DIRECTORY);
479
480 this->GetScrollbar(WID_TF_HSCROLLBAR)->SetPosition(0);
481 this->GetScrollbar(WID_TF_VSCROLLBAR)->SetPosition(0);
482
483 if (anchor.empty() || line != 0) {
484 this->ScrollToLine(line);
485 } else {
486 auto anchor_dest = std::find_if(this->link_anchors.cbegin(), this->link_anchors.cend(), [&](const Hyperlink &other) { return anchor == other.destination; });
487 if (anchor_dest != this->link_anchors.cend()) {
488 this->ScrollToLine(anchor_dest->line);
489 this->UpdateHistoryScrollpos();
490 } else {
491 this->ScrollToLine(0);
492 }
493 }
494 }
495
496 /* virtual */ void TextfileWindow::AfterLoadText()
497 {
498 this->link_anchors.clear();
499
500 if (StrEndsWithIgnoreCase(this->filename, ".md")) this->AfterLoadMarkdown();
501
502 if (this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(this->jumplist.empty() ? SZSP_HORIZONTAL : 0)) this->ReInit();
503 }
504
508 void TextfileWindow::AfterLoadMarkdown()
509 {
510 for (size_t line_index = 0; line_index < this->lines.size(); ++line_index) {
511 Line &line = this->lines[line_index];
512
513 /* Find and mark all hyperlinks in the line. */
514 this->FindHyperlinksInMarkdown(line, line_index);
515
516 /* All lines beginning with # are headings. */
517 if (!line.text.empty() && line.text[0] == '#') {
518 this->jumplist.push_back(line_index);
519 this->lines[line_index].colour = TC_GOLD;
520 this->link_anchors.emplace_back(Hyperlink{ line_index, 0, 0, MakeAnchorSlug(line.text) });
521 }
522 }
523 }
524
525 /* virtual */ void TextfileWindow::OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count)
526 {
527 switch (widget) {
528 case WID_TF_WRAPTEXT:
529 this->ToggleWidgetLoweredState(WID_TF_WRAPTEXT);
530 this->InvalidateData();
531 break;
532
533 case WID_TF_JUMPLIST: {
534 DropDownList list;
535 for (size_t line : this->jumplist) {
536 SetDParamStr(0, this->lines[line].text);
537 list.push_back(std::make_unique<DropDownListStringItem>(STR_TEXTFILE_JUMPLIST_ITEM, (int)line, false));
538 }
539 ShowDropDownList(this, std::move(list), -1, widget);
540 break;
541 }
542
543 case WID_TF_NAVBACK:
544 this->NavigateHistory(-1);
545 break;
546
547 case WID_TF_NAVFORWARD:
548 this->NavigateHistory(+1);
549 break;
550
551 case WID_TF_BACKGROUND:
552 this->CheckHyperlinkClick(pt);
553 break;
554 }
555 }
556
557 /* virtual */ void TextfileWindow::DrawWidget(const Rect &r, WidgetID widget) const
558 {
559 if (widget != WID_TF_BACKGROUND) return;
560
561 Rect fr = r.Shrink(WidgetDimensions::scaled.frametext);
562
563 DrawPixelInfo new_dpi;
564 if (!FillDrawPixelInfo(&new_dpi, fr)) return;
565 AutoRestoreBackup dpi_backup(_cur_dpi, &new_dpi);
566
567 /* Draw content (now coordinates given to DrawString* are local to the new clipping region). */
568 fr = fr.Translate(-fr.left, -fr.top);
569 int line_height = GetCharacterHeight(FS_MONO);
570 int pos = this->vscroll->GetPosition();
571 int cap = this->vscroll->GetCapacity();
572
573 for (auto &line : this->lines) {
574 if (line.bottom < pos) continue;
575 if (line.top > pos + cap) break;
576
577 int y_offset = (line.top - pos) * line_height;
578 if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
579 DrawStringMultiLine(0, fr.right, y_offset, fr.bottom, line.text, line.colour, SA_TOP | SA_LEFT, false, FS_MONO);
580 } else {
581 DrawString(-this->hscroll->GetPosition(), fr.right, y_offset, line.text, line.colour, SA_TOP | SA_LEFT, false, FS_MONO);
582 }
583 }
584 }
585
586 /* virtual */ void TextfileWindow::OnResize()
587 {
588 this->vscroll->SetCapacityFromWidget(this, WID_TF_BACKGROUND, WidgetDimensions::scaled.frametext.Vertical());
589 this->hscroll->SetCapacityFromWidget(this, WID_TF_BACKGROUND);
590
591 this->SetupScrollbars(false);
592 }
593
594 /* virtual */ void TextfileWindow::OnInvalidateData([[maybe_unused]] int data, [[maybe_unused]] bool gui_scope)
595 {
596 if (!gui_scope) return;
597
598 this->SetupScrollbars(true);
599 }
600
601 void TextfileWindow::OnDropdownSelect(WidgetID widget, int index)
602 {
603 if (widget != WID_TF_JUMPLIST) return;
604
605 this->ScrollToLine(index);
606 }
607
608 void TextfileWindow::ScrollToLine(size_t line)
609 {
610 Scrollbar *sb = this->GetScrollbar(WID_TF_VSCROLLBAR);
611 int newpos;
612 if (this->IsWidgetLowered(WID_TF_WRAPTEXT)) {
613 newpos = this->lines[line].top;
614 } else {
615 newpos = static_cast<int>(line);
616 }
617 sb->SetPosition(std::min(newpos, sb->GetCount() - sb->GetCapacity()));
618 this->SetDirty();
619 }
620
621 /* virtual */ void TextfileWindow::Reset()
622 {
623 this->search_iterator = 0;
624 }
625
626 /* virtual */ FontSize TextfileWindow::DefaultSize()
627 {
628 return FS_MONO;
629 }
630
631 /* virtual */ std::optional<std::string_view> TextfileWindow::NextString()
632 {
633 if (this->search_iterator >= this->lines.size()) return std::nullopt;
634
635 return this->lines[this->search_iterator++].text;
636 }
637
638 /* virtual */ bool TextfileWindow::Monospace()
639 {
640 return true;
641 }
642
643 /* virtual */ void TextfileWindow::SetFontNames([[maybe_unused]] FontCacheSettings *settings, [[maybe_unused]] const char *font_name, [[maybe_unused]] const void *os_data)
644 {
645 #if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
646 settings->mono.font = font_name;
647 settings->mono.os_handle = os_data;
648 #endif
649 }
650
651 #if defined(WITH_ZLIB)
652
667 static void Gunzip(byte **bufp, size_t *sizep)
668 {
669 static const int BLOCKSIZE = 8192;
670 byte *buf = nullptr;
671 size_t alloc_size = 0;
672 z_stream z;
673 int res;
674
675 memset(&z, 0, sizeof(z));
676 z.next_in = *bufp;
677 z.avail_in = (uInt)*sizep;
678
679 /* window size = 15, add 32 to enable gzip or zlib header processing */
680 res = inflateInit2(&z, 15 + 32);
681 /* Z_BUF_ERROR just means we need more space */
682 while (res == Z_OK || (res == Z_BUF_ERROR && z.avail_out == 0)) {
683 /* When we get here, we're either just starting, or
684 * inflate is out of output space - allocate more */
685 alloc_size += BLOCKSIZE;
686 z.avail_out += BLOCKSIZE;
687 buf = ReallocT(buf, alloc_size);
688 z.next_out = buf + alloc_size - z.avail_out;
689 res = inflate(&z, Z_FINISH);
690 }
691
692 free(*bufp);
693 inflateEnd(&z);
694
695 if (res == Z_STREAM_END) {
696 *bufp = buf;
697 *sizep = alloc_size - z.avail_out;
698 } else {
699 /* Something went wrong */
700 *bufp = nullptr;
701 *sizep = 0;
702 free(buf);
703 }
704 }
705 #endif
706
707 #if defined(WITH_LIBLZMA)
708
723 static void Xunzip(byte **bufp, size_t *sizep)
724 {
725 static const int BLOCKSIZE = 8192;
726 byte *buf = nullptr;
727 size_t alloc_size = 0;
728 lzma_stream z = LZMA_STREAM_INIT;
729 int res;
730
731 z.next_in = *bufp;
732 z.avail_in = *sizep;
733
734 res = lzma_auto_decoder(&z, UINT64_MAX, LZMA_CONCATENATED);
735 /* Z_BUF_ERROR just means we need more space */
736 while (res == LZMA_OK || (res == LZMA_BUF_ERROR && z.avail_out == 0)) {
737 /* When we get here, we're either just starting, or
738 * inflate is out of output space - allocate more */
739 alloc_size += BLOCKSIZE;
740 z.avail_out += BLOCKSIZE;
741 buf = ReallocT(buf, alloc_size);
742 z.next_out = buf + alloc_size - z.avail_out;
743 res = lzma_code(&z, LZMA_FINISH);
744 }
745
746 free(*bufp);
747 lzma_end(&z);
748
749 if (res == LZMA_STREAM_END) {
750 *bufp = buf;
751 *sizep = alloc_size - z.avail_out;
752 } else {
753 /* Something went wrong */
754 *bufp = nullptr;
755 *sizep = 0;
756 free(buf);
757 }
758 }
759 #endif
760
761
765 /* virtual */ void TextfileWindow::LoadTextfile(const std::string &textfile, Subdirectory dir)
766 {
767 this->lines.clear();
768 this->jumplist.clear();
769
770 if (this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(SZSP_HORIZONTAL)) this->ReInit();
771
772 if (textfile.empty()) return;
773
774 /* Get text from file */
775 size_t filesize;
776 FILE *handle = FioFOpenFile(textfile, "rb", dir, &filesize);
777 if (handle == nullptr) return;
778 /* Early return on empty files. */
779 if (filesize == 0) return;
780
781 char *buf = MallocT<char>(filesize);
782 size_t read = fread(buf, 1, filesize, handle);
783 fclose(handle);
784
785 if (read != filesize) {
786 free(buf);
787 return;
788 }
789
790 #if defined(WITH_ZLIB)
791 /* In-place gunzip */
792 if (textfile.ends_with(".gz")) Gunzip((byte**)&buf, &filesize);
793 #endif
794
795 #if defined(WITH_LIBLZMA)
796 /* In-place xunzip */
797 if (textfile.ends_with(".xz")) Xunzip((byte**)&buf, &filesize);
798 #endif
799
800 if (buf == nullptr) return;
801
802 std::string_view sv_buf(buf, filesize);
803
804 /* Check for the byte-order-mark, and skip it if needed. */
805 if (sv_buf.starts_with("\ufeff")) sv_buf.remove_prefix(3);
806
807 /* Update the filename. */
808 this->filepath = textfile;
809 this->filename = this->filepath.substr(this->filepath.find_last_of(PATHSEP) + 1);
810 /* If it's the first file being loaded, add to history. */
811 if (this->history.empty()) this->history.push_back(HistoryEntry{ this->filepath, 0 });
812
813 /* Process the loaded text into lines, and do any further parsing needed. */
814 this->LoadText(sv_buf);
815 free(buf);
816 }
817
825 void TextfileWindow::LoadText(std::string_view buf)
826 {
827 std::string text = StrMakeValid(buf, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE | SVS_REPLACE_TAB_CR_NL_WITH_SPACE);
828 this->lines.clear();
829
830 /* Split the string on newlines. */
831 std::string_view p(text);
832 int row = 0;
833 auto next = p.find_first_of('\n');
834 while (next != std::string_view::npos) {
835 this->lines.emplace_back(row, p.substr(0, next));
836 p.remove_prefix(next + 1);
837
838 row++;
839 next = p.find_first_of('\n');
840 }
841 this->lines.emplace_back(row, p);
842
843 /* Calculate maximum text line length. */
844 uint max_length = 0;
845 for (auto &line : this->lines) {
846 max_length = std::max(max_length, GetStringBoundingBox(line.text, FS_MONO).width);
847 }
848 this->max_length = max_length;
849
850 this->AfterLoadText();
851
852 CheckForMissingGlyphs(true, this);
853 }
854
862 std::optional<std::string> GetTextfile(TextfileType type, Subdirectory dir, const std::string &filename)
863 {
864 static const char * const prefixes[] = {
865 "readme",
866 "changelog",
867 "license",
868 };
869 static_assert(lengthof(prefixes) == TFT_CONTENT_END);
870
871 /* Only the generic text file types allowed for this function */
872 if (type >= TFT_CONTENT_END) return std::nullopt;
873
874 std::string_view prefix = prefixes[type];
875
876 if (filename.empty()) return std::nullopt;
877
878 auto slash = filename.find_last_of(PATHSEPCHAR);
879 if (slash == std::string::npos) return std::nullopt;
880
881 std::string_view base_path(filename.data(), slash + 1);
882
883 static const std::initializer_list<std::string_view> extensions{
884 "txt",
885 "md",
886 #if defined(WITH_ZLIB)
887 "txt.gz",
888 "md.gz",
889 #endif
890 #if defined(WITH_LIBLZMA)
891 "txt.xz",
892 "md.xz",
893 #endif
894 };
895
896 for (auto &extension : extensions) {
897 std::string file_path = fmt::format("{}{}_{}.{}", base_path, prefix, GetCurrentLanguageIsoCode(), extension);
898 if (FioCheckFileExists(file_path, dir)) return file_path;
899
900 file_path = fmt::format("{}{}_{:.2s}.{}", base_path, prefix, GetCurrentLanguageIsoCode(), extension);
901 if (FioCheckFileExists(file_path, dir)) return file_path;
902
903 file_path = fmt::format("{}{}.{}", base_path, prefix, extension);
904 if (FioCheckFileExists(file_path, dir)) return file_path;
905 }
906 return std::nullopt;
907 }
WID_TF_NAVFORWARD
@ WID_TF_NAVFORWARD
Navigate forward button.
Definition: misc_widget.h:53
TextfileWindow::DefaultSize
FontSize DefaultSize() override
Get the default (font) size of the string.
Definition: textfile_gui.cpp:626
TextfileWindow::OnHyperlinkClick
virtual void OnHyperlinkClick(const Hyperlink &link)
Handle the clicking on a hyperlink.
Definition: textfile_gui.cpp:400
SetFill
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
Definition: widget_type.h:1141
TextfileWindow::history
std::vector< HistoryEntry > history
Browsing history in this window.
Definition: textfile_gui.h:75
SVS_ALLOW_NEWLINE
@ SVS_ALLOW_NEWLINE
Allow newlines; replaces '\r ' with ' ' during processing.
Definition: string_type.h:47
GetCurrentLanguageIsoCode
const char * GetCurrentLanguageIsoCode()
Get the ISO language code of the currently loaded language.
Definition: strings.cpp:2157
TextfileWindow::AfterLoadMarkdown
void AfterLoadMarkdown()
Post-processing of markdown files.
Definition: textfile_gui.cpp:508
WID_TF_CAPTION
@ WID_TF_CAPTION
The caption of the window.
Definition: misc_widget.h:51
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition: geometry_type.hpp:30
WidgetDimensions::scaled
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition: window_gui.h:68
HyperlinkType::Internal
@ Internal
Internal link, or "anchor" in HTML language.
Rect::Shrink
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Definition: geometry_type.hpp:98
Xunzip
static void Xunzip(byte **bufp, size_t *sizep)
Do an in-memory xunzip operation.
Definition: textfile_gui.cpp:723
NWID_HSCROLLBAR
@ NWID_HSCROLLBAR
Horizontal scrollbar.
Definition: widget_type.h:85
WID_TF_BACKGROUND
@ WID_TF_BACKGROUND
Panel to draw the textfile on.
Definition: misc_widget.h:57
TextfileWindow::Line::bottom
int bottom
Bottom scroll position in visual lines.
Definition: textfile_gui.h:48
WWT_CAPTION
@ WWT_CAPTION
Window caption (window title between closebox and stickybox)
Definition: widget_type.h:63
Gunzip
static void Gunzip(byte **bufp, size_t *sizep)
Do an in-memory gunzip operation.
Definition: textfile_gui.cpp:667
TextfileWindow::ReflowContent
uint ReflowContent()
Get the total height of the content displayed in this window, if wrapping is disabled.
Definition: textfile_gui.cpp:108
DropDownList
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
Definition: dropdown_type.h:210
HyperlinkType
HyperlinkType
Types of link we support in markdown files.
Definition: textfile_gui.cpp:169
WWT_DEFSIZEBOX
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX)
Definition: widget_type.h:67
NWID_HORIZONTAL
@ NWID_HORIZONTAL
Horizontal container.
Definition: widget_type.h:77
TextfileWindow::OnResize
void OnResize() override
Called after the window got resized.
Definition: textfile_gui.cpp:586
Window::EnableWidget
void EnableWidget(WidgetID widget_index)
Sets a widget to Enabled.
Definition: window_gui.h:400
StrMakeValid
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.
Definition: string.cpp:114
EndContainer
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
Definition: widget_type.h:1151
Scrollbar::SetStepSize
void SetStepSize(size_t stepsize)
Set the distance to scroll when using the buttons or the wheel.
Definition: widget_type.h:748
Scrollbar::SetCapacityFromWidget
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition: widget.cpp:2334
fileio_func.h
SZSP_HORIZONTAL
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
Definition: widget_type.h:468
RectPadding::Vertical
constexpr uint Vertical() const
Get total vertical padding of RectPadding.
Definition: geometry_type.hpp:69
WWT_PUSHARROWBTN
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
Definition: widget_type.h:112
StrEndsWithIgnoreCase
bool StrEndsWithIgnoreCase(std::string_view str, const std::string_view suffix)
Check whether the given string ends with the given suffix, ignoring case.
Definition: string.cpp:340
MakeAnchorSlug
static std::string MakeAnchorSlug(const std::string &line)
Create a valid slug for the anchor.
Definition: textfile_gui.cpp:203
TextfileWindow::Line::top
int top
Top scroll position in visual lines.
Definition: textfile_gui.h:47
TextfileWindow::SetFontNames
void SetFontNames(FontCacheSettings *settings, const char *font_name, const void *os_data) override
Set the right font names.
Definition: textfile_gui.cpp:643
Scrollbar
Scrollbar data structure.
Definition: widget_type.h:678
Window::GetScrollbar
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition: window.cpp:315
TextfileWindow::file_type
TextfileType file_type
Type of textfile to view.
Definition: textfile_gui.h:22
NWidgetPart
Partial widget specification to allow NWidgets to be written nested.
Definition: widget_type.h:1038
textfile_gui.h
HyperlinkType::File
@ File
Link to a local file.
Scrollbar::GetPosition
uint16_t GetPosition() const
Gets the position of the first visible element in the list.
Definition: widget_type.h:720
TextfileWindow::CheckHyperlinkClick
void CheckHyperlinkClick(Point pt)
Check if the user clicked on a hyperlink, and handle it if so.
Definition: textfile_gui.cpp:305
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
Scrollbar::GetCount
uint16_t GetCount() const
Gets the number of elements in the list.
Definition: widget_type.h:702
ReallocT
T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:111
control_codes.h
TextfileWindow::NavigateHistory
void NavigateHistory(int delta)
Navigate through the history, either forward or backward.
Definition: textfile_gui.cpp:378
gfx_func.h
WindowDesc
High level window description.
Definition: window_gui.h:153
WidgetID
int WidgetID
Widget ID.
Definition: window_type.h:18
RectPadding::Horizontal
constexpr uint Horizontal() const
Get total horizontal padding of RectPadding.
Definition: geometry_type.hpp:63
TextfileWindow::NextString
std::optional< std::string_view > NextString() override
Get the next string to search through.
Definition: textfile_gui.cpp:631
TextfileWindow::Hyperlink
Definition: textfile_gui.h:56
WID_TF_VSCROLLBAR
@ WID_TF_VSCROLLBAR
Vertical scrollbar to scroll through the textfile up-and-down.
Definition: misc_widget.h:58
SetResize
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
Definition: widget_type.h:1086
TextfileWindow::history_pos
size_t history_pos
Position in browsing history (for forward movement).
Definition: textfile_gui.h:76
FontCacheSettings
Settings for the four different fonts.
Definition: fontcache.h:216
Window::resize
ResizeInfo resize
Resize information.
Definition: window_gui.h:308
SA_TOP
@ SA_TOP
Top align the text.
Definition: gfx_type.h:343
Rect::Translate
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
Definition: geometry_type.hpp:174
SetScrollbar
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
Definition: widget_type.h:1244
TextfileWindow::AfterLoadText
virtual void AfterLoadText()
Post-processing after the text is loaded.
Definition: textfile_gui.cpp:496
Window::height
int height
Height of the window (number of pixels down in y direction)
Definition: window_gui.h:306
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:379
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:263
Window::SetDirty
void SetDirty() const
Mark entire window as dirty (in need of re-paint)
Definition: window.cpp:941
TextfileWindow::Line
Definition: textfile_gui.h:46
GetTextfile
std::optional< std::string > GetTextfile(TextfileType type, Subdirectory dir, const std::string &filename)
Search a textfile file next to the given content.
Definition: textfile_gui.cpp:862
TextfileWindow::links
std::vector< Hyperlink > links
Clickable links in lines.
Definition: textfile_gui.h:73
Layouter
The layouter performs all the layout work.
Definition: gfx_layout.h:125
TextfileWindow::Hyperlink::destination
std::string destination
Destination for the link.
Definition: textfile_gui.h:60
TextfileWindow::LoadText
void LoadText(std::string_view buf)
Load a text into the textfile viewer.
Definition: textfile_gui.cpp:825
Scrollbar::GetCapacity
uint16_t GetCapacity() const
Gets the number of visible elements of the scrollbar.
Definition: widget_type.h:711
dropdown_type.h
Window::ReInit
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition: window.cpp:953
TextfileWindow::LoadTextfile
virtual void LoadTextfile(const std::string &textfile, Subdirectory dir)
Loads the textfile text from file and setup lines.
Definition: textfile_gui.cpp:765
NWidget
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=-1)
Widget part function for starting a new 'real' widget.
Definition: widget_type.h:1258
safeguards.h
TextfileWindow::SetupScrollbars
void SetupScrollbars(bool force_reflow)
Set scrollbars to the right lengths.
Definition: textfile_gui.cpp:148
GetStringHeight
int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Definition: gfx.cpp:705
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
gfx_layout.h
ClassifyHyperlink
static HyperlinkType ClassifyHyperlink(const std::string &destination, bool trusted)
Classify the type of hyperlink the destination describes.
Definition: textfile_gui.cpp:183
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
_textfile_desc
static WindowDesc _textfile_desc(__FILE__, __LINE__, WDP_CENTER, "textfile", 630, 460, WC_TEXTFILE, WC_NONE, 0, std::begin(_nested_textfile_widgets), std::end(_nested_textfile_widgets))
Window definition for the textfile window.
stdafx.h
Window::InvalidateData
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing)
Definition: window.cpp:3140
WC_NONE
@ WC_NONE
No window, redirects to WC_MAIN_WINDOW.
Definition: window_type.h:45
WID_TF_WRAPTEXT
@ WID_TF_WRAPTEXT
Whether or not to wrap the text.
Definition: misc_widget.h:54
_nested_textfile_widgets
static constexpr NWidgetPart _nested_textfile_widgets[]
Widgets for the textfile window.
Definition: textfile_gui.cpp:41
NWID_VERTICAL
@ NWID_VERTICAL
Vertical container.
Definition: widget_type.h:79
FillDrawPixelInfo
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:1571
WidgetDimensions::unscaled
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition: window_gui.h:67
Window::SetWidgetDisabledState
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition: window_gui.h:381
TextfileWindow::FindHyperlinksInMarkdown
void FindHyperlinksInMarkdown(Line &line, size_t line_index)
Find any hyperlinks in a given line.
Definition: textfile_gui.cpp:243
TextfileWindow::jumplist
std::vector< size_t > jumplist
Table of contents list, line numbers.
Definition: textfile_gui.h:72
WWT_CLOSEBOX
@ WWT_CLOSEBOX
Close box (at top-left of a window)
Definition: widget_type.h:71
WWT_RESIZEBOX
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window)
Definition: widget_type.h:70
string_func.h
Window::IsWidgetLowered
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition: window_gui.h:491
TextfileWindow::hscroll
Scrollbar * hscroll
Horizontal scrollbar.
Definition: textfile_gui.h:24
DrawStringMultiLine
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.
Definition: gfx.cpp:775
TextfileWindow::max_length
uint max_length
Maximum length of unwrapped text line.
Definition: textfile_gui.h:101
TextfileWindow::Reset
void Reset() override
Reset the search, i.e.
Definition: textfile_gui.cpp:621
Window::CreateNestedTree
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition: window.cpp:1724
NWID_VSCROLLBAR
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition: widget_type.h:86
TextfileWindow::search_iterator
uint search_iterator
Iterator for the font check search.
Definition: textfile_gui.h:100
TextfileWindow::UpdateHistoryScrollpos
void UpdateHistoryScrollpos()
Update the scroll position to the current, so we can restore there if we go back.
Definition: textfile_gui.cpp:368
ShowDropDownList
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, bool instant_close)
Show a drop down list.
Definition: dropdown.cpp:349
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:126
TextfileWindow::filepath
std::string filepath
Full path to the filename.
Definition: textfile_gui.h:69
Window::DisableWidget
void DisableWidget(WidgetID widget_index)
Sets a widget to disabled.
Definition: window_gui.h:391
SetPIP
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
Definition: widget_type.h:1220
HyperlinkType::Unknown
@ Unknown
Unknown link.
NO_DIRECTORY
@ NO_DIRECTORY
A path without any base directory.
Definition: fileio_type.h:126
StringControlCode
StringControlCode
List of string control codes used for string formatting, displaying, and by strgen to generate the la...
Definition: control_codes.h:17
WWT_PANEL
@ WWT_PANEL
Simple depressed panel.
Definition: widget_type.h:52
AutoRestoreBackup
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Definition: backup_type.hpp:153
WID_TF_NAVBACK
@ WID_TF_NAVBACK
Navigate back button.
Definition: misc_widget.h:52
TextfileWindow::Monospace
bool Monospace() override
Whether to search for a monospace font or not.
Definition: textfile_gui.cpp:638
TextfileWindow::lines
std::vector< Line > lines
#text, split into lines in a table with lines.
Definition: textfile_gui.h:71
Scrollbar::SetCount
void SetCount(size_t num)
Sets the number of elements in the list.
Definition: widget_type.h:760
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
SetDParamStr
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:352
openttd.h
Window::FinishInitNested
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition: window.cpp:1734
TextfileWindow::AppendHistory
void AppendHistory(const std::string &filepath)
Append the new location to the history, so the user can go back.
Definition: textfile_gui.cpp:355
NWID_SPACER
@ NWID_SPACER
Invisible widget that takes some space.
Definition: widget_type.h:81
SA_LEFT
@ SA_LEFT
Left align the text.
Definition: gfx_type.h:338
WID_TF_JUMPLIST
@ WID_TF_JUMPLIST
List to jump around the file.
Definition: misc_widget.h:55
CheckForMissingGlyphs
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition: strings.cpp:2268
GetCharacterHeight
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition: fontcache.cpp:78
TextfileWindow::link_anchors
std::vector< Hyperlink > link_anchors
Anchor names of headings that can be linked to.
Definition: textfile_gui.h:74
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
SetMinimalSize
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
Definition: widget_type.h:1097
TextfileWindow::Hyperlink::line
size_t line
Which line the link is on.
Definition: textfile_gui.h:57
DrawString
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.
Definition: gfx.cpp:658
FS_MONO
@ FS_MONO
Index of the monospaced font in the font tables.
Definition: gfx_type.h:206
Window::GetRowFromWidget
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:214
TextfileWindow::Line::text
std::string text
Contents of the line.
Definition: textfile_gui.h:49
fontcache.h
WidgetDimensions::frametext
RectPadding frametext
Padding inside frame with text.
Definition: window_gui.h:43
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:202
Utf8Encode
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:479
Window
Data structure for an opened window.
Definition: window_gui.h:267
TextfileType
TextfileType
Additional text files accompanying Tar archives.
Definition: textfile_type.h:14
SVS_REPLACE_TAB_CR_NL_WITH_SPACE
@ SVS_REPLACE_TAB_CR_NL_WITH_SPACE
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
Definition: string_type.h:54
WID_TF_HSCROLLBAR
@ WID_TF_HSCROLLBAR
Horizontal scrollbar to scroll through the textfile left-to-right.
Definition: misc_widget.h:59
TextfileWindow::NavigateToFile
void NavigateToFile(std::string newfile, size_t line)
Navigate to the requested file.
Definition: textfile_gui.cpp:434
TextfileWindow::filename
std::string filename
Filename of the textfile.
Definition: textfile_gui.h:68
SetDataTip
constexpr NWidgetPart SetDataTip(uint32_t data, StringID tip)
Widget part function for setting the data and tooltip.
Definition: widget_type.h:1162
SetMinimalTextLines
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FS_NORMAL)
Widget part function for setting the minimal text lines.
Definition: widget_type.h:1109
NWID_SELECTION
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition: widget_type.h:82
_markdown_link_regex
static const std::regex _markdown_link_regex
Regular expression that searches for Markdown links.
Definition: textfile_gui.cpp:166
TextfileWindow::HistoryEntry
Definition: textfile_gui.h:63
gfx_type.h
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition: geometry_type.hpp:75
Window::ToggleWidgetLoweredState
void ToggleWidgetLoweredState(WidgetID widget_index)
Invert the lowered/raised status of a widget.
Definition: window_gui.h:450
WID_TF_SEL_JUMPLIST
@ WID_TF_SEL_JUMPLIST
Selection to display the jump list or not.
Definition: misc_widget.h:56
AWV_INCREASE
@ AWV_INCREASE
Arrow to the right or in case of RTL to the left.
Definition: widget_type.h:34
WC_TEXTFILE
@ WC_TEXTFILE
textfile; Window numbers:
Definition: window_type.h:187
SVS_REPLACE_WITH_QUESTION_MARK
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
Definition: string_type.h:46
WDP_CENTER
@ WDP_CENTER
Center the window.
Definition: window_gui.h:142
HyperlinkType::Web
@ Web
Link to an external website.
misc_widget.h
GetStringBoundingBox
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition: gfx.cpp:852
WWT_TEXTBTN
@ WWT_TEXTBTN
(Toggle) Button with text
Definition: widget_type.h:57
debug.h
TextfileWindow::vscroll
Scrollbar * vscroll
Vertical scrollbar.
Definition: textfile_gui.h:23
Scrollbar::SetPosition
bool SetPosition(int position)
Sets the position of the first visible element.
Definition: widget_type.h:790
AWV_DECREASE
@ AWV_DECREASE
Arrow to the left or in case of RTL to the right.
Definition: widget_type.h:33
WWT_DROPDOWN
@ WWT_DROPDOWN
Drop down list.
Definition: widget_type.h:72
DrawPixelInfo
Data about how and where to blit pixels.
Definition: gfx_type.h:151
Layouter::GetCharAtPosition
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.
Definition: gfx_layout.cpp:288
backup_type.hpp