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