The Battle for Wesnoth  1.15.11+dev
wesnoth.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
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 #include "addon/manager.hpp"
16 #include "build_info.hpp"
17 #include "commandline_argv.hpp"
18 #include "commandline_options.hpp" // for commandline_options, etc
19 #include "config.hpp" // for config, config::error, etc
20 #include "cursor.hpp" // for set, CURSOR_TYPE::NORMAL, etc
21 #include "editor/editor_main.hpp"
22 #include "filesystem.hpp" // for filesystem::file_exists, filesystem::io_exception, etc
23 #include "floating_label.hpp"
24 #include "font/error.hpp" // for error
25 #include "font/font_config.hpp" // for load_font_config, etc
26 #include "formula/formula.hpp" // for formula_error
27 #include "game_config.hpp" // for path, debug, debug_lua, etc
28 #include "game_config_manager.hpp" // for game_config_manager, etc
29 #include "game_end_exceptions.hpp"
30 #include "game_launcher.hpp" // for game_launcher, etc
31 #include "gettext.hpp"
32 #include "gui/core/event/handler.hpp" // for tmanager
35 #include "gui/dialogs/message.hpp" // for show_error_message
36 #include "gui/dialogs/title_screen.hpp" // for title_screen, etc
37 #include "gui/gui.hpp" // for init
38 #include "picture.hpp" // for flush_cache, etc
39 #include "log.hpp" // for LOG_STREAM, general, logger, etc
40 #include "preferences/general.hpp" // for core_id, etc
44 #include "sdl/exception.hpp" // for exception
45 #include "sdl/rect.hpp"
46 #include "serialization/binary_or_text.hpp" // for config_writer
47 #include "serialization/parser.hpp" // for read
48 #include "serialization/preprocessor.hpp" // for preproc_define, etc
50 #include "serialization/schema_validator.hpp" // for strict_validation_enabled and schema_validator
51 #include "sound.hpp" // for commit_music_changes, etc
52 #include "statistics.hpp" // for fresh_stats
53 #include <functional>
54 #include "game_version.hpp" // for version_info
55 #include "video.hpp" // for CVideo
56 #include "wesconfig.h" // for PACKAGE
57 #include "widgets/button.hpp" // for button
58 #include "wml_exception.hpp" // for wml_exception
59 
60 #ifdef _WIN32
61 #include "log_windows.hpp"
62 
63 #include <float.h>
64 #endif // _WIN32
65 
66 #ifndef _MSC_VER
67 #include <fenv.h>
68 #endif // _MSC_VER
69 
70 #include <SDL2/SDL.h> // for SDL_Init, SDL_INIT_TIMER
71 
72 #include <boost/iostreams/categories.hpp> // for input, output
73 #include <boost/iostreams/copy.hpp> // for copy
74 #include <boost/iostreams/filter/bzip2.hpp> // for bzip2_compressor, etc
75 
76 #if defined(_MSC_VER)
77 #pragma warning(push)
78 #pragma warning(disable : 4456)
79 #pragma warning(disable : 4458)
80 #endif
81 
82 #include <boost/iostreams/filter/gzip.hpp> // for gzip_compressor, etc
83 
84 #if defined(_MSC_VER)
85 #pragma warning(pop)
86 #endif
87 
88 #include <boost/iostreams/filtering_stream.hpp> // for filtering_stream
89 #include <boost/program_options/errors.hpp> // for error
90 #include <optional>
91 
92 #include <algorithm> // for transform
93 #include <cerrno> // for ENOMEM
94 #include <clocale> // for setlocale, LC_ALL, etc
95 #include <cstdio> // for remove, fprintf, stderr
96 #include <cstdlib> // for srand, exit
97 #include <ctime> // for time, ctime, std::time_t
98 #include <exception> // for exception
99 #include <fstream> // for operator<<, basic_ostream, etc
100 #include <iostream> // for cerr, cout
101 #include <vector>
102 
103 //#define NO_CATCH_AT_GAME_END
104 
105 #ifdef _WIN32
106 
107 #ifdef INADDR_ANY
108 #undef INADDR_ANY
109 #endif
110 
111 #ifdef INADDR_BROADCAST
112 #undef INADDR_BROADCAST
113 #endif
114 
115 #ifdef INADDR_NONE
116 #undef INADDR_NONE
117 #endif
118 
119 #include <windows.h>
120 
121 #endif // _WIN32
122 
123 #ifdef DEBUG_WINDOW_LAYOUT_GRAPHS
124 #include "gui/widgets/debug.hpp"
125 #endif
126 
127 class end_level_exception;
128 namespace game
129 {
130 struct error;
131 }
132 
133 static lg::log_domain log_config("config");
134 #define LOG_CONFIG LOG_STREAM(info, log_config)
135 
136 #define LOG_GENERAL LOG_STREAM(info, lg::general())
137 
138 static lg::log_domain log_preprocessor("preprocessor");
139 #define LOG_PREPROC LOG_STREAM(info, log_preprocessor)
140 
141 // this is needed to allow identical functionality with clean refactoring
142 // play_game only returns on an error, all returns within play_game can
143 // be replaced with this
144 static void safe_exit(int res)
145 {
146  LOG_GENERAL << "exiting with code " << res << "\n";
147  exit(res);
148 }
149 
150 // maybe this should go in a util file somewhere?
151 template<typename filter>
152 static void encode(const std::string& input_file, const std::string& output_file)
153 {
154  try {
155  std::ifstream ifile(input_file.c_str(), std::ios_base::in | std::ios_base::binary);
156  ifile.peek(); // We need to touch the stream to set the eof bit
157 
158  if(!ifile.good()) {
159  std::cerr << "Input file " << input_file
160  << " is not good for reading. Exiting to prevent bzip2 from segfaulting\n";
161  safe_exit(1);
162  }
163 
164  std::ofstream ofile(output_file.c_str(), std::ios_base::out | std::ios_base::binary);
165 
166  boost::iostreams::filtering_stream<boost::iostreams::output> stream;
167  stream.push(filter());
168  stream.push(ofile);
169 
170  boost::iostreams::copy(ifile, stream);
171  ifile.close();
172 
173  safe_exit(remove(input_file.c_str()));
174  } catch(const filesystem::io_exception& e) {
175  std::cerr << "IO error: " << e.what() << "\n";
176  }
177 }
178 
179 template<typename filter>
180 static void decode(const std::string& input_file, const std::string& output_file)
181 {
182  try {
183  std::ofstream ofile(output_file.c_str(), std::ios_base::out | std::ios_base::binary);
184  std::ifstream ifile(input_file.c_str(), std::ios_base::in | std::ios_base::binary);
185 
186  boost::iostreams::filtering_stream<boost::iostreams::input> stream;
187  stream.push(filter());
188  stream.push(ifile);
189 
190  boost::iostreams::copy(stream, ofile);
191  ifile.close();
192 
193  safe_exit(remove(input_file.c_str()));
194  } catch(const filesystem::io_exception& e) {
195  std::cerr << "IO error: " << e.what() << "\n";
196  }
197 }
198 
199 static void gzip_encode(const std::string& input_file, const std::string& output_file)
200 {
201  encode<boost::iostreams::gzip_compressor>(input_file, output_file);
202 }
203 
204 static void gzip_decode(const std::string& input_file, const std::string& output_file)
205 {
206  decode<boost::iostreams::gzip_decompressor>(input_file, output_file);
207 }
208 
209 static void bzip2_encode(const std::string& input_file, const std::string& output_file)
210 {
211  encode<boost::iostreams::bzip2_compressor>(input_file, output_file);
212 }
213 
214 static void bzip2_decode(const std::string& input_file, const std::string& output_file)
215 {
216  decode<boost::iostreams::bzip2_decompressor>(input_file, output_file);
217 }
218 
219 static void handle_preprocess_command(const commandline_options& cmdline_opts)
220 {
221  preproc_map input_macros;
222 
223  if(cmdline_opts.preprocess_input_macros) {
224  std::string file = *cmdline_opts.preprocess_input_macros;
225  if(filesystem::file_exists(file) == false) {
226  std::cerr << "please specify an existing file. File " << file << " doesn't exist.\n";
227  return;
228  }
229 
230  std::cerr << SDL_GetTicks() << " Reading cached defines from: " << file << "\n";
231 
232  config cfg;
233 
234  try {
236  read(cfg, *stream);
237  } catch(const config::error& e) {
238  std::cerr << "Caught a config error while parsing file '" << file << "':\n" << e.message << std::endl;
239  }
240 
241  int read = 0;
242 
243  // use static preproc_define::read_pair(config) to make a object
244  for(const config::any_child& value : cfg.all_children_range()) {
245  const preproc_map::value_type def = preproc_define::read_pair(value.cfg);
246  input_macros[def.first] = def.second;
247  ++read;
248  }
249 
250  std::cerr << SDL_GetTicks() << " Read " << read << " defines.\n";
251  }
252 
253  const std::string resourceToProcess(*cmdline_opts.preprocess_path);
254  const std::string targetDir(*cmdline_opts.preprocess_target);
255 
256  uint32_t startTime = SDL_GetTicks();
257 
258  // If the users add the SKIP_CORE define we won't preprocess data/core
259  bool skipCore = false;
260  bool skipTerrainGFX = false;
261 
262  // The 'core_defines_map' is the one got from data/core macros
263  preproc_map defines_map(input_macros);
264 
265  if(cmdline_opts.preprocess_defines) {
266  // add the specified defines
267  for(const std::string& define : *cmdline_opts.preprocess_defines) {
268  if(define.empty()) {
269  std::cerr << "empty define supplied\n";
270  continue;
271  }
272 
273  LOG_PREPROC << "adding define: " << define << '\n';
274  defines_map.emplace(define, preproc_define(define));
275 
276  if(define == "SKIP_CORE") {
277  std::cerr << "'SKIP_CORE' defined.\n";
278  skipCore = true;
279  } else if(define == "NO_TERRAIN_GFX") {
280  std::cerr << "'NO_TERRAIN_GFX' defined." << std::endl;
281  skipTerrainGFX = true;
282  }
283  }
284  }
285 
286  // add the WESNOTH_VERSION define
287  defines_map["WESNOTH_VERSION"] = preproc_define(game_config::wesnoth_version.str());
288 
289  std::cerr << "added " << defines_map.size() << " defines.\n";
290 
291  // preprocess core macros first if we don't skip the core
292  if(skipCore == false) {
293  std::cerr << "preprocessing common macros from 'data/core' ...\n";
294 
295  // process each folder explicitly to gain speed
296  preprocess_resource(game_config::path + "/data/core/macros", &defines_map);
297 
298  if(skipTerrainGFX == false) {
299  preprocess_resource(game_config::path + "/data/core/terrain-graphics", &defines_map);
300  }
301 
302  std::cerr << "acquired " << (defines_map.size() - input_macros.size()) << " 'data/core' defines.\n";
303  } else {
304  std::cerr << "skipped 'data/core'\n";
305  }
306 
307  // preprocess resource
308  std::cerr << "preprocessing specified resource: " << resourceToProcess << " ...\n";
309 
310  preprocess_resource(resourceToProcess, &defines_map, true, true, targetDir);
311  std::cerr << "acquired " << (defines_map.size() - input_macros.size()) << " total defines.\n";
312 
313  if(cmdline_opts.preprocess_output_macros) {
314  std::string outputFileName = "_MACROS_.cfg";
315  if(!cmdline_opts.preprocess_output_macros->empty()) {
316  outputFileName = *cmdline_opts.preprocess_output_macros;
317  }
318 
319  std::string outputPath = targetDir + "/" + outputFileName;
320 
321  std::cerr << "writing '" << outputPath << "' with " << defines_map.size() << " defines.\n";
322 
324  if(!out->fail()) {
325  config_writer writer(*out, false);
326 
327  for(auto& define_pair : defines_map) {
328  define_pair.second.write(writer, define_pair.first);
329  }
330  } else {
331  std::cerr << "couldn't open the file.\n";
332  }
333  }
334 
335  std::cerr << "preprocessing finished. Took " << SDL_GetTicks() - startTime << " ticks.\n";
336 }
337 
338 static int handle_validate_command(const std::string& file, abstract_validator& validator, const std::vector<std::string>& defines) {
339  preproc_map defines_map;
340  for(const std::string& define : defines) {
341  if(define.empty()) {
342  std::cerr << "empty define supplied\n";
343  continue;
344  }
345 
346  LOG_PREPROC << "adding define: " << define << '\n';
347  defines_map.emplace(define, preproc_define(define));
348  }
349  std::cout << "Validating " << file << " against schema " << validator.name_ << std::endl;
351  filesystem::scoped_istream stream = preprocess_file(file, &defines_map);
352  config result;
353  read(result, *stream, &validator);
354  if(lg::broke_strict()) {
355  std::cout << "validation failed\n";
356  } else {
357  std::cout << "validation succeeded\n";
358  }
359  return lg::broke_strict();
360 }
361 
362 /** Process commandline-arguments */
363 static int process_command_args(const commandline_options& cmdline_opts)
364 {
365  // Options that don't change behavior based on any others should be checked alphabetically below.
366 
367  if(cmdline_opts.log) {
368  for(const auto& log_pair : *cmdline_opts.log) {
369  const std::string log_domain = log_pair.second;
370  const int severity = log_pair.first;
371  if(!lg::set_log_domain_severity(log_domain, severity)) {
372  std::cerr << "unknown log domain: " << log_domain << '\n';
373  return 2;
374  }
375  }
376  }
377 
378  if(cmdline_opts.userconfig_dir) {
380  }
381 
382  if(cmdline_opts.userconfig_path) {
383  std::cout << filesystem::get_user_config_dir() << '\n';
384  return 0;
385  }
386 
387  if(cmdline_opts.userdata_dir) {
389  }
390 
391  if(cmdline_opts.userdata_path) {
392  std::cout << filesystem::get_user_data_dir() << '\n';
393  return 0;
394  }
395 
396  if(cmdline_opts.data_dir) {
397  const std::string datadir = *cmdline_opts.data_dir;
398 #ifdef _WIN32
399  // use c_str to ensure that index 1 points to valid element since c_str() returns null-terminated string
400  if(datadir.c_str()[1] == ':') {
401 #else
402  if(datadir[0] == '/') {
403 #endif
404  game_config::path = datadir;
405  } else {
406  game_config::path = filesystem::get_cwd() + '/' + datadir;
407  }
408 
410  if(!cmdline_opts.nobanner) std::cerr << "Overriding data directory with " << game_config::path << std::endl;
411 
413  std::cerr << "Could not find directory '" << game_config::path << "'\n";
414  throw config::error("directory not found");
415  }
416 
417  // don't update font as we already updating it in game ctor
418  // font_manager_.update_font_path();
419  }
420 
421  if(cmdline_opts.data_path) {
422  std::cout << game_config::path << '\n';
423  return 0;
424  }
425 
426  if(cmdline_opts.debug_lua) {
427  game_config::debug_lua = true;
428  }
429 
430  if(cmdline_opts.strict_lua) {
432  }
433 
434  if(cmdline_opts.gunzip) {
435  const std::string input_file(*cmdline_opts.gunzip);
436  if(!filesystem::is_gzip_file(input_file)) {
437  std::cerr << "file '" << input_file << "'isn't a .gz file\n";
438  return 2;
439  }
440 
441  const std::string output_file(input_file, 0, input_file.length() - 3);
442  gzip_decode(input_file, output_file);
443  }
444 
445  if(cmdline_opts.bunzip2) {
446  const std::string input_file(*cmdline_opts.bunzip2);
447  if(!filesystem::is_bzip2_file(input_file)) {
448  std::cerr << "file '" << input_file << "'isn't a .bz2 file\n";
449  return 2;
450  }
451 
452  const std::string output_file(input_file, 0, input_file.length() - 4);
453  bzip2_decode(input_file, output_file);
454  }
455 
456  if(cmdline_opts.gzip) {
457  const std::string input_file(*cmdline_opts.gzip);
458  const std::string output_file(*cmdline_opts.gzip + ".gz");
459  gzip_encode(input_file, output_file);
460  }
461 
462  if(cmdline_opts.bzip2) {
463  const std::string input_file(*cmdline_opts.bzip2);
464  const std::string output_file(*cmdline_opts.bzip2 + ".bz2");
465  bzip2_encode(input_file, output_file);
466  }
467 
468  if(cmdline_opts.help) {
469  std::cout << cmdline_opts;
470  return 0;
471  }
472 
473  if(cmdline_opts.logdomains) {
474  std::cout << lg::list_logdomains(*cmdline_opts.logdomains);
475  return 0;
476  }
477 
478  if(cmdline_opts.log_precise_timestamps) {
480  }
481 
482  if(cmdline_opts.rng_seed) {
483  srand(*cmdline_opts.rng_seed);
484  }
485 
486  if(cmdline_opts.screenshot || cmdline_opts.render_image) {
487  SDL_setenv("SDL_VIDEODRIVER", "dummy", 1);
488  }
489 
490  if(cmdline_opts.strict_validation) {
492  }
493 
494  if(cmdline_opts.version) {
495  std::cout << "Battle for Wesnoth" << " " << game_config::wesnoth_version.str() << "\n\n";
496  std::cout << "Library versions:\n" << game_config::library_versions_report() << '\n';
497  std::cout << "Optional features:\n" << game_config::optional_features_report();
498 
499  return 0;
500  }
501 
502  if(cmdline_opts.report) {
503  std::cout << "\n========= BUILD INFORMATION =========\n\n" << game_config::full_build_report();
504  return 0;
505  }
506 
507  if(cmdline_opts.validate_schema) {
509  validator.set_create_exceptions(false); // Don't crash if there's an error, just go ahead anyway
510  return handle_validate_command(*cmdline_opts.validate_schema, validator, {});
511  }
512 
513  if(cmdline_opts.do_diff) {
514  config left, right;
515  std::ifstream in_left(cmdline_opts.diff_left);
516  std::ifstream in_right(cmdline_opts.diff_right);
517  read(left, in_left);
518  read(right, in_right);
519  std::ostream* os = &std::cout;
520  if(cmdline_opts.output_file) {
521  os = new std::ofstream(*cmdline_opts.output_file);
522  }
524  out.write(right.get_diff(left));
525  if(os != &std::cout) delete os;
526  return 0;
527  }
528 
529  if(cmdline_opts.do_patch) {
530  config base, diff;
531  std::ifstream in_base(cmdline_opts.diff_left);
532  std::ifstream in_diff(cmdline_opts.diff_right);
533  read(base, in_base);
534  read(diff, in_diff);
535  base.apply_diff(diff);
536  std::ostream* os = &std::cout;
537  if(cmdline_opts.output_file) {
538  os = new std::ofstream(*cmdline_opts.output_file);
539  }
541  out.write(base);
542  if(os != &std::cout) delete os;
543  return 0;
544  }
545 
546  // Options changing their behavior dependent on some others should be checked below.
547 
548  if(cmdline_opts.preprocess) {
549  handle_preprocess_command(cmdline_opts);
550  return 0;
551  }
552 
553  if(cmdline_opts.validate_wml) {
554  std::string schema_path;
555  if(cmdline_opts.validate_with) {
556  schema_path = *cmdline_opts.validate_with;
557  } else {
558  schema_path = filesystem::get_wml_location("schema/game_config.cfg");
559  }
560  schema_validation::schema_validator validator(schema_path);
561  validator.set_create_exceptions(false); // Don't crash if there's an error, just go ahead anyway
562  return handle_validate_command(*cmdline_opts.validate_wml, validator,
563  cmdline_opts.preprocess_defines.value_or<decltype(cmdline_opts.preprocess_defines)::value_type>({}));
564  }
565 
566  if(cmdline_opts.preprocess_defines || cmdline_opts.preprocess_input_macros || cmdline_opts.preprocess_path) {
567  // It would be good if this was supported for running tests too, possibly for other uses.
568  // For the moment show an error message instead of leaving the user wondering why it doesn't work.
569  std::cerr << "That --preprocess-* option is only supported when using --preprocess or --validate-wml.\n";
570  // Return an error status other than -1, because in our caller -1 means no error
571  return -2;
572  }
573 
574  // Not the most intuitive solution, but I wanted to leave current semantics for now
575  return -1;
576 }
577 
578 /**
579  * I would prefer to setup locale first so that early error
580  * messages can get localized, but we need the game_launcher
581  * initialized to have filesystem::get_intl_dir() to work. Note: setlocale()
582  * does not take GUI language setting into account.
583  */
584 static void init_locale()
585 {
586 #if defined _WIN32 || defined __APPLE__
587  setlocale(LC_ALL, "English");
588 #else
589  std::setlocale(LC_ALL, "C");
590 #endif
591 
592  const std::string& intl_dir = filesystem::get_intl_dir();
593 
594  translation::bind_textdomain(PACKAGE, intl_dir.c_str(), "UTF-8");
595  translation::bind_textdomain(PACKAGE "-lib", intl_dir.c_str(), "UTF-8");
597 }
598 
599 /**
600  * Print an alert and instructions to stderr about early initialization errors.
601  *
602  * This is provided as an aid for users dealing with potential data dir
603  * configuration issues. The first code to read core WML *has* the
604  * responsibility to call this function in the event of a problem, to inform
605  * the user of the most likely possible cause and suggest a course of action
606  * to solve the issue.
607  */
609 {
610  // NOTE: wrap output to 80 columns.
611  std::cerr << '\n'
612  << "An error at this point during initialization usually indicates that the data\n"
613  << "directory above was not correctly set or detected. Try passing the correct path\n"
614  << "in the command line with the --data-dir switch or as the only argument.\n";
615 }
616 
617 /**
618  * Handles the lua script command line arguments if present.
619  * This function will only run once.
620  */
622 {
623  static bool first_time = true;
624 
625  if(!first_time) {
626  return;
627  }
628 
629  first_time = false;
630 
631  if(!game->init_lua_script()) {
632  // std::cerr << "error when loading lua scripts at startup\n";
633  // std::cerr << "could not load lua script: " << *cmdline_opts.script_file << std::endl;
634  }
635 }
636 
637 #ifdef _MSC_VER
638 static void check_fpu()
639 {
640  uint32_t f_control;
641 
642  if(_controlfp_s(&f_control, 0, 0) == 0) {
643  uint32_t unused;
644  uint32_t rounding_mode = f_control & _MCW_RC;
645 
646  if(rounding_mode != _RC_NEAR) {
647  std::cerr << "Floating point rounding mode is currently '"
648  << ((rounding_mode == _RC_CHOP)
649  ? "chop"
650  : (rounding_mode == _RC_UP)
651  ? "up"
652  : (rounding_mode == _RC_DOWN)
653  ? "down"
654  : (rounding_mode == _RC_NEAR) ? "near" : "unknown")
655  << "' setting to 'near'\n";
656 
657  if(_controlfp_s(&unused, _RC_NEAR, _MCW_RC)) {
658  std::cerr << "failed to set floating point rounding type to 'near'\n";
659  }
660  }
661 
662 #ifndef _M_AMD64
663  uint32_t precision_mode = f_control & _MCW_PC;
664  if(precision_mode != _PC_53) {
665  std::cerr << "Floating point precision mode is currently '"
666  << ((precision_mode == _PC_53)
667  ? "double"
668  : (precision_mode == _PC_24)
669  ? "single"
670  : (precision_mode == _PC_64) ? "double extended" : "unknown")
671  << "' setting to 'double'\n";
672 
673  if(_controlfp_s(&unused, _PC_53, _MCW_PC)) {
674  std::cerr << "failed to set floating point precision type to 'double'\n";
675  }
676  }
677 #endif
678 
679  } else {
680  std::cerr << "_controlfp_s failed.\n";
681  }
682 }
683 #else
684 static void check_fpu()
685 {
686  switch(fegetround()) {
687  case FE_TONEAREST:
688  break;
689  case FE_DOWNWARD:
690  std::cerr << "Floating point precision mode is currently 'downward'";
691  goto reset_fpu;
692  case FE_TOWARDZERO:
693  std::cerr << "Floating point precision mode is currently 'toward-zero'";
694  goto reset_fpu;
695  case FE_UPWARD:
696  std::cerr << "Floating point precision mode is currently 'upward'";
697  goto reset_fpu;
698  default:
699  std::cerr << "Floating point precision mode is currently 'unknown'";
700  goto reset_fpu;
701  reset_fpu:
702  std::cerr << "setting to 'nearest'";
703  fesetround(FE_TONEAREST);
704  break;
705  }
706 }
707 #endif
708 
709 /**
710  * Setups the game environment and enters
711  * the titlescreen or game loops.
712  */
713 static int do_gameloop(const std::vector<std::string>& args)
714 {
715  srand(std::time(nullptr));
716 
717  commandline_options cmdline_opts = commandline_options(args);
719 
720  int finished = process_command_args(cmdline_opts);
721  if(finished != -1) {
722 #ifdef _WIN32
723  if(lg::using_own_console()) {
724  std::cerr << "Press enter to continue..." << std::endl;
725  std::cin.get();
726  }
727 #endif
728 
729  return finished;
730  }
731 
732  const auto game = std::make_unique<game_launcher>(cmdline_opts);
733  const int start_ticks = SDL_GetTicks();
734 
735  init_locale();
736 
737  bool res;
738 
739  // Do initialize fonts before reading the game config, to have game
740  // config error messages displayed. fonts will be re-initialized later
741  // when the language is read from the game config.
742  res = font::load_font_config();
743  if(res == false) {
744  std::cerr << "could not initialize fonts\n";
745  // The most common symptom of a bogus data dir path -- warn the user.
747  return 1;
748  }
749 
750  res = game->init_language();
751  if(res == false) {
752  std::cerr << "could not initialize the language\n";
753  return 1;
754  }
755 
756  res = game->init_video();
757  if(res == false) {
758  std::cerr << "could not initialize display\n";
759  return 1;
760  }
761 
762  check_fpu();
763  const cursor::manager cursor_manager;
765 
766 #if(defined(_X11) && !defined(__APPLE__)) || defined(_WIN32)
767  SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);
768 #endif
769 
770  gui2::init();
771  const gui2::event::manager gui_event_manager;
772 
773  game_config_manager config_manager(cmdline_opts);
774 
775  gui2::dialogs::loading_screen::display([&res, &config_manager, &cmdline_opts]() {
778 
779  if(res == false) {
780  std::cerr << "could not initialize game config\n";
781  return;
782  }
783 
785 
786  res = font::load_font_config();
787  if(res == false) {
788  std::cerr << "could not re-initialize fonts for the current language\n";
789  return;
790  }
791 
792  if(!game_config::no_addons && !cmdline_opts.noaddons) {
794 
796  }
797  });
798 
799  if(res == false) {
800  return 1;
801  }
802 
803  LOG_CONFIG << "time elapsed: " << (SDL_GetTicks() - start_ticks) << " ms\n";
804 
805  plugins_manager plugins_man(new application_lua_kernel);
806 
807  const plugins_context::reg_vec callbacks {
808  {"play_multiplayer", std::bind(&game_launcher::play_multiplayer, game.get(), game_launcher::mp_mode::CONNECT)},
809  };
810 
811  const plugins_context::areg_vec accessors {
812  {"command_line", std::bind(&commandline_options::to_config, &cmdline_opts)},
813  };
814 
815  plugins_context plugins("titlescreen", callbacks, accessors);
816 
817  plugins.set_callback("exit", [](const config& cfg) { safe_exit(cfg["code"].to_int(0)); }, false);
818 
819  while(true) {
821 
822  if(!game->has_load_data()) {
823  const config& cfg = config_manager.game_config().child("titlescreen_music");
824  if(cfg) {
825  for(const config& i : cfg.child_range("music")) {
827  }
828 
829  config title_music_config;
830  title_music_config["name"] = game_config::title_music;
831  title_music_config["append"] = true;
832  title_music_config["immediate"] = true;
833  sound::play_music_config(title_music_config);
834  } else {
837  }
838  }
839 
840  handle_lua_script_args(&*game, cmdline_opts);
841 
842  plugins.play_slice();
843  plugins.play_slice();
844 
845  if(!cmdline_opts.unit_test.empty()) {
846  return static_cast<int>(game->unit_test());
847  }
848 
849  if(game->play_test() == false) {
850  return 0;
851  }
852 
853  if(game->play_screenshot_mode() == false) {
854  return 0;
855  }
856 
857  if(game->play_render_image_mode() == false) {
858  return 0;
859  }
860 
861  // Start directly a campaign
862  if(game->goto_campaign() == false) {
863  if(game->jump_to_campaign_id().empty())
864  continue; // Go to main menu
865  else
866  return 1; // we got an error starting the campaign from command line
867  }
868 
869  // Start directly a multiplayer
870  // Eventually with a specified server
871  if(game->goto_multiplayer() == false) {
872  continue; // Go to main menu
873  }
874 
875  // Start directly a commandline multiplayer game
876  if(game->play_multiplayer_commandline() == false) {
877  return 0;
878  }
879 
880  if(game->goto_editor() == false) {
881  return 0;
882  }
883 
884  const font::floating_label_context label_manager;
885 
887 
888  // If loading a game, skip the titlescreen entirely
889  if(game->has_load_data() && game->load_game()) {
891  continue;
892  }
893 
895 
896  // Allows re-layout on resize
898  dlg.show();
899  }
900 
901  switch(dlg.get_retval()) {
903  LOG_GENERAL << "quitting game...\n";
904  return 0;
907  game->play_multiplayer(game_launcher::mp_mode::CONNECT);
908  break;
911  game->play_multiplayer(game_launcher::mp_mode::HOST);
912  break;
915  game->play_multiplayer(game_launcher::mp_mode::LOCAL);
916  break;
918  gui2::dialogs::loading_screen::display([&config_manager]() {
919  config_manager.reload_changed_game_config();
920  });
921  break;
923  game->start_editor();
924  break;
926  gui2::dialogs::end_credits::display();
927  break;
930  break;
932  break;
933  }
934  }
935 }
936 
937 #ifndef _WIN32
939 {
940  exit(0);
941 }
942 #endif
943 
944 #ifdef _WIN32
945 #define error_exit(res) \
946  do { \
947  if(lg::using_own_console()) { \
948  std::cerr << "Press enter to continue..." << std::endl; \
949  std::cin.get(); \
950  } \
951  return res; \
952  } while(false)
953 #else
954 #define error_exit(res) return res
955 #endif
956 
957 #ifdef __APPLE__
958 extern "C" int wesnoth_main(int argc, char** argv);
959 int wesnoth_main(int argc, char** argv)
960 #else
961 int main(int argc, char** argv)
962 #endif
963 {
964  auto args = read_argv(argc, argv);
965  assert(!args.empty());
966 
967  // --nobanner needs to be detected before the main command-line parsing happens
968  bool nobanner = false;
969  for(const auto& arg : args) {
970  if(arg == "--nobanner") {
971  nobanner = true;
972  break;
973  }
974  }
975 
976 #ifdef _WIN32
977  bool log_redirect = true, native_console_implied = false;
978  // This is optional<bool> instead of tribool because value_or() is exactly the required semantic
979  std::optional<bool> native_console_force;
980  // Some switches force a Windows console to be attached to the process even
981  // if Wesnoth is an IMAGE_SUBSYSTEM_WINDOWS_GUI executable because they
982  // turn it into a CLI application. Also, --wconsole in particular attaches
983  // a console to a regular GUI game session.
984  //
985  // It's up to commandline_options later to handle these switches (other
986  // --wconsole) later and emit any applicable console output, but right here
987  // we need a rudimentary check for the switches in question to set up the
988  // console before proceeding any further.
989  for(const auto& arg : args) {
990  // Switches that don't take arguments
991  static const std::set<std::string> wincon_switches = {
992  "--wconsole", "-h", "--help", "-v", "--version", "-R", "--report", "--logdomains",
993  "--data-path", "--userdata-path", "--userconfig-path",
994  };
995 
996  // Switches that take arguments, the switch may have the argument past
997  // the first = character, or in a subsequent argv entry which we don't
998  // care about -- we just want to see if the switch is there.
999  static const std::set<std::string> wincon_arg_switches = {
1000  "-D", "--diff", "-p", "--preprocess", "-P", "--patch", "--render-image",
1001  "--screenshot", "-V", "--validate", "--validate-schema",
1002  };
1003 
1004  auto switch_matches_arg = [&arg](const std::string& sw) {
1005  const auto pos = arg.find('=');
1006  return pos == std::string::npos ? arg == sw : arg.substr(0, pos) == sw;
1007  };
1008 
1009  if(wincon_switches.find(arg) != wincon_switches.end() ||
1010  std::find_if(wincon_arg_switches.begin(), wincon_arg_switches.end(), switch_matches_arg) != wincon_arg_switches.end()) {
1011  native_console_implied = true;
1012  }
1013 
1014  if(arg == "--wnoconsole") {
1015  native_console_force = false;
1016  } else if(arg == "--wconsole") {
1017  native_console_force = true;
1018  } else if(arg == "--wnoredirect") {
1019  log_redirect = false;
1020  }
1021  }
1022 
1023  if(native_console_force.value_or(native_console_implied)) {
1025  }
1026  lg::early_log_file_setup(!log_redirect);
1027 #endif
1028 
1029  if(SDL_Init(SDL_INIT_TIMER) < 0) {
1030  fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
1031  return (1);
1032  }
1033 
1034 #ifndef _WIN32
1035  struct sigaction terminate_handler;
1036  terminate_handler.sa_handler = wesnoth_terminate_handler;
1037  terminate_handler.sa_flags = 0;
1038 
1039  sigemptyset(&terminate_handler.sa_mask);
1040  sigaction(SIGTERM, &terminate_handler, nullptr);
1041  sigaction(SIGINT, &terminate_handler, nullptr);
1042 #endif
1043 
1044  // Mac's touchpad generates touch events too.
1045  // Ignore them until Macs have a touchscreen: https://forums.libsdl.org/viewtopic.php?p=45758
1046 #if defined(__APPLE__) && !defined(__IPHONEOS__)
1047  SDL_EventState(SDL_FINGERMOTION, SDL_DISABLE);
1048  SDL_EventState(SDL_FINGERDOWN, SDL_DISABLE);
1049  SDL_EventState(SDL_FINGERUP, SDL_DISABLE);
1050 #endif
1051 
1052  // declare this here so that it will always be at the front of the event queue.
1053  events::event_context global_context;
1054 
1055  SDL_StartTextInput();
1056 
1057  try {
1058  if(!nobanner) {
1059  std::cerr << "Battle for Wesnoth v" << game_config::revision << " " << game_config::build_arch() << '\n';
1060  const std::time_t t = std::time(nullptr);
1061  std::cerr << "Started on " << ctime(&t) << "\n";
1062  }
1063 
1064  const std::string& exe_dir = filesystem::get_exe_dir();
1065  if(!exe_dir.empty()) {
1066  // Try to autodetect the location of the game data dir. Note that
1067  // the root of the source tree currently doubles as the data dir.
1068  std::string auto_dir;
1069 
1070  // scons leaves the resulting binaries at the root of the source
1071  // tree by default.
1072  if(filesystem::file_exists(exe_dir + "/data/_main.cfg")) {
1073  auto_dir = exe_dir;
1074  }
1075  // cmake encourages creating a subdir at the root of the source
1076  // tree for the build, and the resulting binaries are found in it.
1077  else if(filesystem::file_exists(exe_dir + "/../data/_main.cfg")) {
1078  auto_dir = filesystem::normalize_path(exe_dir + "/..");
1079  }
1080  // In Windows debug builds, the EXE is placed away from the game data dir
1081  // (in projectfiles\VCx\Debug), but the working directory is set to the
1082  // game data dir. Thus, check if the working dir is the game data dir.
1083  else if(filesystem::file_exists(filesystem::get_cwd() + "/data/_main.cfg")) {
1084  auto_dir = filesystem::get_cwd();
1085  }
1086 
1087  if(!auto_dir.empty()) {
1088  if(!nobanner) std::cerr << "Automatically found a possible data directory at " << filesystem::sanitize_path(auto_dir) << '\n';
1089  game_config::path = auto_dir;
1090  }
1091  }
1092 
1093  const int res = do_gameloop(args);
1094  safe_exit(res);
1095  } catch(const boost::program_options::error& e) {
1096  std::cerr << "Error in command line: " << e.what() << '\n';
1097  error_exit(1);
1098  } catch(const CVideo::error& e) {
1099  std::cerr << "Could not initialize video.\n\n" << e.what() << "\n\nExiting.\n";
1100  error_exit(1);
1101  } catch(const font::error& e) {
1102  std::cerr << "Could not initialize fonts.\n\n" << e.what() << "\n\nExiting.\n";
1103  error_exit(1);
1104  } catch(const config::error& e) {
1105  std::cerr << e.message << "\n";
1106  error_exit(1);
1107  } catch(const gui::button::error&) {
1108  std::cerr << "Could not create button: Image could not be found\n";
1109  error_exit(1);
1110  } catch(const CVideo::quit&) {
1111  // just means the game should quit
1112  } catch(const return_to_play_side_exception&) {
1113  std::cerr << "caught return_to_play_side_exception, please report this bug (quitting)\n";
1114  } catch(const quit_game_exception&) {
1115  std::cerr << "caught quit_game_exception (quitting)\n";
1116  } catch(const wml_exception& e) {
1117  std::cerr << "WML exception:\nUser message: " << e.user_message << "\nDev message: " << e.dev_message << '\n';
1118  error_exit(1);
1119  } catch(const wfl::formula_error& e) {
1120  std::cerr << e.what() << "\n\nGame will be aborted.\n";
1121  error_exit(1);
1122  } catch(const sdl::exception& e) {
1123  std::cerr << e.what();
1124  error_exit(1);
1125  } catch(const game::error&) {
1126  // A message has already been displayed.
1127  error_exit(1);
1128  } catch(const std::bad_alloc&) {
1129  std::cerr << "Ran out of memory. Aborted.\n";
1130  error_exit(ENOMEM);
1131 #if !defined(NO_CATCH_AT_GAME_END)
1132  } catch(const std::exception& e) {
1133  // Try to catch unexpected exceptions.
1134  std::cerr << "Caught general '" << typeid(e).name() << "' exception:\n" << e.what() << std::endl;
1135  error_exit(1);
1136  } catch(const std::string& e) {
1137  std::cerr << "Caught a string thrown as an exception:\n" << e << std::endl;
1138  error_exit(1);
1139  } catch(const char* e) {
1140  std::cerr << "Caught a string thrown as an exception:\n" << e << std::endl;
1141  error_exit(1);
1142  } catch(...) {
1143  // Ensure that even when we terminate with `throw 42`, the exception
1144  // is caught and all destructors are actually called. (Apparently,
1145  // some compilers will simply terminate without calling destructors if
1146  // the exception isn't caught.)
1147  std::cerr << "Caught unspecified general exception. Terminating." << std::endl;
1148  error_exit(1);
1149 #endif
1150  }
1151 
1152  return 0;
1153 } // end main
1154 
1155 /**
1156  * @page GUIToolkitWML GUIToolkitWML
1157  * @tableofcontents
1158  *
1159  * @section State State
1160  *
1161  * A state contains the info what to do in a state. At the moment this is rather focussed on the drawing part, might change later. Keys:
1162  * Key |Type |Default |Description
1163  * -----------------|------------------------------------|---------|-------------
1164  * draw | @ref guivartype_section "section" |mandatory|Section with drawing directions for a canvas.
1165  *
1166  * @section WindowDefinition Window Definition
1167  *
1168  * A window defines how a window looks in the game.
1169  * Key |Type |Default |Description
1170  * -----------------|------------------------------------|---------|-------------
1171  * id | @ref guivartype_string "string" |mandatory|Unique id for this window.
1172  * description | @ref guivartype_t_string "t_string"|mandatory|Unique translatable name for this window.
1173  * resolution | @ref guivartype_section "section" |mandatory|The definitions of the window in various resolutions.
1174  *
1175  * @section Cell Cell
1176  *
1177  * Every grid cell has some cell configuration values and one widget in the grid cell.
1178  * Here we describe the what is available more information about the usage can be found at @ref GUILayout.
1179  *
1180  * Key |Type |Default |Description
1181  * --------------------|----------------------------------------|---------|-------------
1182  * id | @ref guivartype_string "string" |"" |A grid is a widget and can have an id. This isn't used that often, but is allowed.
1183  * linked_group | @ref guivartype_string "string" |0 |.
1184  *
1185  * @section RowValues Row Values
1186  *
1187  * For every row the following variables are available:
1188  * Key |Type |Default |Description
1189  * --------------------|----------------------------------------|---------|-------------
1190  * grow_factor | @ref guivartype_unsigned "unsigned" |0 |The grow factor for a row.
1191  *
1192  * @section CellValues Cell Values
1193  *
1194  * For every column the following variables are available:
1195  * Key |Type |Default |Description
1196  * --------------------|----------------------------------------|---------|-------------
1197  * grow_factor | @ref guivartype_unsigned "unsigned" |0 |The grow factor for a column, this value is only read for the first row.
1198  * border_size | @ref guivartype_unsigned "unsigned" |0 |The border size for this grid cell.
1199  * border | @ref guivartype_border "border" |"" |Where to place the border in this grid cell.
1200  * vertical_alignment | @ref guivartype_v_align "v_align" |"" |The vertical alignment of the widget in the grid cell. (This value is ignored if vertical_grow is true.)
1201  * horizontal_alignment| @ref guivartype_h_align "h_align" |"" |The horizontal alignment of the widget in the grid cell.(This value is ignored if horizontal_grow is true.)
1202  * vertical_grow | @ref guivartype_bool "bool" |false |Does the widget grow in vertical direction when the grid cell grows in the vertical direction. This is used if the grid cell is wider as the best width for the widget.
1203  * horizontal_grow | @ref guivartype_bool "bool" |false |Does the widget grow in horizontal direction when the grid cell grows in the horizontal direction. This is used if the grid cell is higher as the best width for the widget.
1204  */
1205 
1206 /**
1207  * @page GUILayout GUILayout
1208  * @tableofcontents
1209  *
1210  * @section Abstract Abstract
1211  *
1212  * In the widget library the placement and sizes of elements is determined by
1213  * a grid. Therefore most widgets have no fixed size.
1214  *
1215  * @section Theory Theory
1216  *
1217  * We have two examples for the addon dialog, the first example the lower
1218  * buttons are in one grid, that means if the remove button gets wider
1219  * (due to translations) the connect button (4.1 - 2.2) will be aligned
1220  * to the left of the remove button. In the second example the connect
1221  * button will be partial underneath the remove button.
1222  *
1223  * A grid exists of x rows and y columns for all rows the number of columns
1224  * needs to be the same, there is no column (nor row) span. If spanning is
1225  * required place a nested grid to do so. In the examples every row has 1 column
1226  * but rows 3, 4 (and in the second 5) have a nested grid to add more elements
1227  * per row.
1228  *
1229  * In the grid every cell needs to have a widget, if no widget is wanted place
1230  * the special widget @a spacer. This is a non-visible item which normally
1231  * shouldn't have a size. It is possible to give a spacer a size as well but
1232  * that is discussed elsewhere.
1233  *
1234  * Every row and column has a @a grow_factor, since all columns in a grid are
1235  * aligned only the columns in the first row need to define their grow factor.
1236  * The grow factor is used to determine with the extra size available in a
1237  * dialog. The algorithm determines the extra size work like this:
1238  *
1239  * * determine the extra size
1240  * * determine the sum of the grow factors
1241  * * if this sum is 0 set the grow factor for every item to 1 and sum to sum of items.
1242  * * divide the extra size with the sum of grow factors
1243  * * for every item multiply the grow factor with the division value
1244  *
1245  * eg:
1246  * * extra size 100
1247  * * grow factors 1, 1, 2, 1
1248  * * sum 5
1249  * * division 100 / 5 = 20
1250  * * extra sizes 20, 20, 40, 20
1251  *
1252  * Since we force the factors to 1 if all zero it's not possible to have non
1253  * growing cells. This can be solved by adding an extra cell with a spacer and a
1254  * grow factor of 1. This is used for the buttons in the examples.
1255  *
1256  * Every cell has a @a border_size and @a border the @a border_size is the
1257  * number of pixels in the cell which aren't available for the widget. This is
1258  * used to make sure the items in different cells aren't put side to side. With
1259  * @a border it can be determined which sides get the border. So a border is
1260  * either 0 or @a border_size.
1261  *
1262  * If the widget doesn't grow when there's more space available the alignment
1263  * determines where in the cell the widget is placed.
1264  *
1265  * @subsection AbstractExample Abstract Example
1266  *
1267  * |---------------------------------------|
1268  * | 1.1 |
1269  * |---------------------------------------|
1270  * | 2.1 |
1271  * |---------------------------------------|
1272  * | |-----------------------------------| |
1273  * | | 3.1 - 1.1 | 3.1 - 1.2 | |
1274  * | |-----------------------------------| |
1275  * |---------------------------------------|
1276  * | |-----------------------------------| |
1277  * | | 4.1 - 1.1 | 4.1 - 1.2 | 4.1 - 1.3 | |
1278  * | |-----------------------------------| |
1279  * | | 4.1 - 2.1 | 4.1 - 2.2 | 4.1 - 2.3 | |
1280  * | |-----------------------------------| |
1281  * |---------------------------------------|
1282  *
1283  *
1284  * 1.1 label : title
1285  * 2.1 label : description
1286  * 3.1 - 1.1 label : server
1287  * 3.1 - 1.2 text box : server to connect to
1288  * 4.1 - 1.1 spacer
1289  * 4.1 - 1.2 spacer
1290  * 4.1 - 1.3 button : remove addon
1291  * 4.1 - 2.1 spacer
1292  * 4.1 - 2.2 button : connect
1293  * 4.1 - 2.3 button : cancel
1294  *
1295  *
1296  * |---------------------------------------|
1297  * | 1.1 |
1298  * |---------------------------------------|
1299  * | 2.1 |
1300  * |---------------------------------------|
1301  * | |-----------------------------------| |
1302  * | | 3.1 - 1.1 | 3.1 - 1.2 | |
1303  * | |-----------------------------------| |
1304  * |---------------------------------------|
1305  * | |-----------------------------------| |
1306  * | | 4.1 - 1.1 | 4.1 - 1.2 | |
1307  * | |-----------------------------------| |
1308  * |---------------------------------------|
1309  * | |-----------------------------------| |
1310  * | | 5.1 - 1.1 | 5.1 - 1.2 | 5.1 - 2.3 | |
1311  * | |-----------------------------------| |
1312  * |---------------------------------------|
1313  *
1314  *
1315  * 1.1 label : title
1316  * 2.1 label : description
1317  * 3.1 - 1.1 label : server
1318  * 3.1 - 1.2 text box : server to connect to
1319  * 4.1 - 1.1 spacer
1320  * 4.1 - 1.2 button : remove addon
1321  * 5.1 - 1.1 spacer
1322  * 5.1 - 1.2 button : connect
1323  * 5.1 - 1.3 button : cancel
1324  *
1325  * @subsection ConcreteExample Concrete Example
1326  *
1327  * This is the code needed to create the skeleton for the structure the extra
1328  * flags are omitted.
1329  *
1330  * [grid]
1331  * [row]
1332  * [column]
1333  * [label]
1334  * # 1.1
1335  * [/label]
1336  * [/column]
1337  * [/row]
1338  * [row]
1339  * [column]
1340  * [label]
1341  * # 2.1
1342  * [/label]
1343  * [/column]
1344  * [/row]
1345  * [row]
1346  * [column]
1347  * [grid]
1348  * [row]
1349  * [column]
1350  * [label]
1351  * # 3.1 - 1.1
1352  * [/label]
1353  * [/column]
1354  * [column]
1355  * [text_box]
1356  * # 3.1 - 1.2
1357  * [/text_box]
1358  * [/column]
1359  * [/row]
1360  * [/grid]
1361  * [/column]
1362  * [/row]
1363  * [row]
1364  * [column]
1365  * [grid]
1366  * [row]
1367  * [column]
1368  * [spacer]
1369  * # 4.1 - 1.1
1370  * [/spacer]
1371  * [/column]
1372  * [column]
1373  * [spacer]
1374  * # 4.1 - 1.2
1375  * [/spacer]
1376  * [/column]
1377  * [column]
1378  * [button]
1379  * # 4.1 - 1.3
1380  * [/button]
1381  * [/column]
1382  * [/row]
1383  * [row]
1384  * [column]
1385  * [spacer]
1386  * # 4.1 - 2.1
1387  * [/spacer]
1388  * [/column]
1389  * [column]
1390  * [button]
1391  * # 4.1 - 2.2
1392  * [/button]
1393  * [/column]
1394  * [column]
1395  * [button]
1396  * # 4.1 - 2.3
1397  * [/button]
1398  * [/column]
1399  * [/row]
1400  * [/grid]
1401  * [/column]
1402  * [/row]
1403  * [/grid]
1404  */
1405 
1406 /**
1407  * @defgroup GUIWidgetWML GUIWidgetWML
1408  * In various parts of the GUI there are several variables types in use. This section describes them.
1409  *
1410  * Below are the simple types which have one value or a short list of options:
1411  * Variable |description
1412  * ------------------------------------------------|-----------
1413  * @anchor guivartype_unsigned unsigned |Unsigned number (positive whole numbers and zero).
1414  * @anchor guivartype_f_unsigned f_unsigned |Unsigned number or formula returning an unsigned number.
1415  * @anchor guivartype_int int |Signed number (whole numbers).
1416  * @anchor guivartype_f_int f_int |Signed number or formula returning an signed number.
1417  * @anchor guivartype_bool bool |A boolean value accepts the normal values as the rest of the game.
1418  * @anchor guivartype_f_bool f_bool |Boolean value or a formula returning a boolean value.
1419  * @anchor guivartype_string string |A text.
1420  * @anchor guivartype_t_string t_string |A translatable string.
1421  * @anchor guivartype_f_tstring f_tstring |Formula returning a translatable string.
1422  * @anchor guivartype_function function |A string containing a set of function definition for the formula language.
1423  * @anchor guivartype_color color |A string which contains the color, this a group of 4 numbers between 0 and 255 separated by a comma. The numbers are red component, green component, blue component and alpha. A color of 0 is not available. An alpha of 255 is fully transparent. Omitted values are set to 0.
1424  * @anchor guivartype_font_style font_style |A string which contains the style of the font:<ul><li>normal</li><li>bold</li><li>italic</li><li>underlined</li></ul>Since SDL has problems combining these styles only one can be picked. Once SDL will allow multiple options, this type will be transformed to a comma separated list. If empty we default to the normal style. Since the render engine is replaced by Pango markup this field will change later on. Note widgets that allow marked up text can use markup to change the font style.
1425  * @anchor guivartype_v_align v_align |Vertical alignment; how an item is aligned vertically in the available space. Possible values:<ul><li>top</li><li>bottom</li><li>center</li></ul>When nothing is set or an another value as in the list the item is centered.
1426  * @anchor guivartype_h_align h_align |Horizontal alignment; how an item is aligned horizontal in the available space. Possible values:<ul><li>left</li><li>right</li><li>center</li></ul>
1427  * @anchor guivartype_f_h_align f_h_align |A horizontal alignment or a formula returning a horizontal alignment.
1428  * @anchor guivartype_border border |Comma separated list of borders to use. Possible values:<ul><li>left</li><li>right</li><li>top</li><li>bottom</li><li>all alias for "left, right, top, bottom"</li></ul>
1429  * @anchor guivartype_scrollbar_mode scrollbar_mode|How to show the scrollbar of a widget. Possible values:<ul><li>always - The scrollbar is always shown, regardless whether it's required or not.</li><li>never - The scrollbar is never shown, even not when needed. (Note when setting this mode dialogs might not properly fit anymore).</li><li>auto - Shows the scrollbar when needed. The widget will reserve space for the scrollbar, but only show when needed.</li><li>initial_auto - Like auto, but when the scrollbar is not needed the space is not reserved.</li></ul>Use auto when the list can be changed dynamically eg the game list in the lobby. For optimization you can also use auto when you really expect a scrollbar, but don't want it to be shown when not needed eg the language list will need a scrollbar on most screens.
1430  * @anchor guivartype_resize_mode resize_mode |Determines how an image is resized. Possible values:<ul><li>scale - The image is scaled.</li><li>stretch - The first row or column of pixels is copied over the entire image. (Can only be used to scale resize in one direction, else falls back to scale.)</li><li>tile - The image is placed several times until the entire surface is filled. The last images are truncated.</li></ul>
1431  * @anchor guivartype_grow_direction grow_direction|Determines how an image is resized. Possible values:<ul><li>scale - The image is scaled.</li><li>stretch - The first row or column of pixels is copied over the entire image. (Can only be used to scale resize in one direction, else falls back to scale.)</li><li>tile - The image is placed several times until the entire surface is filled. The last images are truncated.</li></ul>
1432  *
1433  * For more complex parts, there are sections. Sections contain of several lines of WML and can have sub sections. For example a grid has sub sections which contain various widgets. Here's the list of sections:
1434  * Variable |description
1435  * ------------------------------------------------|-----------
1436  * @anchor guivartype_section section |A generic section. The documentation about the section should describe the section in further detail.
1437  * @anchor guivartype_grid grid |A grid contains several widgets.
1438  * @anchor guivartype_config config |.
1439  *
1440  * Every widget has some parts in common. First of all, every definition has the following fields:
1441  * Key |Type |Default |Description
1442  * -------------|------------------------------------|---------|-----------
1443  * id | @ref guivartype_string "string" |mandatory|Unique id for this gui (theme).
1444  * description | @ref guivartype_t_string "t_string"|mandatory|Unique translatable name for this gui.
1445  * resolution | @ref guivartype_section "section" |mandatory|The definitions of the widget in various resolutions.
1446  * Inside a grid (which is inside all container widgets) a widget is instantiated. With this instantiation some more variables of a widget can be tuned.
1447  */
1448 
1449 /**
1450  * @defgroup GUICanvasWML GUICanvasWML
1451  *
1452  * A canvas is a blank drawing area on which the user can draw several shapes.
1453  * The drawing is done by adding WML structures to the canvas.
1454  *
1455  * @section PreCommit Pre-commit
1456  *
1457  * This section contains the pre commit functions.
1458  * These functions will be executed before the drawn canvas is applied on top of the normal background.
1459  * There should only be one pre commit section and its order regarding the other shapes doesn't matter.
1460  * The function has effect on the entire canvas, it's not possible to affect only a small part of the canvas.
1461  *
1462  * @subsection Blur Blur
1463  *
1464  * Blurs the background before applying the canvas. This doesn't make sense if the widget isn't semi-transparent.
1465  *
1466  * Keys:
1467  * Key |Type |Default |Description
1468  * -------------|------------------------------------|---------|-----------
1469  * depth | @ref guivartype_unsigned "unsigned"|0 |The depth to blur.
1470  */
1471 
1472 /**
1473  * @defgroup GUIWindowDefinitionWML GUIWindowDefinitionWML
1474  *
1475  * The window definition define how the windows shown in the dialog look.
1476  */
void empty_playlist()
Definition: sound.cpp:611
bool log_precise_timestamps
True if –log-precise was given on the command line.
std::optional< std::string > preprocess_path
Path to parse that was given to the –preprocess option.
#define error_exit(res)
Definition: wesnoth.cpp:954
static void wesnoth_terminate_handler(int)
Definition: wesnoth.cpp:938
std::vector< Reg > reg_vec
Definition: context.hpp:39
std::optional< std::string > output_file
Output filename for WML diff or preprocessing.
void set_callback(const std::string &name, callback_function)
Definition: context.cpp:51
std::optional< std::string > preprocess_output_macros
Non-empty if –preprocess-output-macros was given on the command line.
static int handle_validate_command(const std::string &file, abstract_validator &validator, const std::vector< std::string > &defines)
Definition: wesnoth.cpp:338
void bind_textdomain(const char *domain, const char *directory, const char *)
Definition: gettext.cpp:430
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:953
bool using_own_console()
Returns true if a console was allocated by the Wesnoth process.
void write(const config &cfg)
bool play_multiplayer(mp_mode mode)
void stop_music()
Definition: sound.cpp:556
void set(CURSOR_TYPE type)
Use the default parameter to reset cursors.
Definition: cursor.cpp:175
std::string library_versions_report()
Produce a plain-text report of library versions suitable for stdout/stderr.
Definition: build_info.cpp:636
static void bzip2_encode(const std::string &input_file, const std::string &output_file)
Definition: wesnoth.cpp:209
static void bzip2_decode(const std::string &input_file, const std::string &output_file)
Definition: wesnoth.cpp:214
Interfaces for manipulating version numbers of engine, add-ons, etc.
static lg::log_domain log_preprocessor("preprocessor")
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
std::string optional_features_report()
Produce a plain-text report of features suitable for stdout/stderr.
Definition: build_info.cpp:641
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:40
bool noaddons
True if –noaddons was given on the command line.
Exception used to escape form the ai or ui code to playsingle_controller::play_side.
void set_user_data_dir(std::string newprefdir)
Definition: filesystem.cpp:608
static bool file_exists(const bfs::path &fpath)
Definition: filesystem.cpp:263
child_itors child_range(config_key_type key)
Definition: config.cpp:356
bool userdata_path
True if –userdata-path was given on the command line.
static void gzip_decode(const std::string &input_file, const std::string &output_file)
Definition: wesnoth.cpp:204
static void progress(loading_stage stage=loading_stage::none)
filesystem::scoped_istream istream_file(const std::string &fname, bool treat_failure_as_error)
std::string user_message
The message for the user explaining what went wrong.
This class implements the title screen.
std::optional< std::string > preprocess_target
Target (output) path that was given to the –preprocess option.
std::optional< std::string > preprocess_input_macros
Non-empty if –preprocess-input-macros was given on the command line.
void fresh_stats()
Definition: statistics.cpp:782
Type that can be thrown as an exception to quit to desktop.
Definition: video.hpp:245
std::optional< std::string > userconfig_dir
Non-empty if –userconfig-dir was given on the command line.
void preprocess_resource(const std::string &res_name, preproc_map *defines_map, bool write_cfg, bool write_plain_cfg, const std::string &parent_directory)
std::vector< std::string > unit_test
Non-empty if –unit was given on the command line.
void early_log_file_setup(bool disable)
Sets up the initial temporary log file.
Don&#39;t reload if the previous defines equal the new defines.
static void safe_exit(int res)
Definition: wesnoth.cpp:144
std::string normalize_path(const std::string &fpath, bool normalize_separators, bool resolve_dot_entries)
Returns the absolute path of a file.
Contains the exception interfaces used to signal completion of a scenario, campaign or turn...
bool show(const unsigned auto_close_time=0)
Shows the window.
Definitions for the interface to Wesnoth Markup Language (WML).
static void decode(const std::string &input_file, const std::string &output_file)
Definition: wesnoth.cpp:180
std::string diff_left
Files for diffing or patching.
const std::string name_
Definition: validator.hpp:99
bool preprocess
True if –preprocess was given on the command line.
bool broke_strict()
Definition: log.cpp:169
config get_diff(const config &c) const
A function to get the differences between this object, and &#39;c&#39;, as another config object...
Definition: config.cpp:979
std::string get_cwd()
Definition: filesystem.cpp:876
One of the realizations of serialization/validator.hpp abstract validator.
unsigned in
If equal to search_counter, the node is off the list.
Used in parsing config file.
Definition: validator.hpp:35
static void warn_early_init_failure()
Print an alert and instructions to stderr about early initialization errors.
Definition: wesnoth.cpp:608
bool report
True if –report was given on the command line.
static void check_fpu()
Definition: wesnoth.cpp:684
std::optional< std::string > gzip
Non-empty if –gzip was given on the command line.
void read(config &cfg, std::istream &in, abstract_validator *validator)
Definition: parser.cpp:626
Class for writing a config out to a file in pieces.
std::string get_user_data_dir()
Definition: filesystem.cpp:789
std::optional< unsigned int > rng_seed
RNG seed specified by –rng-seed option.
std::optional< std::vector< std::pair< int, std::string > > > log
Contains parsed arguments of –log-* (e.g.
std::string get_intl_dir()
static lg::log_domain log_config("config")
bool strict_validation_enabled
Definition: validator.cpp:19
void init()
Initializes the GUI subsystems.
Definition: gui.cpp:35
const game_config_view & game_config() const
#define LOG_GENERAL
Definition: wesnoth.cpp:136
std::optional< std::string > bunzip2
Non-empty if –bunzip2 was given on the command line.
void enable_native_console_output()
Switches to using a native console instead of log file redirection.
bool is_directory(const std::string &fname)
Returns true if the given file is a directory.
std::unique_ptr< std::istream > scoped_istream
Definition: filesystem.hpp:36
std::string path
Definition: game_config.cpp:38
std::string build_arch()
Obtain the processor architecture for this build.
Definition: build_info.cpp:302
void set_default_textdomain(const char *domain)
Definition: gettext.cpp:439
void refresh_addon_version_info_cache()
Refreshes the per-session cache of add-on&#39;s version information structs.
Definition: manager.cpp:355
std::string sanitize_path(const std::string &path)
Sanitizes a path to remove references to the user&#39;s name.
void apply_diff(const config &diff, bool track=false)
A function to apply a diff config onto this config object.
Definition: config.cpp:1100
const char * what() const noexcept
Definition: exceptions.hpp:35
bool userconfig_path
True if –userconfig-path was given on the command line.
static int writer(lua_State *L, const void *b, size_t size, void *ud)
Definition: lstrlib.cpp:221
std::optional< std::string > bzip2
Non-empty if –bzip2 was given on the command line.
static void handle_preprocess_command(const commandline_options &cmdline_opts)
Definition: wesnoth.cpp:219
bool nobanner
True if –nobanner was given on the command line.
lu_byte right
Definition: lparser.cpp:1227
int main(int argc, char **argv)
Definition: wesnoth.cpp:961
bool load_font_config()
std::optional< std::string > logdomains
Non-empty if –logdomains was given on the command line.
std::optional< std::string > render_image
Image path to render.
#define PACKAGE
Definition: wesconfig.h:23
Helper class, don&#39;t construct this directly.
static int do_gameloop(const std::vector< std::string > &args)
Setups the game environment and enters the titlescreen or game loops.
Definition: wesnoth.cpp:713
std::string dev_message
The message for developers telling which problem was triggered, this shouldn&#39;t be translated...
static void gzip_encode(const std::string &input_file, const std::string &output_file)
Definition: wesnoth.cpp:199
std::unique_ptr< std::ostream > scoped_ostream
Definition: filesystem.hpp:37
bool is_gzip_file(const std::string &filename)
Returns true if the file ends with &#39;.gz&#39;.
Some defines: VERSION, PACKAGE, MIN_SAVEGAME_VERSION.
static void handle_lua_script_args(game_launcher *game, commandline_options &)
Handles the lua script command line arguments if present.
Definition: wesnoth.cpp:621
std::string get_exe_dir()
Definition: filesystem.cpp:904
static void init_locale()
I would prefer to setup locale first so that early error messages can get localized, but we need the game_launcher initialized to have filesystem::get_intl_dir() to work.
Definition: wesnoth.cpp:584
Log file control routines for Windows.
std::size_t i
Definition: function.cpp:940
void set_user_config_dir(const std::string &newconfigdir)
Definition: filesystem.cpp:746
bool debug_lua
True if –debug-lua was given in the commandline.
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...
Default, unset return value.
Definition: retval.hpp:31
const std::string revision
void set_strict_severity(int severity)
Definition: log.cpp:159
static int process_command_args(const commandline_options &cmdline_opts)
Process commandline-arguments.
Definition: wesnoth.cpp:363
bool strict_lua
True if –strict-lua was given in the commandline.
std::optional< std::string > gunzip
Non-empty if –gunzip was given on the command line.
An exception object used when an IO error occurs.
Definition: filesystem.hpp:45
structure which will hide all current floating labels, and cause floating labels instantiated after i...
std::optional< std::string > userdata_dir
Non-empty if –userdata-dir was given on the command line.
std::string title_music
Declarations for File-IO.
Contains a basic exception class for SDL operations.
const version_info wesnoth_version(VERSION)
static map_location::DIRECTION sw
bool set_log_domain_severity(const std::string &name, int severity)
Definition: log.cpp:116
std::optional< std::string > data_dir
Non-empty if –data-dir was given on the command line.
bool data_path
True if –data-path was given on the command line.
std::vector< std::string > read_argv([[maybe_unused]] int argc, [[maybe_unused]] char **argv)
std::string get_user_config_dir()
Definition: filesystem.cpp:760
bool screenshot
True if –screenshot was given on the command line.
bool is_bzip2_file(const std::string &filename)
Returns true if the file ends with &#39;.bz2&#39;.
int get_retval() const
Returns the cached window exit code.
static void display(std::function< void()> f)
std::vector< aReg > areg_vec
Definition: context.hpp:40
#define LOG_PREPROC
Definition: wesnoth.cpp:139
Contains the SDL_Rect helper code.
double t
Definition: astarsearch.cpp:64
Base class for all the errors encountered by the engine.
Definition: exceptions.hpp:27
void play_music_config(const config &music_node, bool allow_interrupt_current_track, int i)
Definition: sound.cpp:704
lu_byte left
Definition: lparser.cpp:1226
std::string list_logdomains(const std::string &filter)
Definition: log.cpp:149
bool version
True if –version was given on the command line.
#define LOG_CONFIG
Definition: wesnoth.cpp:134
Standard logging facilities (interface).
std::string str() const
Serializes the version number into string form.
std::string message
Definition: exceptions.hpp:29
std::optional< std::string > validate_with
Non-empty if –use-schema was given on the command line.
std::optional< std::string > validate_wml
Non-empty if –validate was given on the command line.
bool strict_validation
True if –strict-validation was given on the command line.
std::map< std::string, struct preproc_define > preproc_map
#define e
std::optional< std::vector< std::string > > preprocess_defines
Defines that were given to the –preprocess option.
static void encode(const std::string &input_file, const std::string &output_file)
Definition: wesnoth.cpp:152
Realization of serialization/validator.hpp abstract validator.
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:59
filesystem::scoped_istream preprocess_file(const std::string &fname, preproc_map *defines)
Function to use the WML preprocessor on a file.
static preproc_map::value_type read_pair(const config &)
int wesnoth_main(int argc, char **argv)
std::optional< std::string > validate_schema
Non-empty if –validate-schema was given on the command line.
bool init_game_config(FORCE_RELOAD_CONFIG force_reload)
bool help
True if –help was given on the command line.
bool init_lua_script()
const config & child(config_key_type key) const
std::string directory_name(const std::string &file)
Returns the directory name of a file, with filename stripped.
std::string full_build_report()
Produce a bug report-style info dump.
Definition: build_info.cpp:646
std::string wesnoth_program_dir
Definition: game_config.cpp:47
void precise_timestamps(bool pt)
Definition: log.cpp:74
void set_debug(bool new_debug)
void play_slice()
Definition: context.cpp:96
filesystem::scoped_ostream ostream_file(const std::string &fname, bool create_directory)