The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
menu_events.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2006 - 2025
3 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
4 Copyright (C) 2003 by David White <dave@whitevine.net>
5 Part of the Battle for Wesnoth Project https://www.wesnoth.org/
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY.
13
14 See the COPYING file for more details.
15*/
16
17/**
18 * @file
19 * Operations activated from menus/hotkeys while playing a game.
20 * E.g. Unitlist, status_table, save_game, save_map, chat, show_help, etc.
21 */
22
23#include "menu_events.hpp"
24
25#include "actions/create.hpp"
26#include "actions/move.hpp"
27#include "actions/undo.hpp"
29#include "color.hpp"
34#include "game_board.hpp"
38#include "game_state.hpp"
39#include "gettext.hpp"
56#include "help/help.hpp"
57#include "log.hpp"
58#include "map/label.hpp"
59#include "map/location.hpp"
60#include "map/map.hpp"
62#include "mouse_events.hpp"
63#include "play_controller.hpp"
66#include "replay.hpp"
67#include "replay_controller.hpp"
68#include "replay_helper.hpp"
69#include "resources.hpp"
70#include "savegame.hpp"
75#include "synced_context.hpp"
76#include "units/helper.hpp"
77#include "units/ptr.hpp"
78#include "units/unit.hpp"
79#include "units/types.hpp"
81#include "sound.hpp"
82
83static lg::log_domain log_engine("engine");
84#define ERR_NG LOG_STREAM(err, log_engine)
85#define LOG_NG LOG_STREAM(info, log_engine)
86
87// This file acts as launcher for many gui2 dialogs
88using namespace gui2::dialogs;
89
90namespace
91{
92 std::string last_created_unit = "";
93 std::string last_recruit = "";
94 std::string last_variation = "";
96}
97
98namespace events
99{
101 : gui_(nullptr)
102 , pc_(pc)
103 , game_config_(game_config_manager::get()->game_config())
104 , textbox_info_()
105 , last_search_()
106 , last_search_hit_()
107{
108}
109
113
115{
116 return pc_.gamestate();
117}
118
123
125{
126 return gamestate().board_;
127}
128
133
135{
136 if(!gamestate().lua_kernel_) {
137 return;
138 }
139
141}
142
144{
145 statistics_dialog::display(pc_.statistics(), board().get_team(side_num));
146}
147
149{
150 std::vector<unit_const_ptr> unit_list;
151
152 const unit_map& units = gui_->context().units();
153 for(unit_map::const_iterator i = units.begin(); i != units.end(); ++i) {
154 if(i->side() != gui_->viewing_team().side()) {
155 continue;
156 }
157 unit_list.push_back(i.get_shared_ptr());
158 }
159
160 const auto& unit_dlg = units_dialog::build_unit_list_dialog(unit_list);
161
162 if (unit_dlg->show() && unit_dlg->is_selected()) {
163 const map_location& loc = unit_list[unit_dlg->get_selected_index()]->get_location();
166 }
167}
168
170{
171 int selected_side;
172
173 if(game_stats::execute(board(), gui_->viewing_team(), selected_side)) {
174 gui_->scroll_to_leader(selected_side);
175 }
176}
177
179{
180 const std::string input_name = filesystem::get_legacy_editor_dir() + "/maps/";
181
182 file_dialog dlg;
183
184 dlg.set_title(_("Save Map As"))
185 .set_save_mode(true)
186 .set_path(input_name)
188
189 if(!dlg.show()) {
190 return;
191 }
192
193 try {
195 gui2::show_transient_message("", _("Map saved."));
196 } catch(const filesystem::io_exception& e) {
197 utils::string_map symbols;
198 symbols["msg"] = e.what();
199 const std::string msg = VGETTEXT("Could not save the map: $msg", symbols);
201 }
202}
203
205{
206 // Causes MSVC ambiguity
207 gui2::dialogs::preferences_dialog::display();
208 // Needed after changing fullscreen/windowed mode or display resolution
210}
211
213{
214 config c;
215 c["name"] = "prototype of chat log";
216 chat_log::display(vconfig(c), *resources::recorder);
217}
218
223
225{
227 ? board().is_observer()
228 ? _("Send to observers only")
229 : _("Send to allies only")
230 : "", prefs::get().message_private(), *gui_);
231}
232
234{
236 speak();
237}
238
240{
242 speak();
243}
244
246{
247 if(board().is_observer()) {
248 return !gui_->observers().empty();
249 }
250
251 for(const team& t : pc_.get_teams()) {
252 if(gui_->viewing_team().side() == t.side()) {
253 continue; // Can't be friends with yourself
254 }
255
256 if(gui_->viewing_team().team_name() == t.team_name() && t.is_network()) {
257 return true;
258 }
259 }
260
261 return false;
262}
263
264void menu_handler::recruit(int side_num, const map_location& last_hex)
265{
266 std::map<const unit_type*, t_string> err_msgs_map;
267 std::vector<const unit_type*> recruit_list;
268 std::vector<t_string> unknown_units;
269
270 // Required for purse checks
271 team& current_team = board().get_team(side_num);
272 const int reserved_gold = unit_helper::planned_gold_spent(side_num);
273
274 int selected_index = -1, i = 0;
275
276 for(const auto& recruit : actions::get_recruits(side_num, last_hex)) {
277 const unit_type* type = unit_types.find(recruit);
278 if(type) {
279 recruit_list.push_back(type);
280 } else {
281 ERR_NG << "could not find unit '" << recruit << "'";
282 unknown_units.emplace_back(recruit);
283 continue;
284 }
285
286 // Empty if validation passes
287 err_msgs_map[type] = unit_helper::check_recruit_purse(type->cost(), current_team.gold(), reserved_gold);
288
289 // Save index of last selected item
290 if(type->id() == last_recruit) {
291 selected_index = i;
292 }
293
294 i++;
295 }
296
297 if(!unknown_units.empty()) {
298 // TRANSLATORS: An error that should never happen, might happen when loading an old savegame. If there are
299 // any units that the player can recruit then their standard recruitment dialog will be shown after this
300 // error message, otherwise they'll get the "You have no units available to recruit." error after this one.
302 "Error: there’s an unknown unit type on your recruit list: $unknown_ids",
303 "Error: there are several unknown unit types on your recruit list: $unknown_ids",
304 unknown_units.size(),
305 {{ "unknown_ids", utils::format_conjunct_list("", unknown_units) }}
306 ));
307 }
308
309 if(recruit_list.empty()) {
310 gui2::show_transient_message("", _("You have no units available to recruit."));
311 return;
312 }
313
314 auto dlg = units_dialog::build_recruit_dialog(recruit_list, err_msgs_map, current_team);
315 dlg->set_selected_index(selected_index);
316 if (!dlg->show() && !dlg->is_selected()) {
317 return;
318 }
319
320 const unit_type* type = recruit_list[dlg->get_selected_index()];
321 last_recruit = type->id();
322
323 if(dlg->get_retval() == gui2::retval::OK) {
324 if(err_msgs_map[type].empty()) {
325 do_recruit(type->id(), side_num, last_hex);
326 } else {
327 gui2::show_transient_message("", err_msgs_map[type]);
328 }
329 }
330}
331
332void menu_handler::repeat_recruit(int side_num, const map_location& last_hex)
333{
334 team& current_team = board().get_team(side_num);
335 const std::string& last_recruit = current_team.last_recruit();
336 if(last_recruit.empty()) return;
337
338 const auto validation = std::array
339 {
340 // The recruit list may have been modified since the last recruit...
341 unit_helper::check_recruit_list(last_recruit, current_team.side(), last_hex),
342
343 // ...or we may be unable to afford any more units.
345 unit_types.find(last_recruit)->cost(), current_team.gold(), unit_helper::planned_gold_spent(side_num)),
346 };
347
348 // Show the first non-empty error
349 for(const std::string& err : validation) {
350 if(!err.empty()) {
352 return;
353 }
354 }
355
356 do_recruit(last_recruit, side_num, last_hex);
357}
358
359bool menu_handler::do_recruit(const std::string& type, int side_num, const map_location& target_hex)
360{
361 // TODO: do we still need this? Can't tell what exactly it's guarding...
362 const events::command_disabler disable_commands;
363
364 // NOTE: dst may not equal target_hex after validation (when repeating recruits, for example)
365 const auto [err, dst, src] = unit_helper::validate_recruit_target(type, side_num, target_hex);
366
367 if(!err.empty()) {
369 return false;
370 }
371
372 if(auto wb = pc_.get_whiteboard()) {
373 if(wb->save_recruit(type, side_num, dst)) {
374 return false;
375 }
376 }
377
378 // MP_COUNTDOWN grant time bonus for recruiting
379 team& current_team = board().get_team(side_num);
380 current_team.increment_action_bonus_count();
381 current_team.set_last_recruit(type);
382
383 // Do the recruiting.
385 return true;
386}
387
388void menu_handler::recall(int side_num, const map_location& last_hex)
389{
390 if(pc_.get_disallow_recall()) {
391 gui2::show_transient_message("", _("You are separated from your soldiers and may not recall them."));
392 return;
393 }
394
395 team& current_team = board().get_team(side_num);
396
397 std::vector<unit_const_ptr> recall_list_team;
398 {
399 wb::future_map future; // ensures recall list has planned recalls removed
400 recall_list_team = actions::get_recalls(side_num, last_hex);
401 }
402
403 DBG_WB << "menu_handler::recall: Contents of wb-modified recall list:";
404 for(const unit_const_ptr& unit : recall_list_team) {
405 DBG_WB << unit->name() << " [" << unit->id() << "]";
406 }
407
408 if(current_team.recall_list().empty()) {
410 _("There are no troops available to recall.\n(You must have veteran survivors from a previous scenario.)"));
411 return;
412 }
413
414 if(recall_list_team.empty()) {
415 gui2::show_transient_message("", _("You currently can’t recall at the highlighted location."));
416 return;
417 }
418
419 const auto& dlg = units_dialog::build_recall_dialog(recall_list_team, current_team);
420
421 // side_num is the number of the viewing side, not the current turn's player
422 dlg->set_show_dismiss(pc_.current_side() == side_num);
423
424 if(!dlg->show() || !dlg->is_selected()) {
425 return;
426 }
427
428 int res = dlg->get_selected_index();
429
430 int unit_cost = current_team.recall_cost();
431 const unit_const_ptr sel_unit = recall_list_team[res];
432
433 // we need to check if unit has a specific recall cost
434 // if it does we use it elsewise we use the team.recall_cost()
435 // the magic number -1 is what it gets set to if the unit doesn't
436 // have a special recall_cost of its own.
437 if(sel_unit->recall_cost() > -1) {
438 unit_cost = sel_unit->recall_cost();
439 }
440
441 int wb_gold = pc_.get_whiteboard() ? pc_.get_whiteboard()->get_spent_gold_for(side_num) : 0;
442
443 if(current_team.gold() - wb_gold < unit_cost) {
444 utils::string_map i18n_symbols;
445 i18n_symbols["cost"] = std::to_string(unit_cost);
446 std::string msg = VNGETTEXT("You must have at least 1 gold piece to recall a unit.",
447 "You must have at least $cost gold pieces to recall this unit.", unit_cost, i18n_symbols);
449 return;
450 }
451
452 LOG_NG << "recall index: " << res;
453 const events::command_disabler disable_commands;
454
455 map_location recall_location = last_hex;
457 std::string err;
458 {
460 future; // future unit map removes invisible units from map, don't do this outside of planning mode
461 err = actions::find_recall_location(side_num, recall_location, recall_from, *sel_unit);
462 } // end planned unit map scope
463
464 if(!err.empty()) {
466 return;
467 }
468
469 if(!pc_.get_whiteboard()
470 || !pc_.get_whiteboard()->save_recall(*sel_unit, side_num, recall_location)) {
471 bool success = synced_context::run_and_throw("recall",
472 replay_helper::get_recall(sel_unit->id(), recall_location, recall_from));
473
474 if(!success) {
475 ERR_NG << "menu_handler::recall(): Unit does not exist in the recall list.";
476 }
477 }
478}
479
480// Highlights squares that an enemy could move to on their turn, showing how many can reach each square.
481void menu_handler::show_enemy_moves(bool ignore_units, int side_num)
482{
483 wb::future_map future; // use unit positions as if all planned actions were executed
484
485 mouse_handler& mh = pc_.get_mouse_handler_base();
486 const map_location& hex_under_mouse = mh.hovered_hex();
487
488 gui_->unhighlight_reach();
489
490 // Compute enemy movement positions
491 for(auto& u : pc_.get_units()) {
492 bool invisible = u.invisible(u.get_location());
493
494 if(board().get_team(side_num).is_enemy(u.side()) && !gui_->fogged(u.get_location()) && !u.incapacitated()
495 && !invisible) {
496 const unit_movement_resetter move_reset(u);
497 const pathfind::paths& path
498 = pathfind::paths(u, false, true, gui_->viewing_team(), 0, false, ignore_units);
499
500 gui_->highlight_another_reach(path, hex_under_mouse);
501 }
502
503 // Need to recompute ellipses for highlighted enemy units
504 gui_->invalidate(u.get_location());
505 }
506
507 // Find possible unit (no matter whether friend or foe) under the
508 // mouse cursor.
509 const bool selected_hex_has_unit = mh.hex_hosts_unit(hex_under_mouse);
510
511 if(selected_hex_has_unit) {
512 // At this point, a single pixel move would remove the enemy
513 // [best possible] movements hex tiles highlights, so some
514 // prevention on normal unit mouseover movement highlight
515 // has to be toggled temporarily.
517 }
518}
519
520void menu_handler::toggle_shroud_updates(int side_num)
521{
522 team& current_team = board().get_team(side_num);
523 bool auto_shroud = current_team.auto_shroud_updates();
524 // If we're turning automatic shroud updates on, then commit all moves
525 if(!auto_shroud) {
526 update_shroud_now(side_num);
527 }
528
529 // Toggle the setting and record this.
531}
532
533void menu_handler::update_shroud_now(int /* side_num */)
534{
536}
537
538// Helpers for menu_handler::end_turn()
539namespace
540{
541/** Returns true if @a side_num has at least one living unit. */
542bool units_alive(int side_num, const unit_map& units)
543{
544 for(auto& unit : units) {
545 if(unit.side() == side_num) {
546 return true;
547 }
548 }
549 return false;
550}
551
552/** Returns true if @a side_num has at least one unit that can still move. */
553bool partmoved_units(
554 int side_num, const unit_map& units, const game_board& board, const std::shared_ptr<wb::manager>& whiteb)
555{
556 for(auto& unit : units) {
557 if(unit.side() == side_num) {
558 // @todo whiteboard should take into consideration units that have
559 // a planned move but can still plan more movement in the same turn
560 if(board.unit_can_move(unit) && !unit.user_end_turn() && (!whiteb || !whiteb->unit_has_actions(&unit)))
561 return true;
562 }
563 }
564 return false;
565}
566
567/**
568 * Returns true if @a side_num has at least one unit that (can but) has not moved.
569 */
570bool unmoved_units(
571 int side_num, const unit_map& units, const game_board& board, const std::shared_ptr<wb::manager>& whiteb)
572{
573 for(auto& unit : units) {
574 if(unit.side() == side_num) {
575 if(board.unit_can_move(unit) && !unit.has_moved() && !unit.user_end_turn()
576 && (!whiteb || !whiteb->unit_has_actions(&unit))) {
577 return true;
578 }
579 }
580 }
581 return false;
582}
583
584} // end anon namespace
585
586bool menu_handler::end_turn(int side_num)
587{
588 if(!gamedata().allow_end_turn()) {
589 t_string reason = gamedata().cannot_end_turn_reason();
590 if(reason.empty()) {
591 reason = _("You cannot end your turn yet!");
592 }
594 return false;
595 }
596
597 std::size_t team_num = static_cast<std::size_t>(side_num - 1);
598 if(team_num < pc_.get_teams().size() && pc_.get_teams()[team_num].no_turn_confirmation()) {
599 // Skip the confirmations that follow.
600 }
601 // Ask for confirmation if the player hasn't made any moves.
602 else if(prefs::get().confirm_no_moves() && !pc_.get_undo_stack().player_acted()
603 && (!pc_.get_whiteboard() || !pc_.get_whiteboard()->current_side_has_actions())
604 && units_alive(side_num, pc_.get_units())) {
605 const int res = gui2::show_message("",
606 _("You have not started your turn yet. Do you really want to end your turn?"),
608 if(res == gui2::retval::CANCEL) {
609 return false;
610 }
611 }
612 // Ask for confirmation if units still have some movement left.
613 else if(prefs::get().yellow_confirm() && partmoved_units(side_num, pc_.get_units(), board(), pc_.get_whiteboard())) {
614 const int res = gui2::show_message("",
615 _("Some units have movement left. Do you really want to end your turn?"),
617 if(res == gui2::retval::CANCEL) {
618 return false;
619 }
620 }
621 // Ask for confirmation if units still have all movement left.
622 else if(prefs::get().green_confirm() && unmoved_units(side_num, pc_.get_units(), board(), pc_.get_whiteboard())) {
623 const int res = gui2::show_message("",
624 _("Some units have not moved. Do you really want to end your turn?"),
626 if(res == gui2::retval::CANCEL) {
627 return false;
628 }
629 }
630
631 // Auto-execute remaining whiteboard planned actions
632 // Only finish turn if they all execute successfully, i.e. no ambush, etc.
633 if(pc_.get_whiteboard() && !pc_.get_whiteboard()->allow_end_turn()) {
634 return false;
635 }
636
637 return true;
638}
639
640void menu_handler::goto_leader(int side_num)
641{
642 unit_map::const_iterator i = pc_.get_units().find_leader(side_num);
643 if(i != pc_.get_units().end() && i->is_visible_to_team(gui_->viewing_team(), false)) {
644 gui_->scroll_to_tile(i->get_location(), game_display::WARP);
645 }
646}
647
648void menu_handler::unit_description()
649{
650 const unit_map::const_iterator un = current_unit();
651 if(un != pc_.get_units().end()) {
653 }
654}
655
656void menu_handler::terrain_description(mouse_handler& mousehandler)
657{
658 const map_location& loc = mousehandler.get_last_hex();
659 if(pc_.get_map().on_board(loc) == false || gui_->shrouded(loc)) {
660 return;
661 }
662
663 const terrain_type& type = pc_.get_map().get_terrain_info(loc);
664 // const terrain_type& info = board().pc_.get_map().get_terrain_info(terrain);
666}
667
668void menu_handler::rename_unit()
669{
670 const unit_map::iterator un = current_unit();
671 if(un == pc_.get_units().end() || gui_->viewing_team().side() != un->side()) {
672 return;
673 }
674
675 if(un->unrenamable()) {
676 return;
677 }
678
679 std::string name = un->name();
680 const std::string title(_("Rename Unit"));
681 const std::string label(_("Name:"));
682
683 if(edit_text::execute(title, label, name)) {
684 resources::recorder->add_rename(name, un->get_location());
685 un->rename(name);
686 gui_->invalidate_unit();
687 }
688}
689
690unit_map::iterator menu_handler::current_unit()
691{
692 const mouse_handler& mousehandler = pc_.get_mouse_handler_base();
693 const bool see_all = gui_->show_everything() || (pc_.is_replay() && pc_.get_replay_controller()->see_all());
694
695 unit_map::iterator res = board().find_visible_unit(mousehandler.get_last_hex(), gui_->viewing_team(), see_all);
696 if(res != pc_.get_units().end()) {
697 return res;
698 }
699
700 return board().find_visible_unit(mousehandler.get_selected_hex(), gui_->viewing_team(), see_all);
701}
702
703// Helpers for create_unit()
704namespace
705{
706/** Allows a function to return both a type and a gender. */
707typedef std::tuple<const unit_type*, unit_race::GENDER, std::string> type_gender_variation;
708
709/**
710 * Allows the user to select a type of unit, using GUI2.
711 * (Intended for use when a unit is created in debug mode via hotkey or
712 * context menu.)
713 * @returns the selected type and gender. If this is canceled, the
714 * returned type is nullptr.
715 */
716type_gender_variation choose_unit()
717{
718 const auto& types_list = unit_types.types_list();
719
720 const auto& create_dlg = units_dialog::build_create_dialog(types_list);
721 // Restore saved choices
722 for (std::size_t i = 0; i < types_list.size(); i++) {
723 if (types_list[i]->id() == last_created_unit) {
724 create_dlg->set_selected_index(i);
725 create_dlg->set_gender(last_gender);
726 create_dlg->set_variation(last_variation);
727 break;
728 }
729 }
730
731 auto info = type_gender_variation(nullptr, unit_race::NUM_GENDERS, "");
732 if(!create_dlg->show()) {
733 return info;
734 }
735
736 if(!create_dlg->is_selected()) {
737 return info;
738 }
739
740 const unit_type* ut = types_list[create_dlg->get_selected_index()];
741 last_created_unit = ut->id();
742 last_gender = create_dlg->gender();
743 last_variation = create_dlg->variation();
744
745 if (create_dlg->get_retval() == gui2::retval::OK) {
746 if (create_dlg->is_selected()) {
747 info = type_gender_variation(ut, last_gender, last_variation);
748 } else {
749 ERR_NG << "Create unit dialog returned nonexistent or unusable unit_type id.";
750 }
751 }
752
753 return info;
754}
755
756/**
757 * Creates a unit and places it on the board.
758 * (Intended for use with any units created via debug mode.)
759 */
760void create_and_place(
761 const map_location& loc,
762 const unit_type& u_type,
764 const std::string& variation = "")
765{
766 synced_context::run_and_throw("debug_create_unit",
767 config {
768 "x", loc.wml_x(),
769 "y", loc.wml_y(),
770 "type", u_type.id(),
771 "gender", gender_string(gender),
772 "variation", variation,
773 }
774 );
775}
776
777} // Anonymous namespace
778
779/**
780 * Creates a unit (in debug mode via hotkey or context menu).
781 */
782void menu_handler::create_unit(mouse_handler& mousehandler)
783{
784 // Save the current mouse location before popping up the choice menu (which
785 // gives time for the mouse to move, changing the location).
786 const map_location destination = mousehandler.get_last_hex();
787
788 // Let the user select the kind of unit to create.
789 if(const auto& [type, gender, variation] = choose_unit(); type != nullptr) {
790 create_and_place(destination, *type, gender, variation);
791 }
792}
793
794void menu_handler::change_side(mouse_handler& mousehandler)
795{
796 const map_location& loc = mousehandler.get_last_hex();
797 const unit_map::iterator i = pc_.get_units().find(loc);
798 if(i == pc_.get_units().end()) {
799 if(!pc_.get_map().is_village(loc)) {
800 return;
801 }
802
803 // village_owner returns 0 for free village, so team 0 will get it
804 int team = board().village_owner(loc);
805 // team is 0-based so team=team::nteams() is not a team
806 // but this will make get_village free it
807 if(team > static_cast<int>(pc_.get_teams().size())) {
808 team = 0;
809 }
811 } else {
812 int side = i->side();
813 ++side;
814 if(side > static_cast<int>(pc_.get_teams().size())) {
815 side = 1;
816 }
817 i->set_side(side);
818
819 if(pc_.get_map().is_village(loc)) {
821 }
822 }
823}
824
825void menu_handler::kill_unit(mouse_handler& mousehandler)
826{
827 const map_location loc = mousehandler.get_last_hex();
828 synced_context::run_and_throw("debug_kill", config {"x", loc.wml_x(), "y", loc.wml_y()});
829}
830
831void menu_handler::label_terrain(mouse_handler& mousehandler, bool team_only)
832{
833 const map_location& loc = mousehandler.get_last_hex();
834 if(pc_.get_map().on_board(loc) == false) {
835 return;
836 }
837
838 const terrain_label* old_label = gui_->labels().get_label(loc);
839 std::string label = old_label ? old_label->text() : "";
840
841 if(edit_label::execute(label, team_only)) {
842 std::string team_name;
844
845 if(team_only) {
846 team_name = gui_->labels().team_name();
847 } else {
848 color = team::get_side_color(gui_->viewing_team().side());
849 }
850 const terrain_label* res = gui_->labels().set_label(loc, label, gui_->viewing_team_index(), team_name, color);
851 if(res) {
853 }
854 }
855}
856
857void menu_handler::clear_labels()
858{
859 if(!board().is_observer()) {
860 const int res = gui2::show_message(
861 _("Clear Labels"),
862 _("Are you sure you want to clear map labels?"),
864 );
865
866 if(res == gui2::retval::OK) {
867 std::string viewing_team = gui_->viewing_team().team_name();
868 gui_->labels().clear(viewing_team, false);
869 resources::recorder->clear_labels(viewing_team, false);
870 }
871 }
872}
873
874void menu_handler::label_settings()
875{
876 if(label_settings::execute(board())) {
877 gui_->labels().recalculate_labels();
878 }
879}
880
881void menu_handler::continue_move(mouse_handler& mousehandler, int side_num)
882{
883 unit_map::iterator i = current_unit();
884 if(i == pc_.get_units().end() || !i->move_interrupted()) {
885 i = pc_.get_units().find(mousehandler.get_selected_hex());
886 if(i == pc_.get_units().end() || !i->move_interrupted()) {
887 return;
888 }
889 }
890 move_unit_to_loc(i, i->get_interrupted_move(), true, side_num, mousehandler);
891}
892
893void menu_handler::move_unit_to_loc(
894 const unit_map::iterator& ui,
895 const map_location& target,
896 bool continue_move,
897 int side_num,
898 mouse_handler& mousehandler)
899{
900 assert(ui != pc_.get_units().end());
901
902 pathfind::marked_route route = mousehandler.get_route(&*ui, target, board().get_team(side_num));
903
904 if(route.steps.empty()) {
905 return;
906 }
907
908 assert(route.steps.front() == ui->get_location());
909
910 gui_->set_route(&route);
911 gui_->unhighlight_reach();
912
913 {
914 LOG_NG << "move_unit_to_loc " << route.steps.front() << " to " << route.steps.back();
915 actions::move_unit_and_record(route.steps, continue_move);
916 }
917
918 mousehandler.deselect_hex();
919 gui_->set_route(nullptr);
920 gui_->invalidate_game_status();
921}
922
923void menu_handler::execute_gotos(mouse_handler& mousehandler, int side)
924{
925 // we will loop on all gotos and try to fully move a maximum of them,
926 // but we want to avoid multiple blocking of the same unit,
927 // so, if possible, it's better to first wait that the blocker move
928
929 bool wait_blocker_move = true;
930 std::set<map_location> fully_moved;
931
932 bool change = false;
933 bool blocked_unit = false;
934 do {
935 change = false;
936 blocked_unit = false;
937 for(auto& unit : pc_.get_units()) {
938 if(unit.side() != side || unit.movement_left() == 0) {
939 continue;
940 }
941
942 const map_location& current_loc = unit.get_location();
943 const map_location& goto_loc = unit.get_goto();
944
945 if(goto_loc == current_loc) {
947 continue;
948 }
949
950 if(!pc_.get_map().on_board(goto_loc)) {
951 continue;
952 }
953
954 // avoid pathfinding calls for finished units
955 if(fully_moved.count(current_loc)) {
956 continue;
957 }
958
959 pathfind::marked_route route = mousehandler.get_route(&unit, goto_loc, board().get_team(side));
960
961 if(route.steps.size() <= 1) { // invalid path
962 fully_moved.insert(current_loc);
963 continue;
964 }
965
966 // look where we will stop this turn (turn_1 waypoint or goto)
967 map_location next_stop = goto_loc;
968 pathfind::marked_route::mark_map::const_iterator w = route.marks.begin();
969 for(; w != route.marks.end(); ++w) {
970 if(w->second.turns == 1) {
971 next_stop = w->first;
972 break;
973 }
974 }
975
976 if(next_stop == current_loc) {
977 fully_moved.insert(current_loc);
978 continue;
979 }
980
981 // we delay each blocked move because some other change
982 // may open a another not blocked path
983 if(pc_.get_units().count(next_stop)) {
984 blocked_unit = true;
985 if(wait_blocker_move)
986 continue;
987 }
988
989 gui_->set_route(&route);
990
991 {
992 LOG_NG << "execute goto from " << route.steps.front() << " to " << route.steps.back();
993 int moves = actions::move_unit_and_record(route.steps);
994 change = moves > 0;
995 }
996
997 if(change) {
998 // something changed, resume waiting blocker (maybe one can move now)
999 wait_blocker_move = true;
1000 }
1001 }
1002
1003 if(!change && wait_blocker_move) {
1004 // no change when waiting, stop waiting and retry
1005 wait_blocker_move = false;
1006 change = true;
1007 }
1008 } while(change && blocked_unit);
1009
1010 // erase the footsteps after movement
1011 gui_->set_route(nullptr);
1012 gui_->invalidate_game_status();
1013}
1014
1015void menu_handler::toggle_ellipses()
1016{
1017 prefs::get().set_show_side_colors(!prefs::get().show_side_colors());
1018 gui_->invalidate_all(); // TODO can fewer tiles be invalidated?
1019}
1020
1021void menu_handler::toggle_grid()
1022{
1023 prefs::get().set_grid(!prefs::get().grid());
1024 gui_->invalidate_all();
1025}
1026
1027void menu_handler::unit_hold_position(mouse_handler& mousehandler, int side_num)
1028{
1029 const unit_map::iterator un = pc_.get_units().find(mousehandler.get_selected_hex());
1030 if(un != pc_.get_units().end() && un->side() == side_num && un->movement_left() >= 0) {
1031 un->toggle_hold_position();
1032 gui_->invalidate(mousehandler.get_selected_hex());
1033
1034 mousehandler.set_current_paths(pathfind::paths());
1035
1036 if(un->hold_position()) {
1037 mousehandler.cycle_units(false);
1038 }
1039 }
1040}
1041
1042void menu_handler::end_unit_turn(mouse_handler& mousehandler, int side_num)
1043{
1044 const unit_map::iterator un = pc_.get_units().find(mousehandler.get_selected_hex());
1045 if(un != pc_.get_units().end() && un->side() == side_num && un->movement_left() >= 0) {
1046 un->toggle_user_end_turn();
1047 gui_->invalidate(mousehandler.get_selected_hex());
1048
1049 mousehandler.set_current_paths(pathfind::paths());
1050
1051 if(un->user_end_turn()) {
1052 mousehandler.cycle_units(false);
1053 }
1054
1055 // If cycle_units hasn't found a new unit to cycle to then the original unit is still selected, but
1056 // in a state where left-clicking on it does nothing. Make it respond to mouse clicks again.
1057 if(un == pc_.get_units().find(mousehandler.get_selected_hex())) {
1058 mousehandler.deselect_hex();
1059 }
1060 }
1061}
1062
1063void menu_handler::search()
1064{
1065 std::ostringstream msg;
1066 msg << _("Search");
1067 if(last_search_hit_.valid()) {
1068 msg << " [" << last_search_ << "]";
1069 }
1070 msg << ':';
1071 textbox_info_.show(gui::TEXTBOX_SEARCH, msg.str(), "", false, *gui_);
1072}
1073
1074bool menu_handler::do_speak()
1075{
1076 // None of the two parameters really needs to be passed since the information belong to members of the class.
1077 // But since it makes the called method more generic, it is done anyway.
1078 return chat_handler::do_speak(
1079 textbox_info_.box()->text(), textbox_info_.check() != nullptr ? textbox_info_.check()->checked() : false);
1080}
1081
1082void menu_handler::add_chat_message(const std::chrono::system_clock::time_point& time,
1083 const std::string& speaker,
1084 int side,
1085 const std::string& message,
1087{
1088 gui_->get_chat_manager().add_chat_message(time, speaker, side, message, type, false);
1089
1091 config {
1092 "sender", prefs::get().login(),
1093 "message", message,
1094 "whisper", type == events::chat_handler::MESSAGE_PRIVATE,
1095 }
1096 );
1097}
1098
1099// command handler for user :commands. Also understands all chat commands
1100// via inheritance. This complicates some things a bit.
1101class console_handler : public map_command_handler<console_handler>, private chat_command_handler
1102{
1103public:
1104 // convenience typedef
1107 : chmap()
1109 , menu_handler_(menu_handler)
1110 , team_num_(menu_handler.pc_.current_side())
1111 {
1112 }
1113
1114 using chmap::dispatch; // disambiguate
1115 using chmap::get_commands_list;
1116 using chmap::command_failed;
1117
1118protected:
1119 // chat_command_handler's init_map() and handlers will end up calling these.
1120 // this makes sure the commands end up in our map
1121 virtual void register_command(const std::string& cmd,
1122 chat_command_handler::command_handler h,
1123 const std::string& help = "",
1124 const std::string& usage = "",
1125 const std::string& flags = "")
1126 {
1127 chmap::register_command(cmd, h, help, usage, flags + "N"); // add chat commands as network_only
1128 }
1129
1130 virtual void register_alias(const std::string& to_cmd, const std::string& cmd)
1131 {
1132 chmap::register_alias(to_cmd, cmd);
1133 }
1134
1135 virtual std::string get_arg(unsigned i) const
1136 {
1137 return chmap::get_arg(i);
1138 }
1139
1140 virtual std::string get_cmd() const
1141 {
1142 return chmap::get_cmd();
1143 }
1144
1145 virtual std::string get_data(unsigned n = 1) const
1146 {
1147 return chmap::get_data(n);
1148 }
1149
1150 // these are needed to avoid ambiguities introduced by inheriting from console_command_handler
1151 using chmap::register_command;
1152 using chmap::register_alias;
1153 using chmap::help;
1154 using chmap::is_enabled;
1155 using chmap::command_failed_need_arg;
1156
1157 void do_refresh();
1158 void do_droid();
1159 void do_terrain();
1160 void do_idle();
1161 void do_theme();
1162 void do_control();
1163 void do_controller();
1164 void do_clear();
1165 void do_foreground();
1166 void do_layers();
1167 void do_fps();
1168 void do_benchmark();
1169 void do_save();
1170 void do_save_quit();
1171 void do_quit();
1172 void do_ignore_replay_errors();
1173 void do_nosaves();
1174 void do_next_level();
1175 void do_choose_level();
1176 void do_turn();
1177 void do_turn_limit();
1178 void do_debug();
1179 void do_nodebug();
1180 void do_lua();
1181 void do_unsafe_lua();
1182 void do_custom();
1183 void do_set_alias();
1184 void do_set_var();
1185 void do_show_var();
1186 void do_inspect();
1187 void do_control_dialog();
1188 void do_unit();
1189 // void do_buff();
1190 // void do_unbuff();
1191 void do_discover();
1192 void do_undiscover();
1193 void do_create();
1194 void do_fog();
1195 void do_shroud();
1196 void do_gold();
1197 void do_event();
1198 void do_toggle_draw_coordinates();
1199 void do_toggle_draw_terrain_codes();
1200 void do_toggle_draw_num_of_bitmaps();
1201 void do_toggle_whiteboard();
1202 void do_whiteboard_options();
1203
1204 std::string get_flags_description() const
1205 {
1206 return _("(D) — debug only, (N) — network only, (A) — admin only");
1207 }
1208
1209 using chat_command_handler::get_command_flags_description; // silence a warning
1210 std::string get_command_flags_description(const chmap::command& c) const
1211 {
1212 std::string space(" ");
1213 return (c.has_flag('D') ? space + _("(debug command)") : "")
1214 + (c.has_flag('N') ? space + _("(network only)") : "")
1215 + (c.has_flag('A') ? space + _("(admin only)") : "")
1216 + (c.has_flag('S') ? space + _("(not during other events)") : "");
1217 }
1218
1219 using map::is_enabled;
1220 bool is_enabled(const chmap::command& c) const
1221 {
1222 return !((c.has_flag('D') && !game_config::debug)
1223 || (c.has_flag('N') && !menu_handler_.pc_.is_networked_mp())
1224 || (c.has_flag('A') && !mp::logged_in_as_moderator())
1225 || (c.has_flag('S') && (synced_context::get_synced_state() != synced_context::UNSYNCED || !menu_handler_.pc_.current_team().is_local())));
1226 }
1227
1228 void print(const std::string& title, const std::string& message)
1229 {
1230 menu_handler_.add_chat_message(std::chrono::system_clock::now(), title, 0, message);
1231 }
1232
1234 {
1235 chat_command_handler::init_map(); // grab chat_ /command handlers
1236
1237 chmap::get_command("log")->flags = ""; // clear network-only flag from log
1238 chmap::get_command("version")->flags = ""; // clear network-only flag
1239 chmap::get_command("ignore")->flags = ""; // clear network-only flag
1240 chmap::get_command("friend")->flags = ""; // clear network-only flag
1241 chmap::get_command("remove")->flags = ""; // clear network-only flag
1242
1243 chmap::set_cmd_prefix(":");
1244 chmap::set_cmd_flag(true);
1245
1246 register_command("refresh", &console_handler::do_refresh, _("Refresh gui."));
1247 register_command("droid", &console_handler::do_droid, _("Switch a side to/from AI control."),
1248 // TRANSLATORS: These are the arguments accepted by the "droid" command,
1249 // which must be a side-number and then optionally one of "on", "off" or "full".
1250 // As with the command's name, "on", "off" and "full" are hardcoded, and shouldn't change in the translation.
1251 _("[<side> [on/off/full]]\n“on” = enable but retain vision, “full” = as if it’s controlled by another player"));
1252 register_command("terrain", &console_handler::do_terrain, _("Change terrain type of current hex"),
1253 // TRANSLATORS: [both|base|overlay] are hardcoded literal arguments and shouldn't be translated.
1254 _("<terrain type> [both|base|overlay]"), "DS");
1255 register_command("idle", &console_handler::do_idle, _("Switch a side to/from idle state."),
1256 // TRANSLATORS: These are the arguments accepted by the "idle" command,
1257 // which must be a side-number and then optionally "on" or "off".
1258 // As with the command's name, "on" and "off" are hardcoded, and shouldn't change in the translation.
1259 _("command_idle^[<side> [on/off]]"));
1260 register_command("theme", &console_handler::do_theme, _("Change the in-game theme."));
1261 register_command("control", &console_handler::do_control,
1262 _("Assign control of a side to a different player or observer."), _("<side> <nickname>"), "N");
1263 register_command("controller", &console_handler::do_controller, _("Query the controller status of a side."),
1264 _("<side>"));
1265 register_command("clear", &console_handler::do_clear, _("Clear chat history."));
1266 register_command("foreground", &console_handler::do_foreground, _("Debug foreground terrain."), "", "D");
1267 register_command(
1268 "layers", &console_handler::do_layers, _("Debug layers from terrain under the mouse."), "", "D");
1269 register_command("fps", &console_handler::do_fps, _("Display and log fps (Frames Per Second)."));
1270 register_command("benchmark", &console_handler::do_benchmark, _("Similar to the ‘fps’ command, but also forces everything to redraw instead of only things that have changed."));
1271 register_command("save", &console_handler::do_save, _("Save game."));
1272 register_alias("save", "w");
1273 register_command("quit", &console_handler::do_quit, _("Quit game."));
1274 // Note the next value is used hardcoded in the init tests.
1275 register_alias("quit", "q!");
1276 register_command("save_quit", &console_handler::do_save_quit, _("Save and quit."));
1277 register_alias("save_quit", "wq");
1278 register_command("ignore_replay_errors", &console_handler::do_ignore_replay_errors, _("Ignore replay errors."));
1279 register_command("nosaves", &console_handler::do_nosaves, _("Disable autosaves."));
1280 register_command("next_level", &console_handler::do_next_level,
1281 _("Advance to the next scenario, or scenario identified by ‘id’"), _("<id>"), "DS");
1282 register_alias("next_level", "n");
1283 register_command("choose_level", &console_handler::do_choose_level, _("Choose next scenario"), "", "DS");
1284 register_alias("choose_level", "cl");
1285 register_command("turn", &console_handler::do_turn,
1286 _("Change turn number (and time of day), or increase by one if no number is specified."), _("[turn]"),
1287 "DS");
1288 register_command("turn_limit", &console_handler::do_turn_limit,
1289 _("Change turn limit, or turn the turn limit off if no number is specified or it’s −1."), _("[limit]"),
1290 "DS");
1291 register_command("debug", &console_handler::do_debug, _("Turn debug mode on."));
1292 register_command("nodebug", &console_handler::do_nodebug, _("Turn debug mode off."), "", "D");
1293 register_command(
1294 "lua", &console_handler::do_lua, _("Execute a Lua statement."), _("<command>[;<command>...]"), "DS");
1295 register_command(
1296 "unsafe_lua", &console_handler::do_unsafe_lua, _("Grant higher privileges to Lua scripts."), "", "D");
1297 register_command("custom", &console_handler::do_custom, _("Set the command used by the custom command hotkey"),
1298 _("<command>[;<command>...]"));
1299 register_command("give_control", &console_handler::do_control_dialog,
1300 _("Invoke a dialog allowing changing control of MP sides."), "", "N");
1301 register_command("inspect", &console_handler::do_inspect, _("Launch the gamestate inspector"), "", "D");
1302 register_command(
1303 "alias", &console_handler::do_set_alias, _("Set or show alias to a command"), _("<name>[=<command>]"));
1304 register_command(
1305 "set_var", &console_handler::do_set_var, _("Set a scenario variable."), _("<var>=<value>"), "DS");
1306 register_command("show_var", &console_handler::do_show_var, _("Show a scenario variable."), _("<var>"), "D");
1307 register_command("unit", &console_handler::do_unit,
1308 // TRANSLATORS: Do not translate the word "advances"; it is a hardcoded literal argument.
1309 _("Modify a unit variable. (Only top level keys are supported, and advances=<number>.)"),
1310 _("<var>=<value>"), "DS");
1311
1312 // register_command("buff", &console_handler::do_buff,
1313 // _("Add a trait to a unit."), "", "D");
1314 // register_command("unbuff", &console_handler::do_unbuff,
1315 // _("Remove a trait from a unit. (Does not work yet.)"), "", "D");
1316 register_command("discover", &console_handler::do_discover, _("Discover all units in help."), "");
1317 register_command("undiscover", &console_handler::do_undiscover, _("‘Undiscover’ all units in help."), "");
1318 register_command("create", &console_handler::do_create, _("Create a unit."), _("<unit type id>"), "DS");
1319 register_command("fog", &console_handler::do_fog, _("Toggle fog for the current player."), "", "DS");
1320 register_command("shroud", &console_handler::do_shroud, _("Toggle shroud for the current player."), "", "DS");
1321 register_command("gold", &console_handler::do_gold, _("Give gold to the current player."), _("<amount>"), "DS");
1322 register_command("throw", &console_handler::do_event, _("Fire a game event."), _("<event name>"), "DS");
1323 register_alias("throw", "fire");
1324 register_command("show_coordinates", &console_handler::do_toggle_draw_coordinates,
1325 _("Toggle overlaying of x,y coordinates on hexes."));
1326 register_alias("show_coordinates", "sc");
1327 register_command("show_terrain_codes", &console_handler::do_toggle_draw_terrain_codes,
1328 _("Toggle overlaying of terrain codes on hexes."));
1329 register_alias("show_terrain_codes", "tc");
1330 register_command("show_num_of_bitmaps", &console_handler::do_toggle_draw_num_of_bitmaps,
1331 _("Toggle overlaying of number of bitmaps on hexes."));
1332 register_alias("show_num_of_bitmaps", "bn");
1333 register_command("whiteboard", &console_handler::do_toggle_whiteboard, _("Toggle planning mode."));
1334 register_alias("whiteboard", "wb");
1335 register_command(
1336 "whiteboard_options", &console_handler::do_whiteboard_options, _("Access whiteboard options dialog."));
1337 register_alias("whiteboard_options", "wbo");
1338
1339 if(auto alias_list = prefs::get().get_alias()) {
1340 for(const auto& [key, value] : alias_list->attribute_range()) {
1341 register_alias(value, key);
1342 }
1343 }
1344 }
1345
1346private:
1348 const unsigned int team_num_;
1349};
1350
1351void menu_handler::send_chat_message(const std::string& message, bool allies_only)
1352{
1353 config cfg;
1354 cfg["id"] = prefs::get().login();
1355 cfg["message"] = message;
1356 auto now = std::chrono::system_clock::now();
1357 cfg["time"] = chrono::serialize_timestamp(now);
1358
1359 const int side = board().is_observer() ? 0 : gui_->viewing_team().side();
1360 if(!board().is_observer()) {
1361 cfg["side"] = side;
1362 }
1363
1364 bool private_message = has_friends() && allies_only;
1365
1366 if(private_message) {
1367 if(board().is_observer()) {
1369 } else {
1370 cfg["to_sides"] = gui_->viewing_team().allied_human_teams();
1371 }
1372 }
1373
1375
1376 add_chat_message(now, cfg["id"], side, message,
1378}
1379
1380void menu_handler::do_search(const std::string& new_search)
1381{
1382 if(new_search.empty() == false && new_search != last_search_)
1383 last_search_ = new_search;
1384
1385 if(last_search_.empty())
1386 return;
1387
1388 bool found = false;
1389 map_location loc = last_search_hit_;
1390 // If this is a location search, just center on that location.
1391 std::vector<std::string> args = utils::split(last_search_, ',');
1392 if(args.size() == 2) {
1393 int x, y;
1394 x = lexical_cast_default<int>(args[0], 0) - 1;
1395 y = lexical_cast_default<int>(args[1], 0) - 1;
1396 if(x >= 0 && x < pc_.get_map().w() && y >= 0 && y < pc_.get_map().h()) {
1397 loc = map_location(x, y);
1398 found = true;
1399 }
1400 }
1401 // Start scanning the game map
1402 if(loc.valid() == false) {
1403 loc = map_location(pc_.get_map().w() - 1, pc_.get_map().h() - 1);
1404 }
1405
1406 map_location start = loc;
1407 while(!found) {
1408 // Move to the next location
1409 loc.x = (loc.x + 1) % pc_.get_map().w();
1410 if(loc.x == 0)
1411 loc.y = (loc.y + 1) % pc_.get_map().h();
1412
1413 // Search label
1414 if(!gui_->shrouded(loc)) {
1415 const terrain_label* label = gui_->labels().get_label(loc);
1416 if(label) {
1417 const std::string& label_text = label->text().str();
1418 found = translation::ci_search(label_text, last_search_);
1419 }
1420 }
1421
1422 // Search unit name
1423 if(!gui_->fogged(loc)) {
1424 unit_map::const_iterator ui = pc_.get_units().find(loc);
1425 if(ui != pc_.get_units().end()) {
1426 const std::string& unit_name = ui->name();
1427 if(translation::ci_search(unit_name, last_search_)) {
1428 if(!gui_->viewing_team().is_enemy(ui->side())
1429 || !ui->invisible(ui->get_location())) {
1430 found = true;
1431 }
1432 }
1433 }
1434 }
1435
1436 if(loc == start)
1437 break;
1438 }
1439
1440 if(found) {
1441 last_search_hit_ = loc;
1442 gui_->scroll_to_tile(loc, game_display::ONSCREEN, false);
1443 gui_->highlight_hex(loc);
1444 } else {
1445 last_search_hit_ = map_location();
1446 // Not found, inform the player
1447 utils::string_map symbols;
1448 symbols["search"] = last_search_;
1449 const std::string msg = VGETTEXT("Could not find label or unit "
1450 "containing the string ‘$search’.",
1451 symbols);
1452 (void) gui2::show_message("", msg, message::auto_close);
1453 }
1454}
1455
1456void menu_handler::do_command(const std::string& str)
1457{
1458 console_handler ch(*this);
1459 ch.dispatch(str);
1460}
1461
1462std::vector<std::string> menu_handler::get_commands_list()
1463{
1464 console_handler ch(*this);
1465 // HACK: we need to call dispatch() at least once to get the
1466 // command list populated *at all*. Terrible design.
1467 // An empty command is silently ignored and has negligible
1468 // overhead, so we use that for this purpose here.
1469 ch.dispatch("");
1470 return ch.get_commands_list();
1471}
1472
1473void console_handler::do_refresh()
1474{
1477
1478 menu_handler_.gui_->create_buttons();
1479 menu_handler_.gui_->queue_rerender();
1480}
1481
1482void console_handler::do_droid()
1483{
1484 // :droid [<side> [on/off/full]]
1485 const std::string side_s = get_arg(1);
1486 std::string action = get_arg(2);
1487 std::transform(action.begin(), action.end(), action.begin(), tolower);
1488 // default to the current side if empty
1489 const unsigned int side = side_s.empty() ? team_num_ : lexical_cast_default<unsigned int>(side_s);
1490 const bool is_your_turn = menu_handler_.pc_.current_side() == static_cast<int>(menu_handler_.gui_->viewing_team().side());
1491 team& team = menu_handler_.board().get_team(side);
1492
1494 symbols["side"] = std::to_string(side);
1495
1496 if(side < 1 || side > menu_handler_.pc_.get_teams().size()) {
1497 command_failed(VGETTEXT("Can’t droid invalid side: ‘$side’.", symbols));
1498 return;
1499 } else if(team.is_network()) {
1500 command_failed(VGETTEXT("Can’t droid networked side: ‘$side’.", symbols));
1501 return;
1502 } else if(team.is_local()) {
1503 bool changed = false;
1504
1505 const bool is_human = team.is_human();
1506 const bool is_droid = team.is_droid();
1507 const bool is_proxy_human = team.is_proxy_human();
1508 const bool is_ai = team.is_ai();
1509
1510 if(action == "on") {
1511 if(is_ai && !is_your_turn) {
1512 command_failed(_("It is not allowed to change a side from AI to human control when it’s not your turn."));
1513 return;
1514 }
1515 if(!is_human || !is_droid) {
1516 team.make_human();
1517 team.make_droid();
1518 changed = true;
1519 if(is_ai) {
1520 menu_handler_.pc_.send_to_wesnothd(config {"change_controller", config {"side", side, "player", prefs::get().login(), "to", side_controller::human}});
1521 }
1522 print(get_cmd(), VGETTEXT("Side ‘$side’ controller is now controlled by: AI.", symbols));
1523 } else {
1524 print(get_cmd(), VGETTEXT("Side ‘$side’ is already droided.", symbols));
1525 }
1526 } else if(action == "off") {
1527 if(is_ai && !is_your_turn) {
1528 command_failed(_("It is not allowed to change a side from AI to human control when it’s not your turn."));
1529 return;
1530 }
1531 if(!is_human || !is_proxy_human) {
1532 team.make_human();
1534 changed = true;
1535 if(is_ai) {
1536 menu_handler_.pc_.send_to_wesnothd(config {"change_controller", config {"side", side, "player", prefs::get().login(), "to", side_controller::human}});
1537 }
1538 print(get_cmd(), VGETTEXT("Side ‘$side’ controller is now controlled by: human.", symbols));
1539 } else {
1540 print(get_cmd(), VGETTEXT("Side ‘$side’ is already not droided.", symbols));
1541 }
1542 } else if(action == "full") {
1543 if(!is_your_turn) {
1544 command_failed(_("It is not allowed to change a side from human to AI control when it’s not your turn."));
1545 return;
1546 }
1547 if(!is_ai || !is_droid) {
1548 team.make_ai();
1549 team.make_droid();
1550 changed = true;
1551 if(is_human || is_proxy_human) {
1552 menu_handler_.pc_.send_to_wesnothd(config {"change_controller", config {"side", side, "player", prefs::get().login(), "to", side_controller::ai}});
1553 }
1554 print(get_cmd(), VGETTEXT("Side ‘$side’ controller is now fully controlled by: AI.", symbols));
1555 } else {
1556 print(get_cmd(), VGETTEXT("Side ‘$side’ is already fully AI controlled.", symbols));
1557 }
1558 } else if(action == "") {
1559 if(is_ai && !is_your_turn) {
1560 command_failed(_("It is not allowed to change a side from AI to human control when it’s not your turn."));
1561 return;
1562 }
1563 if(is_ai || is_droid) {
1564 team.make_human();
1566 changed = true;
1567 if(is_ai) {
1568 menu_handler_.pc_.send_to_wesnothd(config {"change_controller", config {"side", side, "player", prefs::get().login(), "to", side_controller::human}});
1569 }
1570 print(get_cmd(), VGETTEXT("Side ‘$side’ controller is now controlled by: human.", symbols));
1571 } else {
1572 team.make_human();
1573 team.make_droid();
1574 changed = true;
1575 if(is_ai) {
1576 menu_handler_.pc_.send_to_wesnothd(config {"change_controller", config {"side", side, "player", prefs::get().login(), "to", side_controller::human}});
1577 }
1578 print(get_cmd(), VGETTEXT("Side ‘$side’ controller is now controlled by: AI.", symbols));
1579 }
1580 } else {
1581 print(get_cmd(), VGETTEXT("Invalid action provided for side ‘$side’. Valid actions are: on, off, full.", symbols));
1582 }
1583
1584 if(team_num_ == side && changed) {
1585 if(playsingle_controller* psc = dynamic_cast<playsingle_controller*>(&menu_handler_.pc_)) {
1586 psc->set_player_type_changed();
1587 }
1588 }
1589 } else {
1590 command_failed(VGETTEXT("Side ‘$side’ is not a human or AI player.", symbols));
1591 return;
1592 }
1593 menu_handler_.textbox_info_.close();
1594}
1595
1596void console_handler::do_terrain()
1597{
1598 // :terrain [<terrain type> [both|base|overlay]]
1599 const std::string terrain_type = get_arg(1);
1600 const std::string mode_str = get_arg(2);
1601
1602 const mouse_handler& mousehandler = menu_handler_.pc_.get_mouse_handler_base();
1603 const map_location& loc = mousehandler.get_last_hex();
1604
1605 synced_context::run_and_throw("debug_terrain",
1606 config {
1607 "x", loc.wml_x(),
1608 "y", loc.wml_y(),
1609 "terrain_type", terrain_type,
1610 "mode_str", mode_str,
1611 }
1612 );
1613}
1614
1615void console_handler::do_idle()
1616{
1617 // :idle [<side> [on/off]]
1618 const std::string side_s = get_arg(1);
1619 const std::string action = get_arg(2);
1620 // default to the current side if empty
1621 const unsigned int side = side_s.empty() ? team_num_ : lexical_cast_default<unsigned int>(side_s);
1622 team& team = menu_handler_.board().get_team(side);
1623
1624 if(side < 1 || side > menu_handler_.pc_.get_teams().size()) {
1626 symbols["side"] = side_s;
1627 command_failed(VGETTEXT("Can’t idle invalid side: ‘$side’.", symbols));
1628 return;
1629 } else if(team.is_network()) {
1631 symbols["side"] = std::to_string(side);
1632 command_failed(VGETTEXT("Can’t idle networked side: ‘$side’.", symbols));
1633 return;
1634 } else if(team.is_local_ai()) {
1636 symbols["side"] = std::to_string(side);
1637 command_failed(VGETTEXT("Can’t idle local ai side: ‘$side’.", symbols));
1638 return;
1639 } else if(team.is_local_human()) {
1640 if(team.is_idle() ? action == " on" : action == " off") {
1641 return;
1642 }
1643 // toggle the proxy controller between idle / non idle
1644 team.toggle_idle();
1645 if(team_num_ == side) {
1646 if(playsingle_controller* psc = dynamic_cast<playsingle_controller*>(&menu_handler_.pc_)) {
1647 psc->set_player_type_changed();
1648 }
1649 }
1650 }
1651 menu_handler_.textbox_info_.close();
1652}
1653
1654void console_handler::do_theme()
1655{
1657}
1658
1659void console_handler::do_control()
1660{
1661 // :control <side> <nick>
1662 if(!menu_handler_.pc_.is_networked_mp()) {
1663 return;
1664 }
1665
1666 const std::string side = get_arg(1);
1667 const std::string player = get_arg(2);
1668 if(player.empty()) {
1669 command_failed_need_arg(2);
1670 return;
1671 }
1672
1673 unsigned int side_num;
1674 try {
1675 side_num = lexical_cast<unsigned int>(side);
1676 } catch(const bad_lexical_cast&) {
1677 const auto& teams = menu_handler_.pc_.get_teams();
1678 const auto it_t = utils::ranges::find(teams, side, &team::save_id);
1679
1680 if(it_t == teams.end()) {
1682 symbols["side"] = side;
1683 command_failed(VGETTEXT("Can’t change control of invalid side: ‘$side’.", symbols));
1684 return;
1685 } else {
1686 side_num = it_t->side();
1687 }
1688 }
1689
1690 if(side_num < 1 || side_num > menu_handler_.pc_.get_teams().size()) {
1692 symbols["side"] = side;
1693 command_failed(VGETTEXT("Can’t change control of out-of-bounds side: ‘$side’.", symbols));
1694 return;
1695 }
1696
1697 menu_handler_.request_control_change(side_num, player);
1698 menu_handler_.textbox_info_.close();
1699}
1700
1701void console_handler::do_controller()
1702{
1703 const std::string side = get_arg(1);
1704 unsigned int side_num;
1705 try {
1706 side_num = lexical_cast<unsigned int>(side);
1707 } catch(const bad_lexical_cast&) {
1709 symbols["side"] = side;
1710 command_failed(VGETTEXT("Can’t query control of invalid side: ‘$side’.", symbols));
1711 return;
1712 }
1713
1714 if(side_num < 1 || side_num > menu_handler_.pc_.get_teams().size()) {
1716 symbols["side"] = side;
1717 command_failed(VGETTEXT("Can’t query control of out-of-bounds side: ‘$side’.", symbols));
1718 return;
1719 }
1720
1721 std::string report = side_controller::get_string(menu_handler_.board().get_team(side_num).controller());
1722 if(!menu_handler_.board().get_team(side_num).is_proxy_human()) {
1723 report += " (" + side_proxy_controller::get_string(menu_handler_.board().get_team(side_num).proxy_controller()) + ")";
1724 }
1725
1726 if(menu_handler_.board().get_team(side_num).is_network()) {
1727 report += " (networked)";
1728 }
1729
1730 print(get_cmd(), report);
1731}
1732
1733void console_handler::do_clear()
1734{
1735 menu_handler_.gui_->get_chat_manager().clear_chat_messages();
1736}
1737
1738void console_handler::do_foreground()
1739{
1740 menu_handler_.gui_->toggle_debug_flag(display::DEBUG_FOREGROUND);
1741 menu_handler_.gui_->invalidate_all();
1742}
1743
1744void console_handler::do_layers()
1745{
1746 display& disp = *(menu_handler_.gui_);
1747
1748 const mouse_handler& mousehandler = menu_handler_.pc_.get_mouse_handler_base();
1749 const map_location& loc = mousehandler.get_last_hex();
1750
1751 //
1752 // It's possible to invoke this dialog even if loc isn't a valid hex. I'm not sure
1753 // exactly how that happens, but it does seem to occur when moving the mouse outside
1754 // the window to the menu bar. Not sure if there's a bug when the set-last-hex code
1755 // in that case, but this check at least ensures the dialog is only ever shown for a
1756 // valid, on-map location. Otherwise, an assertion gets thrown.
1757 //
1758 // -- vultraz, 2017-09-21
1759 //
1760 if(menu_handler_.pc_.get_map().on_board_with_border(loc)) {
1761 terrain_layers::display(disp, loc);
1762 }
1763}
1764
1765void console_handler::do_fps()
1766{
1767 prefs::get().set_show_fps(!prefs::get().show_fps());
1768}
1769
1770void console_handler::do_benchmark()
1771{
1772 menu_handler_.gui_->toggle_debug_flag(display::DEBUG_BENCHMARK);
1773}
1774
1775void console_handler::do_save()
1776{
1777 menu_handler_.pc_.do_consolesave(get_data());
1778}
1779
1780void console_handler::do_save_quit()
1781{
1782 do_save();
1783 do_quit();
1784}
1785
1786void console_handler::do_quit()
1787{
1789}
1790
1791void console_handler::do_ignore_replay_errors()
1792{
1793 game_config::ignore_replay_errors = (get_data() != "off") ? true : false;
1794}
1795
1796void console_handler::do_nosaves()
1797{
1798 game_config::disable_autosave = (get_data() != "off") ? true : false;
1799}
1800
1801void console_handler::do_next_level()
1802{
1803 synced_context::run_and_throw("debug_next_level", config {"next_level", get_data()});
1804}
1805
1806void console_handler::do_choose_level()
1807{
1808 std::string tag = menu_handler_.pc_.get_classification().get_tagname();
1809 std::vector<std::string> options;
1810 std::string next;
1811 if(tag != "multiplayer") {
1812 for(const config& sc : menu_handler_.game_config_.child_range(tag)) {
1813 const std::string& id = sc["id"];
1814 options.push_back(id);
1815 if(id == menu_handler_.gamedata().next_scenario()) {
1816 next = id;
1817 }
1818 }
1819 } else {
1820 // find scenarios of multiplayer campaigns
1821 // (assumes that scenarios are ordered properly in the game_config)
1822 std::string scenario_id = menu_handler_.pc_.get_mp_settings().mp_scenario;
1823 if(auto this_scenario = menu_handler_.game_config_.find_child(tag, "id", scenario_id)) {
1824 std::string addon_id = this_scenario["addon_id"].str();
1825 for(const config& sc : menu_handler_.game_config_.child_range(tag)) {
1826 if(sc["addon_id"] == addon_id) {
1827 std::string id = sc["id"];
1828 options.push_back(id);
1829 if(id == menu_handler_.gamedata().next_scenario()) {
1830 next = id;
1831 }
1832 }
1833 }
1834 }
1835 }
1836 std::sort(options.begin(), options.end());
1837 int choice = std::distance(options.begin(), std::lower_bound(options.begin(), options.end(), next));
1838 {
1839 simple_item_selector dlg(_("Choose Scenario (Debug!)"), "", options);
1840 dlg.set_selected_index(choice);
1841 dlg.show();
1842 choice = dlg.selected_index();
1843 }
1844
1845 if(choice == -1) {
1846 return;
1847 }
1848
1849 if(std::size_t(choice) < options.size()) {
1850 synced_context::run_and_throw("debug_next_level", config {"next_level", options[choice]});
1851 }
1852}
1853
1854void console_handler::do_turn()
1855{
1856 tod_manager& tod_man = menu_handler_.gamestate().tod_manager_;
1857
1858 int turn = tod_man.turn() + 1;
1859 const std::string& data = get_data();
1860 if(!data.empty()) {
1862 }
1863 synced_context::run_and_throw("debug_turn", config {"turn", turn});
1864}
1865
1866void console_handler::do_turn_limit()
1867{
1868 int limit = get_data().empty() ? -1 : lexical_cast_default<int>(get_data(), 1);
1869 synced_context::run_and_throw("debug_turn_limit", config {"turn_limit", limit});
1870}
1871
1872void console_handler::do_debug()
1873{
1874 if(!menu_handler_.pc_.is_networked_mp() || game_config::mp_debug) {
1875 print(get_cmd(), _("Debug mode activated!"));
1877 } else {
1878 command_failed(_("Debug mode not available in network games"));
1879 }
1880}
1881
1882void console_handler::do_nodebug()
1883{
1884 if(game_config::debug) {
1885 print(get_cmd(), _("Debug mode deactivated!"));
1887 }
1888}
1889
1890void console_handler::do_lua()
1891{
1892 if(!menu_handler_.gamestate().lua_kernel_) {
1893 return;
1894 }
1895
1896 synced_context::run_and_throw("debug_lua", config {"code", get_data()});
1897}
1898
1899void console_handler::do_unsafe_lua()
1900{
1901 if(!menu_handler_.gamestate().lua_kernel_) {
1902 return;
1903 }
1904
1905 const int retval = gui2::show_message(_("WARNING! Unsafe Lua Mode"),
1906 _("Executing Lua code in in this manner opens your computer to potential security breaches from any "
1907 "malicious add-ons or other programs you may have installed.\n\n"
1908 "Do not continue unless you really know what you are doing."), message::ok_cancel_buttons);
1909
1910 if(retval == gui2::retval::OK) {
1911 print(get_cmd(), _("Unsafe mode enabled!"));
1912 menu_handler_.gamestate().lua_kernel_->load_package();
1913 }
1914}
1915
1916void console_handler::do_custom()
1917{
1918 prefs::get().set_custom_command(get_data());
1919}
1920
1921void console_handler::do_set_alias()
1922{
1923 const std::string data = get_data();
1924 const std::string::const_iterator j = std::find(data.begin(), data.end(), '=');
1925 const std::string alias(data.begin(), j);
1926 if(j != data.end()) {
1927 const std::string command(j + 1, data.end());
1928 if(!command.empty()) {
1929 register_alias(command, alias);
1930 } else {
1931 // "alias something=" deactivate this alias. We just set it
1932 // equal to itself here. Later preferences will filter empty alias.
1933 register_alias(alias, alias);
1934 }
1935 prefs::get().add_alias(alias, command);
1936 // directly save it for the moment, but will slow commands sequence
1938 } else {
1939 // "alias something" display its value
1940 // if no alias, will be "'something' = 'something'"
1941 const std::string command = chmap::get_actual_cmd(alias);
1942 print(get_cmd(), "'" + alias + "'" + " = " + "'" + command + "'");
1943 }
1944}
1945
1946void console_handler::do_set_var()
1947{
1948 const std::string data = get_data();
1949 if(data.empty()) {
1950 command_failed_need_arg(1);
1951 return;
1952 }
1953
1954 const std::string::const_iterator j = std::find(data.begin(), data.end(), '=');
1955 if(j != data.end()) {
1956 const std::string name(data.begin(), j);
1957 const std::string value(j + 1, data.end());
1958 synced_context::run_and_throw("debug_set_var", config {"name", name, "value", value});
1959 } else {
1960 command_failed(_("Variable not found"));
1961 }
1962}
1963
1964void console_handler::do_show_var()
1965{
1966 gui2::show_transient_message("", menu_handler_.gamedata().get_variable_const(get_data()));
1967}
1968
1969void console_handler::do_inspect()
1970{
1972 gamestate_inspector::display(
1973 menu_handler_.gamedata().get_variables(), *resources::game_events, menu_handler_.board());
1974}
1975
1976void console_handler::do_control_dialog()
1977{
1978 mp_change_control::display(menu_handler_);
1979}
1980
1981void console_handler::do_unit()
1982{
1983 // prevent SIGSEGV due to attempt to set HP during a fight
1985 return;
1986 }
1987
1988 unit_map::iterator i = menu_handler_.current_unit();
1989 if(i == menu_handler_.pc_.get_units().end()) {
1991 symbols["unit"] = get_arg(1);
1992 command_failed(VGETTEXT(
1993 "Debug command ‘unit: $unit’ failed: no unit selected or hovered over.",
1994 symbols));
1995 return;
1996 }
1997
1998 const map_location loc = i->get_location();
1999 const std::string data = get_data(1);
2000 std::vector<std::string> parameters = utils::split(data, '=', utils::STRIP_SPACES);
2001 if(parameters.size() < 2) {
2002 return;
2003 }
2004
2005 if(parameters[0] == "alignment") {
2006 auto alignment = unit_alignments::get_enum(parameters[1]);
2007 if(!alignment) {
2009 symbols["alignment"] = get_arg(1);
2010 command_failed(VGETTEXT(
2011 "Invalid alignment: ‘$alignment’, needs to be one of lawful, neutral, chaotic, or liminal.",
2012 symbols));
2013 return;
2014 }
2015 }
2016
2017 synced_context::run_and_throw("debug_unit",
2018 config {
2019 "x", loc.wml_x(),
2020 "y", loc.wml_y(),
2021 "name", parameters[0],
2022 "value", parameters[1],
2023 }
2024 );
2025}
2026
2027void console_handler::do_discover()
2028{
2029 for(const unit_type_data::unit_type_map::value_type& i : unit_types.types()) {
2030 prefs::get().encountered_units().insert(i.second.id());
2031 }
2032}
2033
2034void console_handler::do_undiscover()
2035{
2036 const int res = gui2::show_message("Undiscover",
2037 _("Do you wish to clear all of your discovered units from help?"), message::yes_no_buttons);
2038 if(res != gui2::retval::CANCEL) {
2039 prefs::get().encountered_units().clear();
2040 }
2041}
2042
2043/** Implements the (debug mode) console command that creates a unit. */
2044void console_handler::do_create()
2045{
2046 const mouse_handler& mousehandler = menu_handler_.pc_.get_mouse_handler_base();
2047 const map_location& loc = mousehandler.get_last_hex();
2048 if(menu_handler_.pc_.get_map().on_board(loc)) {
2049 const unit_type* ut = unit_types.find(get_data());
2050 if(!ut) {
2051 command_failed(_("Invalid unit type"));
2052 return;
2053 }
2054
2055 // Create the unit.
2057 } else {
2058 command_failed(_("Invalid location"));
2059 }
2060}
2061
2062void console_handler::do_fog()
2063{
2064 synced_context::run_and_throw("debug_fog", config());
2065}
2066
2067void console_handler::do_shroud()
2068{
2069 synced_context::run_and_throw("debug_shroud", config());
2070}
2071
2072void console_handler::do_gold()
2073{
2074 synced_context::run_and_throw("debug_gold", config {"gold", lexical_cast_default<int>(get_data(), 1000)});
2075}
2076
2077void console_handler::do_event()
2078{
2079 synced_context::run_and_throw("debug_event", config {"eventname", get_data()});
2080}
2081
2082void console_handler::do_toggle_draw_coordinates()
2083{
2084 menu_handler_.gui_->toggle_debug_flag(display::DEBUG_COORDINATES);
2085 menu_handler_.gui_->invalidate_all();
2086}
2087void console_handler::do_toggle_draw_terrain_codes()
2088{
2089 menu_handler_.gui_->toggle_debug_flag(display::DEBUG_TERRAIN_CODES);
2090 menu_handler_.gui_->invalidate_all();
2091}
2092
2093void console_handler::do_toggle_draw_num_of_bitmaps()
2094{
2095 menu_handler_.gui_->toggle_debug_flag(display::DEBUG_NUM_BITMAPS);
2096 menu_handler_.gui_->invalidate_all();
2097}
2098
2099void console_handler::do_toggle_whiteboard()
2100{
2101 if(const std::shared_ptr<wb::manager>& whiteb = menu_handler_.pc_.get_whiteboard()) {
2102 whiteb->set_active(!whiteb->is_active());
2103 if(whiteb->is_active()) {
2104 print(get_cmd(), _("Planning mode activated!"));
2105 whiteb->print_help_once();
2106 } else {
2107 print(get_cmd(), _("Planning mode deactivated!"));
2108 }
2109 }
2110}
2111
2112void console_handler::do_whiteboard_options()
2113{
2114 if(menu_handler_.pc_.get_whiteboard()) {
2115 menu_handler_.pc_.get_whiteboard()->options_dlg();
2116 }
2117}
2118
2119// TODO: rename this function - it only does general wfl now
2120void menu_handler::do_ai_formula(const std::string& str, int /*side_num*/, mouse_handler& /*mousehandler*/)
2121{
2122 try {
2124 add_chat_message(std::chrono::system_clock::now(), "wfl", 0, result.to_debug_string());
2125 } catch(const wfl::formula_error&) {
2126 } catch(...) {
2127 add_chat_message(std::chrono::system_clock::now(), "wfl", 0, "UNKNOWN ERROR IN FORMULA: "+utils::get_unknown_exception_type());
2128 }
2129}
2130
2131void menu_handler::user_command()
2132{
2133 textbox_info_.show(gui::TEXTBOX_COMMAND, translation::sgettext("prompt^Command:"), "", false, *gui_);
2134}
2135
2136void menu_handler::request_control_change(int side_num, const std::string& player)
2137{
2138 std::string side = std::to_string(side_num);
2139 if(board().get_team(side_num).is_local_human() && player == prefs::get().login()) {
2140 // this is already our side.
2141 return;
2142 } else {
2143 // The server will (or won't because we aren't allowed to change the controller)
2144 // send us a [change_controller] back, which we then handle in playturn.cpp
2145 pc_.send_to_wesnothd(config {"change_controller", config {"side", side, "player", player}});
2146 }
2147}
2148
2149void menu_handler::custom_command()
2150{
2151 for(const std::string& command : utils::split(prefs::get().custom_command(), ';')) {
2152 do_command(command);
2153 }
2154}
2155
2156void menu_handler::ai_formula()
2157{
2158 if(!pc_.is_networked_mp()) {
2159 textbox_info_.show(gui::TEXTBOX_AI, translation::sgettext("prompt^Formula:"), "", false, *gui_);
2160 }
2161}
2162
2163void menu_handler::clear_messages()
2164{
2165 gui_->get_chat_manager().clear_chat_messages(); // also clear debug-messages and WML-error-messages
2166}
2167
2168void menu_handler::send_to_server(const config& cfg)
2169{
2170 pc_.send_to_wesnothd(cfg);
2171}
2172
2173} // end namespace events
map_location loc
Definition move.cpp:172
Various functions related to moving units.
#define ERR_NG
double t
A config object defines a single node in a WML file, with access to child nodes.
Definition config.hpp:157
int village_owner(const map_location &loc) const
Given the location of a village, will return the 1-based number of the team that currently owns it,...
bool is_observer() const
Check if we are an observer in this game.
can_move_result unit_can_move(const unit &u) const
Work out what u can do - this does not check which player's turn is currently active,...
virtual const unit_map & units() const =0
Sort-of-Singleton that many classes, both GUI and non-GUI, use to access the game data.
Definition display.hpp:88
const team & viewing_team() const
Definition display.cpp:337
@ DEBUG_COORDINATES
Overlays x,y coords on tiles.
Definition display.hpp:898
@ DEBUG_BENCHMARK
Toggle to continuously redraw the whole map.
Definition display.hpp:910
@ DEBUG_NUM_BITMAPS
Overlays number of bitmaps on tiles.
Definition display.hpp:904
@ DEBUG_FOREGROUND
Separates background and foreground terrain layers.
Definition display.hpp:907
@ DEBUG_TERRAIN_CODES
Overlays terrain codes on tiles.
Definition display.hpp:901
void scroll_to_tile(const map_location &loc, SCROLL_TYPE scroll_type=ONSCREEN, bool check_fogged=true, bool force=true)
Scroll such that location loc is on-screen.
Definition display.cpp:1815
void queue_rerender()
Marks everything for rendering including all tiles and sidebar.
Definition display.cpp:2105
const display_context & context() const
Definition display.hpp:187
virtual std::string get_arg(unsigned i) const
std::string get_flags_description() const
virtual std::string get_cmd() const
console_handler(menu_handler &menu_handler)
void print(const std::string &title, const std::string &message)
virtual void register_alias(const std::string &to_cmd, const std::string &cmd)
bool is_enabled(const chmap::command &c) const
virtual std::string get_data(unsigned n=1) const
menu_handler & menu_handler_
std::string get_command_flags_description(const chmap::command &c) const
virtual void register_command(const std::string &cmd, chat_command_handler::command_handler h, const std::string &help="", const std::string &usage="", const std::string &flags="")
map_command_handler< console_handler > chmap
const unsigned int team_num_
std::vector< std::string > get_commands_list() const
game_board & board() const
gui::floating_textbox & get_textbox()
menu_handler(play_controller &pc)
game_data & gamedata()
gui::floating_textbox textbox_info_
void show_statistics(int side_num)
void recruit(int side_num, const map_location &last_hex)
play_controller & pc_
game_display * gui_
bool has_friends() const
game_state & gamestate() const
void disable_units_highlight()
Use this to disable hovering an unit from highlighting its movement range.
void set_current_paths(const pathfind::paths &new_paths)
pathfind::marked_route get_route(const unit *un, map_location go_to, const team &team) const
map_location get_selected_hex() const
const map_location hovered_hex() const
Uses SDL and game_display::hex_clicked_on to fetch the hex the mouse is hovering, if applicable.
bool hex_hosts_unit(const map_location &hex) const
Unit exists on the hex, no matter if friend or foe.
void cycle_units(const bool browse, const bool reverse=false)
const map_location & get_last_hex() const
Game board class.
unit_map::iterator find_visible_unit(const map_location &loc, const team &current_team, bool see_all=false)
team & get_team(int i)
void scroll_to_leader(int side, SCROLL_TYPE scroll_type=ONSCREEN, bool force=true)
Scrolls to the leader of a certain side.
virtual const std::set< std::string > & observers() const override
virtual void select_hex(map_location hex) override
Function to display a location as selected.
game_board board_
game_data gamedata_
std::string write() const
Definition map.cpp:172
file_dialog & set_path(const std::string &value)
Sets the initial file selection.
file_dialog & set_save_mode(bool value)
Sets the dialog's behavior on non-existent file name inputs.
std::string path() const
Gets the current file selection.
file_dialog & set_extension(const std::string &value)
Sets allowed file extensions for file names in save mode.
file_dialog & set_title(const std::string &value)
Sets the current dialog title text.
static bool execute(game_board &board, const team &viewing_team, int &selected_side_number)
Main class to show messages to the user.
Definition message.hpp:36
@ yes_no_buttons
Shows a yes and no button.
Definition message.hpp:81
@ ok_cancel_buttons
Shows an ok and cancel button.
Definition message.hpp:77
@ auto_close
Enables auto close.
Definition message.hpp:71
bool show(const unsigned auto_close_time=0)
Shows the window.
static std::unique_ptr< units_dialog > build_unit_list_dialog(std::vector< unit_const_ptr > &units_list)
static std::unique_ptr< units_dialog > build_create_dialog(const std::vector< const unit_type * > &types_list)
static std::unique_ptr< units_dialog > build_recruit_dialog(const std::vector< const unit_type * > &recruit_list, recruit_msgs_map &err_msgs_map, const team &team)
static std::unique_ptr< units_dialog > build_recall_dialog(std::vector< unit_const_ptr > &recall_list, const team &team)
Base container class.
Definition grid.hpp:32
const t_string & get_label() const
void show(gui::TEXTBOX_MODE mode, const std::string &label, const std::string &check_label, bool checked, game_display &gui)
void show_objectives() const
const gamemap & get_map() const
std::vector< team > & get_teams()
statistics_t & statistics()
game_state & gamestate()
void notify_event(const std::string &name, const config &data)
Definition manager.cpp:144
static plugins_manager * get()
Definition manager.cpp:58
bool show_theme_dialog()
static prefs & get()
std::set< std::string > & encountered_units()
void add_alias(const std::string &alias, const std::string &command)
void write_preferences()
bool message_private()
void set_message_private(bool value)
void set_show_fps(bool value)
bool confirm_no_moves()
std::string login()
bool empty() const
Is it empty?
static config get_recall(const std::string &unit_id, const map_location &loc, const map_location &from)
static config get_recruit(const std::string &type_id, const map_location &loc, const map_location &from)
static config get_update_shroud()
Records that the player has manually updated fog/shroud.
static config get_auto_shroud(bool turned_on, bool block_undo=true)
Records that the player has toggled automatic shroud updates.
void add_rename(const std::string &name, const map_location &loc)
Definition replay.cpp:278
void add_label(const terrain_label *)
Definition replay.cpp:257
void speak(const config &cfg)
Definition replay.cpp:335
void clear_labels(const std::string &, bool)
Definition replay.cpp:268
static synced_state get_synced_state()
static bool run_and_throw(const std::string &commandname, const config &data, action_spectator &spectator=get_default_spectator())
bool empty() const
Definition tstring.hpp:200
This class stores all the data for a single 'side' (in game nomenclature).
Definition team.hpp:74
bool is_ai() const
Definition team.hpp:292
bool is_proxy_human() const
Definition team.hpp:309
int side() const
Definition team.hpp:182
bool is_human() const
Definition team.hpp:291
const std::string & save_id() const
Definition team.hpp:258
int recall_cost() const
Definition team.hpp:198
bool is_droid() const
Definition team.hpp:310
bool auto_shroud_updates() const
Definition team.hpp:366
bool is_local() const
Definition team.hpp:288
bool is_local_human() const
Definition team.hpp:294
void toggle_idle()
Definition team.hpp:321
int gold() const
Definition team.hpp:183
void set_last_recruit(const std::string &u_type)
Definition team.hpp:256
recall_list_manager & recall_list()
Definition team.hpp:242
bool is_network() const
Definition team.hpp:289
bool is_local_ai() const
Definition team.hpp:295
bool is_idle() const
Definition team.hpp:311
void make_droid()
Definition team.hpp:313
void make_ai()
Definition team.hpp:301
const std::string & team_name() const
Definition team.hpp:323
void make_proxy_human()
Definition team.hpp:315
void make_human()
Definition team.hpp:300
static color_t get_side_color(int side)
Definition team.cpp:943
void increment_action_bonus_count()
Definition team.hpp:240
const std::string & last_recruit() const
Definition team.hpp:255
To store label data Class implements logic for rendering.
Definition label.hpp:111
const t_string & text() const
Definition label.hpp:139
int turn() const
Container associating units to locations.
Definition map.hpp:98
unit_iterator end()
Definition map.hpp:428
unit_iterator begin()
Definition map.hpp:418
@ NUM_GENDERS
Definition race.hpp:28
const std::vector< const unit_type * > types_list() const
Definition types.hpp:399
const unit_type * find(const std::string &key, unit_type::BUILD_STATUS status=unit_type::FULL) const
Finds a unit_type by its id() and makes sure it is built to the specified level.
Definition types.cpp:1252
const unit_type_map & types() const
Definition types.hpp:398
A single unit type that the player may recruit.
Definition types.hpp:43
int cost() const
Definition types.hpp:176
const std::string & id() const
The id for this unit_type.
Definition types.hpp:145
This class represents a single unit of a specific type.
Definition unit.hpp:39
A variable-expanding proxy for the config class.
Definition variable.hpp:45
static vconfig empty_vconfig()
Definition variable.cpp:142
static variant evaluate(const const_formula_ptr &f, const formula_callable &variables, formula_debugger *fdb=nullptr, variant default_res=variant(0))
Definition formula.hpp:48
An object representing the state of the game, providing access to the map and basic information.
std::string to_debug_string(bool verbose=false, formula_seen_stack *seen=nullptr) const
Definition variant.cpp:686
Various functions related to the creation of units (recruits, recalls, and placed units).
const config * cfg
static void print(std::stringstream &sstr, const std::string &queue, const std::string &id)
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
#define VNGETTEXT(msgid, msgid_plural, count,...)
Contains the exception interfaces used to signal completion of a scenario, campaign or turn.
void throw_quit_game_exception()
static std::string _(const char *str)
Definition gettext.hpp:100
bool user_end_turn() const
Check whether the user ended their turn.
Definition unit.hpp:707
const std::string & id() const
Gets this unit's id.
Definition unit.hpp:286
int side() const
The side this unit belongs to.
Definition unit.hpp:249
const t_string & name() const
Gets this unit's translatable display name.
Definition unit.hpp:309
const map_location & get_goto() const
The map location to which this unit is moving over multiple turns, if any.
Definition unit.hpp:1358
const map_location & get_location() const
The current map location this unit is at.
Definition unit.hpp:1327
bool has_moved() const
Checks if this unit has moved.
Definition unit.hpp:1282
void set_goto(const map_location &new_goto)
Sets this unit's long term destination.
Definition unit.hpp:1364
int movement_left() const
Gets how far a unit can move, considering the incapacitated flag.
Definition unit.hpp:1252
std::string label
What to show in the filter's drop-down list.
Definition manager.cpp:201
std::string id
Text to match against addon_info.tags()
Definition manager.cpp:199
Standard logging facilities (interface).
static lg::log_domain log_engine("engine")
#define ERR_NG
#define LOG_NG
std::set< std::string > get_recruits(int side, const map_location &recruit_loc)
Gets the recruitable units from a side's leaders' personal recruit lists who can recruit on or from a...
Definition create.cpp:60
game_events::pump_result_t get_village(const map_location &loc, int side, bool *action_timebonus, bool fire_event)
Makes it so the village at the given location is owned by the given side.
Definition move.cpp:221
std::vector< unit_const_ptr > get_recalls(int side, const map_location &recall_loc)
Gets the recallable units for a side, restricted by that side's leaders' personal abilities to recall...
Definition create.cpp:160
std::size_t move_unit_and_record(const std::vector< map_location > &steps, bool continued_move, bool *interrupted)
Wrapper around the other overload.
Definition move.cpp:1435
std::string find_recall_location(const int side, map_location &recall_location, map_location &recall_from, const unit &unit_recall)
Finds a location on which to recall unit_recall.
Definition create.cpp:330
auto serialize_timestamp(const std::chrono::system_clock::time_point &time)
Definition chrono.hpp:58
Handling of system events.
std::string get_legacy_editor_dir()
const std::string map_extension
void write_file(const std::string &fname, const std::string &data, std::ios_base::openmode mode=std::ios_base::binary)
Throws io_exception if an error occurs.
const color_t LABEL_COLOR
Game configuration data as global variables.
bool ignore_replay_errors
const bool & debug
bool disable_autosave
const std::string observer_team_name
observer team name used for observer team chat
void set_debug(bool new_debug)
void show_transient_error_message(const std::string &message, const std::string &image, const bool message_use_markup)
Shows a transient error message to the user.
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)
Shows a transient message to the user.
void show_message(const std::string &title, const std::string &msg, const std::string &button_caption, const bool auto_close, const bool message_use_markup, const bool title_use_markup)
Shows a message to the user.
Definition message.cpp:148
retval
Default window/dialog return values.
Definition retval.hpp:30
@ OK
Dialog was closed with the OK button.
Definition retval.hpp:35
@ CANCEL
Dialog was closed with the CANCEL button.
Definition retval.hpp:38
void show_terrain_description(const terrain_type &t)
Definition help.cpp:74
void show_unit_description(const unit &u)
Definition help.cpp:64
void show_help(const std::string &show_topic)
Open the help browser.
Definition help.cpp:84
void flush_cache()
Purges all image caches.
Definition picture.cpp:318
logger & info()
Definition log.cpp:352
bool logged_in_as_moderator()
Gets whether the currently logged-in user is a moderator.
game_events::manager * game_events
Definition resources.cpp:24
replay * recorder
Definition resources.cpp:28
void flush_cache()
Definition sound.cpp:1072
bool ci_search(const std::string &s1, const std::string &s2)
Case-insensitive search.
Definition gettext.cpp:559
static std::string sgettext(const char *str)
Definition gettext.hpp:64
std::string check_recruit_list(const std::string &type, int side_number, const map_location &target_hex)
Definition helper.cpp:186
std::string check_recruit_purse(int unit_cost, int current_purse, int investments)
Definition helper.cpp:174
int planned_gold_spent(int side_number)
Definition helper.cpp:167
std::tuple< std::string, map_location, map_location > validate_recruit_target(const std::string &type, int side_number, const map_location &target_hex)
Verifies that target_hex is a valid recruit location for the given side.
Definition helper.cpp:198
auto find(Container &container, const Value &value, const Projection &projection={})
Definition general.hpp:213
@ STRIP_SPACES
REMOVE_EMPTY: remove empty elements.
std::string get_unknown_exception_type()
Utility function for finding the type of thing caught with catch(...).
Definition general.cpp:23
std::map< std::string, t_string > string_map
std::vector< std::string > split(const config_attribute_value &val)
Definition display.hpp:45
int w
Definition pathfind.cpp:188
std::string_view data
Definition picture.cpp:188
std::shared_ptr< const unit > unit_const_ptr
Definition ptr.hpp:27
const std::string & gender_string(unit_race::GENDER gender)
Definition race.cpp:140
Replay control code.
static config unit_name(const unit *u)
Definition reports.cpp:163
std::unique_ptr< MIX_Audio, decltype(&MIX_DestroyAudio)> value
Definition sound.cpp:139
rect dst
Location on the final composed sheet.
rect src
Non-transparent portion of the surface to compose.
Thrown when a lexical_cast fails.
The basic class for representing 8-bit RGB or RGBA colour values.
Definition color.hpp:51
An exception object used when an IO error occurs.
Encapsulates the map of the game.
Definition location.hpp:46
bool valid() const
Definition location.hpp:111
int wml_y() const
Definition location.hpp:187
int wml_x() const
Definition location.hpp:186
static const map_location & null_location()
Definition location.hpp:103
Structure which holds a single route and marks for special events.
Definition pathfind.hpp:142
std::vector< map_location > & steps
Definition pathfind.hpp:187
Object which contains all the possible locations a unit can move to, with associated best routes to t...
Definition pathfind.hpp:73
static std::string get_string(enum_type key)
Converts a enum to its string equivalent.
Definition enum_base.hpp:46
static constexpr utils::optional< enum_type > get_enum(const std::string_view value)
Converts a string into its enum equivalent.
Definition enum_base.hpp:57
Object which temporarily resets a unit's movement.
Definition unit.hpp:2017
ONLY IF whiteboard is currently active, applies the planned unit map for the duration of the struct's...
Definition manager.hpp:274
Applies the planned unit map for the duration of the struct's life.
Definition manager.hpp:253
const std::string & gamedata
static map_location::direction n
#define DBG_WB
Definition typedefs.hpp:28
unit_type_data unit_types
Definition types.cpp:1498
Various functions that implement the undoing (and redoing) of in-game commands.
#define i
#define e
#define h
#define c