Changeset - r27903:a7a9733e21aa
[Not reviewed]
master
0 13 3
Niels Martin Hansen - 18 months ago 2023-06-18 15:10:08
nielsm@indvikleren.dk
Feature: Help and manuals access window
16 files changed with 841 insertions and 40 deletions:
0 comments (0 inline, 0 general)
CMakeLists.txt
Show inline comments
 
@@ -392,10 +392,12 @@ if(EMSCRIPTEN)
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/debugging_desyncs.md@/docs/debugging_desyncs.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/desync.md@/docs/desync.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/directory_structure.md@/docs/directory_structure.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/eints.md@/docs/eints.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/linkgraph.md@/docs/linkgraph.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/logging_and_performance_metrics.md@/docs/logging_and_performance_metrics.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/multiplayer.md@/docs/multiplayer.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/savegame_format.md@/docs/savegame_format.md")
 
    target_link_libraries(WASM::WASM INTERFACE "--preload-file ${CMAKE_SOURCE_DIR}/docs/symbol_server.md@/docs/symbol_server.md")
 

	
 
    # We use IDBFS for persistent storage.
 
    target_link_libraries(WASM::WASM INTERFACE "-lidbfs.js")
cmake/InstallAndPackage.cmake
Show inline comments
 
@@ -49,11 +49,13 @@ install(FILES
 
                ${CMAKE_SOURCE_DIR}/docs/debugging_desyncs.md
 
                ${CMAKE_SOURCE_DIR}/docs/desync.md
 
                ${CMAKE_SOURCE_DIR}/docs/directory_structure.md
 
                ${CMAKE_SOURCE_DIR}/docs/eints.md
 
                ${CMAKE_SOURCE_DIR}/docs/game_coordinator.md
 
                ${CMAKE_SOURCE_DIR}/docs/linkgraph.md
 
                ${CMAKE_SOURCE_DIR}/docs/logging_and_performance_metrics.md
 
                ${CMAKE_SOURCE_DIR}/docs/multiplayer.md
 
                ${CMAKE_SOURCE_DIR}/docs/savegame_format.md
 
                ${CMAKE_SOURCE_DIR}/docs/symbol_server.md
 
                ${CMAKE_SOURCE_DIR}/docs/obg_format.txt
 
                ${CMAKE_SOURCE_DIR}/docs/obm_format.txt
 
                ${CMAKE_SOURCE_DIR}/docs/obs_format.txt
src/CMakeLists.txt
Show inline comments
 
@@ -201,6 +201,8 @@ add_files(
 
    gui.h
 
    heightmap.cpp
 
    heightmap.h
 
    help_gui.cpp
 
    help_gui.h
 
    highscore.cpp
 
    highscore.h
 
    highscore_gui.cpp
src/help_gui.cpp
Show inline comments
 
new file 100644
 
/*
 
 * This file is part of OpenTTD.
 
 * 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.
 
 * 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.
 
 * 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/>.
 
 */
 

	
 
 /** @file help_gui.cpp GUI to access manuals and related. */
 

	
 
#include "stdafx.h"
 
#include "gui.h"
 
#include "window_gui.h"
 
#include "textfile_gui.h"
 
#include "fileio_func.h"
 
#include "table/control_codes.h"
 
#include "string_func.h"
 
#include "openttd.h"
 

	
 
#include "help_gui.h"
 
#include "widgets/help_widget.h"
 
#include "widgets/misc_widget.h"
 

	
 
#include "safeguards.h"
 

	
 
static const std::string README_FILENAME = "README.md";
 
static const std::string CHANGELOG_FILENAME = "changelog.txt";
 
static const std::string KNOWN_BUGS_FILENAME = "known-bugs.txt";
 
static const std::string LICENSE_FILENAME = "COPYING.md";
 

	
 
static const std::string WEBSITE_LINK = "https://www.openttd.org/";
 
static const std::string WIKI_LINK = "https://wiki.openttd.org/";
 
static const std::string BUGTRACKER_LINK = "https://bugs.openttd.org/";
 
static const std::string COMMUNITY_LINK = "https://community.openttd.org/";
 

	
 
/** Only show the first 20 changelog versions in the textfile viewer. */
 
static constexpr size_t CHANGELOG_VERSIONS_LIMIT = 20;
 

	
 
/**
 
 * Find the path to the game manual file.
 
 *
 
 * @param filename The filename to find.
 
 * @return std::string The path to the filename if found.
 
 */
 
static std::optional<std::string> FindGameManualFilePath(std::string_view filename)
 
{
 
	static const Searchpath searchpaths[] = {
 
		SP_APPLICATION_BUNDLE_DIR, SP_INSTALLATION_DIR, SP_SHARED_DIR, SP_BINARY_DIR, SP_WORKING_DIR
 
	};
 

	
 
	for (Searchpath sp : searchpaths) {
 
		auto file_path = FioGetDirectory(sp, BASE_DIR) + filename.data();
 
		if (FioCheckFileExists(file_path, NO_DIRECTORY)) return file_path;
 
	}
 

	
 
	return {};
 
}
 

	
 
/** Window class displaying the game manual textfile viewer. */
 
struct GameManualTextfileWindow : public TextfileWindow {
 
	GameManualTextfileWindow(std::string_view filename) : TextfileWindow(TFT_GAME_MANUAL)
 
	{
 
		/* Mark the content of these files as trusted. */
 
		this->trusted = true;
 

	
 
		auto filepath = FindGameManualFilePath(filename);
 
		/* The user could, in theory, have moved the file. So just show an empty window if that is the case. */
 
		if (!filepath.has_value()) {
 
			return;
 
		}
 

	
 
		this->filepath = filepath.value();
 
		this->LoadTextfile(this->filepath, NO_DIRECTORY);
 
		this->OnClick({ 0, 0 }, WID_TF_WRAPTEXT, 1);
 
	}
 

	
 
	void SetStringParameters(int widget) const override
 
	{
 
		if (widget == WID_TF_CAPTION) {
 
			SetDParamStr(0, this->filename);
 
		}
 
	}
 

	
 
	void AfterLoadText() override
 
	{
 
		if (this->filename == CHANGELOG_FILENAME) {
 
			this->link_anchors.clear();
 
			this->AfterLoadChangelog();
 
			this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(this->jumplist.empty() ? SZSP_HORIZONTAL : 0);
 
		} else {
 
			this->TextfileWindow::AfterLoadText();
 
		}
 
	}
 

	
 
	/**
 
	 * For changelog files, add a jumplist entry for each version.
 
	 *
 
	 * This is hardcoded and assumes "---" are used to separate versions.
 
	 */
 
	void AfterLoadChangelog()
 
	{
 
		/* Look for lines beginning with ---, they indicate that the previous line was a release name. */
 
		for (size_t line_index = 0; line_index < this->lines.size(); ++line_index) {
 
			const Line &line = this->lines[line_index];
 
			if (line.text.find("---", 0) != 0) continue;
 

	
 
			if (this->jumplist.size() >= CHANGELOG_VERSIONS_LIMIT) {
 
				this->lines.resize(line_index - 2);
 
				break;
 
			}
 

	
 
			/* Mark the version header with a colour, and add it to the jumplist. */
 
			this->lines[line_index - 1].colour = TC_GOLD;
 
			this->lines[line_index].colour = TC_GOLD;
 
			this->jumplist.push_back(line_index - 1);
 
		}
 
	}
 
};
 

	
 
/** Window class displaying the help window. */
 
struct HelpWindow : public Window {
 

	
 
	HelpWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
 
	{
 
		this->InitNested(number);
 

	
 
		this->EnableTextfileButton(README_FILENAME, WID_HW_README);
 
		this->EnableTextfileButton(CHANGELOG_FILENAME, WID_HW_CHANGELOG);
 
		this->EnableTextfileButton(KNOWN_BUGS_FILENAME, WID_HW_KNOWN_BUGS);
 
		this->EnableTextfileButton(LICENSE_FILENAME, WID_HW_LICENSE);
 
	}
 

	
 
	void OnClick(Point pt, int widget, int click_count) override
 
	{
 
		switch (widget) {
 
			case WID_HW_README:
 
				new GameManualTextfileWindow(README_FILENAME);
 
				break;
 
			case WID_HW_CHANGELOG:
 
				new GameManualTextfileWindow(CHANGELOG_FILENAME);
 
				break;
 
			case WID_HW_KNOWN_BUGS:
 
				new GameManualTextfileWindow(KNOWN_BUGS_FILENAME);
 
				break;
 
			case WID_HW_LICENSE:
 
				new GameManualTextfileWindow(LICENSE_FILENAME);
 
				break;
 
			case WID_HW_WEBSITE:
 
				OpenBrowser(WEBSITE_LINK.c_str());
 
				break;
 
			case WID_HW_WIKI:
 
				OpenBrowser(WIKI_LINK.c_str());
 
				break;
 
			case WID_HW_BUGTRACKER:
 
				OpenBrowser(BUGTRACKER_LINK.c_str());
 
				break;
 
			case WID_HW_COMMUNITY:
 
				OpenBrowser(COMMUNITY_LINK.c_str());
 
				break;
 
		}
 
	}
 

	
 
private:
 
	void EnableTextfileButton(std::string_view filename, int button_widget)
 
	{
 
		this->GetWidget<NWidgetLeaf>(button_widget)->SetDisabled(!FindGameManualFilePath(filename).has_value());
 
	}
 
};
 

	
 
static const NWidgetPart _nested_helpwin_widgets[] = {
 
	NWidget(NWID_HORIZONTAL),
 
		NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
 
		NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_HELP_WINDOW_CAPTION, STR_NULL),
 
	EndContainer(),
 

	
 
	NWidget(WWT_PANEL, COLOUR_DARK_GREEN),
 
		NWidget(NWID_SPACER), SetMinimalSize(0, 8),
 

	
 
		NWidget(NWID_HORIZONTAL),
 
			NWidget(NWID_SPACER), SetMinimalSize(10, 0),
 

	
 
			NWidget(NWID_VERTICAL), SetPIP(0, 2, 0),
 
				NWidget(WWT_FRAME, COLOUR_DARK_GREEN), SetDataTip(STR_HELP_WINDOW_WEBSITES, STR_NULL),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_WEBSITE), SetDataTip(STR_HELP_WINDOW_MAIN_WEBSITE, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_WIKI), SetDataTip(STR_HELP_WINDOW_MANUAL_WIKI, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_BUGTRACKER), SetDataTip(STR_HELP_WINDOW_BUGTRACKER, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_COMMUNITY), SetDataTip(STR_HELP_WINDOW_COMMUNITY, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
				EndContainer(),
 
			EndContainer(),
 

	
 
			NWidget(NWID_SPACER), SetMinimalSize(10, 0),
 

	
 
			NWidget(NWID_VERTICAL), SetPIP(0, 2, 0),
 
				NWidget(WWT_FRAME, COLOUR_DARK_GREEN), SetDataTip(STR_HELP_WINDOW_DOCUMENTS, STR_NULL),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_README), SetDataTip(STR_HELP_WINDOW_README, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_CHANGELOG), SetDataTip(STR_HELP_WINDOW_CHANGELOG, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_KNOWN_BUGS),SetDataTip(STR_HELP_WINDOW_KNOWN_BUGS, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
					NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_HW_LICENSE), SetDataTip(STR_HELP_WINDOW_LICENSE, STR_NULL), SetMinimalSize(128, 12), SetFill(1, 0),
 
				EndContainer(),
 
			EndContainer(),
 

	
 
			NWidget(NWID_SPACER), SetMinimalSize(10, 0),
 
		EndContainer(),
 

	
 
		NWidget(NWID_SPACER), SetMinimalSize(0, 8),
 
	EndContainer(),
 
};
 

	
 
