38#include "table/strings.h"
44static bool _fios_path_changed;
45static bool _savegame_sort_dirty;
78 this->map_size_x = this->map_size_y = 256;
110 SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
133 SetStringTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
170 SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
193 SetStringTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
195 SetStringTip(STR_SAVELOAD_LOAD_BUTTON, STR_SAVELOAD_LOAD_HEIGHTMAP_TOOLTIP),
237 SetStringTip(STR_SAVELOAD_LOAD_BUTTON, STR_SAVELOAD_LOAD_TOWN_DATA_TOOLTIP),
262 SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
283 NWidget(
WWT_EDITBOX,
Colours::Grey,
WID_SL_SAVE_OSK_TITLE),
SetPadding(2, 2, 2, 2),
SetFill(1, 0),
SetResize(1, 0),
284 SetStringTip(STR_SAVELOAD_OSKTITLE, STR_SAVELOAD_EDITBOX_TOOLTIP),
326 size_t sort_start = 0;
333 for (
const auto &item : file_list) {
334 switch (item.type.detailed) {
342 std::sort(file_list.begin() + sort_start, file_list.end() - sort_end,
FiosItemSorter);
347 static const uint EDITBOX_MAX_SIZE = 50;
363 static void SaveGameConfirmationCallback(
Window *,
bool confirmed)
369 static void SaveHeightmapConfirmationCallback(
Window *,
bool confirmed)
375 static void DeleteFileConfirmationCallback(
Window *window,
bool confirmed)
377 auto *save_load_window =
static_cast<SaveLoadWindow*
>(window);
379 assert(save_load_window->selected !=
nullptr);
382 if (!
FioRemove(save_load_window->selected->name)) {
400 assert(!name.empty());
403 if (name.find_first_of(
"/\\:") != std::string::npos)
return STR_ERROR_DIRECTORY_ILLEGAL_NAME;
405 if (name.front() ==
'.')
return STR_ERROR_DIRECTORY_LEADING_DOT;
419 STR_SAVELOAD_NEW_DIRECTORY_QUERY_CAPTION,
435 const std::string name{StrTrimView(query_text,
" ")};
438 if (name.empty())
return;
478 switch (this->abstract_filetype) {
485 this->filename_editbox.text.
Assign(
"UNNAMED");
517 caption_string = STR_SAVELOAD_LOAD_TOWN_DATA;
544 o_dir.type = FIOS_TYPE_DIRECT;
574 void Close([[maybe_unused]]
int data = 0)
override
594 static std::string path;
595 static std::optional<uint64_t> free_space = std::nullopt;
597 if (_fios_path_changed) {
599 free_space = FiosGetDiskFreeSpace(path);
600 _fios_path_changed =
false;
605 if (free_space.has_value()) {
620 for (
auto it = first; it != last; ++it) {
623 if (item == this->selected) {
625 }
else if (item == this->highlighted) {
635 this->DrawDetails(r);
640 void DrawDetails(
const Rect &r)
const
647 tr.top += HEADER_HEIGHT;
653 if (this->selected ==
nullptr)
return;
657 if (tr.top > tr.bottom)
return;
661 DrawString(tr, STR_SAVELOAD_DETAIL_NOT_AVAILABLE);
670 if (tr.top > tr.bottom)
return;
679 if (tr.top > tr.bottom)
return;
686 if (tr.top > tr.bottom)
return;
698 if (tr.top > tr.bottom)
return;
704 if (tr.top > tr.bottom)
return;
709 if (tr.top > tr.bottom)
return;
713 const CompanyProperties &c = *pair.second;
714 if (c.
name.empty()) {
722 if (tr.top > tr.bottom)
break;
737 size.height =
resize.height * 10 + padding.height;
743 d.height += padding.height;
752 if (_savegame_sort_dirty) {
753 _savegame_sort_dirty =
false;
767 _savegame_sort_dirty =
true;
774 _savegame_sort_dirty =
true;
818 if (it == this->display_list.end())
return;
829 if (click_count == 1) {
830 if (this->selected != file) {
831 this->selected = file;
847 this->selected = file;
868 switch (this->abstract_filetype) {
869 default: NOT_REACHED();
894 if (it == this->display_list.end())
return;
899 if (file != this->highlighted) {
900 this->highlighted = file;
903 }
else if (this->highlighted !=
nullptr) {
904 this->highlighted =
nullptr;
911 if (keycode == WKC_ESC) {
926 this, SaveLoadWindow::DeleteFileConfirmationCallback);
932 this, SaveLoadWindow::SaveGameConfirmationCallback);
940 this, SaveLoadWindow::SaveHeightmapConfirmationCallback);
956 void BuildDisplayList()
959 this->display_list.clear();
960 this->display_list.reserve(this->fios_items.size());
962 if (this->string_filter.
IsEmpty()) {
964 for (
auto &it : this->fios_items) {
965 this->display_list.push_back(&it);
995 this->selected =
nullptr;
997 if (!gui_scope)
break;
999 _fios_path_changed =
true;
1000 this->fios_items.BuildFileList(this->abstract_filetype, this->fop,
true);
1001 this->selected =
nullptr;
1011 if (!gui_scope)
break;
1017 switch (this->abstract_filetype) {
1042 this->BuildDisplayList();
1055 this->selected =
nullptr;
1069 WindowClass::SaveLoad, WindowClass::None,
1077 WindowClass::SaveLoad, WindowClass::None,
1085 WindowClass::SaveLoad, WindowClass::None,
1093 WindowClass::SaveLoad, WindowClass::None,
1111 switch (abstract_filetype) {
std::string GetDecodedString() const
Decode the encoded string.
List of file information.
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
static constexpr TimerGame< struct Calendar >::Date MIN_DATE
Functions related to commands.
void StartupEngines()
Start/initialise all our engines.
Functions related to engines.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Functions related to errors.
void ClearErrorMessages()
Clear all errors from the queue.
@ Error
Errors (eg. saving/loading failed).
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
bool FioRemove(const std::string &filename)
Remove a file.
std::string _personal_dir
custom directory for personal settings, saves, newgrf, etc.
bool FioCheckFileExists(std::string_view filename, Subdirectory subdir)
Check whether the given file exists.
Functions for standard in/out file operations.
SaveLoadOperation
Operation performed on the file.
@ Check
Load file for checking and/or preview.
@ Save
File is being saved.
@ Load
File is being loaded.
@ FiosDrive
A drive (letter) entry.
@ GameFile
Save game or scenario file.
@ FiosDirectory
A directory entry.
@ FiosParent
A parent directory entry.
@ Scenario
Base directory for all scenarios.
@ Heightmap
Subdirectory of scenario for heightmaps.
@ None
A path without any base directory.
@ Save
Base directory for all savegames.
AbstractFileType
The different abstract types of files that the system knows about.
@ Savegame
old or new savegame
@ Scenario
old or new scenario
@ Heightmap
heightmap file
bool FiosItemModificationDateSorter(const FiosItem &a, const FiosItem &b)
Sort files by their modification date, and name when they are equal.
std::string FiosMakeSavegameName(std::string_view name)
Make a save game or scenario filename from a name.
bool FiosItemNameSorter(const FiosItem &a, const FiosItem &b)
Sort files by their name.
std::string FiosGetCurrentPath()
Get the current path/working directory.
std::string FiosMakeHeightmapName(std::string_view name)
Construct a filename for a height map.
DirectoryCreateResult FiosCreateDirectory(std::string_view name)
Create a new subdirectory inside the current FIOS path.
bool FiosBrowseTo(const FiosItem *item)
Browse to a new path based on the passed item, starting at _fios_path.
Declarations for savegames operations.
bool FiosItemSorter(const FiosItem &a, const FiosItem &b)
Sorts the FiosItems based on the savegame sorter and order.
@ PermissionDenied
The OS rejected the operation for permission reasons.
@ Success
Directory was created.
@ OtherError
Any other filesystem error.
@ AlreadyExists
A file or directory with that name already exists.
@ SLIWD_FILTER_CHANGES
The filename filter has changed (via the editbox).
@ SLIWD_SELECTION_CHANGES
File selection has changed (user click, ...).
@ SLIWD_RESCAN_FILES
Rescan all files (when changed directory, ...).
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
static WindowDesc _save_dialog_desc(WindowPosition::Center, "save_game", 500, 294, WindowClass::SaveLoad, WindowClass::None, {}, _nested_save_dialog_widgets)
Save game/scenario.
bool FiosItemSorter(const FiosItem &a, const FiosItem &b)
Sorts the FiosItems based on the savegame sorter and order.
static SavegameSorter _savegame_sorter
Sorter for savegames.
static bool _savegame_sorter_ascending
Sorter for savegames.
void ShowSaveLoadDialog(AbstractFileType abstract_filetype, SaveLoadOperation fop)
Launch save/load dialog in the given mode.
static constexpr std::initializer_list< NWidgetPart > _nested_save_dialog_widgets
Save game/scenario.
static constexpr std::initializer_list< NWidgetPart > _nested_load_heightmap_dialog_widgets
Load heightmap with content download.
static WindowDesc _load_town_data_dialog_desc(WindowPosition::Center, "load_town_data", 257, 320, WindowClass::SaveLoad, WindowClass::None, {}, _nested_load_town_data_dialog_widgets)
Load town data.
static WindowDesc _load_dialog_desc(WindowPosition::Center, "load_game", 500, 294, WindowClass::SaveLoad, WindowClass::None, {}, _nested_load_dialog_widgets)
Load game/scenario.
static constexpr std::initializer_list< NWidgetPart > _nested_load_dialog_widgets
Load game/scenario with optional content download.
static WindowDesc _load_heightmap_dialog_desc(WindowPosition::Center, "load_heightmap", 257, 320, WindowClass::SaveLoad, WindowClass::None, {}, _nested_load_heightmap_dialog_widgets)
Load heightmap.
static constexpr std::initializer_list< NWidgetPart > _nested_load_town_data_dialog_widgets
Load town data.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
SavegameSorter
The available sorters for FiosItems.
static const EnumIndexArray< ExtendedTextColour, DetailedFileType, DetailedFileType::End > _fios_colours
Text colours of DetailedFileType fios entries in the window.
static void SortSaveGameList(FileList &file_list)
Sort the collected list save games prior to displaying it in the save/load gui.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Functions to be called to log fundamental changes to the game.
Declaration shared among gamelog.cpp and saveload/gamelog_sl.cpp.
void LoadTownData()
Load town data from _file_to_saveload, place towns at the appropriate locations, and expand them to t...
Functions related to world/map generation.
void ShowHeightmapLoad()
Start with loading a heightmap.
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
@ Centre
Align to the centre.
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
SwitchMode _switch_mode
The next mainloop command.
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Functions related to the gfx engine.
@ Normal
Index of the normal font in the font tables.
@ LightBrown
Light brown colour.
@ LightBlue
Light blue colour.
@ FromString
Marker for telling to use the colour from the string.
@ DarkGreen
Dark green colour.
static const CursorID SPR_CURSOR_ZZZ
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
GUI functions that shouldn't be here.
Types related to the landscape.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
Miscellaneous command definitions.
void ShowQuery(EncodedString &&caption, EncodedString &&message, Window *parent, QueryCallbackProc *callback, bool focus)
Show a confirmation window with standard 'yes' and 'no' buttons The window is aligned to the centre o...
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
bool _network_available
is network mode available?
bool _networking
are we in networking mode?
Basic functions/variables used all over the place.
Part of the network protocol handling content distribution.
void ShowNetworkContentListWindow(ContentVector *cv=nullptr, ContentType type1=ContentType::End, ContentType type2=ContentType::End)
Show the content list window with a given set of content.
void ShowMissingContentWindow(const GRFConfigList &list)
Show the content list window with all missing grfs from the given list.
void ClearGRFConfigList(GRFConfigList &config)
Clear a GRF Config list, freeing all nodes.
@ NotFound
At least one GRF couldn't be found (higher priority than GRFListCompatibility::Compatible).
@ AllGood
All GRF needed by game are present.
void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfigList &config)
Setup the NewGRF gui.
@ SaveLoad
A game paused for saving/loading.
@ Editor
In the scenario editor.
@ LoadGame
Load game, Play Scenario.
@ LoadScenario
Load scenario from scenario editor.
@ SaveHeightmap
Save heightmap.
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
@ Lightest
Lightest colour shade.
static constexpr PixelColour PC_DARK_BLUE
Dark blue palette colour.
static constexpr PixelColour PC_BLACK
Black palette colour.
static constexpr PixelColour PC_VERY_DARK_BLUE
Almost-black blue palette colour.
Base for the GUIs that have an edit box in them.
A number of safeguards to prevent using unsafe methods.
SaveLoadResult SaveOrLoad(std::string_view filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
std::string GenerateDefaultSaveName()
Get the default name for a savegame or screenshot.
Functions related to saving and loading games.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
ClientSettings _settings_client
The current settings for this game.
This file contains all sprite-related enums and defines.
Definition of base types and functions in a cross-platform compatible way.
Functions related to low-level strings.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Searching and filtering using a stringterm.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
uint32_t name_2
Parameter of name_1.
StringID name_1
Name of the company if the user did not change it.
std::string name
Name of the company if the user changed it.
Dimensions (a width and height) of a rectangle in 2D.
Deals with finding savegames.
DetailedFileType detailed
Detailed file type.
LandscapeType landscape
the landscape we're currently in
GameCreationSettings game_creation
settings used during the creation of a game (map)
Container for loading in mode SL_LOAD_CHECK.
bool checkable
True if the savegame could be checked by SL_LOAD_CHECK. (Old savegames are not checkable....
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
std::string error_msg
Data to pass to string parameters when displaying error.
TimerGameCalendar::Year starting_year
Starting date.
CompanyPropertiesMap companies
Company information.
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Gamelog gamelog
Gamelog actions.
void Clear()
Reset read data.
GRFListCompatibility grf_compatibility
Summary state of NewGrfs, whether missing files or only compatible found.
LandscapeType landscape
Landscape type.
GRFConfigList grfconfig
NewGrf configuration from save.
Data stored about a string that can be modified in the GUI.
static const int ACTION_CLEAR
Clear editbox.
Specification of a rectangle with absolute coordinates of all edges.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect WithHeight(int height, bool end=false) const
Copy Rect and set its height.
Rect WithY(int new_top, int new_bottom) const
Create a new Rect, replacing the top and bottom coordinates.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
static std::optional< StringID > GetDirectoryNameError(const std::string &name)
Check a user-entered name for use as a single directory component.
void OnTimeout() override
Called when this window's timeout has been reached.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
const FiosItem * highlighted
Item in fios_items highlighted by mouse pointer, or nullptr.
QueryString filter_editbox
Filter editbox;.
void GenerateFileName()
Generate a default save filename.
StringFilter string_filter
Filter for available items.
void ShowNewDirectoryQuery(std::string_view initial_name={})
Open the query used to enter a new directory name.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
std::vector< FiosItem * > display_list
Filtered display list.
void OnMouseOver(Point pt, WidgetID widget) override
The mouse is currently moving over the window or has just moved outside of the window.
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnResize() override
Called after the window got resized.
SaveLoadOperation fop
File operation to perform.
FileList fios_items
Item list.
QueryString filename_editbox
Filename editbox.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnPaint() override
The window must be repainted.
void HandleNewDirectoryRequest(const std::string &query_text)
Validate a user-entered directory name and, if valid, create the directory in the current FIOS path.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
AbstractFileType abstract_filetype
Type of file to select.
const FiosItem * selected
Selected item in fios_items, or nullptr.
FiosItem o_dir
Original dir (home dir for this browser).
EventState OnKeyPress(char32_t key, uint16_t keycode) override
A key has been pressed.
static const uint MAX_DIRECTORY_NAME_CHARS
Maximum length of a new directory name in characters.
void OnEditboxChanged(WidgetID wid) override
The text in an editbox has been edited.
bool IsEmpty() const
Check whether any filter words were entered.
void SetFilterTerm(std::string_view str)
Set the term to filter on.
std::string_view GetText() const
Get the current text.
void Assign(std::string_view text)
Copy a string into the textbuffer.
High level window description.
Data structure for an opened window.
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
static int SortButtonWidth()
Get width of up/down arrow of sort button state.
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
std::map< WidgetID, QueryString * > querystrings
QueryString associated to WWT_EDITBOX widgets.
void DrawWidgets() const
Paint all widgets of a window.
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
ResizeInfo resize
Resize information.
void DrawSortButton(WidgetID widget, bool descending) const
Draw a sort button's up or down arrow symbol.
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
bool SetFocusedWidget(WidgetID widget_index)
Set focus within this window to the given widget.
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
void HandleButtonClick(WidgetID widget)
Do all things to make a button look clicked and mark it to be unclicked in a few ticks.
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
@ Scenario
The content consists of a scenario.
@ Heightmap
The content consists of a heightmap.
@ AcceptUnchanged
return success even when the text didn't change
@ LengthIsInChars
the length of the string is counted in characters
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
Definition of the game-calendar-timer.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Window functions not directly related to making/drawing windows.
@ Center
Center the window.
EventState
State of handling an event.
@ Handled
The passed event is handled.
@ NotHandled
The passed event is not handled.