The Battle for Wesnoth  1.15.2+dev
game_launcher.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #include "game_launcher.hpp"
16 #include "game_errors.hpp"
17 
18 #include "ai/manager.hpp" // for manager
20 #include "commandline_options.hpp" // for commandline_options
21 #include "config.hpp" // for config, etc
22 #include "cursor.hpp" // for set, CURSOR_TYPE::NORMAL
23 #include "exceptions.hpp" // for error
24 #include "filesystem.hpp" // for get_user_config_dir, etc
25 #include "game_classification.hpp" // for game_classification, etc
26 #include "game_config.hpp" // for path, no_delay, revision, etc
27 #include "game_config_manager.hpp" // for game_config_manager
28 #include "game_end_exceptions.hpp" // for LEVEL_RESULT, etc
29 #include "generators/map_generator.hpp" // for mapgen_exception
30 #include "gettext.hpp" // for _
32 #include "gui/dialogs/language_selection.hpp" // for language_selection
34 #include "gui/dialogs/message.hpp" //for show error message
36 #include "gui/dialogs/multiplayer/mp_host_game_prompt.hpp" //for host game prompt
38 #include "gui/dialogs/outro.hpp"
40 #include "gui/dialogs/transient_message.hpp" // for show_transient_message
41 #include "gui/dialogs/title_screen.hpp" // for show_debug_clock_button
42 #include "gui/widgets/settings.hpp" // for new_widgets
43 #include "gui/widgets/retval.hpp" // for window, etc
44 #include "language.hpp" // for language_def, etc
45 #include "log.hpp" // for LOG_STREAM, logger, general, etc
46 #include "map/exception.hpp"
47 #include "game_initialization/multiplayer.hpp" // for start_client, etc
49 #include "game_initialization/playcampaign.hpp" // for play_game, etc
50 #include "preferences/general.hpp" // for disable_preferences_save, etc
51 #include "preferences/display.hpp"
52 #include "savegame.hpp" // for clean_saves, etc
53 #include "save_index.hpp"
55 #include "sdl/surface.hpp" // for surface
56 #include "serialization/compression.hpp" // for format::NONE
57 #include "serialization/string_utils.hpp" // for split
58 #include "game_initialization/singleplayer.hpp" // for sp_create_mode
59 #include "statistics.hpp"
60 #include "tstring.hpp" // for operator==, operator!=
61 #include "utils/general.hpp" // for clamp
62 #include "video.hpp" // for CVideo
64 #include "wml_exception.hpp" // for wml_exception
65 
66 #include <algorithm> // for copy, max, min, stable_sort
67 #include <cstdlib> // for system
68 #include <iostream> // for operator<<, basic_ostream, etc
69 #include <new>
70 #include <utility> // for pair
71 #include <SDL2/SDL.h> // for SDL_INIT_JOYSTICK, etc
72 
73 #ifdef DEBUG_WINDOW_LAYOUT_GRAPHS
74 #include "gui/widgets/debug.hpp"
75 #endif
76 
77 // For wesnothd launch code.
78 #ifdef _WIN32
79 
80 #define WIN32_LEAN_AND_MEAN
81 #include <windows.h>
82 
83 #endif // _WIN32
84 
86 
87 static lg::log_domain log_config("config");
88 #define ERR_CONFIG LOG_STREAM(err, log_config)
89 #define WRN_CONFIG LOG_STREAM(warn, log_config)
90 #define LOG_CONFIG LOG_STREAM(info, log_config)
91 
92 #define LOG_GENERAL LOG_STREAM(info, lg::general())
93 #define WRN_GENERAL LOG_STREAM(warn, lg::general())
94 #define DBG_GENERAL LOG_STREAM(debug, lg::general())
95 
96 static lg::log_domain log_mp_create("mp/create");
97 #define DBG_MP LOG_STREAM(debug, log_mp_create)
98 
99 static lg::log_domain log_network("network");
100 #define ERR_NET LOG_STREAM(err, log_network)
101 
102 static lg::log_domain log_enginerefac("enginerefac");
103 #define LOG_RG LOG_STREAM(info, log_enginerefac)
104 
105 game_launcher::game_launcher(const commandline_options& cmdline_opts, const char *appname) :
106  cmdline_opts_(cmdline_opts),
107  video_(new CVideo()),
108  font_manager_(),
109  prefs_manager_(),
110  image_manager_(),
111  main_event_context_(),
112  hotkey_manager_(),
113  music_thinker_(),
114  music_muter_(),
115  test_scenarios_{"test"},
116  screenshot_map_(),
118  state_(),
119  play_replay_(false),
121  jump_to_multiplayer_(false),
122  jump_to_campaign_(false, false, -1, "", ""),
123  jump_to_editor_(false),
124  load_data_()
125 {
126  bool no_music = false;
127  bool no_sound = false;
128 
129  // The path can be hardcoded and it might be a relative path.
130  if(!game_config::path.empty() &&
131 #ifdef _WIN32
132  // use c_str to ensure that index 1 points to valid element since c_str() returns null-terminated string
133  game_config::path.c_str()[1] != ':'
134 #else
135  game_config::path[0] != '/'
136 #endif
137  )
138  {
140  // font_manager_.update_font_path()
141  // To update the font path, destroy and recreate the manager
143  new (&font_manager_) font::manager();
144  }
145 
146  const std::string app_basename = filesystem::base_name(appname);
147  jump_to_editor_ = app_basename.find("editor") != std::string::npos;
148 
149  if (cmdline_opts_.core_id) {
151  }
152  if (cmdline_opts_.campaign) {
153  jump_to_campaign_.jump_ = true;
155  std::cerr << "selected campaign id: [" << jump_to_campaign_.campaign_id_ << "]\n";
156 
159  std::cerr << "selected difficulty: [" << jump_to_campaign_.difficulty_ << "]\n";
160  }
161  else
162  jump_to_campaign_.difficulty_ = -1; // let the user choose the difficulty
163 
166  std::cerr << "selected scenario id: [" << jump_to_campaign_.scenario_id_ << "]\n";
167  }
168 
171  }
172  }
173  if (cmdline_opts_.clock)
175  if (cmdline_opts_.debug) {
177  game_config::mp_debug = true;
178  }
179 #ifdef DEBUG_WINDOW_LAYOUT_GRAPHS
180  if (cmdline_opts_.debug_dot_domain)
181  gui2::debug_layout_graph::set_domain (*cmdline_opts_.debug_dot_domain);
182  if (cmdline_opts_.debug_dot_level)
184 #endif
185  if (cmdline_opts_.editor)
186  {
187  jump_to_editor_ = true;
188  if (!cmdline_opts_.editor->empty())
189  load_data_.reset(new savegame::load_game_metadata{ savegame::save_index_class::default_saves_dir(), *cmdline_opts_.editor });
190  }
191  if (cmdline_opts_.fps)
194  video().set_fullscreen(true);
195  if (cmdline_opts_.load)
197  if (cmdline_opts_.max_fps) {
198  int fps = utils::clamp(*cmdline_opts_.max_fps, 1, 1000);
199  fps = 1000 / fps;
200  // increase the delay to avoid going above the maximum
201  if(1000 % fps != 0) {
202  ++fps;
203  }
205  }
207  no_sound = true;
209  }
211  gui2::new_widgets = true;
213  game_config::no_delay = true;
215  no_music = true;
217  no_sound = true;
219  const int xres = std::get<0>(*cmdline_opts_.resolution);
220  const int yres = std::get<1>(*cmdline_opts_.resolution);
221  if(xres > 0 && yres > 0) {
222  preferences::_set_resolution(point(xres, yres));
224  }
225  }
227  //TODO it could be simplified to use cmdline_opts_ directly if there is no other way to enter screenshot mode
230  no_sound = true;
232  }
233  if (cmdline_opts_.server){
234  jump_to_multiplayer_ = true;
235  //Do we have any server specified ?
236  if (!cmdline_opts_.server->empty())
238  else //Pick the first server in config
239  {
242  else
243  multiplayer_server_ = "";
244  }
245  if (cmdline_opts_.username) {
248  if (cmdline_opts_.password) {
250  preferences::set_password(*cmdline_opts.server, *cmdline_opts.username, *cmdline_opts_.password);
251  }
252  }
253  }
254  if (cmdline_opts_.test)
255  {
256  if (!cmdline_opts_.test->empty())
258  }
259  if (!cmdline_opts_.unit_test.empty())
260  {
262  }
264  video().set_fullscreen(false);
266  load_data_->show_replay = true;
269 
270  std::cerr
271  << "\nData directory: " << filesystem::sanitize_path(game_config::path)
272  << "\nUser configuration directory: " << filesystem::sanitize_path(filesystem::get_user_config_dir())
273  << "\nUser data directory: " << filesystem::sanitize_path(filesystem::get_user_data_dir())
274  << "\nCache directory: " << filesystem::sanitize_path(filesystem::get_cache_dir())
275  << '\n';
276  std::cerr << '\n';
277 
278  // disable sound in nosound mode, or when sound engine failed to initialize
279  if (no_sound || ((preferences::sound_on() || preferences::music_on() ||
281  !sound::init_sound())) {
282  preferences::set_sound(false);
283  preferences::set_music(false);
286  }
287  else if (no_music) { // else disable the music in nomusic mode
288  preferences::set_music(false);
289  }
290 }
291 
293 {
294  if(!::load_language_list())
295  return false;
296 
297  language_def locale;
298  if(cmdline_opts_.language) {
299  std::vector<language_def> langs = get_languages();
300  for(const language_def & def : langs) {
301  if(def.localename == *cmdline_opts_.language) {
302  locale = def;
303  break;
304  }
305  }
306  if(locale.localename.empty()) {
307  std::cerr << "Language symbol '" << *cmdline_opts_.language << "' not found.\n";
308  return false;
309  }
310  } else {
311  locale = get_locale();
312  }
313  ::set_language(locale);
314 
315  return true;
316 }
317 
319 {
320  // Handle special commandline launch flags
323  std::cerr << "--nogui flag is only valid with --multiplayer or --screenshot or --plugin flags\n";
324  return false;
325  }
326  video().make_fake();
327  game_config::no_delay = true;
328  return true;
329  }
330 
331  // Initialize a new window
332  video().init_window();
333 
334  // Set window title and icon
336 
337 #if !(defined(__APPLE__))
338  surface icon(image::get_image("icons/icon-game.png", image::UNSCALED));
339  if(icon != nullptr) {
340 
341  video().set_window_icon(icon);
342  }
343 #endif
344  return true;
345 }
346 
348 {
349  bool error = false;
350 
351  std::cerr << "Checking lua scripts... ";
352 
354  plugins_manager::get()->get_kernel_base()->load_package(); //load the "package" package, so that scripts can get what packages they want
355  }
356 
357  // get the application lua kernel, load and execute script file, if script file is present
359  {
361 
362  if (!sf->fail()) {
363  /* Cancel all "jumps" to editor / campaign / multiplayer */
364  jump_to_multiplayer_ = false;
365  jump_to_editor_ = false;
366  jump_to_campaign_.jump_ = false;
367 
368  std::string full_script((std::istreambuf_iterator<char>(*sf)), std::istreambuf_iterator<char>());
369 
370  std::cerr << "\nRunning lua script: " << *cmdline_opts_.script_file << std::endl;
371 
373  } else {
374  std::cerr << "Encountered failure when opening script '" << *cmdline_opts_.script_file << "'\n";
375  error = true;
376  }
377  }
378 
380  {
381  std::string filename = *cmdline_opts_.plugin_file;
382 
383  std::cerr << "Loading a plugin file'" << filename << "'...\n";
384 
386 
387  try {
388  if (sf->fail()) {
389  throw std::runtime_error("failed to open plugin file");
390  }
391 
392  /* Cancel all "jumps" to editor / campaign / multiplayer */
393  jump_to_multiplayer_ = false;
394  jump_to_editor_ = false;
395  jump_to_campaign_.jump_ = false;
396 
397  std::string full_plugin((std::istreambuf_iterator<char>(*sf)), std::istreambuf_iterator<char>());
398 
400 
401  std::size_t i = pm.add_plugin(filename, full_plugin);
402 
403  for (std::size_t j = 0 ; j < pm.size(); ++j) {
404  std::cerr << j << ": " << pm.get_name(j) << " -- " << pm.get_detailed_status(j) << std::endl;
405  }
406 
407  std::cerr << "Starting a plugin...\n";
408  pm.start_plugin(i);
409 
410  for (std::size_t j = 0 ; j < pm.size(); ++j) {
411  std::cerr << j << ": " << pm.get_name(j) << " -- " << pm.get_detailed_status(j) << std::endl;
412  }
413 
414  plugins_context pc("init");
415 
416  for (std::size_t repeat = 0; repeat < 5; ++repeat) {
417  std::cerr << "Playing a slice...\n";
418  pc.play_slice();
419 
420  for (std::size_t j = 0 ; j < pm.size(); ++j) {
421  std::cerr << j << ": " << pm.get_name(j) << " -- " << pm.get_detailed_status(j) << std::endl;
422  }
423  }
424 
425  return true;
426  } catch (const std::exception & e) {
427  gui2::show_error_message(std::string("When loading a plugin, error:\n") + e.what());
428  error = true;
429  }
430  }
431 
432  if (!error) {
433  std::cerr << "ok\n";
434  }
435 
436  return !error;
437 }
438 
439 void game_launcher::set_test(const std::string& id)
440 {
441  state_.clear();
442  state_.classification().campaign_type = game_classification::CAMPAIGN_TYPE::TEST;
444 
445  state_.mp_settings().mp_era = "era_default";
446 
448  config {"next_scenario", id}
449  );
450 }
451 
453 {
454  // This first_time variable was added in 70f3c80a3e2 so that using the GUI
455  // menu to load a game works. That seems to have edge-cases, for example if
456  // you try to load a game a second time then Wesnoth exits.
457  static bool first_time = true;
458 
459  if(!cmdline_opts_.test) {
460  return true;
461  }
462  if(!first_time)
463  return false;
464 
465  first_time = false;
466 
467  if(test_scenarios_.size() == 0) {
468  // shouldn't happen, as test_scenarios_ is initialised to {"test"}
469  std::cerr << "Error in the test handling code" << std::endl;
470  return false;
471  }
472  if(test_scenarios_.size() > 1) {
473  std::cerr << "You can't run more than one unit test in interactive mode" << std::endl;
474  }
475  set_test(test_scenarios_.at(0));
476 
478  load_game_config_for_game(state_.classification());
479 
480  try {
481  campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types());
482  ccontroller.play_game();
483  } catch(const savegame::load_game_exception &e) {
484  load_data_.reset(new savegame::load_game_metadata(std::move(e.data_)));
485  return true;
486  }
487 
488  return false;
489 }
490 
491 /**
492  * Runs unit tests specified on the command line.
493  *
494  * If multiple unit tests were specified, then this will stop at the first test
495  * which returns a non-zero status.
496  */
497 // Same as play_test except that we return the results of play_game.
498 // \todo "same ... except" ... and many other changes, such as testing the replay
500 {
501  // There's no copy of play_test's first_time variable. That seems to be for handling
502  // the player loading a game via the GUI, which makes no sense in a non-interactive test.
503  if(cmdline_opts_.unit_test.empty()) {
505  }
506 
507  auto ret = unit_test_result::TEST_FAIL; // will only be returned if no test is run
508  for(const auto& scenario : test_scenarios_) {
509  set_test(scenario);
510  ret = single_unit_test();
511  const char* describe_result;
512  switch(ret) {
514  describe_result = "PASS TEST";
515  break;
517  describe_result = "FAIL TEST (INVALID REPLAY)";
518  break;
520  describe_result = "FAIL TEST (ERRORED REPLAY)";
521  break;
522  default:
523  describe_result = "FAIL TEST";
524  break;
525  }
526  std::cerr << describe_result << ": " << scenario << std::endl;
527  if (ret != unit_test_result::TEST_PASS) {
528  break;
529  }
530  }
531  return ret;
532 }
533 
535 {
537  load_game_config_for_game(state_.classification());
538 
539  try {
540  campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types(), true);
541  LEVEL_RESULT res = ccontroller.play_game();
542  if (!(res == LEVEL_RESULT::VICTORY) || lg::broke_strict()) {
544  }
545  } catch(const wml_exception& e) {
546  std::cerr << "Caught WML Exception:" << e.dev_message << std::endl;
548  }
549 
551 
553  return unit_test_result::TEST_PASS; //we passed, huzzah!
554 
556  save.save_game_automatic(false, "unit_test_replay"); //false means don't check for overwrite
557 
558  load_data_.reset(new savegame::load_game_metadata{ savegame::save_index_class::default_saves_dir(), "unit_test_replay" , "", true, true, false });
559 
560  if (!load_game()) {
561  std::cerr << "Failed to load the replay!" << std::endl;
562  return unit_test_result::TEST_FAIL_LOADING_REPLAY; //failed to load replay
563  }
564 
565  try {
566  campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types(), true);
567  LEVEL_RESULT res = ccontroller.play_replay();
568  if (!(res == LEVEL_RESULT::VICTORY) || lg::broke_strict()) {
569  std::cerr << "Observed failure on replay" << std::endl;
571  }
572  } catch(const wml_exception& e) {
573  std::cerr << "WML Exception while playing replay: " << e.dev_message << std::endl;
575  }
576 
577  return unit_test_result::TEST_PASS; //we passed, huzzah!
578 }
579 
581 {
583  return true;
584  }
585 
587 
589 
591  return false;
592 }
593 
595 {
597  return true;
598  }
599 
600  state_.classification().campaign_type = game_classification::CAMPAIGN_TYPE::MULTIPLAYER;
601  DBG_GENERAL << "Current campaign type: " << state_.classification().campaign_type << std::endl;
602 
603  try {
605  load_game_config_for_game(state_.classification());
606  } catch(const config::error& e) {
607  std::cerr << "Error loading game config: " << e.what() << std::endl;
608  return false;
609  }
610 
611  // A default output filename
612  std::string outfile = "wesnoth_image.bmp";
613 
614  // If a output path was given as an argument, use that instead
616  outfile = *cmdline_opts_.render_image_dst;
617  }
618 
620  exit(1);
621  }
622 
623  return false;
624 }
625 
627 {
628  return !!load_data_;
629 }
630 
632 {
633  assert(game_config_manager::get());
634 
635  DBG_GENERAL << "Current campaign type: " << state_.classification().campaign_type << std::endl;
636 
638  if (load_data_) {
639  std::unique_ptr<savegame::load_game_metadata> load_data = std::move(load_data_);
640  load.data() = std::move(*load_data);
641  }
642 
643  try {
644  if(!load.load_game()) {
645  return false;
646  }
647 
648  try {
650  load_game_config_for_game(state_.classification());
651  } catch(const config::error&) {
652  return false;
653  }
654 
655  load.set_gamestate();
656 
657  } catch(const config::error& e) {
658  if(e.message.empty()) {
659  gui2::show_error_message(_("The file you have tried to load is corrupt"));
660  }
661  else {
662  gui2::show_error_message(_("The file you have tried to load is corrupt: '") + e.message + '\'');
663  }
664  return false;
665  } catch(const wml_exception& e) {
666  e.show();
667  return false;
668  } catch(const filesystem::io_exception& e) {
669  if(e.message.empty()) {
670  gui2::show_error_message(_("File I/O Error while reading the game"));
671  } else {
672  gui2::show_error_message(_("File I/O Error while reading the game: '") + e.message + '\'');
673  }
674  return false;
675  } catch(const game::error& e) {
676  if(e.message.empty()) {
677  gui2::show_error_message(_("The file you have tried to load is corrupt"));
678  }
679  else {
680  gui2::show_error_message(_("The file you have tried to load is corrupt: '") + e.message + '\'');
681  }
682  return false;
683  }
684 
685  play_replay_ = load.data().show_replay;
686  LOG_CONFIG << "is middle game savefile: " << (state_.is_mid_game_save() ? "yes" : "no") << "\n";
687  LOG_CONFIG << "show replay: " << (play_replay_ ? "yes" : "no") << "\n";
688  // in case load.data().show_replay && !state_.is_mid_game_save()
689  // there won't be any turns to replay, but the
690  // user gets to watch the intro sequence again ...
691 
692  if(state_.is_mid_game_save() && load.data().show_replay)
693  {
695  }
696 
697  if(state_.classification().campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER) {
699  }
700 
701  if (load.data().cancel_orders) {
703  }
704 
705  return true;
706 }
707 
709 {
710  state_.clear();
711  state_.classification().campaign_type = game_classification::CAMPAIGN_TYPE::TUTORIAL;
712  state_.classification().campaign_define = "TUTORIAL";
713  state_.classification().campaign = "Tutorial";
714  state_.mp_settings().mp_era = "era_default";
716  config {"next_scenario", "tutorial"}
717  );
718 
719 }
720 
721 void game_launcher::mark_completed_campaigns(std::vector<config> &campaigns)
722 {
723  for (config &campaign : campaigns) {
724  campaign["completed"] = preferences::is_campaign_completed(campaign["id"]);
725  }
726 }
727 
729 {
730  state_.clear();
732  play_replay_ = false;
733 
735 }
736 
738 {
740 }
741 
743 {
745  if(new_campaign()) {
747  jump_to_campaign_.jump_ = false;
749  }else{
750  jump_to_campaign_.jump_ = false;
751  return false;
752  }
753  }
754  return true;
755 }
756 
758 {
760  jump_to_multiplayer_ = false;
762  ;
763  }else{
764  return false;
765  }
766  }
767  return true;
768 }
769 
771 {
772  if(jump_to_editor_){
773  jump_to_editor_ = false;
774  std::unique_ptr<savegame::load_game_metadata> load_data = std::move(load_data_);
775  if (start_editor(filesystem::normalize_path(load_data ? load_data->filename : "")) ==
777  {
778  return false;
779  }
780  }
781  return true;
782 }
783 
785 {
786  const std::string wesnothd_program =
789 
790  std::string config = filesystem::get_user_config_dir() + "/lan_server.cfg";
791  if (!filesystem::file_exists(config)) {
792  // copy file if it isn't created yet
794  }
795 
796 #ifndef _WIN32
797  std::string command = "\"" + wesnothd_program +"\" -c \"" + config + "\" -d -t 2 -T 5";
798 #else
799  // start wesnoth as background job
800  std::string command = "cmd /C start \"wesnoth server\" /B \"" + wesnothd_program + "\" -c \"" + config + "\" -t 2 -T 5";
801  // Make sure wesnothd's console output is visible on the console window by
802  // disabling SDL's stdio redirection code for this and future child
803  // processes. No need to bother cleaning this up because it's only
804  // meaningful to SDL applications during pre-main initialization.
805  SetEnvironmentVariableA("SDL_STDIO_REDIRECT", "0");
806 #endif
807  LOG_GENERAL << "Starting wesnothd: "<< command << "\n";
808  if (std::system(command.c_str()) == 0) {
809  // Give server a moment to start up
810  SDL_Delay(50);
811  return;
812  }
814 
815  // Couldn't start server so throw error
816  WRN_GENERAL << "Failed to run server start script" << std::endl;
817  throw game::mp_server_error("Starting MP server failed!");
818 }
819 
821 {
822  state_.clear();
823  state_.classification().campaign_type = game_classification::CAMPAIGN_TYPE::MULTIPLAYER;
824 
825  try {
826  if (res == MP_HOST)
827  {
828  try {
829  start_wesnothd();
830  } catch(const game::mp_server_error&)
831  {
833 
834  try {
835  start_wesnothd();
836  } catch(const game::mp_server_error&)
837  {
838  return false;
839  }
840  }
841 
842 
843  }
844 
845  // If a server address wasn't specified, prompt for it now.
846  if(res != MP_LOCAL && multiplayer_server_.empty()) {
847  if(!gui2::dialogs::mp_connect::execute()) {
848  return false;
849  }
850 
851  // The prompt saves its input to preferences.
853 
854  if(multiplayer_server_ != preferences::builtin_servers_list().front().address) {
856  }
857  }
858 
859  //create_engine already calls game_config_manager::get()->load_config but maybe its better to have MULTIPLAYER defined while we are in the lobby.
861 
862  events::discard_input(); // prevent the "keylogger" effect
864 
865  if(res == MP_LOCAL) {
868  } else {
871  multiplayer_server_.clear();
872  }
873 
874  } catch(const wesnothd_rejected_client_error& e) {
876  } catch(const game::mp_server_error& e) {
877  gui2::show_error_message(_("Error while starting server: ") + e.message);
878  } catch(const game::load_game_failed& e) {
879  gui2::show_error_message(_("The game could not be loaded: ") + e.message);
880  } catch(const game::game_error& e) {
881  gui2::show_error_message(_("Error while playing the game: ") + e.message);
882  } catch (const mapgen_exception& e) {
883  gui2::show_error_message(_("Map generator error: ") + e.message);
884  } catch(const wesnothd_error& e) {
885  if(!e.message.empty()) {
886  ERR_NET << "caught network error: " << e.message << std::endl;
887 
888  std::string user_msg;
889  auto conn_err = dynamic_cast<const wesnothd_connection_error*>(&e);
890 
891  if(conn_err) {
892  // The wesnothd_connection_error subclass is only thrown with messages
893  // from boost::system::error_code which we can't translate ourselves.
894  // It's also the originator of the infamous EOF error that happens when
895  // the server dies. <https://github.com/wesnoth/wesnoth/issues/3005>. It
896  // will provide a translated string instead of that when it happens.
897  user_msg = !conn_err->user_message.empty()
898  ? conn_err->user_message
899  : _("Connection failed: ") + e.message;
900  } else {
901  // This will be a message from the server itself, which we can
902  // probably translate.
903  user_msg = translation::gettext(e.message.c_str());
904  }
905 
906  gui2::show_error_message(user_msg);
907  } else {
908  ERR_NET << "caught network error" << std::endl;
909  }
910  } catch(const config::error& e) {
911  if(!e.message.empty()) {
912  ERR_CONFIG << "caught config::error: " << e.message << std::endl;
914  } else {
915  ERR_CONFIG << "caught config::error" << std::endl;
916  }
917  } catch(const incorrect_map_format_error& e) {
918  gui2::show_error_message(_("The game map could not be loaded: ") + e.message);
919  } catch (const savegame::load_game_exception & e) {
920  load_data_.reset(new savegame::load_game_metadata(std::move(e.data_)));
921  //this will make it so next time through the title screen loop, this game is loaded
922  } catch(const wml_exception& e) {
923  e.show();
924  } catch (const game::error & e) {
925  std::cerr << "caught game::error...\n";
926  gui2::show_error_message(_("Error: ") + e.message);
927  }
928 
929  return false;
930 }
931 
933 {
935  return true;
936  }
937 
938  DBG_MP << "starting multiplayer game from the commandline" << std::endl;
939 
940  // These are all the relevant lines taken literally from play_multiplayer() above
941  state_.clear();
942  state_.classification().campaign_type = game_classification::CAMPAIGN_TYPE::MULTIPLAYER;
943 
945  load_game_config_for_game(state_.classification());
946 
947  events::discard_input(); // prevent the "keylogger" effect
949 
952 
953  return false;
954 }
955 
957 {
958  if(!gui2::dialogs::language_selection::execute()) {
959  return false;
960  }
961 
964  }
965 
966  return true;
967 }
968 
970 {
972 }
973 
975 {
976  assert(!load_data_);
977  if(play_replay_)
978  {
979  play_replay();
980  return;
981  }
982 
983  gui2::dialogs::loading_screen::display([this, reload]() {
984 
986  if(reload == RELOAD_DATA) {
987  try {
989  load_game_config_for_game(state_.classification());
990  } catch(const config::error&) {
991  return;
992  }
993  }
994  });
995 
996  try {
997  campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types());
998  LEVEL_RESULT result = ccontroller.play_game();
999  ai::manager::singleton_ = nullptr;
1000  // don't show The End for multiplayer scenario
1001  // change this if MP campaigns are implemented
1002  if(result == LEVEL_RESULT::VICTORY && !state_.classification().is_normal_mp_game()) {
1004 
1005  gui2::dialogs::outro::display(state_.classification().end_text, state_.classification().end_text_duration);
1006 
1008  gui2::dialogs::end_credits::display(state_.classification().campaign);
1009  }
1010  }
1011  } catch (const savegame::load_game_exception &e) {
1012  load_data_.reset(new savegame::load_game_metadata(std::move(e.data_)));
1013  //this will make it so next time through the title screen loop, this game is loaded
1014  } catch(const wml_exception& e) {
1015  e.show();
1016  } catch(const mapgen_exception& e) {
1017  gui2::show_error_message(_("Map generator error: ") + e.message);
1018  }
1019 }
1020 
1022 {
1023  assert(!load_data_);
1024  try {
1025  campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types());
1026  ccontroller.play_replay();
1027  } catch (const savegame::load_game_exception &e) {
1028  load_data_.reset(new savegame::load_game_metadata(std::move(e.data_)));
1029  //this will make it so next time through the title screen loop, this game is loaded
1030  } catch(const wml_exception& e) {
1031  e.show();
1032  }
1033 }
1034 
1036 {
1037  while(true){
1039 
1041 
1042  editor::EXIT_STATUS res = editor::start(filename);
1043 
1044  if(res != editor::EXIT_RELOAD_DATA)
1045  return res;
1046 
1048  }
1049  return editor::EXIT_ERROR; // not supposed to happen
1050 }
1051 
1053 {
1054  load_data_.reset();
1055 }
1056 
1058 {
1059  try {
1061  } catch (...) {}
1062 }
boost::optional< std::string > core_id
Non-empty if –core was given on the command line. Chooses the core to be loaded. ...
constexpr const T & clamp(const T &value, const T &min, const T &max)
Definition: general.hpp:31
an error occurred inside the underlying network communication code (boost asio) TODO: find a short na...
CVideo & video()
boost::optional< std::string > script_file
File to load lua script from.
An error occurred during when trying to coommunicate with the wesnothd server.
bool new_widgets
Do we wish to use the new library or not.
Definition: settings.cpp:21
surface get_image(const image::locator &i_locator, TYPE type)
function to get the surface corresponding to an image.
Definition: picture.cpp:833
unsigned int end_text_duration
for how long the end-of-campaign text is shown
void set_window_icon(surface &icon)
Sets the icon of the main window.
Definition: video.cpp:355
bool set_sound(bool ison)
Definition: general.cpp:673
void close_sound()
Definition: sound.cpp:463
std::string get_program_invocation(const std::string &program_name)
Returns the appropriate invocation for a Wesnoth-related binary, assuming that it is located in the s...
LEVEL_RESULT play_replay()
bool load_game()
Load a game with pre-setting information for the load-game dialog.
Definition: savegame.cpp:165
static lg::log_domain log_mp_create("mp/create")
bool turn_bell()
Definition: general.cpp:615
void discard_input()
Discards all input events.
Definition: events.cpp:853
bool end_credits
whether to show the standard credits at the end
void start_local_game_commandline(const config &game_config, saved_game &state, const commandline_options &cmdline_opts)
Starts a multiplayer game in single-user mode.
Error used when the client is rejected by the MP server.
LEVEL_RESULT play_game()
bool is_mid_game_save() const
Definition: saved_game.hpp:93
bool nogui
True if –nogui was given on the command line. Disables GUI.
The class for loading a savefile.
Definition: savegame.hpp:108
bool script_unsafe_mode
Whether to load the "package" package for the scripting environment. (This allows to load arbitrary l...
void set(CURSOR_TYPE type)
Use the default parameter to reset cursors.
Definition: cursor.cpp:175
void _set_maximized(bool ison)
Definition: general.cpp:405
std::string label
Name of the game (e.g.
void disable_preferences_save()
Definition: general.cpp:246
std::string filename
Name of the savefile to be loaded (not including the directory).
Definition: savegame.hpp:57
void set_gamestate()
Generate the gamestate out of the loaded game config.
Definition: savegame.cpp:274
bool cancel_orders
State of the "cancel_orders" checkbox in the load-game dialog.
Definition: savegame.hpp:66
std::vector< game_tip > load(const config &cfg)
Loads the tips from a config.
Definition: tips.cpp:35
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
#define DBG_MP
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
Error used when game loading fails.
Definition: game_errors.hpp:30
void show_wesnothd_server_search()
Definition: display.cpp:150
void show_preferences()
static std::shared_ptr< save_index_class > default_saves_dir()
Returns an instance for managing saves in filesystem::get_saves_dir()
Definition: save_index.cpp:188
Definition: video.hpp:31
static bool file_exists(const bfs::path &fpath)
Definition: filesystem.cpp:266
bool is_campaign_completed(const std::string &campaign_id)
Definition: game.cpp:333
std::string network_host()
Definition: game.cpp:414
void show_transient_message(const std::string &title, const std::string &message, const std::string &image, const bool message_use_markup, const bool title_use_markup, const bool restore_background)
Shows a transient message to the user.
static void progress(loading_stage stage=loading_stage::none)
void unify_controllers()
Definition: saved_game.cpp:662
const language_def & get_locale()
Definition: language.cpp:263
filesystem::scoped_istream istream_file(const std::string &fname, bool treat_failure_as_error)
Definition: filesystem.cpp:992
void _set_resolution(const point &res)
Definition: general.cpp:399
void set_language(const std::string &language, const std::vector< std::string > *)
Definition: gettext.cpp:449
boost::optional< std::string > username
Non-empty if –username was given on the command line. Forces Wesnoth to use this network username...
void mark_completed_campaigns(std::vector< config > &campaigns)
save_result save_image(const locator &i_locator, const std::string &filename)
Definition: picture.cpp:1101
boost::optional< std::string > campaign_scenario
Non-empty if –campaign-scenario was given on the command line. Chooses starting scenario in the camp...
std::string get_default_title_string()
void set_min_translation_percent(int percent)
Definition: language.cpp:132
void clear()
Definition: saved_game.cpp:752
boost::optional< int > max_fps
Max FPS specified by –max-fps option.
bool fps
True if –fps was given on the command line. Shows number of fps.
std::vector< std::string > unit_test
Non-empty if –unit was given on the command line. Goes directly into unit test mode, into a scenario, if specified.
unit_test_result unit_test()
Runs unit tests specified on the command line.
bool change_language()
void set_network_host(const std::string &host)
Definition: game.cpp:424
std::string normalize_path(const std::string &fpath, bool normalize_separators, bool resolve_dot_entries)
Returns the absolute path of a file.
bool noreplaycheck
True if –noreplaycheck was given on the command line. Dependent on –unit.
Contains the exception interfaces used to signal completion of a scenario, campaign or turn...
std::string jump_to_campaign_id() const
Return the ID of the campaign to jump to (skipping the main menu).
-file util.hpp
Definitions for the interface to Wesnoth Markup Language (WML).
load_game_metadata & data()
Definition: savegame.hpp:127
boost::optional< std::string > plugin_file
File to load a lua plugin (similar to a script) from. Experimental / may replace script.
bool sound_on()
Definition: general.cpp:668
#define DBG_GENERAL
load_game_metadata data_
Definition: savegame.hpp:101
std::string user_message
User-friendly and potentially translated message for use in the UI.
jump_to_campaign_info jump_to_campaign_
boost::optional< std::string > load
Non-empty if –load was given on the command line. Savegame specified to load after start...
bool init_sound()
Definition: sound.cpp:411
static lg::log_domain log_config("config")
bool broke_strict()
Definition: log.cpp:171
bool play_multiplayer(mp_selection res)
std::vector< std::string > test_scenarios_
std::string get_cwd()
Definition: filesystem.cpp:881
bool with_replay
True if –with-replay was given on the command line. Shows replay of the loaded file.
void set_mp_server_program_name(const std::string &path)
Definition: game.cpp:536
void set_window_title(const std::string &title)
Sets the title of the main window.
Definition: video.cpp:349
void show() const
Shows the error in a dialog.
bool play_render_image_mode()
bool headless_unit_test
True if –unit is used and –showgui is not present.
static game_config_manager * get()
void make_fake()
Definition: video.cpp:172
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:91
unit_test_result
Status code after running a unit test, should match the run_wml_tests script and the documentation fo...
#define ERR_CONFIG
font::manager font_manager_
const std::vector< game_config::server_info > & builtin_servers_list()
Definition: game.cpp:383
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:86
static lg::log_domain log_enginerefac("enginerefac")
void start_plugin(std::size_t idx)
Definition: manager.cpp:101
std::string get_name(std::size_t idx)
Definition: manager.cpp:94
This file contains the settings handling of the widget library.
bool nodelay
True if –nodelay was given on the command line.
std::string get_user_data_dir()
Definition: filesystem.cpp:794
void write_file(const std::string &fname, const std::string &data)
Throws io_exception if an error occurs.
static lg::log_domain log_network("network")
std::string multiplayer_server_
std::string campaign_define
If there is a define the campaign uses to customize data.
editor::EXIT_STATUS start_editor()
void set_login(const std::string &login)
boost::optional< unsigned int > translation_percent
Non-empty if –all-translations or –translations-over is given on the command line.
std::string localename
Definition: language.hpp:52
void load_package()
Loads the package library into lua environment.
bool windowed
True if –windowed was given on the command line. Starts Wesnoth in windowed mode.
boost::optional< std::string > editor
Non-empty if –editor was given on the command line. Goes directly into editor. If string is longer t...
void set_show_fps(bool value)
Definition: general.cpp:840
std::unique_ptr< std::istream > scoped_istream
Definition: filesystem.hpp:39
void set_test(const std::string &id)
std::string end_text
end-of-campaign text
void set_password(const std::string &server, const std::string &login, const std::string &key)
void set_core_id(const std::string &core_id)
Definition: general.cpp:319
std::string path
Definition: game_config.cpp:39
boost::optional< std::string > test
Non-empty if –test was given on the command line. Goes directly into test mode, into a scenario...
void init_textdomains(const config &cfg)
Initializes the list of textdomains from a configuration object.
Definition: language.cpp:303
bool multiplayer
True if –multiplayer was given on the command line. Goes directly into multiplayer mode...
Managing the AIs lifecycle - headers TODO: Refactor history handling and internal commands...
bool UI_sound_on()
Definition: general.cpp:639
std::string sanitize_path(const std::string &path)
Sanitizes a path to remove references to the user&#39;s name.
if(win_locale=="af") win_locale
game_launcher(const commandline_options &cmdline_opts, const char *appname)
std::string campaign
The id of the campaign being played.
const char * what() const noexcept
Definition: exceptions.hpp:37
bool clock
True if –clock was given on the command line. Enables.
static UNUSEDNOWARN std::string gettext(const char *str)
Definition: gettext.hpp:66
Error used for any general game error, e.g.
Definition: game_errors.hpp:46
std::string read_file(const std::string &fname)
Basic disk I/O - read file.
Definition: filesystem.cpp:984
std::string screenshot_map_
std::unique_ptr< savegame::load_game_metadata > load_data_
#define LOG_CONFIG
void set_draw_delay(int value)
Definition: general.cpp:850
boost::optional< std::string > render_image
Image path to render. First parameter after –render-image.
void start_client(const config &game_config, saved_game &state, const std::string &host)
Starts a multiplayer game in client mode.
void set_level(const std::string &value)
Definition: game.cpp:738
boost::optional< int > campaign_difficulty
Non-empty if –campaign-difficulty was given on the command line. Numerical difficulty of the campaig...
Helper class, don&#39;t construct this directly.
bool nomusic
True if –nomusic was given on the command line. Disables music.
std::string dev_message
The message for developers telling which problem was triggered, this shouldn&#39;t be translated...
std::string get_cache_dir()
Definition: filesystem.cpp:799
Exception used to signal that the user has decided to abortt a game, and to load another game instead...
Definition: savegame.hpp:92
void run(char const *prog, const std::string &name, int nArgs=0)
Runs a plain script.
static void display(const config &game_cfg, const preferences::PREFERENCE_VIEW initial_view=preferences::VIEW_DEFAULT)
The display function – see modal_dialog for more information.
#define WRN_GENERAL
boost::optional< std::string > password
Non-empty if –password was given on the command line. Forces Wesnoth to use this network password...
bool is_loading() const
bool debug
True if –debug was given on the command line. Enables debug mode.
void start_local_game(const config &game_config, saved_game &state)
Starts a multiplayer game in single-user mode.
std::size_t i
Definition: function.cpp:933
std::size_t add_plugin(const std::string &name, const std::string &prog)
Definition: manager.cpp:118
std::string get_mp_server_program_name()
Definition: game.cpp:548
boost::optional< std::string > screenshot_map_file
Map file to make a screenshot of. First parameter given after –screenshot.
std::string get_wml_location(const std::string &filename, const std::string &current_dir)
Returns a complete path to the actual WML file or directory or an empty string if the file isn&#39;t pres...
void clean_saves(const std::string &label)
Delete all autosaves of a certain scenario from the default save directory.
Definition: savegame.cpp:68
void load_game_config_for_create(bool is_mp, bool is_test=false)
Game configuration data as global variables.
Definition: build_info.cpp:49
bool new_widgets
True if –new-widgets was given on the command line. Hidden option to enable the new widget toolkit...
#define ERR_NET
void init_window()
Initializes a new SDL window instance, taking into account any preiously saved states.
Definition: video.cpp:213
An exception object used when an IO error occurs.
Definition: filesystem.hpp:48
bool music_on()
Definition: general.cpp:691
void add_completed_campaign(const std::string &campaign_id, const std::string &difficulty_level)
Definition: game.cpp:329
bool load_language_list()
Definition: language.cpp:92
language_list get_languages()
Definition: language.cpp:115
void set_fullscreen(bool ison)
Definition: video.cpp:519
Holds a 2D point.
Definition: point.hpp:23
bool set_UI_sound(bool ison)
Definition: general.cpp:644
bool goto_multiplayer()
Declarations for File-IO.
static void save(LexState *ls, int c)
Definition: llex.cpp:57
void launch_game(RELOAD_GAME_DATA reload=RELOAD_DATA)
Class for replay saves (either manually or automatically).
Definition: savegame.hpp:275
-file mapgen.hpp
bool campaign_skip_story
True if –skip-story was given on the command line. Skips [story] and [message]s through the end of t...
std::string difficulty
The difficulty level the game is being played on.
unit_test_result single_unit_test()
Internal to the implementation of unit_test().
boost::optional< std::string > render_image_dst
Output file to put rendered image path in. Optional second parameter after –render-image.
std::string base_name(const std::string &file, const bool remove_extension)
Returns the base filename of a file, with directory name stripped.
static manager * singleton_
Definition: manager.hpp:478
std::string get_user_config_dir()
Definition: filesystem.cpp:765
bool screenshot
True if –screenshot was given on the command line. Starts Wesnoth in screenshot mode.
void cancel_orders()
Definition: saved_game.cpp:645
std::string get_detailed_status(std::size_t idx)
Definition: manager.cpp:83
bool show_replay
State of the "show_replay" checkbox in the load-game dialog.
Definition: savegame.hpp:63
static void display(std::function< void()> f)
const commandline_options & cmdline_opts_
Base class for all the errors encountered by the engine.
Definition: exceptions.hpp:29
game_classification & classification()
Definition: saved_game.hpp:55
std::string screenshot_filename_
void set_carryover_sides_start(config carryover_sides_start)
Definition: saved_game.cpp:161
saved_game state_
bool set_music(bool ison)
Definition: general.cpp:696
Standard logging facilities (interface).
void set_skip_story(bool skip_story)
Definition: saved_game.hpp:126
boost::optional< std::string > screenshot_output_file
Output file to put screenshot in. Second parameter given after –screenshot.
bool set_turn_bell(bool ison)
Definition: general.cpp:620
void clear_loaded_game()
std::string message
Definition: exceptions.hpp:31
EXIT_STATUS start(const std::string &filename, bool take_screenshot, const std::string &screenshot_filename)
Main interface for launching the editor from the title screen.
Definition: editor_main.cpp:28
bool fullscreen
True if –fullscreen was given on the command line. Starts Wesnoth in fullscreen mode.
void show_error_message(const std::string &msg, bool message_use_markup)
Shows an error message to the user.
Definition: message.cpp:205
boost::optional< std::string > language
Non-empty if –language was given on the command line. Sets the language for this session...
#define e
bool nosound
True if –nosound was given on the command line. Disables sound.
boost::optional< std::pair< int, int > > resolution
Pair of AxB values specified after –resolution. Changes Wesnoth resolution.
bool play_screenshot_mode()
lua_kernel_base * get_kernel_base()
Definition: manager.cpp:63
boost::optional< std::string > campaign
Non-empty if –campaign was given on the command line. ID of the campaign we want to start...
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
void clear_current_scenario()
Delete the current scenario from the stats.
Definition: statistics.cpp:785
mp_game_settings & mp_settings()
Multiplayer parameters for this game.
Definition: saved_game.hpp:59
bool enter_create_mode(saved_game &state, jump_to_campaign_info jump_to_campaign)
bool init_lua_script()
std::vector< server_info > server_list
Definition: game_config.cpp:94
bool save_game_automatic(bool ask_for_overwrite=false, const std::string &filename="")
Saves a game without user interaction, unless the file exists and it should be asked to overwrite it...
Definition: savegame.cpp:355
boost::optional< std::string > server
Non-empty if –server was given on the command line. Connects Wesnoth to specified server...
bool play_multiplayer_commandline()
void set_debug(bool new_debug)
static plugins_manager * get()
Definition: manager.cpp:58
void play_slice()
Definition: context.cpp:96
#define LOG_GENERAL
bool show_debug_clock_button
Do we wish to show the button for the debug clock.