static WindowDesc _helpwin_desc(
 
	WDP_CENTER, nullptr, 0, 0,
 
	WC_HELPWIN, WC_NONE,
 
	0,
 
	std::begin(_nested_helpwin_widgets), std::end(_nested_helpwin_widgets)
 
);
 

	
 
void ShowHelpWindow()
 
{
 
	AllocateWindowDescFront<HelpWindow>(&_helpwin_desc, 0);
 
}
src/help_gui.h
Show inline comments
 
new file 100644
 
/*
 
 * This file is part of OpenTTD.
 
 * 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.
 
 * 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.
 
 * 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/>.
 
 */
 

	
 
 /** @file help_gui.h GUI to access manuals and related. */
 

	
 
#ifndef HELP_GUI_H
 
#define HELP_GUI_H
 

	
 
void ShowHelpWindow();
 

	
 
#endif /* HELP_GUI_H */
src/intro_gui.cpp
Show inline comments
 
@@ -13,6 +13,7 @@
 
#include "window_gui.h"
 
#include "window_func.h"
 
#include "textbuf_gui.h"
 
#include "help_gui.h"
 
#include "network/network.h"
 
#include "genworld.h"
 
#include "network/network_gui.h"
 
@@ -360,6 +361,7 @@ struct SelectGameWindow : public Window 
 

	
 
			case WID_SGI_OPTIONS:         ShowGameOptions(); break;
 
			case WID_SGI_HIGHSCORE:       ShowHighscoreTable(); break;
 
			case WID_SGI_HELP:            ShowHelpWindow(); break;
 
			case WID_SGI_SETTINGS_OPTIONS:ShowGameSettings(); break;
 
			case WID_SGI_GRF_SETTINGS:    ShowNewGRFSettings(true, true, false, &_grfconfig_newgame); break;
 
			case WID_SGI_CONTENT_DOWNLOAD:
 
@@ -470,10 +472,12 @@ static const NWidgetPart _nested_select_
 

	
 
	NWidget(NWID_SPACER), SetMinimalSize(0, 6),
 

	
 
	/* 'Highscore Table' button */
 
	NWidget(NWID_HORIZONTAL),
 
		NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_SGI_HIGHSCORE), SetMinimalSize(316, 12),
 
							SetDataTip(STR_INTRO_HIGHSCORE, STR_INTRO_TOOLTIP_HIGHSCORE), SetPadding(0, 10, 0, 10), SetFill(1, 0),
 
	/* 'Help and Manuals' and 'Highscore Table' buttons */
 
	NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
 
		NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_SGI_HELP), SetMinimalSize(158, 12),
 
							SetDataTip(STR_INTRO_HELP, STR_INTRO_TOOLTIP_HELP), SetPadding(0, 0, 0, 10), SetFill(1, 0),
 
		NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_SGI_HIGHSCORE), SetMinimalSize(158, 12),
 
							SetDataTip(STR_INTRO_HIGHSCORE, STR_INTRO_TOOLTIP_HIGHSCORE), SetPadding(0, 10, 0, 0), SetFill(1, 0),
 
	EndContainer(),
 

	
 
	NWidget(NWID_SPACER), SetMinimalSize(0, 6),
