The Battle for Wesnoth  1.15.9+dev
game_load.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2008 - 2018 by Jörg Hinrichs <joerg.hinrichs@alice-dsl.de>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #define GETTEXT_DOMAIN "wesnoth-lib"
16 
18 
19 #include "desktop/open.hpp"
20 #include "filesystem.hpp"
21 #include "font/pango/escape.hpp"
22 #include "formatter.hpp"
23 #include "formula/string_utils.hpp"
24 #include "game_classification.hpp"
25 #include "game_config.hpp"
26 #include "gettext.hpp"
27 #include "gui/auxiliary/field.hpp"
28 #include "gui/core/log.hpp"
30 #include "gui/widgets/button.hpp"
31 #include "gui/widgets/image.hpp"
32 #include "gui/widgets/label.hpp"
33 #include "gui/widgets/listbox.hpp"
34 #include "gui/widgets/minimap.hpp"
36 #include "gui/widgets/settings.hpp"
37 #include "gui/widgets/text_box.hpp"
39 #include "gui/widgets/window.hpp"
40 #include "language.hpp"
41 #include "picture.hpp"
42 #include "preferences/game.hpp"
44 #include "utils/general.hpp"
45 #include <functional>
46 #include "game_config_view.hpp"
47 
48 #include <cctype>
49 
50 static lg::log_domain log_gameloaddlg{"gui/dialogs/game_load_dialog"};
51 #define ERR_GAMELOADDLG LOG_STREAM(err, log_gameloaddlg)
52 #define WRN_GAMELOADDLG LOG_STREAM(warn, log_gameloaddlg)
53 #define LOG_GAMELOADDLG LOG_STREAM(info, log_gameloaddlg)
54 #define DBG_GAMELOADDLG LOG_STREAM(debug, log_gameloaddlg)
55 
56 namespace gui2
57 {
58 namespace dialogs
59 {
60 
61 REGISTER_DIALOG(game_load)
62 
63 game_load::game_load(const game_config_view& cache_config, savegame::load_game_metadata& data)
64  : filename_(data.filename)
65  , save_index_manager_(data.manager)
66  , change_difficulty_(register_bool("change_difficulty", true, data.select_difficulty))
67  , show_replay_(register_bool("show_replay", true, data.show_replay))
68  , cancel_orders_(register_bool("cancel_orders", true, data.cancel_orders))
69  , summary_(data.summary)
70  , games_()
71  , cache_config_(cache_config)
72  , last_words_()
73 {
74 }
75 
77 {
78  // Allow deleting saves with the Delete key.
79  connect_signal_pre_key_press(window, std::bind(&game_load::key_press_callback, this, std::placeholders::_5));
80 
81  text_box* filter = find_widget<text_box>(&window, "txtFilter", false, true);
82 
83  filter->set_text_changed_callback(std::bind(&game_load::filter_text_changed, this, std::placeholders::_2));
84 
85  listbox& list = find_widget<listbox>(&window, "savegame_list", false);
86 
88 
89  window.keyboard_capture(filter);
90  window.add_to_keyboard_chain(&list);
91 
92  list.register_sorting_option(0, [this](const int i) { return games_[i].name(); });
93  list.register_sorting_option(1, [this](const int i) { return games_[i].modified(); });
94 
96 
97  connect_signal_mouse_left_click(find_widget<button>(&window, "delete", false),
98  std::bind(&game_load::delete_button_callback, this));
99 
100  connect_signal_mouse_left_click(find_widget<button>(&window, "browse_saves_folder", false),
101  std::bind(&game_load::browse_button_callback, this));
102 
103  menu_button& dir_list = find_widget<menu_button>(&window, "dirList", false);
104 
105  dir_list.set_use_markup(true);
106  set_save_dir_list(dir_list);
107 
109 
111 }
112 
114 {
115  const auto other_dirs = filesystem::find_other_version_saves_dirs();
116  if(other_dirs.empty()) {
118  return;
119  }
120 
121  std::vector<config> options;
122 
123  // The first option in the list is the current version's save dir
124  options.emplace_back("label", _("game_version^Current Version"), "path", "");
125 
126  for(const auto& known_dir : other_dirs) {
127  if(!known_dir.path.empty()) {
128  options.emplace_back(
129  "label", VGETTEXT("game_version^Wesnoth $version", utils::string_map{{"version", known_dir.version}}),
130  "path", known_dir.path
131  );
132  }
133  }
134 
135  dir_list.set_values(options);
136 }
137 
139 {
140  listbox& list = find_widget<listbox>(get_window(), "savegame_list", false);
141 
142  list.clear();
143 
144  games_ = save_index_manager_->get_saves_list();
145 
146  for(const auto& game : games_) {
147  std::map<std::string, string_map> data;
149 
150  std::string name = game.name();
151  utils::ellipsis_truncate(name, 40);
152  item["label"] = name;
153  data.emplace("filename", item);
154 
155  item["label"] = game.format_time_summary();
156  data.emplace("date", item);
157 
158  list.add_row(data);
159  }
160 
161  find_widget<button>(get_window(), "delete", false).set_active(!save_index_manager_->read_only());
162 }
163 
165 {
166  const int selected_row =
167  find_widget<listbox>(get_window(), "savegame_list", false).get_selected_row();
168 
169  if(selected_row == -1) {
170  return;
171  }
172 
173  savegame::save_info& game = games_[selected_row];
174  filename_ = game.name();
175  summary_ = game.summary();
176 
177  find_widget<minimap>(get_window(), "minimap", false)
178  .set_map_data(summary_["map_data"]);
179 
180  find_widget<label>(get_window(), "lblScenario", false)
181  .set_label(summary_["label"]);
182 
183  listbox& leader_list = find_widget<listbox>(get_window(), "leader_list", false);
184 
185  leader_list.clear();
186 
187  const std::string sprite_scale_mod = (formatter() << "~SCALE_INTO(" << game_config::tile_size << ',' << game_config::tile_size << ')').str();
188 
189  for(const auto& leader : summary_.child_range("leader")) {
190  std::map<std::string, string_map> data;
192 
193  // First, we evaluate whether the leader image as provided exists.
194  // If not, we try getting a binary path-independent path. If that still doesn't
195  // work, we fallback on unknown-unit.png.
196  std::string leader_image = leader["leader_image"].str();
197  if(!::image::exists(leader_image)) {
198  leader_image = filesystem::get_independent_image_path(leader_image);
199 
200  // The leader TC modifier isn't appending if the independent image path can't
201  // be resolved during save_index entry creation, so we need to add it here.
202  if(!leader_image.empty()) {
203  leader_image += leader["leader_image_tc_modifier"].str();
204  }
205  }
206 
207  if(leader_image.empty()) {
208  leader_image = "units/unknown-unit.png" + leader["leader_image_tc_modifier"].str();
209  } else {
210  // Scale down any sprites larger than 72x72
211  leader_image += sprite_scale_mod;
212  }
213 
214  item["label"] = leader_image;
215  data.emplace("imgLeader", item);
216 
217  item["label"] = leader["leader_name"];
218  data.emplace("leader_name", item);
219 
220  item["label"] = leader["gold"];
221  data.emplace("leader_gold", item);
222 
223  item["label"] = leader["units"];
224  data.emplace("leader_troops", item);
225 
226  item["label"] = leader["recall_units"];
227  data.emplace("leader_reserves", item);
228 
229  leader_list.add_row(data);
230  }
231 
232  std::stringstream str;
233  str << game.format_time_local() << "\n";
235 
236  // The new label value may have more or less lines than the previous value, so invalidate the layout.
237  find_widget<scroll_label>(get_window(), "slblSummary", false).set_label(str.str());
239 
240  toggle_button& replay_toggle = dynamic_cast<toggle_button&>(*show_replay_->get_widget());
241  toggle_button& cancel_orders_toggle = dynamic_cast<toggle_button&>(*cancel_orders_->get_widget());
242  toggle_button& change_difficulty_toggle = dynamic_cast<toggle_button&>(*change_difficulty_->get_widget());
243 
244  const bool is_replay = savegame::loadgame::is_replay_save(summary_);
245  const bool is_scenario_start = summary_["turn"].empty();
246 
247  // Always toggle show_replay on if the save is a replay
248  replay_toggle.set_value(is_replay);
249  replay_toggle.set_active(!is_replay && !is_scenario_start);
250 
251  // Cancel orders doesn't make sense on replay saves or start-of-scenario saves
252  cancel_orders_toggle.set_active(!is_replay && !is_scenario_start);
253 
254  // Changing difficulty doesn't make sense on non-start-of-scenario saves
255  change_difficulty_toggle.set_active(!is_replay && is_scenario_start);
256 }
257 
258 // This is a wrapper that prevents a corrupted save file (if it happens to be
259 // the first in the list) from making the dialog fail to open.
261 {
262  try {
264  } catch(const config::error& e) {
265  // Clear the UI widgets, show an error message.
266  const std::string preamble = _("The selected file is corrupt: ");
267  const std::string message = e.message.empty() ? "(no details)" : e.message;
268  ERR_GAMELOADDLG << preamble << message << "\n";
269  find_widget<minimap>(get_window(), "minimap", false).set_map_data("");
270  find_widget<label>(get_window(), "lblScenario", false)
271  .set_label(preamble);
272  find_widget<scroll_label>(get_window(), "slblSummary", false)
273  .set_label(message);
274 
275  listbox& leader_list = find_widget<listbox>(get_window(), "leader_list", false);
276  leader_list.clear();
277 
278  toggle_button& replay_toggle = dynamic_cast<toggle_button&>(*show_replay_->get_widget());
279  toggle_button& cancel_orders_toggle = dynamic_cast<toggle_button&>(*cancel_orders_->get_widget());
280  toggle_button& change_difficulty_toggle = dynamic_cast<toggle_button&>(*change_difficulty_->get_widget());
281 
282  replay_toggle.set_active(false);
283  cancel_orders_toggle.set_active(false);
284  change_difficulty_toggle.set_active(false);
285  }
286 }
287 
288 void game_load::filter_text_changed(const std::string& text)
289 {
290  listbox& list = find_widget<listbox>(get_window(), "savegame_list", false);
291 
292  const std::vector<std::string> words = utils::split(text, ' ');
293 
294  if(words == last_words_)
295  return;
296  last_words_ = words;
297 
298  boost::dynamic_bitset<> show_items;
299  show_items.resize(list.get_item_count(), true);
300 
301  if(!text.empty()) {
302  for(unsigned int i = 0; i < list.get_item_count() && i < games_.size(); i++) {
303  bool found = false;
304  for(const auto & word : words)
305  {
306  found = std::search(games_[i].name().begin(),
307  games_[i].name().end(),
308  word.begin(),
309  word.end(),
311  != games_[i].name().end();
312 
313  if(!found) {
314  // one word doesn't match, we don't reach words.end()
315  break;
316  }
317  }
318 
319  show_items[i] = found;
320  }
321  }
322 
323  list.set_row_shown(show_items);
324 
325  const bool any_shown = list.any_rows_shown();
326 
327  // Disable Load button if no games are available
328  find_widget<button>(get_window(), "ok", false).set_active(any_shown);
329 
330  // Disable 'Enter' loading if no games are available
331  get_window()->set_enter_disabled(!any_shown);
332 }
333 
334 void game_load::evaluate_summary_string(std::stringstream& str, const config& cfg_summary)
335 {
336  std::string difficulty_human_str = string_table[cfg_summary["difficulty"]];
337  if(cfg_summary["corrupt"].to_bool()) {
338  str << "\n<span color='#f00'>" << _("(Invalid)") << "</span>";
339 
340  return;
341  }
342 
343  const std::string& campaign_type = cfg_summary["campaign_type"];
344 
345  try {
346  switch(game_classification::CAMPAIGN_TYPE::string_to_enum(campaign_type).v) {
348  const std::string campaign_id = cfg_summary["campaign"];
349 
350  const config* campaign = nullptr;
351  if(!campaign_id.empty()) {
352  if(const config& c = cache_config_.find_child("campaign", "id", campaign_id)) {
353  campaign = &c;
354  }
355  }
356 
357  if (campaign != nullptr) {
358  try {
359  const config &difficulty = campaign->find_child("difficulty", "define", cfg_summary["difficulty"]);
360  std::ostringstream ss;
361  ss << difficulty["label"] << " (" << difficulty["description"] << ")";
362  difficulty_human_str = ss.str();
363  } catch(const config::error&) {
364  }
365  }
366 
367  utils::string_map symbols;
368  if(campaign != nullptr) {
369  symbols["campaign_name"] = (*campaign)["name"];
370  } else {
371  // Fallback to nontranslatable campaign id.
372  symbols["campaign_name"] = "(" + campaign_id + ")";
373  }
374 
375  str << VGETTEXT("Campaign: $campaign_name", symbols);
376 
377  // Display internal id for debug purposes if we didn't above
378  if(game_config::debug && (campaign != nullptr)) {
379  str << '\n' << "(" << campaign_id << ")";
380  }
381  break;
382  }
383  case game_classification::CAMPAIGN_TYPE::MULTIPLAYER:
384  str << _("Multiplayer");
385  break;
386  case game_classification::CAMPAIGN_TYPE::TUTORIAL:
387  str << _("Tutorial");
388  break;
389  case game_classification::CAMPAIGN_TYPE::TEST:
390  str << _("Test scenario");
391  break;
392  }
393  } catch(const bad_enum_cast&) {
394  str << campaign_type;
395  }
396 
397  str << "\n";
398 
399  if(savegame::loadgame::is_replay_save(cfg_summary)) {
400  str << _("Replay");
401  } else if(!cfg_summary["turn"].empty()) {
402  str << _("Turn") << " " << cfg_summary["turn"];
403  } else {
404  str << _("Scenario start");
405  }
406 
407  str << "\n" << _("Difficulty: ")
408  << difficulty_human_str;
409 
410  if(!cfg_summary["version"].empty()) {
411  str << "\n" << _("Version: ") << cfg_summary["version"];
412  }
413 
414  const std::vector<std::string>& active_mods = utils::split(cfg_summary["active_mods"]);
415  if(!active_mods.empty()) {
416  str << "\n" << _("Modifications: ");
417  for(const auto& mod_id : active_mods) {
418  std::string mod_name;
419  try {
420  mod_name = cache_config_.find_child("modification", "id", mod_id)["name"].str();
421  } catch(const config::error&) {
422  // Fallback to nontranslatable mod id.
423  mod_name = "(" + mod_id + ")";
424  }
425 
426  str << "\n" << font::unicode_bullet << " " << mod_name;
427  }
428  }
429 }
431 {
433 }
434 
436 {
437  listbox& list = find_widget<listbox>(get_window(), "savegame_list", false);
438 
439  const std::size_t index = std::size_t(list.get_selected_row());
440  if(index < games_.size()) {
441 
442  // See if we should ask the user for deletion confirmation
444  if(!gui2::dialogs::game_delete::execute()) {
445  return;
446  }
447  }
448 
449  // Delete the file
450  save_index_manager_->delete_game(games_[index].name());
451 
452  // Remove it from the list of saves
453  games_.erase(games_.begin() + index);
454 
455  list.remove_row(index);
456 
457  // Close the dialog if there are no more saves
458  if(list.get_item_count() == 0) {
460  }
461 
463  }
464 }
465 
466 void game_load::key_press_callback(const SDL_Keycode key)
467 {
468  //
469  // Don't delete games when we're typing in the textbox!
470  //
471  // I'm not sure if this check was necessary when I first added this feature
472  // (I didn't check at the time), but regardless, it's needed now. If it turns
473  // out I screwed something up in my refactoring, I'll remove this.
474  //
475  // - vultraz, 2017-08-28
476  //
477  if(find_widget<text_box>(get_window(), "txtFilter", false).get_state() == text_box_base::FOCUSED) {
478  return;
479  }
480 
481  if(key == SDLK_DELETE) {
483  }
484 }
485 
487 {
488  menu_button& dir_list = find_widget<menu_button>(get_window(), "dirList", false);
489 
490  const auto& path = dir_list.get_value_config()["path"].str();
491  if(path.empty()) {
493  } else {
494  save_index_manager_ = std::make_shared<savegame::save_index_class>(path);
495  }
496 
499 }
500 
501 } // namespace dialogs
502 } // namespace gui2
Define the common log macros for the gui toolkit.
Dialog was closed with the CANCEL button.
Definition: retval.hpp:37
void set_text_changed_callback(std::function< void(text_box_base *textbox, const std::string text)> cb)
Set the text_changed callback.
const ::config & get_value_config() const
Returns the entire config object for the selected row.
virtual void set_value(unsigned selected, bool fire_event=false) override
Inherited from selectable_item.
std::map< std::string, t_string > string_map
A menu_button is a styled_widget to choose an element from a list of elements.
Definition: menu_button.hpp:64
field_bool * change_difficulty_
Definition: game_load.hpp:84
config & find_child(config_key_type key, const std::string &name, const std::string &value)
Returns the first child of tag key with a name attribute containing value.
Definition: config.cpp:831
Main class to show messages to the user.
Definition: message.hpp:34
This shows the dialog to select and load a savegame file.
Definition: game_load.hpp:48
#define ERR_GAMELOADDLG
Definition: game_load.cpp:51
static std::shared_ptr< save_index_class > default_saves_dir()
Returns an instance for managing saves in filesystem::get_saves_dir()
Definition: save_index.cpp:188
std::shared_ptr< savegame::save_index_class > & save_index_manager_
Definition: game_load.hpp:82
void populate_game_list()
Update (both internally and visually) the list of games.
Definition: game_load.cpp:138
const game_config_view & cache_config_
Definition: game_load.hpp:91
This file contains the window object, this object is a top level container which has the event manage...
child_itors child_range(config_key_type key)
Definition: config.cpp:357
void ellipsis_truncate(std::string &str, const std::size_t size)
Truncates a string to a given utf-8 character count and then appends an ellipsis. ...
void key_press_callback(const SDL_Keycode key)
Definition: game_load.cpp:466
bool chars_equal_insensitive(char a, char b)
Definition: general.hpp:24
void set_save_dir_list(menu_button &dir_list)
Definition: game_load.cpp:113
window * get_window() const
Returns a pointer to the dialog&#39;s window.
int get_selected_row() const
Returns the first selected row.
Definition: listbox.cpp:276
Implements some helper classes to ease adding fields to a dialog and hide the synchronization needed...
static std::string _(const char *str)
Definition: gettext.hpp:92
std::vector< std::string > last_words_
Definition: game_load.hpp:93
const config & summary() const
Definition: save_index.cpp:231
Class for a single line text area.
Definition: text_box.hpp:140
std::string filename_
Definition: action_wml.cpp:562
Generic file dialog.
Definition: field-fwd.hpp:22
bool exists(const image::locator &i_locator)
Returns true if the given image actually exists, without loading it.
Definition: picture.cpp:1010
The listbox class.
Definition: listbox.hpp:42
std::string format_time_local() const
Definition: save_index.cpp:236
const config & options()
Definition: game.cpp:563
Desktop environment interaction functions.
void connect_signal_notify_modified(dispatcher &dispatcher, const signal_notification_function &signal)
Connects a signal handler for getting a notification upon modification.
Definition: dispatcher.cpp:186
This file contains the settings handling of the widget library.
std::ostringstream wrapper.
Definition: formatter.hpp:38
void clear()
Removes all the rows in the listbox, clearing it.
Definition: listbox.cpp:126
void set_visible(const visibility visible)
Definition: widget.cpp:475
void connect_signal_mouse_left_click(dispatcher &dispatcher, const signal_function &signal)
Connects a signal handler for a left mouse button click.
Definition: dispatcher.cpp:171
static bool is_replay_save(const config &cfg)
Definition: savegame.hpp:126
void set_values(const std::vector<::config > &values, unsigned selected=0)
std::string path
Definition: game_config.cpp:38
unsigned get_item_count() const
Returns the number of items in the listbox.
Definition: listbox.cpp:132
std::string get_independent_image_path(const std::string &filename)
Returns an image path to filename for binary path-independent use in saved games. ...
virtual void set_use_markup(bool use_markup)
bool any_rows_shown() const
Definition: listbox.cpp:227
std::vector< savegame::save_info > games_
Definition: game_load.hpp:90
const std::string & name() const
Definition: save_index.hpp:39
Various uncategorised dialogs.
styled_widget * get_widget()
Definition: field.hpp:206
bool open_object(const std::string &path_or_url)
Opens the specified object with the default application configured for its type.
Definition: open.cpp:46
virtual void pre_show(window &window) override
Inherited from modal_dialog.
Definition: game_load.cpp:76
std::size_t i
Definition: function.cpp:933
The user set the widget invisible, that means:
void filter_text_changed(const std::string &text)
Definition: game_load.cpp:288
std::string name
Definition: sdl_ttf.cpp:70
std::map< std::string, t_string > string_map
Definition: widget.hpp:26
grid & add_row(const string_map &item, const int index=-1)
When an item in the list is selected by the user we need to update the state.
Definition: listbox.cpp:67
field_bool * show_replay_
Definition: game_load.hpp:85
Declarations for File-IO.
const bool & debug
std::size_t index(const std::string &str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
Definition: unicode.cpp:71
const std::string unicode_bullet
Definition: constants.cpp:43
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
bool ask_delete_saves()
Definition: game.cpp:784
const config & find_child(config_key_type key, const std::string &name, const std::string &value) const
field_bool * cancel_orders_
Definition: game_load.hpp:86
std::string & filename_
Definition: game_load.hpp:81
Filename and modification date for a file list.
Definition: save_index.hpp:26
void connect_signal_pre_key_press(dispatcher &dispatcher, const signal_keyboard_function &signal)
Connects the signal for &#39;snooping&#39; on the keypress.
Definition: dispatcher.cpp:166
std::vector< std::string > split(const config_attribute_value &val)
unsigned int tile_size
Definition: game_config.cpp:67
symbol_table string_table
Definition: language.cpp:64
void remove_row(const unsigned row, unsigned count=1)
Removes a row in the listbox.
Definition: listbox.cpp:87
std::string message
Definition: exceptions.hpp:31
void invalidate_layout()
Updates the size of the window.
Definition: window.cpp:796
static lg::log_domain log_gameloaddlg
Definition: game_load.cpp:50
#define e
std::vector< other_version_dir > find_other_version_saves_dirs()
Searches for directories containing saves created by other versions of Wesnoth.
Definition: filesystem.cpp:825
void register_sorting_option(const int col, const Func &f)
Definition: listbox.hpp:271
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:59
mock_char c
void set_retval(int retval)
Convenience wrapper to set the window&#39;s exit code.
base class of top level items, the only item which needs to store the final canvases to draw on...
Definition: window.hpp:64
void set_row_shown(const unsigned row, const bool shown)
Makes a row visible or invisible.
Definition: listbox.cpp:144
void evaluate_summary_string(std::stringstream &str, const config &cfg_summary)
Definition: game_load.cpp:334
bool empty() const
Definition: config.cpp:879
Class for a toggle button.
std::pair< std::string, unsigned > item
Definition: help_impl.hpp:407
virtual void set_active(const bool active) override
See styled_widget::set_active.
void set_enter_disabled(const bool enter_disabled)
Disable the enter key.
Definition: window.hpp:285