The Battle for Wesnoth  1.15.0-dev
game_config_manager.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2013 - 2018 by Andrius Silinskas <silinskas.andrius@gmail.com>
3  Part of the Battle for Wesnoth Project http://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 #include "game_config_manager.hpp"
15 
16 #include "about.hpp"
17 #include "addon/manager.hpp"
18 #include "ai/configuration.hpp"
19 #include "cursor.hpp"
20 #include "events.hpp"
21 #include "game_config.hpp"
22 #include "gettext.hpp"
23 #include "game_classification.hpp"
26 #include "hotkey/hotkey_item.hpp"
28 #include "language.hpp"
29 #include "log.hpp"
30 #include "preferences/general.hpp"
32 #include "terrain/builder.hpp"
33 #include "terrain/type_data.hpp"
34 #include "units/types.hpp"
35 #include "version.hpp"
36 #include "theme.hpp"
37 #include "image.hpp"
38 
39 static lg::log_domain log_config("config");
40 #define ERR_CONFIG LOG_STREAM(err, log_config)
41 #define WRN_CONFIG LOG_STREAM(warn, log_config)
42 #define LOG_CONFIG LOG_STREAM(info, log_config)
43 
45 
47  const commandline_options& cmdline_opts,
48  const bool jump_to_editor) :
49  cmdline_opts_(cmdline_opts),
50  jump_to_editor_(jump_to_editor),
51  game_config_(),
52  old_defines_map_(),
53  paths_manager_(),
54  cache_(game_config::config_cache::instance())
55 {
56  assert(!singleton);
57  singleton = this;
58 
60  cache_.set_use_cache(false);
61  }
64  }
65 }
66 
68 {
69  assert(singleton);
70  singleton = nullptr;
71 }
72 
74  return singleton;
75 }
76 
78 {
79  // Add preproc defines according to the command line arguments.
80  game_config::scoped_preproc_define multiplayer("MULTIPLAYER",
85  game_config::scoped_preproc_define title_screen("TITLE_SCREEN",
87 
90 
92 
95 
96  // Load the standard hotkeys, then apply any player customizations.
99 
103 
104  return true;
105 }
106 
107 namespace {
108 /// returns true if every define in special is also defined in general
109 bool map_includes(const preproc_map& general, const preproc_map& special)
110 {
111  for (const preproc_map::value_type& pair : special)
112  {
113  preproc_map::const_iterator it = general.find(pair.first);
114  if (it == general.end() || it->second != pair.second) {
115  return false;
116  }
117  }
118  return true;
119 }
120 } // end anonymous namespace
121 
124 {
125  game_config::scoped_preproc_define debug_mode("DEBUG_MODE",
127 
128  // Game_config already holds requested config in memory.
129  if (!game_config_.empty()) {
130  if ((force_reload == NO_FORCE_RELOAD) && old_defines_map_ == cache_.get_preproc_map()) {
131  return;
132  }
133  if ((force_reload == NO_INCLUDE_RELOAD) && map_includes(old_defines_map_, cache_.get_preproc_map())) {
134  return;
135  }
136  }
137 
138  gui2::dialogs::loading_screen::display([this, force_reload, classification]() {
139  load_game_config(force_reload, classification);
140  });
141 }
142 
145 {
146  // Make sure that 'debug mode' symbol is set
147  // if command line parameter is selected
148  // also if we're in multiplayer and actual debug mode is disabled.
149 
150  // The loadscreen will erase the titlescreen.
151  // NOTE: even without loadscreen, needed after MP lobby.
152  try {
153  // Read all game configs.
154  // First we load all core configs, the mainline one and the ones from the addons.
155  // Validate the cores and discard the invalid.
156  // Then find the path to the selected core.
157  // Load the selected core.
158  // Handle terrains so that they are last loaded from the core.
159  // Load every compatible addon.
163 
164  // Start transaction so macros are shared.
165  game_config::config_cache_transaction main_transaction;
166 
167  config cores_cfg;
168  // Load mainline cores definition file.
169  cache_.get_config(game_config::path + "/data/cores.cfg", cores_cfg);
170 
171  // Append the $user_campaign_dir/*/cores.cfg files to the cores.
172  std::vector<std::string> user_dirs;
173  {
174  const std::string user_campaign_dir = filesystem::get_addons_dir();
175  std::vector<std::string> user_files;
176  filesystem::get_files_in_dir(user_campaign_dir, &user_files, &user_dirs,
178  }
179  for (const std::string& umc : user_dirs) {
180  const std::string cores_file = umc + "/cores.cfg";
181  if (filesystem::file_exists(cores_file)) {
182  config cores;
183  cache_.get_config(cores_file, cores);
184  cores_cfg.append(cores);
185  }
186  }
187 
188  // Validate every core
189  config valid_cores;
190  bool current_core_valid = false;
191  std::string wml_tree_root;
192  for (const config& core : cores_cfg.child_range("core")) {
193 
194  const std::string& id = core["id"];
195  if (id.empty()) {
198  _("Error validating data core."),
199  _("Found a core without id attribute.")
200  + '\n' + _("Skipping the core."));
201  });
202  continue;
203  }
204  if (*&valid_cores.find_child("core", "id", id)) {
207  _("Error validating data core."),
208  _("Core ID: ") + id
209  + '\n' + _("The ID is already in use.")
210  + '\n' + _("Skipping the core."));
211  });
212  continue;
213  }
214 
215  const std::string& path = core["path"];
219  _("Error validating data core."),
220  _("Core ID: ") + id
221  + '\n' + _("Core Path: ") + path
222  + '\n' + _("File not found.")
223  + '\n' + _("Skipping the core."));
224  });
225  continue;
226  }
227 
228  if (id == "default" && !current_core_valid) {
229  wml_tree_root = path;
230  }
231  if (id == preferences::core_id()) {
232  current_core_valid = true;
233  wml_tree_root = path;
234  }
235 
236  valid_cores.add_child("core", core); // append(core);
237  }
238 
239  if (!current_core_valid) {
242  _("Error loading core data."),
243  _("Core ID: ") + preferences::core_id()
244  + '\n' + _("Error loading the core with named id.")
245  + '\n' + _("Falling back to the default core."));
246  });
247  preferences::set_core_id("default");
248  }
249 
250  // check if we have a valid default core which should always be the case.
251  if (wml_tree_root.empty()) {
254  _("Error loading core data."),
255  _("Can't locate the default core.")
256  + '\n' + _("The game will now exit."));
257  });
258  throw;
259  }
260 
261  // Load the selected core
263  game_config_.append(valid_cores);
264 
265  main_transaction.lock();
266 
267  // Put the gfx rules aside so that we can prepend the add-on
268  // rules to them.
269  config core_terrain_rules;
270  core_terrain_rules.splice_children(game_config_, "terrain_graphics");
271 
273  load_addons_cfg();
274 
275  // If multiplayer campaign is being loaded, [scenario] tags should
276  // become [multiplayer] tags and campaign's id should be added to them
277  // to allow to recognize which scenarios belongs to a loaded campaign.
278  if (classification != nullptr) {
279  if (const config& campaign = game_config().find_child("campaign", "id", classification->campaign))
280  {
281  const bool require_campaign = campaign["require_campaign"].to_bool(true);
282  for (config& scenario : game_config_.child_range("scenario"))
283  {
284  scenario["require_scenario"] = require_campaign;
285  }
286  }
287  }
288 
289  // Extract the Lua scripts at toplevel.
292 
293  // Put the gfx rules back to game config.
294  game_config_.splice_children(core_terrain_rules, "terrain_graphics");
295 
297  set_unit_data();
299 
301  tdata_ = std::make_shared<terrain_type_data>(game_config_);
304  } catch(const game::error& e) {
305  ERR_CONFIG << "Error loading game configuration files\n" << e.message << '\n';
306 
307  // Try reloading without add-ons
308  if (!game_config::no_addons) {
309  game_config::no_addons = true;
312  _("Error loading custom game configuration files. The game will try without loading add-ons."),
313  e.message);
314  });
315  load_game_config(force_reload, classification);
316  } else if (preferences::core_id() != "default") {
319  _("Error loading custom game configuration files. The game will fallback to the default core files."),
320  e.message);
321  });
322  preferences::set_core_id("default");
323  game_config::no_addons = false;
324  load_game_config(force_reload, classification);
325  } else {
328  _("Error loading default core game configuration files. The game will now exit."),
329  e.message);
330  });
331  throw;
332  }
333  }
334 
336 
337  // Set new binary paths.
339 }
340 
342 {
343  std::string main_cfg;
344  std::string addon_id;
345  std::string addon_title;
347 };
348 
350 {
351  const std::string user_campaign_dir = filesystem::get_addons_dir();
352 
353  std::vector<std::string> error_addons;
354  std::vector<std::string> user_dirs;
355  std::vector<std::string> user_files;
356  std::vector<addon_source> addons_to_load;
357 
358  filesystem::get_files_in_dir(user_campaign_dir, &user_files, &user_dirs,
360 
361  std::vector<std::string> error_log;
362 
363  // Append the $user_campaign_dir/*.cfg files to addons_to_load.
364  for(const std::string& uc : user_files) {
365  const std::string file = uc;
366  const int size_minus_extension = file.size() - 4;
367  if(file.substr(size_minus_extension, file.size()) == ".cfg") {
368  const int userdata_loc = file.find("data/add-ons") + 5;
369  ERR_CONFIG << "error reading usermade add-on '"
370  << file << "'\n";
371  error_addons.push_back(file);
372  error_log.push_back("The format '~" + file.substr(userdata_loc)
373  + "' (for single-file add-ons) is not supported anymore, use '~"
374  + file.substr(userdata_loc,
375  size_minus_extension - userdata_loc)
376  + "/_main.cfg' instead.");
377  }
378  }
379 
380  // Rerun the directory scan using filename only, to get the addon_ids more easily.
381  user_files.clear();
382  user_dirs.clear();
383  filesystem::get_files_in_dir(user_campaign_dir, &user_files, &user_dirs,
385 
386  // Append the $user_campaign_dir/*/_main.cfg files to addons_to_load.
387  for (const std::string& uc : user_dirs) {
388  const std::string addon_id = uc;
389  const std::string addon_dir = user_campaign_dir + "/" + uc;
390 
391  const std::string main_cfg = addon_dir + "/_main.cfg";
392  const std::string info_cfg = addon_dir + "/_info.cfg";
393 
394  addon_source addon;
395  addon.main_cfg = main_cfg;
396  addon.addon_id = addon_id;
397 
398  if(filesystem::file_exists(main_cfg)) {
399  if(filesystem::file_exists(info_cfg)) {
400  config info;
401  cache_.get_config(info_cfg, info);
402 
403  const config& info_tag = info.child_or_empty("info");
404 
405  std::string core = info_tag["core"];
406  if(core.empty()) {
407  core = "default";
408  }
409 
410  addon.addon_title = info_tag["title"].str();
411 
412  // Skip add-ons not matching our current core.
413  //
414  // Don't skip:
415  // - addons which have no [info], they are most likely manually installed.
416  // - cores, we want them selectable at all times.
417  // - addons matching our current core.
418  if(!info_tag.empty() && info_tag["type"] != "core" && core != preferences::core_id()) {
419  continue;
420  }
421  }
422 
423  // Fall back to ID if no title was found (most likely in the case of missing _info.cfg).
424  // TODO: account for case where _info.cfg is missing but a .pbl file is present.
425  if(addon.addon_title.empty()) {
426  addon.addon_title = addon_id;
427  }
428 
429  // Ask the addon manager to find version info for us (from info, pbl file)
430  addon.version = get_addon_version_info(addon_id);
431  addons_to_load.push_back(addon);
432  }
433  }
434 
435  // Load the addons.
436  for (const addon_source & addon : addons_to_load) {
437  try {
438  // Load this addon from the cache, to a config
439  config umc_cfg;
440  cache_.get_config(addon.main_cfg, umc_cfg);
441 
442  // Annotate "era", "modification", and scenario tags with addon_id info
443  static const std::set<std::string> tags_with_addon_id { "era", "modification", "resource", "multiplayer", "scenario", "campaign" };
444 
445  for(auto child : umc_cfg.all_children_range()) {
446  if(tags_with_addon_id.count(child.key) > 0) {
447  auto& cfg = child.cfg;
448  cfg["addon_id"] = addon.addon_id;
449  cfg["addon_title"] = addon.addon_title;
450  // Note that this may reformat the string in a canonical form.
451  cfg["addon_version"] = addon.version.str();
452  }
453  }
454 
455  game_config_.append(umc_cfg);
456  } catch(const config::error& err) {
457  ERR_CONFIG << "error reading usermade add-on '" << addon.main_cfg << "'" << std::endl;
458  ERR_CONFIG << err.message << '\n';
459  error_addons.push_back(addon.main_cfg);
460  error_log.push_back(err.message);
461  } catch(const preproc_config::error& err) {
462  ERR_CONFIG << "error reading usermade add-on '" << addon.main_cfg << "'" << std::endl;
463  ERR_CONFIG << err.message << '\n';
464  error_addons.push_back(addon.main_cfg);
465  error_log.push_back(err.message);
466  } catch(const filesystem::io_exception&) {
467  ERR_CONFIG << "error reading usermade add-on '" << addon.main_cfg << "'" << std::endl;
468  error_addons.push_back(addon.main_cfg);
469  }
470  }
471  if(error_addons.empty() == false) {
472  const std::size_t n = error_addons.size();
473  const std::string& msg1 =
474  _n("The following add-on had errors and could not be loaded:",
475  "The following add-ons had errors and could not be loaded:",
476  n);
477  const std::string& msg2 =
478  _n("Please report this to the author or maintainer of this add-on.",
479  "Please report this to the respective authors or maintainers of these add-ons.",
480  n);
481 
482  const std::string& report = utils::join(error_log, "\n\n");
484  gui2::dialogs::wml_error::display(msg1, msg2, error_addons, report);
485  });
486  }
487 }
488 
490 {
491  config& hashes = game_config_.add_child("multiplayer_hashes");
492  for (const config &ch : game_config_.child_range("multiplayer")) {
493  hashes[ch["id"].str()] = ch.hash();
494  }
495 }
496 
498 {
499  game_config_.merge_children("units");
501  if(config &units = game_config_.child("units")) {
502  unit_types.set_config(units);
503  }
504 }
505 
507 {
508  // Rebuild addon version info cache.
510 
511  // Force a reload of configuration information.
513  old_defines_map_.clear();
516 
518 }
519 
521 {
524 }
525 
528 {
529  game_config::scoped_preproc_define difficulty(classification.difficulty,
530  !classification.difficulty.empty());
531  game_config::scoped_preproc_define campaign(classification.campaign_define,
532  !classification.campaign_define.empty());
533  game_config::scoped_preproc_define scenario(classification.scenario_define,
534  !classification.scenario_define.empty());
536  !classification.era_define.empty());
537  game_config::scoped_preproc_define multiplayer("MULTIPLAYER",
538  classification.campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER);
540  classification.campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER);
541 
542  //
543  // NOTE: these deques aren't used here, but the objects within are utilized as RAII helpers.
544  //
545 
546  typedef std::unique_ptr<game_config::scoped_preproc_define> define;
547 
548  std::deque<define> extra_defines;
549  for(const std::string& extra_define : classification.campaign_xtra_defines) {
550  extra_defines.emplace_back(new game_config::scoped_preproc_define(extra_define));
551  }
552 
553  std::deque<define> modification_defines;
554  for(const std::string& mod_define : classification.mod_defines) {
555  modification_defines.emplace_back(new game_config::scoped_preproc_define(mod_define, !mod_define.empty()));
556  }
557 
558  try {
560  } catch(const game::error&) {
562 
563  std::deque<define> previous_defines;
564  for(const preproc_map::value_type& preproc : old_defines_map_) {
565  previous_defines.emplace_back(new game_config::scoped_preproc_define(preproc.first));
566  }
567 
569 
570  throw;
571  }
572 
574 }
576 {
577  game_config::scoped_preproc_define multiplayer("MULTIPLAYER", is_mp);
578  game_config::scoped_preproc_define test("TEST", is_test);
579  game_config::scoped_preproc_define mptest("MP_TEST", cmdline_opts_.mptest && is_mp);
580 ///During an mp game the default difficuly define is also defined so better already load it now if we alreeady must reload config cache.
582 
583  typedef std::unique_ptr<game_config::scoped_preproc_define> define;
584  try{
586  }
587  catch(const game::error&) {
589 
590  std::deque<define> previous_defines;
591  for (const preproc_map::value_type& preproc : old_defines_map_) {
592  previous_defines.emplace_back(new game_config::scoped_preproc_define(preproc.first));
593  }
594 
596 
597  throw;
598  }
599 }
void set_config(config &cfg)
Resets all data based on the provided config.
Definition: types.cpp:1113
Don&#39;t reload if the previous defines include the new defines.
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:423
bool mptest
True if –mp-test was given on the command line.
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:874
void set_paths(const config &cfg)
void clear_children(T... keys)
Definition: config.hpp:477
std::string era()
Definition: game.cpp:699
game_classification * classification
Definition: resources.cpp:34
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:291
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
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:789
static void set_known_themes(const config *cfg)
Definition: theme.cpp:875
static bool file_exists(const fs::path &fpath)
Definition: filesystem.cpp:300
void merge_children(const std::string &key)
All children with the given key will be merged into the first element with that key.
Definition: config.cpp:329
bool noaddons
True if –noaddons was given on the command line. Disables the loading of all add-ons.
logger & info()
Definition: log.cpp:90
void lock()
Lock the transaction so no more macros are added.
void set_scope_active(scope s, bool set)
child_itors child_range(config_key_type key)
Definition: config.cpp:366
filesystem::binary_paths_manager paths_manager_
static void progress(loading_stage stage=loading_stage::none)
const std::string DEFAULT_DIFFICULTY
The default difficulty setting for campaigns.
#define ERR_CONFIG
unit_type_data unit_types
Definition: types.cpp:1452
Don&#39;t reload if the previous defines equal the new defines.
static lg::log_domain log_config("config")
void load_config(const config &v)
static void add_color_info(const config &v, bool build_defaults)
version_info get_addon_version_info(const std::string &addon)
Returns a particular installed add-on&#39;s version information.
Definition: manager.cpp:325
Used to set and unset scoped defines to preproc_map.
void call_in_main_thread(const std::function< void(void)> &f)
Definition: events.cpp:747
void flush_cache()
Definition: image.cpp:250
void clear_binary_paths_cache()
static void extract_preload_scripts(const config &game_config)
static game_config_manager * get()
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:89
void splice_children(config &src, const std::string &key)
Moves all the children with tag key from src to this.
Definition: config.cpp:579
void load_hotkeys()
Definition: general.cpp:857
std::string campaign_define
If there is a define the campaign uses to customize data.
void get_config(const std::string &path, config &cfg)
Gets a config object from given path.
static UNUSEDNOWARN std::string _n(const char *str1, const char *str2, int n)
Definition: gettext.hpp:93
void set_force_valid_cache(bool force)
Enable/disable cache validation.
void set_core_id(const std::string &core_id)
Definition: general.cpp:321
static game_config_manager * singleton
std::string path
Definition: game_config.cpp:39
boost::optional< std::string > test
Non-empty if –test was given on the command line. Goes directly into test mode, into a scenario...
void init_textdomains(const config &cfg)
Initializes the list of textdomains from a configuration object.
Definition: language.cpp:303
bool multiplayer
True if –multiplayer was given on the command line. Goes directly into multiplayer mode...
void refresh_addon_version_info_cache()
Refreshes the per-session cache of add-on&#39;s version information structs.
Definition: manager.cpp:283
std::string campaign
The id of the campaign being played.
void deactivate_all_scopes()
log_domain & general()
Definition: log.cpp:104
std::string era_define
If there is a define the era uses to customize data.
void set_use_cache(bool use)
Enable/disable caching.
void clear_defines()
Clear stored defines map to default values.
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs, file_name_option mode, file_filter_option filter, file_reorder_option reorder, file_tree_checksum *checksum)
Populates &#39;files&#39; with all the files and &#39;dirs&#39; with all the directories in dir.
Definition: filesystem.cpp:386
game_config_manager(const commandline_options &cmdline_opts, const bool jump_to_editor)
bool nocache
True if –nocache was given on the command line. Disables cache usage.
logger & err()
Definition: log.cpp:78
std::vector< std::string > campaign_xtra_defines
more customization of data
std::string get_wml_location(const std::string &filename, const std::string &current_dir)
Returns a complete path to the actual WML file or directory or an empty string if the file isn&#39;t pres...
void load_game_config_for_create(bool is_mp, bool is_test=false)
Game configuration data as global variables.
Definition: build_info.cpp:46
const preproc_map & get_preproc_map() const
An exception object used when an IO error occurs.
Definition: filesystem.hpp:48
void reset_color_info()
std::string scenario_define
If there is a define the scenario uses to customize data.
std::vector< std::string > mod_defines
If there are defines the modifications use to customize data.
Definitions related to theme-support.
const bool & debug
Definitions for the terrain builder.
static void display(const std::string &summary, const std::string &post_summary, const std::vector< std::string > &files, const std::string &details)
The display function; see modal_dialog for more information.
Definition: wml_error.hpp:43
Represents version numbers.
Definition: version.hpp:43
config & add_child(config_key_type key)
Definition: config.cpp:479
const file_tree_checksum & data_tree_checksum(bool reset=false)
Get the time at which the data/ tree was last modified at.
std::string difficulty
The difficulty level the game is being played on.
std::string core_id()
Definition: general.cpp:315
void set_about(const config &cfg)
Regenerates the credits config.
Definition: about.cpp:106
Used to share macros between cache objects You have to create transaction object to load all macros t...
static void display(std::function< void()> f)
void load_game_config_for_game(const game_classification &classification)
static void set_terrain_rules_cfg(const config &cfg)
Set the config where we will parse the global terrain rules.
Definition: builder.cpp:290
Base class for all the errors encountered by the engine.
Definition: exceptions.hpp:29
void load_hotkeys(const config &cfg, bool set_as_default)
Iterates through all hotkeys present in the config struct and creates and adds them to the hotkey lis...
std::string get_addons_dir()
Managing the AIs configuration - headers.
Standard logging facilities (interface).
std::string message
Definition: exceptions.hpp:31
version_info version
const commandline_options & cmdline_opts_
bool validcache
True if –validcache was given on the command line. Makes Wesnoth assume the cache is valid...
bool init_strings(const config &cfg)
Initializes certain English strings.
Definition: language.cpp:326
game_config::config_cache & cache_
std::map< std::string, struct preproc_define > preproc_map
#define e
const config & child_or_empty(config_key_type key) const
Returns the first child with the given key, or an empty config if there is none.
Definition: config.cpp:456
std::string addon_title
static void init(const config &game_config)
Init the parameters of ai configuration parser.
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
Interfaces for manipulating version numbers of engine, add-ons, etc.
static map_location::DIRECTION n
bool init_game_config(FORCE_RELOAD_CONFIG force_reload)
std::string hash() const
Definition: config.cpp:1275
std::string path
File path.
bool empty() const
Definition: config.cpp:837
const config & game_config() const
void load_game_config(FORCE_RELOAD_CONFIG force_reload, game_classification const *classification=nullptr)
void recheck_filetree_checksum()
Force cache checksum validation.
void load_game_config_with_loadscreen(FORCE_RELOAD_CONFIG force_reload, game_classification const *classification=nullptr)