src/lang/english.txt
Show inline comments
 
@@ -521,8 +521,9 @@ STR_NEWS_MENU_MESSAGE_HISTORY_MENU      
 
STR_NEWS_MENU_DELETE_ALL_MESSAGES                               :Delete all messages
 

	
 
# About menu
 
###length 10
 
###length 11
 
STR_ABOUT_MENU_LAND_BLOCK_INFO                                  :Land area information
 
STR_ABOUT_MENU_HELP                                             :Help & manuals
 
STR_ABOUT_MENU_SEPARATOR                                        :
 
STR_ABOUT_MENU_TOGGLE_CONSOLE                                   :Toggle console
 
STR_ABOUT_MENU_AI_DEBUG                                         :AI/Game script debug
 
@@ -2124,6 +2125,7 @@ STR_INTRO_MULTIPLAYER                   
 

	
 
STR_INTRO_GAME_OPTIONS                                          :{BLACK}Game Options
 
STR_INTRO_HIGHSCORE                                             :{BLACK}Highscore Table
 
STR_INTRO_HELP                                                  :{BLACK}Help & Manuals
 
STR_INTRO_CONFIG_SETTINGS_TREE                                  :{BLACK}Settings
 
STR_INTRO_NEWGRF_SETTINGS                                       :{BLACK}NewGRF Settings
 
STR_INTRO_ONLINE_CONTENT                                        :{BLACK}Check Online Content
 
@@ -2145,6 +2147,7 @@ STR_INTRO_TOOLTIP_TOYLAND_LANDSCAPE     
 

	
 
STR_INTRO_TOOLTIP_GAME_OPTIONS                                  :{BLACK}Display game options
 
STR_INTRO_TOOLTIP_HIGHSCORE                                     :{BLACK}Display highscore table
 
STR_INTRO_TOOLTIP_HELP                                          :{BLACK}Get access to documentation and online resources
 
STR_INTRO_TOOLTIP_CONFIG_SETTINGS_TREE                          :{BLACK}Display settings
 
STR_INTRO_TOOLTIP_NEWGRF_SETTINGS                               :{BLACK}Display NewGRF settings
 
STR_INTRO_TOOLTIP_ONLINE_CONTENT                                :{BLACK}Check for new and updated content to download
 
@@ -2166,6 +2169,19 @@ STR_ABANDON_GAME_CAPTION                
 
STR_ABANDON_GAME_QUERY                                          :{YELLOW}Are you sure you want to abandon this game?
 
STR_ABANDON_SCENARIO_QUERY                                      :{YELLOW}Are you sure you want to abandon this scenario?
 

	
 
# Help window
 
STR_HELP_WINDOW_CAPTION                                         :{WHITE}Help & Manuals
 
STR_HELP_WINDOW_WEBSITES                                        :{BLACK}Websites
 
STR_HELP_WINDOW_DOCUMENTS                                       :{BLACK}Documents
 
STR_HELP_WINDOW_README                                          :{BLACK}Readme
 
STR_HELP_WINDOW_CHANGELOG                                       :{BLACK}Changelog
 
STR_HELP_WINDOW_KNOWN_BUGS                                      :{BLACK}Known Bugs
 
STR_HELP_WINDOW_LICENSE                                         :{BLACK}License
 
STR_HELP_WINDOW_MAIN_WEBSITE                                    :{BLACK}OpenTTD
 
STR_HELP_WINDOW_MANUAL_WIKI                                     :{BLACK}Manual / Wiki
 
STR_HELP_WINDOW_BUGTRACKER                                      :{BLACK}Report a Bug
 
STR_HELP_WINDOW_COMMUNITY                                       :{BLACK}Community
 

	
 
# Cheat window
 
STR_CHEATS                                                      :{WHITE}Cheats
 
STR_CHEATS_TOOLTIP                                              :{BLACK}Checkboxes indicate if you have used this cheat before
 
@@ -4699,16 +4715,22 @@ STR_AI_SETTINGS_SETTING                 
 

	
 

	
 
# Textfile window
 
STR_TEXTFILE_JUMPLIST                                           :{WHITE}Table of Contents
 
STR_TEXTFILE_JUMPLIST_TOOLTIP                                   :{BLACK}Quickly jump to a section in the displayed file via this list
 
STR_TEXTFILE_JUMPLIST_ITEM                                      :{WHITE}{RAW_STRING}
 
STR_TEXTFILE_NAVBACK_TOOLTIP                                    :{BLACK}Go back in navigation history
 
STR_TEXTFILE_NAVFORWARD_TOOLTIP                                 :{BLACK}Return forward in navigation history
 
STR_TEXTFILE_WRAP_TEXT                                          :{WHITE}Wrap text
 
STR_TEXTFILE_WRAP_TEXT_TOOLTIP                                  :{BLACK}Wrap the text of the window so it all fits without having to scroll
 
STR_TEXTFILE_VIEW_README                                        :{BLACK}View readme
 
STR_TEXTFILE_VIEW_CHANGELOG                                     :{BLACK}Changelog
 
STR_TEXTFILE_VIEW_LICENCE                                       :{BLACK}Licence
 
###length 4
 
###length 5
 
STR_TEXTFILE_README_CAPTION                                     :{WHITE}{STRING} readme of {RAW_STRING}
 
STR_TEXTFILE_CHANGELOG_CAPTION                                  :{WHITE}{STRING} changelog of {RAW_STRING}
 
STR_TEXTFILE_LICENCE_CAPTION                                    :{WHITE}{STRING} licence of {RAW_STRING}
 
STR_TEXTFILE_SURVEY_RESULT_CAPTION                              :{WHITE}Preview of survey result
 
STR_TEXTFILE_GAME_MANUAL_CAPTION                                :{WHITE}OpenTTD document '{RAW_STRING}'
 

	
 

	
 
# Vehicle loading indicators
src/textfile_gui.cpp
Show inline comments
 
@@ -15,10 +15,15 @@
 
#include "gfx_func.h"
 
#include "string_func.h"
 
#include "textfile_gui.h"
 
#include "widgets/dropdown_type.h"
 
#include "gfx_layout.h"
 
#include "debug.h"
 
#include "openttd.h"
 

	
 
#include "widgets/misc_widget.h"
 

	
 
#include "table/strings.h"
 
#include "table/control_codes.h"
 

	
 
#if defined(WITH_ZLIB)
 
#include <zlib.h>
 
@@ -28,16 +33,33 @@
 
#include <lzma.h>
 
#endif
 

	
 
#include <regex>
 

	
 
#include "safeguards.h"
 

	
 
/** Widgets for the textfile window. */
 
