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