static const NWidgetPart _nested_textfile_widgets[] = {
 
	NWidget(NWID_HORIZONTAL),
 
		NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
 
		NWidget(WWT_PUSHARROWBTN, COLOUR_MAUVE, WID_TF_NAVBACK), SetFill(0, 1), SetMinimalSize(15, 1), SetDataTip(AWV_DECREASE, STR_TEXTFILE_NAVBACK_TOOLTIP),
 
		NWidget(WWT_PUSHARROWBTN, COLOUR_MAUVE, WID_TF_NAVFORWARD), SetFill(0, 1), SetMinimalSize(15, 1), SetDataTip(AWV_INCREASE, STR_TEXTFILE_NAVFORWARD_TOOLTIP),
 
		NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_TF_CAPTION), SetDataTip(STR_NULL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
 
		NWidget(WWT_TEXTBTN, COLOUR_MAUVE, WID_TF_WRAPTEXT), SetDataTip(STR_TEXTFILE_WRAP_TEXT, STR_TEXTFILE_WRAP_TEXT_TOOLTIP),
 
		NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
 
	EndContainer(),
 
	NWidget(NWID_SELECTION, INVALID_COLOUR, WID_TF_SEL_JUMPLIST),
 
		NWidget(WWT_PANEL, COLOUR_MAUVE),
 
			NWidget(NWID_HORIZONTAL), SetPIP(WidgetDimensions::unscaled.frametext.left, 0, WidgetDimensions::unscaled.frametext.right),
 
				/* As this widget can be toggled, it needs to be a multiplier of FS_MONO. So add a spacer that ensures this. */
 
				NWidget(NWID_SPACER), SetMinimalSize(1, 0), SetMinimalTextLines(2, 0, FS_MONO),
 
				NWidget(NWID_VERTICAL),
 
					NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
 
					NWidget(WWT_DROPDOWN, COLOUR_MAUVE, WID_TF_JUMPLIST), SetDataTip(STR_TEXTFILE_JUMPLIST, STR_TEXTFILE_JUMPLIST_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
 
					NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
 
				EndContainer(),
 
			EndContainer(),
 
		EndContainer(),
 
	EndContainer(),
 
	NWidget(NWID_HORIZONTAL),
 
		NWidget(WWT_PANEL, COLOUR_MAUVE, WID_TF_BACKGROUND), SetMinimalSize(200, 125), SetResize(1, 12), SetScrollbar(WID_TF_VSCROLLBAR),
 
		EndContainer(),
 
@@ -66,7 +88,10 @@ TextfileWindow::TextfileWindow(TextfileT
 
	this->hscroll = this->GetScrollbar(WID_TF_HSCROLLBAR);
 
	this->FinishInitNested(file_type);
 
	this->GetWidget<NWidgetCore>(WID_TF_CAPTION)->SetDataTip(STR_TEXTFILE_README_CAPTION + file_type, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
 
	this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(SZSP_HORIZONTAL);
 

	
 
	this->DisableWidget(WID_TF_NAVBACK);
 
	this->DisableWidget(WID_TF_NAVFORWARD);
 
	this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
 
}
 

	
 
@@ -130,6 +155,367 @@ void TextfileWindow::SetupScrollbars(boo
 
	this->SetWidgetDisabledState(WID_TF_HSCROLLBAR, IsWidgetLowered(WID_TF_WRAPTEXT));
 
}
 

	
 

	
 
/** Regular expression that searches for Markdown links. */
 
static const std::regex _markdown_link_regex{"\\[(.+?)\\]\\((.+?)\\)", std::regex_constants::ECMAScript | std::regex_constants::optimize};
 

	
 
/** Types of link we support in markdown files. */
 
enum class LinkType {
 
	Internal, ///< Internal link, or "anchor" in HTML language.
 
	Web,      ///< Link to an external website.
 
	File,     ///< Link to a local file.
 
	Unknown,  ///< Unknown link.
 
};
 

	
 
/**
 
 * Classify the type of hyperlink the destination describes.
 
 *
 
 * @param destination The hyperlink destination.
 
 * @param trusted Whether we trust the content of this file.
 
 * @return LinkType The classification of the link.
 
 */
 
static LinkType ClassifyHyperlink(const std::string &destination, bool trusted)
 
{
 
	if (destination.empty()) return LinkType::Unknown;
 
	if (StrStartsWith(destination, "#")) return LinkType::Internal;
 

	
 
	/* Only allow external / internal links for sources we trust. */
 
	if (!trusted) return LinkType::Unknown;
 

	
 
	if (StrStartsWith(destination, "http://")) return LinkType::Web;
 
	if (StrStartsWith(destination, "https://")) return LinkType::Web;
 
	if (StrStartsWith(destination, "./")) return LinkType::File;
 
	return LinkType::Unknown;
 
}
 

	
 
/**
 
 * Create a valid slug for the anchor.
 
 *
 
 * @param line The line to create the slug for.
 
 * @return std::string The slug.
 
 */
 
static std::string MakeAnchorSlug(const std::string &line)
 
{
 
	std::string r = "#";
 
	uint state = 0;
 
	for (char c : line) {
 
		if (state == 0) {
 
			/* State 0: Skip leading hashmarks and spaces. */
 
			if (c == '#') continue;
 
			if (c == ' ') continue;
 
			state = 1;
 
		}
 
		if (state == 2) {
 
			/* State 2: Wait for a non-space/dash character.
 
			 * When found, output a dash and that character. */
 
			if (c == ' ' || c == '-') continue;
 
			r += '-';
 
			state = 1;
 
		}
 
		if (state == 1) {
 
			/* State 1: Normal text.
 
			 * Lowercase alphanumerics,
 
			 * spaces and dashes become dashes,
 
			 * everything else is removed. */
 
			if (isalnum(c)) {
 
				r += tolower(c);
 
			} else if (c == ' ' || c == '-') {
 
				state = 2;
 
			}
 
		}
 
	}
 

	
 
	return r;
 
}
 

	
 
/**
 
 * Find any hyperlinks in a given line.
 
 *
 
 * @param line The line to search for hyperlinks.
 
 * @param line_index The index of the line.
 
 */
 
void TextfileWindow::FindHyperlinksInMarkdown(Line &line, size_t line_index)
 
{
 
	std::string::const_iterator last_match_end = line.text.cbegin();
 
	std::string fixed_line;
 
	char ccbuf[5];
 

	
 
	std::sregex_iterator matcher{ line.text.cbegin(), line.text.cend(), _markdown_link_regex};
 
	while (matcher != std::sregex_iterator()) {
 
		std::smatch match = *matcher;
 

	
 
		Hyperlink link;
 
		link.line = line_index;
 
		link.destination = match[2].str();
 
		this->links.push_back(link);
 

	
 
		LinkType link_type = ClassifyHyperlink(link.destination, this->trusted);
 
		StringControlCode link_colour;
 
		switch (link_type) {
 
			case LinkType::Internal:
 
				link_colour = SCC_GREEN;
 
				break;
 
			case LinkType::Web:
 
				link_colour = SCC_LTBLUE;
 
				break;
 
			case LinkType::File:
 
				link_colour = SCC_LTBROWN;
 
				break;
 
			default:
 
				/* Don't make other link types fancy as they aren't handled (yet). */
 
				link_colour = SCC_CONTROL_END;
 
				break;
 
		}
 

	
 
		if (link_colour != SCC_CONTROL_END) {
 
			/* Format the link to look like a link. */
 
			fixed_line += std::string(last_match_end, match[0].first);
 
			this->links.back().begin = fixed_line.length();
 
			fixed_line += std::string(ccbuf, Utf8Encode(ccbuf, SCC_PUSH_COLOUR));
 
			fixed_line += std::string(ccbuf, Utf8Encode(ccbuf, link_colour));
 
			fixed_line += match[1].str();
 
			this->links.back().end = fixed_line.length();
 
			fixed_line += std::string(ccbuf, Utf8Encode(ccbuf, SCC_POP_COLOUR));
 
			last_match_end = match[0].second;
 
		}
 

	
 
		/* Find next link. */
 
		++matcher;
 
	}
 
	if (last_match_end == line.text.cbegin()) return; // nothing found
 

	
 
	/* Add remaining text on line. */
 
	fixed_line += std::string(last_match_end, line.text.cend());
 

	
 
	/* Overwrite original line text with "fixed" line text. */
 
	line.text = fixed_line;
 
}
 

	
 
/**
 
 * Check if the user clicked on a hyperlink, and handle it if so.
 
 *
 
 * @param pt The loation the user clicked.
 
 */
 
void TextfileWindow::CheckHyperlinkClick(Point pt)
 
{
 
	if (this->links.empty()) return;
 

	
 
	/* Which line was clicked. */
 
	const int clicked_row = this->GetRowFromWidget(pt.y, WID_TF_BACKGROUND, WidgetDimensions::scaled.frametext.top, FONT_HEIGHT_MONO) + this->GetScrollbar(WID_TF_VSCROLLBAR)->GetPosition();
 
	size_t line_index;
 
	size_t subline;
 
	if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
 
		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; });
 
		if (it == this->lines.cend()) return;
 
		line_index = it - this->lines.cbegin();
 
		subline = clicked_row - it->top;
 
		Debug(misc, 4, "TextfileWindow check hyperlink: clicked_row={}, line_index={}, line.top={}, subline={}", clicked_row, line_index, it->top, subline);
 
	} else {
 
		line_index = clicked_row / FONT_HEIGHT_MONO;
 
		subline = 0;
 
	}
 

	
 
	/* Find hyperlinks in this line. */
 
	std::vector<Hyperlink> found_links;
 
	for (const auto &link : this->links) {
 
		if (link.line == line_index) found_links.push_back(link);
 
	}
 
	if (found_links.empty()) return;
 

	
 
	/* Build line layout to figure out character position that was clicked. */
 
	uint window_width = IsWidgetLowered(WID_TF_WRAPTEXT) ? this->GetWidget<NWidgetCore>(WID_TF_BACKGROUND)->current_x - WidgetDimensions::scaled.frametext.Horizontal() : INT_MAX;
 
	Layouter layout(this->lines[line_index].text, window_width, this->lines[line_index].colour, FS_MONO);
 
	assert(subline < layout.size());
 
	ptrdiff_t char_index = layout.GetCharAtPosition(pt.x - WidgetDimensions::scaled.frametext.left, subline);
 
	if (char_index < 0) return;
 
	Debug(misc, 4, "TextfileWindow check hyperlink click: line={}, subline={}, char_index={}", line_index, subline, (int)char_index);
 

	
 
	/* Found character index in line, check if any links are at that position. */
 
	for (const auto &link : found_links) {
 
		Debug(misc, 4, "Checking link from char {} to {}", link.begin, link.end);
 
		if ((size_t)char_index >= link.begin && (size_t)char_index < link.end) {
 
			Debug(misc, 4, "Activating link with destination: {}", link.destination);
 
			this->OnHyperlinkClick(link);
 
			return;
 
		}
 
	}
 
}
 

	
 
/**
 
 * Append the new location to the history, so the user can go back.
 
 *
 
 * @param filepath The location the user is navigating to.
 
 */
 
void TextfileWindow::AppendHistory(const std::string &filepath)
 
{
 
	this->history.erase(this->history.begin() + this->history_pos + 1, this->history.end());
 
	this->UpdateHistoryScrollpos();
 
	this->history.push_back(HistoryEntry{ filepath, 0 });
 
	this->EnableWidget(WID_TF_NAVBACK);
 
	this->DisableWidget(WID_TF_NAVFORWARD);
 
	this->history_pos = this->history.size() - 1;
 
}
 

	
 
/**
 
 * Update the scroll position to the current, so we can restore there if we go back.
 
 */
 
void TextfileWindow::UpdateHistoryScrollpos()
 
{
 
	this->history[this->history_pos].scrollpos = this->GetScrollbar(WID_TF_VSCROLLBAR)->GetPosition();
 
}
 

	
 
/**
 
 * Navigate through the history, either forward or backward.
 
 *
 
 * @param delta The direction to navigate.
 
 */
 
void TextfileWindow::NavigateHistory(int delta)
 
{
 
	if (delta == 0) return;
 
	if (delta < 0 && static_cast<int>(this->history_pos) < -delta) return;
 
	if (delta > 0 && this->history_pos + delta >= this->history.size()) return;
 

	
 
	this->UpdateHistoryScrollpos();
 
	this->history_pos += delta;
 

	
 
	if (this->history[this->history_pos].filepath != this->filepath) {
 
		this->filepath = this->history[this->history_pos].filepath;
 
		this->filename = this->filepath.substr(this->filepath.find_last_of(PATHSEP) + 1);
 
		this->LoadTextfile(this->filepath, NO_DIRECTORY);
 
	}
 

	
 
	this->SetWidgetDisabledState(WID_TF_NAVFORWARD, this->history_pos + 1 >= this->history.size());
 
	this->SetWidgetDisabledState(WID_TF_NAVBACK, this->history_pos == 0);
 
	this->GetScrollbar(WID_TF_VSCROLLBAR)->SetPosition(this->history[this->history_pos].scrollpos);
 
	this->GetScrollbar(WID_TF_HSCROLLBAR)->SetPosition(0);
 
	this->SetDirty();
 
}
 

	
 
/* virtual */ void TextfileWindow::OnHyperlinkClick(const Hyperlink &link)
 
{
 
	switch (ClassifyHyperlink(link.destination, this->trusted)) {
 
		case LinkType::Internal:
 
		{
 
			auto it = std::find_if(this->link_anchors.cbegin(), this->link_anchors.cend(), [&](const Hyperlink &other) { return link.destination == other.destination; });
 
			if (it != this->link_anchors.cend()) {
 
				this->AppendHistory(this->filepath);
 
				this->ScrollToLine(it->line);
 
				this->UpdateHistoryScrollpos();
 
			}
 
			break;
 
		}
 

	
 
		case LinkType::Web:
 
			OpenBrowser(link.destination.c_str());
 
			break;
 

	
 
		case LinkType::File:
 
			this->NavigateToFile(link.destination, 0);
 
			break;
 

	
 
		default:
 
			/* Do nothing */
 
			break;
 
	}
 
}
 

	
 
/**
 
 * Navigate to the requested file.
 
 *
 
 * @param newfile The file to navigate to.
 
 * @param line The line to scroll to.
 
 */
 
void TextfileWindow::NavigateToFile(std::string newfile, size_t line)
 
{
 
	/* Double-check that the file link begins with ./ as a relative path. */
 
	if (!StrStartsWith(newfile, "./")) return;
 

	
 
	/* Get the path portion of the current file path. */
 
	std::string newpath = this->filepath;
 
	size_t pos = newpath.find_last_of(PATHSEPCHAR);
 
	if (pos == std::string::npos) {
 
		newpath.clear();
 
	} else {
 
		newpath.erase(pos + 1);
 
	}
 

	
 
	/* Check and remove for anchor in link. Do this before we find the filename, as people might have a / after the hash. */
 
	size_t anchor_pos = newfile.find_first_of('#');
 
	std::string anchor;
 
	if (anchor_pos != std::string::npos) {
 
		anchor = newfile.substr(anchor_pos);
 
		newfile.erase(anchor_pos);
 
	}
 

	
 
	/* Now the anchor is gone, check if this is a markdown or textfile. */
 
	if (!StrEndsWithIgnoreCase(newfile, ".md") && !StrEndsWithIgnoreCase(newfile, ".txt")) return;
 

	
 
	/* Convert link destination to acceptable local filename (replace forward slashes with correct path separator). */
 
	newfile = newfile.substr(2);
 
	if (PATHSEPCHAR != '/') {
 
		for (char &c : newfile) {
 
			if (c == '/') c = PATHSEPCHAR;
 
		}
 
	}
 

	
 
	/* Paste the two together and check file exists. */
 
	newpath = newpath + newfile;
 
	if (!FioCheckFileExists(newpath, NO_DIRECTORY)) return;
 

	
 
	/* Update history. */
 
	this->AppendHistory(newpath);
 

	
 
	/* Load the new file. */
 
	this->filepath = newpath;
 
	this->filename = newpath.substr(newpath.find_last_of(PATHSEP) + 1);
 

	
 
	this->LoadTextfile(this->filepath, NO_DIRECTORY);
 

	
 
	this->GetScrollbar(WID_TF_HSCROLLBAR)->SetPosition(0);
 
	this->GetScrollbar(WID_TF_VSCROLLBAR)->SetPosition(0);
 

	
 
	if (anchor.empty() || line != 0) {
 
		this->ScrollToLine(line);
 
	} else {
 
		auto anchor_dest = std::find_if(this->link_anchors.cbegin(), this->link_anchors.cend(), [&](const Hyperlink &other) { return anchor == other.destination; });
 
		if (anchor_dest != this->link_anchors.cend()) {
 
			this->ScrollToLine(anchor_dest->line);
 
			this->UpdateHistoryScrollpos();
 
		} else {
 
			this->ScrollToLine(0);
 
		}
 
	}
 
}
 

	
 
/* virtual */ void TextfileWindow::AfterLoadText()
 
{
 
	this->link_anchors.clear();
 

	
 
	if (StrEndsWithIgnoreCase(this->filename, ".md")) this->AfterLoadMarkdown();
 

	
 
	this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(this->jumplist.empty() ? SZSP_HORIZONTAL : 0);
 
}
 

	
 
/**
 
 * Post-processing of markdown files.
 
 */
 
void TextfileWindow::AfterLoadMarkdown()
 
{
 
	for (size_t line_index = 0; line_index < this->lines.size(); ++line_index) {
 
		Line &line = this->lines[line_index];
 

	
 
		/* Find and mark all hyperlinks in the line. */
 
		this->FindHyperlinksInMarkdown(line, line_index);
 

	
 
		/* All lines beginning with # are headings. */
 
		if (!line.text.empty() && line.text[0] == '#') {
 
			this->jumplist.push_back(line_index);
 
			this->lines[line_index].colour = TC_GOLD;
 
			this->link_anchors.emplace_back(Hyperlink{ line_index, 0, 0, MakeAnchorSlug(line.text) });
 
		}
 
	}
 
}
 

	
 
/* virtual */ void TextfileWindow::OnClick(Point pt, int widget, int click_count)
 
{
 
	switch (widget) {
 
@@ -137,6 +523,29 @@ void TextfileWindow::SetupScrollbars(boo
 
			this->ToggleWidgetLoweredState(WID_TF_WRAPTEXT);
 
			this->InvalidateData();
 
			break;
 

	
 
		case WID_TF_JUMPLIST: {
 
			DropDownList list;
 
			for (size_t line : this->jumplist) {
 
				SetDParamStr(0, this->lines[line].text);
 
				DropDownListStringItem *item = new DropDownListStringItem(STR_TEXTFILE_JUMPLIST_ITEM, (int)line, false);
 
				list.emplace_back(item);
 
			}
 
			ShowDropDownList(this, std::move(list), -1, widget);
 
			break;
 
		}
 

	
 
		case WID_TF_NAVBACK:
 
			this->NavigateHistory(-1);
 
			break;
 

	
 
		case WID_TF_NAVFORWARD:
 
			this->NavigateHistory(+1);
 
			break;
 

	
 
		case WID_TF_BACKGROUND:
 
			this->CheckHyperlinkClick(pt);
 
			break;
 
	}
 
}
 

	
 
@@ -162,9 +571,9 @@ void TextfileWindow::SetupScrollbars(boo
 

	
 
		int y_offset = (line.top - pos) * line_height;
 
		if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
 
			DrawStringMultiLine(0, fr.right, y_offset, fr.bottom, line.text, TC_BLACK, SA_TOP | SA_LEFT, false, FS_MONO);
 
			DrawStringMultiLine(0, fr.right, y_offset, fr.bottom, line.text, line.colour, SA_TOP | SA_LEFT, false, FS_MONO);
 
		} else {
 
			DrawString(-this->hscroll->GetPosition(), fr.right, y_offset, line.text, TC_BLACK, SA_TOP | SA_LEFT, false, FS_MONO);
 
			DrawString(-this->hscroll->GetPosition(), fr.right, y_offset, line.text, line.colour, SA_TOP | SA_LEFT, false, FS_MONO);
 
		}
 
	}
 
}
 
@@ -184,6 +593,26 @@ void TextfileWindow::SetupScrollbars(boo
 
	this->SetupScrollbars(true);
 
}
 

	
 
void TextfileWindow::OnDropdownSelect(int widget, int index)
 
{
 
	if (widget != WID_TF_JUMPLIST) return;
 

	
 
	this->ScrollToLine(index);
 
}
 

	
 
void TextfileWindow::ScrollToLine(size_t line)
 
{
 
	Scrollbar *sb = this->GetScrollbar(WID_TF_VSCROLLBAR);
 
	int newpos;
 
	if (this->IsWidgetLowered(WID_TF_WRAPTEXT)) {
 
		newpos = this->lines[line].top;
 
	} else {
 
		newpos = static_cast<int>(line);
 
	}
 
	sb->SetPosition(std::min(newpos, sb->GetCount() - sb->GetCapacity()));
 
	this->SetDirty();
 
}
 

	
 
/* virtual */ void TextfileWindow::Reset()
 
{
 
	this->search_iterator = 0;
 
@@ -330,14 +759,20 @@ static void Xunzip(byte **bufp, size_t *
 
 */
 
/* virtual */ void TextfileWindow::LoadTextfile(const std::string &textfile, Subdirectory dir)
 
{
 
	if (textfile.empty()) return;
 
	this->lines.clear();
 
	this->jumplist.clear();
 

	
 
	this->lines.clear();
 
	this->GetWidget<NWidgetStacked>(WID_TF_SEL_JUMPLIST)->SetDisplayedPlane(SZSP_HORIZONTAL);
 
	this->ReInit();
 

	
 
	if (textfile.empty()) return;
 

	
 
	/* Get text from file */
 
	size_t filesize;
 
	FILE *handle = FioFOpenFile(textfile, "rb", dir, &filesize);
 
	if (handle == nullptr) return;
 
	/* Early return on empty files. */
 
	if (filesize == 0) return;
 

	
 
	char *buf = MallocT<char>(filesize);
 
	size_t read = fread(buf, 1, filesize, handle);
 
@@ -365,7 +800,13 @@ static void Xunzip(byte **bufp, size_t *
 
	/* Check for the byte-order-mark, and skip it if needed. */
 
	if (StrStartsWith(sv_buf, u8"\ufeff")) sv_buf.remove_prefix(3);
 

	
 
	/* Replace any invalid characters with a question-mark. This copies the buf in the process. */
 
	/* Update the filename. */
 
	this->filepath = textfile;
 
	this->filename = this->filepath.substr(this->filepath.find_last_of(PATHSEP) + 1);
 
	/* If it's the first file being loaded, add to history. */
 
	if (this->history.empty()) this->history.push_back(HistoryEntry{ this->filepath, 0 });
 

	
 
	/* Process the loaded text into lines, and do any further parsing needed. */
 
	this->LoadText(sv_buf);
 
	free(buf);
 
}
 
@@ -379,11 +820,11 @@ static void Xunzip(byte **bufp, size_t *
 
 */
 
void TextfileWindow::LoadText(std::string_view buf)
 
{
 
	this->text = StrMakeValid(buf, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE | SVS_REPLACE_TAB_CR_NL_WITH_SPACE);
 
	std::string text = StrMakeValid(buf, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE | SVS_REPLACE_TAB_CR_NL_WITH_SPACE);
 
	this->lines.clear();
 

	
 
	/* Split the string on newlines. */
 
	std::string_view p(this->text);
 
	std::string_view p(text);
 
	int row = 0;
 
	auto next = p.find_first_of('\n');
 
	while (next != std::string_view::npos) {
 
@@ -402,6 +843,8 @@ void TextfileWindow::LoadText(std::strin
 
	}
 
	this->max_length = max_length;
 

	
 
	this->AfterLoadText();
 

	
 
	CheckForMissingGlyphs(true, this);
 
}
 

	
 
@@ -421,6 +864,9 @@ std::optional<std::string> GetTextfile(T
 
	};
 
	static_assert(lengthof(prefixes) == TFT_CONTENT_END);
 

	
 
	/* Only the generic text file types allowed for this function */
 
	if (type >= TFT_CONTENT_END) return std::nullopt;
 

	
 
	std::string_view prefix = prefixes[type];
 

	
 
	if (filename.empty()) return std::nullopt;
 
@@ -432,11 +878,14 @@ std::optional<std::string> GetTextfile(T
 

	
 
	static const std::initializer_list<std::string_view> extensions{
 
		"txt",
 
		"md",
 
#if defined(WITH_ZLIB)
 
		"txt.gz",
 
		"md.gz",
 
#endif
 
#if defined(WITH_LIBLZMA)
 
		"txt.xz",
 
		"md.xz",
 
#endif
 
	};
 

	
src/textfile_gui.h
Show inline comments
 
@@ -22,9 +22,6 @@ struct TextfileWindow : public Window, M
 
	TextfileType file_type;          ///< Type of textfile to view.
 
	Scrollbar *vscroll;              ///< Vertical scrollbar.
 
	Scrollbar *hscroll;              ///< Horizontal scrollbar.
 
	uint search_iterator;            ///< Iterator for the font check search.
 

	
 
	uint max_length;                 ///< Maximum length of unwrapped text line.
 

	
 
	TextfileWindow(TextfileType file_type);
 

	
 
@@ -33,33 +30,81 @@ struct TextfileWindow : public Window, M
 
	void DrawWidget(const Rect &r, int widget) const override;
 
	void OnResize() override;
 
	void OnInvalidateData(int data = 0, bool gui_scope = true) override;
 
	void OnDropdownSelect(int widget, int index) override;
 

	
 
	void Reset() override;
 
	FontSize DefaultSize() override;
 
	std::optional<std::string_view> NextString() override;
 
	bool Monospace() override;
 
	void SetFontNames(FontCacheSettings *settings, const char *font_name, const void *os_data) override;
 
	void ScrollToLine(size_t line);
 

	
 
	virtual void LoadTextfile(const std::string &textfile, Subdirectory dir);
 

	
 
protected:
 
	struct Line {
 
		int top{0};                  ///< Top scroll position in visual lines.
 
		int bottom{0};               ///< Bottom scroll position in visual lines.
 
		std::string text{};          ///< Contents of the line.
 
		TextColour colour{TC_WHITE}; ///< Colour to render text line in.
 

	
 
		Line(int top, std::string_view text) : top(top), bottom(top + 1), text(text) {}
 
		Line() {}
 
	};
 

	
 
	struct Hyperlink {
 
		size_t line;             ///< Which line the link is on.
 
		size_t begin;            ///< Character position on line the link begins.
 
		size_t end;              ///< Character position on line the link end.
 
		std::string destination; ///< Destination for the link.
 
	};
 

	
 
	struct HistoryEntry {
 
		std::string filepath;    ///< File the history entry is in.
 
		int scrollpos;           ///< Scrolling position the file was at at navigation time.
 
	};
 

	
 
	std::string filename{};              ///< Filename of the textfile.
 
	std::string filepath{};              ///< Full path to the filename.
 

	
 
	std::vector<Line> lines;             ///< #text, split into lines in a table with lines.
 
	std::vector<size_t> jumplist;        ///< Table of contents list, line numbers.
 
	std::vector<Hyperlink> links;        ///< Clickable links in lines.
 
	std::vector<Hyperlink> link_anchors; ///< Anchor names of headings that can be linked to.
 
	std::vector<HistoryEntry> history;   ///< Browsing history in this window.
 
	size_t history_pos{0};               ///< Position in browsing history (for forward movement).
 
	bool trusted{false};                 ///< Whether the content is trusted (read: not from content like NewGRFs, etc).
 

	
 
	void LoadText(std::string_view buf);
 
	void FindHyperlinksInMarkdown(Line &line, size_t line_index);
 

	
 
	/**
 
	 * Handle the clicking on a hyperlink.
 
	 *
 
	 * @param link The link that is clicked on.
 
	 */
 
	virtual void OnHyperlinkClick(const Hyperlink &link);
 

	
 
	/**
 
	 * Post-processing after the text is loaded.
 
	 */
 
	virtual void AfterLoadText();
 

	
 
	void NavigateToFile(std::string newfile, size_t line);
 
	void AppendHistory(const std::string &filepath);
 
	void UpdateHistoryScrollpos();
 
	void NavigateHistory(int delta);
 

	
 
private:
 
	struct Line {
 
		int top;               ///< Top scroll position.
 
		int bottom;            ///< Bottom scroll position.
 
		std::string_view text; ///< Pointer to text buffer.
 

	
 
		Line(int top, std::string_view text) : top(top), bottom(top + 1), text(text) {}
 
	};
 

	
 
	std::string text;                ///< Lines of text from the NewGRF's textfile.
 
	std::vector<Line> lines;         ///< #text, split into lines in a table with lines.
 
	uint search_iterator{0};     ///< Iterator for the font check search.
 
	uint max_length{0};          ///< Maximum length of unwrapped text line.
 

	
 
	uint ReflowContent();
 
	uint GetContentHeight();
 
	void SetupScrollbars(bool force_reflow);
 
	void CheckHyperlinkClick(Point pt);
 

	
 
	void AfterLoadMarkdown();
 
};
 

	
 
#endif /* TEXTFILE_GUI_H */
src/textfile_type.h
Show inline comments
 
@@ -21,6 +21,9 @@ enum TextfileType {
 
	TFT_CONTENT_END, // This marker is used to generate the above three buttons in sequence by various of places in the code.
 

	
 
	TFT_SURVEY_RESULT = TFT_CONTENT_END, ///< Survey result (preview)
 
	TFT_GAME_MANUAL,                ///< Game manual/documentation file
 

	
 
	TFT_END,
 
};
 
DECLARE_POSTFIX_INCREMENT(TextfileType)
 

	
src/toolbar_gui.cpp
Show inline comments
 
@@ -55,6 +55,7 @@
 
#include "timer/timer.h"
 
#include "timer/timer_window.h"
 
#include "timer/timer_game_calendar.h"
 
#include "help_gui.h"
 

	
 
#include "widgets/toolbar_widget.h"
 

	
 
@@ -1104,7 +1105,7 @@ static CallBackFunction PlaceLandBlockIn
 

	
 
static CallBackFunction ToolbarHelpClick(Window *w)
 
{
 
	PopupMainToolbMenu(w, _game_mode == GM_EDITOR ? (int)WID_TE_HELP : (int)WID_TN_HELP, STR_ABOUT_MENU_LAND_BLOCK_INFO, _settings_client.gui.newgrf_developer_tools ? 10 : 7);
 
	PopupMainToolbMenu(w, _game_mode == GM_EDITOR ? (int)WID_TE_HELP : (int)WID_TN_HELP, STR_ABOUT_MENU_LAND_BLOCK_INFO, _settings_client.gui.newgrf_developer_tools ? 11 : 8);
 
	return CBF_NONE;
 
}
 

	
 
@@ -1164,14 +1165,15 @@ static CallBackFunction MenuClickHelp(in
 
{
 
	switch (index) {
 
		case  0: return PlaceLandBlockInfo();
 
		case  2: IConsoleSwitch();                 break;
 
		case  3: ShowScriptDebugWindow();          break;
 
		case  4: ShowScreenshotWindow();           break;
 
		case  5: ShowFramerateWindow();            break;
 
		case  6: ShowAboutWindow();                break;
 
		case  7: ShowSpriteAlignerWindow();        break;
 
		case  8: ToggleBoundingBoxes();            break;
 
		case  9: ToggleDirtyBlocks();              break;
 
		case  1: ShowHelpWindow();                 break;
 
		case  3: IConsoleSwitch();                 break;
 
		case  4: ShowScriptDebugWindow();          break;
 
		case  5: ShowScreenshotWindow();           break;
 
		case  6: ShowFramerateWindow();            break;
 
		case  7: ShowAboutWindow();                break;
 
		case  8: ShowSpriteAlignerWindow();        break;
 
		case  9: ToggleBoundingBoxes();            break;
 
		case 10: ToggleDirtyBlocks();              break;
 
	}
 
	return CBF_NONE;
 
}
src/widgets/CMakeLists.txt
Show inline comments
 
@@ -24,6 +24,7 @@ add_files(
 
    goal_widget.h
 
    graph_widget.h
 
    group_widget.h
 
    help_widget.h
 
    highscore_widget.h
 
    industry_widget.h
 
    intro_widget.h
src/widgets/help_widget.h
Show inline comments
 
new file 100644
 
/*
 
 * This file is part of OpenTTD.
 
 * 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.
 
 * 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.
 
 * 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/>.
 
 */
 

	
 
 /** @file help_widget.h Types related to the help window widgets. */
 

	
 
#ifndef WIDGETS_HELP_WIDGET_H
 
#define WIDGETS_HELP_WIDGET_H
 

	
 
/** Widgets of the #HelpWindow class. */
 
enum HelpWindowWidgets {
 
	WID_HW_README,
 
	WID_HW_CHANGELOG,
 
	WID_HW_KNOWN_BUGS,
 
	WID_HW_LICENSE,
 
	WID_HW_WEBSITE,
 
	WID_HW_WIKI,
 
	WID_HW_BUGTRACKER,
 
	WID_HW_COMMUNITY,
 
};
 

	
 
#endif /* WIDGETS_HELP_WIDGET_H */
src/widgets/intro_widget.h
Show inline comments
 
@@ -28,6 +28,7 @@ enum SelectGameIntroWidgets {
 
	WID_SGI_TRANSLATION,           ///< Translation errors.
 
	WID_SGI_OPTIONS,               ///< Options button.
 
	WID_SGI_HIGHSCORE,             ///< Highscore button.
 
	WID_SGI_HELP,                  ///< Help and manuals button.
 
	WID_SGI_SETTINGS_OPTIONS,      ///< Settings button.
 
	WID_SGI_GRF_SETTINGS,          ///< NewGRF button.
 
	WID_SGI_CONTENT_DOWNLOAD,      ///< Content Download button.
src/widgets/misc_widget.h
Show inline comments
 
@@ -48,11 +48,15 @@ enum QueryWidgets {
 

	
 
/** Widgets of the #TextfileWindow class. */
 
enum TextfileWidgets {
 
	WID_TF_CAPTION,    ///< The caption of the window.
 
	WID_TF_WRAPTEXT,   ///< Whether or not to wrap the text.
 
	WID_TF_BACKGROUND, ///< Panel to draw the textfile on.
 
	WID_TF_VSCROLLBAR, ///< Vertical scrollbar to scroll through the textfile up-and-down.
 
	WID_TF_HSCROLLBAR, ///< Horizontal scrollbar to scroll through the textfile left-to-right.
 
	WID_TF_CAPTION,      ///< The caption of the window.
 
	WID_TF_NAVBACK,      ///< Navigate back button.
 
	WID_TF_NAVFORWARD,   ///< Navigate forward button.
 
	WID_TF_WRAPTEXT,     ///< Whether or not to wrap the text.
 
	WID_TF_JUMPLIST,     ///< List to jump around the file.
 
	WID_TF_SEL_JUMPLIST, ///< Selection to display the jump list or not.
 
	WID_TF_BACKGROUND,   ///< Panel to draw the textfile on.
 
	WID_TF_VSCROLLBAR,   ///< Vertical scrollbar to scroll through the textfile up-and-down.
 
	WID_TF_HSCROLLBAR,   ///< Horizontal scrollbar to scroll through the textfile left-to-right.
 
};
 

	
 
#endif /* WIDGETS_MISC_WIDGET_H */
src/window_type.h
Show inline comments
 
@@ -703,6 +703,12 @@ enum WindowClass {
 
	 */
 
	WC_SCREENSHOT,
 

	
 
	/*
 
	 * Help and manuals window; %Window numbers:
 
	 *   - 0 = #HelpWindowWidgets
 
	 */
 
	WC_HELPWIN,
 

	
 
	WC_INVALID = 0xFFFF, ///< Invalid window.
 
};
 

	
0 comments (0 inline, 0 general)