Fix ICU iterators on leading/trailing whitespace
[openttd/fttd.git] / src / console_cmds.cpp
blobb51d6d2d33be3a08d5e6328e832a617d4e598241
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file console_cmds.cpp Implementation of the console hooks. */
12 #include "stdafx.h"
13 #include "console_internal.h"
14 #include "debug.h"
15 #include "engine_func.h"
16 #include "landscape.h"
17 #include "saveload/saveload.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "network/network_base.h"
21 #include "network/network_admin.h"
22 #include "network/network_client.h"
23 #include "command_func.h"
24 #include "settings_func.h"
25 #include "fios.h"
26 #include "fileio_func.h"
27 #include "screenshot.h"
28 #include "genworld.h"
29 #include "strings_func.h"
30 #include "viewport_func.h"
31 #include "window_func.h"
32 #include "date_func.h"
33 #include "company_func.h"
34 #include "gamelog.h"
35 #include "ai/ai.hpp"
36 #include "ai/ai_config.hpp"
37 #include "newgrf.h"
38 #include "console_func.h"
39 #include "engine_base.h"
40 #include "game/game.hpp"
41 #include "table/strings.h"
43 /* scriptfile handling */
44 static bool _script_running; ///< Script is running (used to abort execution when #ConReturn is encountered).
46 /* console command defines */
47 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
48 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
51 /****************
52 * command hooks
53 ****************/
55 #ifdef ENABLE_NETWORK
57 /**
58 * Check network availability and inform in console about failure of detection.
59 * @return Network availability.
61 static inline bool NetworkAvailable(bool echo)
63 if (!_network_available) {
64 if (echo) IConsoleError("You cannot use this command because there is no network available.");
65 return false;
67 return true;
70 /**
71 * Check whether we are a server.
72 * @return Are we a server? True when yes, false otherwise.
74 DEF_CONSOLE_HOOK(ConHookServerOnly)
76 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
78 if (!_network_server) {
79 if (echo) IConsoleError("This command is only available to a network server.");
80 return CHR_DISALLOW;
82 return CHR_ALLOW;
85 /**
86 * Check whether we are a client in a network game.
87 * @return Are we a client in a network game? True when yes, false otherwise.
89 DEF_CONSOLE_HOOK(ConHookClientOnly)
91 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
93 if (_network_server) {
94 if (echo) IConsoleError("This command is not available to a network server.");
95 return CHR_DISALLOW;
97 return CHR_ALLOW;
101 * Check whether we are in a multiplayer game.
102 * @return True when we are client or server in a network game.
104 DEF_CONSOLE_HOOK(ConHookNeedNetwork)
106 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
108 if (!_networking || (!_network_server && !MyClient::IsConnected())) {
109 if (echo) IConsoleError("Not connected. This command is only available in multiplayer.");
110 return CHR_DISALLOW;
112 return CHR_ALLOW;
116 * Check whether we are in single player mode.
117 * @return True when no network is active.
119 DEF_CONSOLE_HOOK(ConHookNoNetwork)
121 if (_networking) {
122 if (echo) IConsoleError("This command is forbidden in multiplayer.");
123 return CHR_DISALLOW;
125 return CHR_ALLOW;
128 #else
129 # define ConHookNoNetwork NULL
130 #endif /* ENABLE_NETWORK */
132 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
134 if (_settings_client.gui.newgrf_developer_tools) {
135 if (_game_mode == GM_MENU) {
136 if (echo) IConsoleError("This command is only available in game and editor.");
137 return CHR_DISALLOW;
139 #ifdef ENABLE_NETWORK
140 return ConHookNoNetwork(echo);
141 #else
142 return CHR_ALLOW;
143 #endif
145 return CHR_HIDE;
149 * Show help for the console.
150 * @param str String to print in the console.
152 static void IConsoleHelp(const char *str)
154 IConsolePrintF(CC_WARNING, "- %s", str);
158 * Reset status of all engines.
159 * @return Will always succeed.
161 DEF_CONSOLE_CMD(ConResetEngines)
163 if (argc == 0) {
164 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
165 return true;
168 StartupEngines();
169 return true;
173 * Reset status of the engine pool.
174 * @return Will always return true.
175 * @note Resetting the pool only succeeds when there are no vehicles ingame.
177 DEF_CONSOLE_CMD(ConResetEnginePool)
179 if (argc == 0) {
180 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
181 return true;
184 if (_game_mode == GM_MENU) {
185 IConsoleError("This command is only available in game and editor.");
186 return true;
189 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
190 IConsoleError("This can only be done when there are no vehicles in the game.");
191 return true;
194 return true;
197 #ifdef _DEBUG
199 * Reset a tile to bare land in debug mode.
200 * param tile number.
201 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
203 DEF_CONSOLE_CMD(ConResetTile)
205 if (argc == 0) {
206 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
207 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
208 return true;
211 if (argc == 2) {
212 uint32 result;
213 if (GetArgumentInteger(&result, argv[1])) {
214 DoClearSquare((TileIndex)result);
215 return true;
219 return false;
221 #endif /* _DEBUG */
224 * Scroll to a tile on the map.
225 * @param arg1 tile tile number or tile x coordinate.
226 * @param arg2 optionally tile y coordinate.
227 * @note When only one argument is given it is intepreted as the tile number.
228 * When two arguments are given, they are interpreted as the tile's x
229 * and y coordinates.
230 * @return True when either console help was shown or a proper amount of parameters given.
232 DEF_CONSOLE_CMD(ConScrollToTile)
234 switch (argc) {
235 case 0:
236 IConsoleHelp("Center the screen on a given tile.");
237 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
238 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
239 return true;
241 case 2: {
242 uint32 result;
243 if (GetArgumentInteger(&result, argv[1])) {
244 if (result >= MapSize()) {
245 IConsolePrint(CC_ERROR, "Tile does not exist");
246 return true;
248 ScrollMainWindowToTile((TileIndex)result);
249 return true;
251 break;
254 case 3: {
255 uint32 x, y;
256 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
257 if (x >= MapSizeX() || y >= MapSizeY()) {
258 IConsolePrint(CC_ERROR, "Tile does not exist");
259 return true;
261 ScrollMainWindowToTile(TileXY(x, y));
262 return true;
264 break;
268 return false;
272 * Save the map to a file.
273 * @param filename the filename to save the map to.
274 * @return True when help was displayed or the file attempted to be saved.
276 DEF_CONSOLE_CMD(ConSave)
278 if (argc == 0) {
279 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
280 return true;
283 if (argc == 2) {
284 char *filename = str_fmt("%s.sav", argv[1]);
285 IConsolePrint(CC_DEFAULT, "Saving map...");
287 if (!SaveGame(filename, SAVE_DIR)) {
288 IConsolePrint(CC_ERROR, "Saving map failed");
289 } else {
290 IConsolePrintF(CC_DEFAULT, "Map successfully saved to %s", filename);
292 free(filename);
293 return true;
296 return false;
300 * Explicitly save the configuration.
301 * @return True.
303 DEF_CONSOLE_CMD(ConSaveConfig)
305 if (argc == 0) {
306 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
307 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
308 return true;
311 SaveToConfig();
312 IConsolePrint(CC_DEFAULT, "Saved config.");
313 return true;
317 * Get savegame file informations.
318 * @param file The savegame filename to return information about. Can be the actual name
319 * or a numbered entry into the filename list.
320 * @return FiosItem The information on the file.
322 static const FiosItem *GetFiosItem(const char *file)
324 _saveload_mode = SLD_LOAD_GAME;
325 BuildFileList();
327 for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
328 if (strcmp(file, item->name) == 0) return item;
329 if (strcmp(file, item->title) == 0) return item;
332 /* If no name matches, try to parse it as number */
333 char *endptr;
334 int i = strtol(file, &endptr, 10);
335 if (file == endptr || *endptr != '\0') i = -1;
337 if (IsInsideMM(i, 0, _fios_items.Length())) return _fios_items.Get(i);
339 /* As a last effort assume it is an OpenTTD savegame and
340 * that the ".sav" part was not given. */
341 char long_file[MAX_PATH];
342 seprintf(long_file, lastof(long_file), "%s.sav", file);
343 for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
344 if (strcmp(long_file, item->name) == 0) return item;
345 if (strcmp(long_file, item->title) == 0) return item;
348 return NULL;
352 DEF_CONSOLE_CMD(ConLoad)
354 if (argc == 0) {
355 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
356 return true;
359 if (argc != 2) return false;
361 const char *file = argv[1];
362 const FiosItem *item = GetFiosItem(file);
363 if (item != NULL) {
364 switch (item->type) {
365 case FIOS_TYPE_FILE: case FIOS_TYPE_OLDFILE: {
366 _switch_mode = SM_LOAD_GAME;
367 SetFiosType(item->type);
369 strecpy(_file_to_saveload.name, FiosBrowseTo(item), lastof(_file_to_saveload.name));
370 strecpy(_file_to_saveload.title, item->title, lastof(_file_to_saveload.title));
371 break;
373 default: IConsolePrintF(CC_ERROR, "%s: Not a savegame.", file);
375 } else {
376 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
379 FiosFreeSavegameList();
380 return true;
384 DEF_CONSOLE_CMD(ConRemove)
386 if (argc == 0) {
387 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
388 return true;
391 if (argc != 2) return false;
393 const char *file = argv[1];
394 const FiosItem *item = GetFiosItem(file);
395 if (item != NULL) {
396 if (!FiosDelete(item->name)) {
397 IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file);
399 } else {
400 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
403 FiosFreeSavegameList();
404 return true;
408 /* List all the files in the current dir via console */
409 DEF_CONSOLE_CMD(ConListFiles)
411 if (argc == 0) {
412 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
413 return true;
416 BuildFileList();
418 for (uint i = 0; i < _fios_items.Length(); i++) {
419 IConsolePrintF(CC_DEFAULT, "%d) %s", i, _fios_items[i].title);
422 FiosFreeSavegameList();
423 return true;
426 /* Change the dir via console */
427 DEF_CONSOLE_CMD(ConChangeDirectory)
429 if (argc == 0) {
430 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
431 return true;
434 if (argc != 2) return false;
436 const char *file = argv[1];
437 const FiosItem *item = GetFiosItem(file);
438 if (item != NULL) {
439 switch (item->type) {
440 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
441 FiosBrowseTo(item);
442 break;
443 default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file);
445 } else {
446 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
449 FiosFreeSavegameList();
450 return true;
453 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
455 const char *path;
457 if (argc == 0) {
458 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
459 return true;
462 /* XXX - Workaround for broken file handling */
463 FiosGetSavegameList(SLD_LOAD_GAME);
464 FiosFreeSavegameList();
466 FiosGetDescText(&path, NULL);
467 IConsolePrint(CC_DEFAULT, path);
468 return true;
471 DEF_CONSOLE_CMD(ConClearBuffer)
473 if (argc == 0) {
474 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
475 return true;
478 IConsoleClearBuffer();
479 SetWindowDirty(WC_CONSOLE, 0);
480 return true;
484 /**********************************
485 * Network Core Console Commands
486 **********************************/
487 #ifdef ENABLE_NETWORK
489 static bool ConKickOrBan(const char *argv, bool ban)
491 uint n;
493 if (strchr(argv, '.') == NULL && strchr(argv, ':') == NULL) { // banning with ID
494 ClientID client_id = (ClientID)atoi(argv);
496 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
497 * kicking frees closes and subsequently free the connection related instances, which we
498 * would be reading from and writing to after returning. So we would read or write data
499 * from freed memory up till the segfault triggers. */
500 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
501 IConsolePrintF(CC_ERROR, "ERROR: Silly boy, you can not %s yourself!", ban ? "ban" : "kick");
502 return true;
505 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
506 if (ci == NULL) {
507 IConsoleError("Invalid client");
508 return true;
511 if (!ban) {
512 /* Kick only this client, not all clients with that IP */
513 NetworkServerKickClient(client_id);
514 return true;
517 /* When banning, kick+ban all clients with that IP */
518 n = NetworkServerKickOrBanIP(client_id, ban);
519 } else {
520 n = NetworkServerKickOrBanIP(argv, ban);
523 if (n == 0) {
524 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist" : "Client not found");
525 } else {
526 IConsolePrintF(CC_DEFAULT, "%sed %u client(s)", ban ? "Bann" : "Kick", n);
529 return true;
532 DEF_CONSOLE_CMD(ConKick)
534 if (argc == 0) {
535 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
536 IConsoleHelp("For client-id's, see the command 'clients'");
537 return true;
540 if (argc != 2) return false;
542 return ConKickOrBan(argv[1], false);
545 DEF_CONSOLE_CMD(ConBan)
547 if (argc == 0) {
548 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id>'");
549 IConsoleHelp("For client-id's, see the command 'clients'");
550 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
551 return true;
554 if (argc != 2) return false;
556 return ConKickOrBan(argv[1], true);
559 DEF_CONSOLE_CMD(ConUnBan)
562 if (argc == 0) {
563 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | client-id>'");
564 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
565 return true;
568 if (argc != 2) return false;
570 uint index = (strchr(argv[1], '.') == NULL) ? atoi(argv[1]) : 0;
571 index--;
572 uint i = 0;
574 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
575 if (strcmp(_network_ban_list[i], argv[1]) == 0 || index == i) {
576 free(_network_ban_list[i]);
577 _network_ban_list.Erase(iter);
578 IConsolePrint(CC_DEFAULT, "IP unbanned.");
579 return true;
583 IConsolePrint(CC_DEFAULT, "IP not in ban-list.");
584 return true;
587 DEF_CONSOLE_CMD(ConBanList)
589 if (argc == 0) {
590 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
591 return true;
594 IConsolePrint(CC_DEFAULT, "Banlist: ");
596 uint i = 1;
597 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
598 IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter);
601 return true;
604 DEF_CONSOLE_CMD(ConPauseGame)
606 if (argc == 0) {
607 IConsoleHelp("Pause a network game. Usage: 'pause'");
608 return true;
611 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
612 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
613 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
614 } else {
615 IConsolePrint(CC_DEFAULT, "Game is already paused.");
618 return true;
621 DEF_CONSOLE_CMD(ConUnpauseGame)
623 if (argc == 0) {
624 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
625 return true;
628 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
629 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
630 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
631 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
632 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
633 } else if (_pause_mode != PM_UNPAUSED) {
634 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
635 } else {
636 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
639 return true;
642 DEF_CONSOLE_CMD(ConRcon)
644 if (argc == 0) {
645 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
646 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
647 return true;
650 if (argc < 3) return false;
652 if (_network_server) {
653 IConsoleCmdExec(argv[2]);
654 } else {
655 NetworkClientSendRcon(argv[1], argv[2]);
657 return true;
660 DEF_CONSOLE_CMD(ConStatus)
662 if (argc == 0) {
663 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
664 return true;
667 NetworkServerShowStatusToConsole();
668 return true;
671 DEF_CONSOLE_CMD(ConServerInfo)
673 if (argc == 0) {
674 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
675 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
676 return true;
679 IConsolePrintF(CC_DEFAULT, "Current/maximum clients: %2d/%2d", _network_game_info.clients_on, _settings_client.network.max_clients);
680 IConsolePrintF(CC_DEFAULT, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client.network.max_companies);
681 IConsolePrintF(CC_DEFAULT, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client.network.max_spectators);
683 return true;
686 DEF_CONSOLE_CMD(ConClientNickChange)
688 if (argc != 3) {
689 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
690 IConsoleHelp("For client-id's, see the command 'clients'");
691 return true;
694 ClientID client_id = (ClientID)atoi(argv[1]);
696 if (client_id == CLIENT_ID_SERVER) {
697 IConsoleError("Please use the command 'name' to change your own name!");
698 return true;
701 if (NetworkClientInfo::GetByClientID(client_id) == NULL) {
702 IConsoleError("Invalid client");
703 return true;
706 if (!NetworkServerChangeClientName(client_id, argv[2])) {
707 IConsoleError("Cannot give a client a duplicate name");
710 return true;
713 DEF_CONSOLE_CMD(ConJoinCompany)
715 if (argc < 2) {
716 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
717 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
718 return true;
721 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
723 /* Check we have a valid company id! */
724 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
725 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
726 return true;
729 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
730 IConsoleError("You are already there!");
731 return true;
734 if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) {
735 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
736 return true;
739 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
740 IConsoleError("Cannot join AI company.");
741 return true;
744 /* Check if the company requires a password */
745 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
746 IConsolePrintF(CC_ERROR, "Company %d requires a password to join.", company_id + 1);
747 return true;
750 /* non-dedicated server may just do the move! */
751 if (_network_server) {
752 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
753 } else {
754 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
757 return true;
760 DEF_CONSOLE_CMD(ConMoveClient)
762 if (argc < 3) {
763 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
764 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
765 return true;
768 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
769 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
771 /* check the client exists */
772 if (ci == NULL) {
773 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
774 return true;
777 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
778 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
779 return true;
782 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
783 IConsoleError("You cannot move clients to AI companies.");
784 return true;
787 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
788 IConsoleError("Silly boy, you cannot move the server!");
789 return true;
792 if (ci->client_playas == company_id) {
793 IConsoleError("You cannot move someone to where he/she already is!");
794 return true;
797 /* we are the server, so force the update */
798 NetworkServerDoMove(ci->client_id, company_id);
800 return true;
803 DEF_CONSOLE_CMD(ConResetCompany)
805 if (argc == 0) {
806 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
807 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
808 return true;
811 if (argc != 2) return false;
813 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
815 /* Check valid range */
816 if (!Company::IsValidID(index)) {
817 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
818 return true;
821 if (!Company::IsHumanID(index)) {
822 IConsoleError("Company is owned by an AI.");
823 return true;
826 if (NetworkCompanyHasClients(index)) {
827 IConsoleError("Cannot remove company: a client is connected to that company.");
828 return false;
830 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
831 if (ci->client_playas == index) {
832 IConsoleError("Cannot remove company: the server is connected to that company.");
833 return true;
836 /* It is safe to remove this company */
837 DoCommandP(0, 2 | index << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
838 IConsolePrint(CC_DEFAULT, "Company deleted.");
840 return true;
843 DEF_CONSOLE_CMD(ConNetworkClients)
845 if (argc == 0) {
846 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
847 return true;
850 NetworkPrintClients();
852 return true;
855 DEF_CONSOLE_CMD(ConNetworkReconnect)
857 if (argc == 0) {
858 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
859 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
860 IConsoleHelp("All others are a certain company with Company 1 being #1");
861 return true;
864 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
865 switch (playas) {
866 case 0: playas = COMPANY_NEW_COMPANY; break;
867 case COMPANY_SPECTATOR: /* nothing to do */ break;
868 default:
869 /* From a user pov 0 is a new company, internally it's different and all
870 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
871 playas--;
872 if (playas < COMPANY_FIRST || playas >= MAX_COMPANIES) return false;
873 break;
876 if (StrEmpty(_settings_client.network.last_host)) {
877 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
878 return true;
881 /* Don't resolve the address first, just print it directly as it comes from the config file. */
882 IConsolePrintF(CC_DEFAULT, "Reconnecting to %s:%d...", _settings_client.network.last_host, _settings_client.network.last_port);
884 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), playas);
885 return true;
888 DEF_CONSOLE_CMD(ConNetworkConnect)
890 if (argc == 0) {
891 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
892 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
893 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
894 return true;
897 if (argc < 2) return false;
898 if (_networking) NetworkDisconnect(); // we are in network-mode, first close it!
900 const char *port = NULL;
901 const char *company = NULL;
902 char *ip = argv[1];
903 /* Default settings: default port and new company */
904 uint16 rport = NETWORK_DEFAULT_PORT;
905 CompanyID join_as = COMPANY_NEW_COMPANY;
907 ParseConnectionString(&company, &port, ip);
909 IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip);
910 if (company != NULL) {
911 join_as = (CompanyID)atoi(company);
912 IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as);
914 /* From a user pov 0 is a new company, internally it's different and all
915 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
916 if (join_as != COMPANY_SPECTATOR) {
917 if (join_as > MAX_COMPANIES) return false;
918 join_as--;
921 if (port != NULL) {
922 rport = atoi(port);
923 IConsolePrintF(CC_DEFAULT, " port: %s", port);
926 NetworkClientConnectGame(NetworkAddress(ip, rport), join_as);
928 return true;
931 #endif /* ENABLE_NETWORK */
933 /*********************************
934 * script file console commands
935 *********************************/
937 DEF_CONSOLE_CMD(ConExec)
939 if (argc == 0) {
940 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
941 return true;
944 if (argc < 2) return false;
946 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
948 if (script_file == NULL) {
949 if (argc == 2 || atoi(argv[2]) != 0) IConsoleError("script file not found");
950 return true;
953 _script_running = true;
955 char cmdline[ICON_CMDLN_SIZE];
956 while (_script_running && fgets(cmdline, sizeof(cmdline), script_file) != NULL) {
957 /* Remove newline characters from the executing script */
958 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
959 if (*cmdptr == '\n' || *cmdptr == '\r') {
960 *cmdptr = '\0';
961 break;
964 IConsoleCmdExec(cmdline);
967 if (ferror(script_file)) {
968 IConsoleError("Encountered error while trying to read from script file");
971 _script_running = false;
972 FioFCloseFile(script_file);
973 return true;
976 DEF_CONSOLE_CMD(ConReturn)
978 if (argc == 0) {
979 IConsoleHelp("Stop executing a running script. Usage: 'return'");
980 return true;
983 _script_running = false;
984 return true;
987 /*****************************
988 * default console commands
989 ******************************/
990 extern bool CloseConsoleLogIfActive();
992 DEF_CONSOLE_CMD(ConScript)
994 extern FILE *_iconsole_output_file;
996 if (argc == 0) {
997 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
998 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
999 return true;
1002 if (!CloseConsoleLogIfActive()) {
1003 if (argc < 2) return false;
1005 IConsolePrintF(CC_DEFAULT, "file output started to: %s", argv[1]);
1006 _iconsole_output_file = fopen(argv[1], "ab");
1007 if (_iconsole_output_file == NULL) IConsoleError("could not open file");
1010 return true;
1014 DEF_CONSOLE_CMD(ConEcho)
1016 if (argc == 0) {
1017 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1018 return true;
1021 if (argc < 2) return false;
1022 IConsolePrint(CC_DEFAULT, argv[1]);
1023 return true;
1026 DEF_CONSOLE_CMD(ConEchoC)
1028 if (argc == 0) {
1029 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1030 return true;
1033 if (argc < 3) return false;
1034 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1035 return true;
1038 DEF_CONSOLE_CMD(ConNewGame)
1040 if (argc == 0) {
1041 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1042 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1043 return true;
1046 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], NULL, 10) : GENERATE_NEW_SEED);
1047 return true;
1050 DEF_CONSOLE_CMD(ConRestart)
1052 if (argc == 0) {
1053 IConsoleHelp("Restart game. Usage: 'restart'");
1054 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1055 IConsoleHelp("However:");
1056 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1057 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1058 return true;
1061 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1062 _settings_game.game_creation.map_x = MapLogX();
1063 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1064 _switch_mode = SM_RESTARTGAME;
1065 return true;
1069 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1070 * @param buf The buffer to print.
1071 * @note All newlines are replace by '\0' characters.
1073 static void PrintLineByLine(char *buf)
1075 char *p = buf;
1076 /* Print output line by line */
1077 for (char *p2 = buf; *p2 != '\0'; p2++) {
1078 if (*p2 == '\n') {
1079 *p2 = '\0';
1080 IConsolePrintF(CC_DEFAULT, "%s", p);
1081 p = p2 + 1;
1086 DEF_CONSOLE_CMD(ConListAILibs)
1088 char buf[4096];
1089 AI::GetConsoleLibraryList(buf, lastof(buf));
1091 PrintLineByLine(buf);
1093 return true;
1096 DEF_CONSOLE_CMD(ConListAI)
1098 char buf[4096];
1099 AI::GetConsoleList(buf, lastof(buf));
1101 PrintLineByLine(buf);
1103 return true;
1106 DEF_CONSOLE_CMD(ConListGameLibs)
1108 char buf[4096];
1109 Game::GetConsoleLibraryList(buf, lastof(buf));
1111 PrintLineByLine(buf);
1113 return true;
1116 DEF_CONSOLE_CMD(ConListGame)
1118 char buf[4096];
1119 Game::GetConsoleList(buf, lastof(buf));
1121 PrintLineByLine(buf);
1123 return true;
1126 DEF_CONSOLE_CMD(ConStartAI)
1128 if (argc == 0 || argc > 3) {
1129 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1130 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1131 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1132 return true;
1135 if (_game_mode != GM_NORMAL) {
1136 IConsoleWarning("AIs can only be managed in a game.");
1137 return true;
1140 if (Company::GetNumItems() == Company::Pool::MAX_SIZE) {
1141 IConsoleWarning("Can't start a new AI (no more free slots).");
1142 return true;
1144 if (_networking && !_network_server) {
1145 IConsoleWarning("Only the server can start a new AI.");
1146 return true;
1148 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1149 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1150 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1151 return true;
1153 if (!AI::CanStartNew()) {
1154 IConsoleWarning("Can't start a new AI.");
1155 return true;
1158 int n = 0;
1159 Company *c;
1160 /* Find the next free slot */
1161 FOR_ALL_COMPANIES(c) {
1162 if (c->index != n) break;
1163 n++;
1166 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1167 if (argc >= 2) {
1168 config->Change(argv[1], -1, true);
1169 if (!config->HasScript()) {
1170 IConsoleWarning("Failed to load the specified AI");
1171 return true;
1173 if (argc == 3) {
1174 config->StringToSettings(argv[2]);
1178 /* Start a new AI company */
1179 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1181 return true;
1184 DEF_CONSOLE_CMD(ConReloadAI)
1186 if (argc != 2) {
1187 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1188 IConsoleHelp("Reload the AI with the given company id. For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
1189 return true;
1192 if (_game_mode != GM_NORMAL) {
1193 IConsoleWarning("AIs can only be managed in a game.");
1194 return true;
1197 if (_networking && !_network_server) {
1198 IConsoleWarning("Only the server can reload an AI.");
1199 return true;
1202 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1203 if (!Company::IsValidID(company_id)) {
1204 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1205 return true;
1208 if (Company::IsHumanID(company_id)) {
1209 IConsoleWarning("Company is not controlled by an AI.");
1210 return true;
1213 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1214 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1215 DoCommandP(0, 1 | company_id << 16, 0, CMD_COMPANY_CTRL);
1216 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1218 return true;
1221 DEF_CONSOLE_CMD(ConStopAI)
1223 if (argc != 2) {
1224 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1225 IConsoleHelp("Stop the AI with the given company id. For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
1226 return true;
1229 if (_game_mode != GM_NORMAL) {
1230 IConsoleWarning("AIs can only be managed in a game.");
1231 return true;
1234 if (_networking && !_network_server) {
1235 IConsoleWarning("Only the server can stop an AI.");
1236 return true;
1239 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1240 if (!Company::IsValidID(company_id)) {
1241 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1242 return true;
1245 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1246 IConsoleWarning("Company is not controlled by an AI.");
1247 return true;
1250 /* Now kill the company of the AI. */
1251 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1252 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1254 return true;
1257 DEF_CONSOLE_CMD(ConRescanAI)
1259 if (argc == 0) {
1260 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1261 return true;
1264 if (_networking && !_network_server) {
1265 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1266 return true;
1269 AI::Rescan();
1271 return true;
1274 DEF_CONSOLE_CMD(ConRescanGame)
1276 if (argc == 0) {
1277 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1278 return true;
1281 if (_networking && !_network_server) {
1282 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1283 return true;
1286 Game::Rescan();
1288 return true;
1291 DEF_CONSOLE_CMD(ConRescanNewGRF)
1293 if (argc == 0) {
1294 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1295 return true;
1298 ScanNewGRFFiles(NULL);
1300 return true;
1303 DEF_CONSOLE_CMD(ConGetSeed)
1305 if (argc == 0) {
1306 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1307 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1308 return true;
1311 IConsolePrintF(CC_DEFAULT, "Generation Seed: %u", _settings_game.game_creation.generation_seed);
1312 return true;
1315 DEF_CONSOLE_CMD(ConGetDate)
1317 if (argc == 0) {
1318 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1319 return true;
1322 YearMonthDay ymd;
1323 ConvertDateToYMD(_date, &ymd);
1324 IConsolePrintF(CC_DEFAULT, "Date: %d-%d-%d", ymd.day, ymd.month + 1, ymd.year);
1325 return true;
1329 DEF_CONSOLE_CMD(ConAlias)
1331 IConsoleAlias *alias;
1333 if (argc == 0) {
1334 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1335 return true;
1338 if (argc < 3) return false;
1340 alias = IConsoleAliasGet(argv[1]);
1341 if (alias == NULL) {
1342 IConsoleAliasRegister(argv[1], argv[2]);
1343 } else {
1344 free(alias->cmdline);
1345 alias->cmdline = strdup(argv[2]);
1347 return true;
1350 DEF_CONSOLE_CMD(ConScreenShot)
1352 if (argc == 0) {
1353 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [file name]'");
1354 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1355 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1356 "screenshots are always drawn without console");
1357 return true;
1360 if (argc > 3) return false;
1362 ScreenshotType type = SC_VIEWPORT;
1363 const char *name = NULL;
1365 if (argc > 1) {
1366 if (strcmp(argv[1], "big") == 0) {
1367 /* screenshot big [filename] */
1368 type = SC_ZOOMEDIN;
1369 if (argc > 2) name = argv[2];
1370 } else if (strcmp(argv[1], "giant") == 0) {
1371 /* screenshot giant [filename] */
1372 type = SC_WORLD;
1373 if (argc > 2) name = argv[2];
1374 } else if (strcmp(argv[1], "no_con") == 0) {
1375 /* screenshot no_con [filename] */
1376 IConsoleClose();
1377 if (argc > 2) name = argv[2];
1378 } else if (argc == 2) {
1379 /* screenshot filename */
1380 name = argv[1];
1381 } else {
1382 /* screenshot argv[1] argv[2] - invalid */
1383 return false;
1387 MakeScreenshot(type, name);
1388 return true;
1391 DEF_CONSOLE_CMD(ConInfoCmd)
1393 if (argc == 0) {
1394 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1395 return true;
1398 if (argc < 2) return false;
1400 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1401 if (cmd == NULL) {
1402 IConsoleError("the given command was not found");
1403 return true;
1406 IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
1407 IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
1409 if (cmd->hook != NULL) IConsoleWarning("command is hooked");
1411 return true;
1414 DEF_CONSOLE_CMD(ConDebugLevel)
1416 if (argc == 0) {
1417 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1418 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1419 return true;
1422 if (argc > 2) return false;
1424 if (argc == 1) {
1425 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1426 } else {
1427 SetDebugString(argv[1]);
1430 return true;
1433 DEF_CONSOLE_CMD(ConExit)
1435 if (argc == 0) {
1436 IConsoleHelp("Exit the game. Usage: 'exit'");
1437 return true;
1440 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1442 _exit_game = true;
1443 return true;
1446 DEF_CONSOLE_CMD(ConPart)
1448 if (argc == 0) {
1449 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1450 return true;
1453 if (_game_mode != GM_NORMAL) return false;
1455 _switch_mode = SM_MENU;
1456 return true;
1459 DEF_CONSOLE_CMD(ConHelp)
1461 if (argc == 2) {
1462 const IConsoleCmd *cmd;
1463 const IConsoleAlias *alias;
1465 RemoveUnderscores(argv[1]);
1466 cmd = IConsoleCmdGet(argv[1]);
1467 if (cmd != NULL) {
1468 cmd->proc(0, NULL);
1469 return true;
1472 alias = IConsoleAliasGet(argv[1]);
1473 if (alias != NULL) {
1474 cmd = IConsoleCmdGet(alias->cmdline);
1475 if (cmd != NULL) {
1476 cmd->proc(0, NULL);
1477 return true;
1479 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1480 return true;
1483 IConsoleError("command not found");
1484 return true;
1487 IConsolePrint(CC_WARNING, " ---- OpenTTD Console Help ---- ");
1488 IConsolePrint(CC_DEFAULT, " - commands: [command to list all commands: list_cmds]");
1489 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1490 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes");
1491 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'");
1492 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information");
1493 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown)");
1494 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows");
1495 IConsolePrint(CC_DEFAULT, "");
1496 return true;
1499 DEF_CONSOLE_CMD(ConListCommands)
1501 if (argc == 0) {
1502 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1503 return true;
1506 for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != NULL; cmd = cmd->next) {
1507 if (argv[1] == NULL || strstr(cmd->name, argv[1]) != NULL) {
1508 if (cmd->hook == NULL || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
1512 return true;
1515 DEF_CONSOLE_CMD(ConListAliases)
1517 if (argc == 0) {
1518 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1519 return true;
1522 for (const IConsoleAlias *alias = _iconsole_aliases; alias != NULL; alias = alias->next) {
1523 if (argv[1] == NULL || strstr(alias->name, argv[1]) != NULL) {
1524 IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
1528 return true;
1531 DEF_CONSOLE_CMD(ConCompanies)
1533 if (argc == 0) {
1534 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1535 return true;
1538 Company *c;
1539 FOR_ALL_COMPANIES(c) {
1540 /* Grab the company name */
1541 char company_name[512];
1542 SetDParam(0, c->index);
1543 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1545 const char *password_state = "";
1546 if (c->is_ai) {
1547 password_state = "AI";
1549 #ifdef ENABLE_NETWORK
1550 else if (_network_server) {
1551 password_state = StrEmpty(_network_company_states[c->index].password) ? "unprotected" : "protected";
1553 #endif
1555 char colour[512];
1556 GetString(colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index], lastof(colour));
1557 IConsolePrintF(CC_INFO, "#:%d(%s) Company Name: '%s' Year Founded: %d Money: " OTTD_PRINTF64 " Loan: " OTTD_PRINTF64 " Value: " OTTD_PRINTF64 " (T:%d, R:%d, P:%d, S:%d) %s",
1558 c->index + 1, colour, company_name,
1559 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1560 c->group_all[VEH_TRAIN].num_vehicle,
1561 c->group_all[VEH_ROAD].num_vehicle,
1562 c->group_all[VEH_AIRCRAFT].num_vehicle,
1563 c->group_all[VEH_SHIP].num_vehicle,
1564 password_state);
1567 return true;
1570 #ifdef ENABLE_NETWORK
1572 DEF_CONSOLE_CMD(ConSay)
1574 if (argc == 0) {
1575 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1576 return true;
1579 if (argc != 2) return false;
1581 if (!_network_server) {
1582 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1583 } else {
1584 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1585 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1588 return true;
1591 DEF_CONSOLE_CMD(ConSayCompany)
1593 if (argc == 0) {
1594 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1595 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1596 return true;
1599 if (argc != 3) return false;
1601 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1602 if (!Company::IsValidID(company_id)) {
1603 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1604 return true;
1607 if (!_network_server) {
1608 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1609 } else {
1610 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1611 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1614 return true;
1617 DEF_CONSOLE_CMD(ConSayClient)
1619 if (argc == 0) {
1620 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1621 IConsoleHelp("For client-id's, see the command 'clients'");
1622 return true;
1625 if (argc != 3) return false;
1627 if (!_network_server) {
1628 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1629 } else {
1630 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1631 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1634 return true;
1637 DEF_CONSOLE_CMD(ConCompanyPassword)
1639 if (argc == 0) {
1640 const char *helpmsg;
1642 if (_network_dedicated) {
1643 helpmsg = "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1644 } else if (_network_server) {
1645 helpmsg = "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1646 } else {
1647 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1650 IConsoleHelp(helpmsg);
1651 IConsoleHelp("Use \"*\" to disable the password.");
1652 return true;
1655 CompanyID company_id;
1656 const char *password;
1657 const char *errormsg;
1659 if (argc == 2) {
1660 company_id = _local_company;
1661 password = argv[1];
1662 errormsg = "You have to own a company to make use of this command.";
1663 } else if (argc == 3 && _network_server) {
1664 company_id = (CompanyID)(atoi(argv[1]) - 1);
1665 password = argv[2];
1666 errormsg = "You have to specify the ID of a valid human controlled company.";
1667 } else {
1668 return false;
1671 if (!Company::IsValidHumanID(company_id)) {
1672 IConsoleError(errormsg);
1673 return false;
1676 password = NetworkChangeCompanyPassword(company_id, password);
1678 if (StrEmpty(password)) {
1679 IConsolePrintF(CC_WARNING, "Company password cleared");
1680 } else {
1681 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1684 return true;
1687 /* Content downloading only is available with ZLIB */
1688 #if defined(WITH_ZLIB)
1689 #include "network/network_content.h"
1691 /** Resolve a string to a content type. */
1692 static ContentType StringToContentType(const char *str)
1694 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1695 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1696 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1698 return CONTENT_TYPE_END;
1701 /** Asynchronous callback */
1702 struct ConsoleContentCallback : public ContentCallback {
1703 void OnConnect(bool success)
1705 IConsolePrintF(CC_DEFAULT, "Content server connection %s", success ? "established" : "failed");
1708 void OnDisconnect()
1710 IConsolePrintF(CC_DEFAULT, "Content server connection closed");
1713 void OnDownloadComplete(ContentID cid)
1715 IConsolePrintF(CC_DEFAULT, "Completed download of %d", cid);
1720 * Outputs content state information to console
1721 * @param ci the content info
1723 static void OutputContentState(const ContentInfo *const ci)
1725 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1726 assert_compile(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1727 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1728 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1730 char buf[sizeof(ci->md5sum) * 2 + 1];
1731 md5sumToString(buf, lastof(buf), ci->md5sum);
1732 IConsolePrintF(state_to_colour[ci->state], "%d, %s, %s, %s, %08X, %s", ci->id, types[ci->type - 1], states[ci->state], ci->name, ci->unique_id, buf);
1735 DEF_CONSOLE_CMD(ConContent)
1737 static ContentCallback *cb = NULL;
1738 if (cb == NULL) {
1739 cb = new ConsoleContentCallback();
1740 _network_content_client.AddCallback(cb);
1743 if (argc <= 1) {
1744 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1745 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1746 IConsoleHelp(" upgrade: select all items that are upgrades");
1747 IConsoleHelp(" select: select a specific item given by its id or 'all' to select all. If no parameter is given, all selected content will be listed");
1748 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1749 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1750 IConsoleHelp(" download: download all content you've selected");
1751 return true;
1754 if (strcasecmp(argv[1], "update") == 0) {
1755 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1756 return true;
1759 if (strcasecmp(argv[1], "upgrade") == 0) {
1760 _network_content_client.SelectUpgrade();
1761 return true;
1764 if (strcasecmp(argv[1], "select") == 0) {
1765 if (argc <= 2) {
1766 /* List selected content */
1767 IConsolePrintF(CC_WHITE, "id, type, state, name");
1768 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1769 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1770 OutputContentState(*iter);
1772 } else if (strcasecmp(argv[2], "all") == 0) {
1773 _network_content_client.SelectAll();
1774 } else {
1775 _network_content_client.Select((ContentID)atoi(argv[2]));
1777 return true;
1780 if (strcasecmp(argv[1], "unselect") == 0) {
1781 if (argc <= 2) {
1782 IConsoleError("You must enter the id.");
1783 return false;
1785 if (strcasecmp(argv[2], "all") == 0) {
1786 _network_content_client.UnselectAll();
1787 } else {
1788 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1790 return true;
1793 if (strcasecmp(argv[1], "state") == 0) {
1794 IConsolePrintF(CC_WHITE, "id, type, state, name");
1795 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1796 if (argc > 2 && strcasestr((*iter)->name, argv[2]) == NULL) continue;
1797 OutputContentState(*iter);
1799 return true;
1802 if (strcasecmp(argv[1], "download") == 0) {
1803 uint files;
1804 uint bytes;
1805 _network_content_client.DownloadSelectedContent(files, bytes);
1806 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1807 return true;
1810 return false;
1812 #endif /* defined(WITH_ZLIB) */
1813 #endif /* ENABLE_NETWORK */
1815 DEF_CONSOLE_CMD(ConSetting)
1817 if (argc == 0) {
1818 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1819 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1820 return true;
1823 if (argc == 1 || argc > 3) return false;
1825 if (argc == 2) {
1826 IConsoleGetSetting(argv[1]);
1827 } else {
1828 IConsoleSetSetting(argv[1], argv[2]);
1831 return true;
1834 DEF_CONSOLE_CMD(ConSettingNewgame)
1836 if (argc == 0) {
1837 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1838 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1839 return true;
1842 if (argc == 1 || argc > 3) return false;
1844 if (argc == 2) {
1845 IConsoleGetSetting(argv[1], true);
1846 } else {
1847 IConsoleSetSetting(argv[1], argv[2], true);
1850 return true;
1853 DEF_CONSOLE_CMD(ConListSettings)
1855 if (argc == 0) {
1856 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1857 return true;
1860 if (argc > 2) return false;
1862 IConsoleListSettings((argc == 2) ? argv[1] : NULL);
1863 return true;
1866 DEF_CONSOLE_CMD(ConGamelogPrint)
1868 GamelogPrintConsole();
1869 return true;
1872 DEF_CONSOLE_CMD(ConNewGRFReload)
1874 if (argc == 0) {
1875 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1876 return true;
1879 ReloadNewGRFData();
1880 return true;
1883 #ifdef _DEBUG
1884 /******************
1885 * debug commands
1886 ******************/
1888 static void IConsoleDebugLibRegister()
1890 IConsoleCmdRegister("resettile", ConResetTile);
1891 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1892 IConsoleAliasRegister("dbg_echo2", "echo %!");
1894 #endif
1896 /*******************************
1897 * console command registration
1898 *******************************/
1900 void IConsoleStdLibRegister()
1902 IConsoleCmdRegister("debug_level", ConDebugLevel);
1903 IConsoleCmdRegister("echo", ConEcho);
1904 IConsoleCmdRegister("echoc", ConEchoC);
1905 IConsoleCmdRegister("exec", ConExec);
1906 IConsoleCmdRegister("exit", ConExit);
1907 IConsoleCmdRegister("part", ConPart);
1908 IConsoleCmdRegister("help", ConHelp);
1909 IConsoleCmdRegister("info_cmd", ConInfoCmd);
1910 IConsoleCmdRegister("list_cmds", ConListCommands);
1911 IConsoleCmdRegister("list_aliases", ConListAliases);
1912 IConsoleCmdRegister("newgame", ConNewGame);
1913 IConsoleCmdRegister("restart", ConRestart);
1914 IConsoleCmdRegister("getseed", ConGetSeed);
1915 IConsoleCmdRegister("getdate", ConGetDate);
1916 IConsoleCmdRegister("quit", ConExit);
1917 IConsoleCmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
1918 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
1919 IConsoleCmdRegister("return", ConReturn);
1920 IConsoleCmdRegister("screenshot", ConScreenShot);
1921 IConsoleCmdRegister("script", ConScript);
1922 IConsoleCmdRegister("scrollto", ConScrollToTile);
1923 IConsoleCmdRegister("alias", ConAlias);
1924 IConsoleCmdRegister("load", ConLoad);
1925 IConsoleCmdRegister("rm", ConRemove);
1926 IConsoleCmdRegister("save", ConSave);
1927 IConsoleCmdRegister("saveconfig", ConSaveConfig);
1928 IConsoleCmdRegister("ls", ConListFiles);
1929 IConsoleCmdRegister("cd", ConChangeDirectory);
1930 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory);
1931 IConsoleCmdRegister("clear", ConClearBuffer);
1932 IConsoleCmdRegister("setting", ConSetting);
1933 IConsoleCmdRegister("setting_newgame", ConSettingNewgame);
1934 IConsoleCmdRegister("list_settings",ConListSettings);
1935 IConsoleCmdRegister("gamelog", ConGamelogPrint);
1936 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF);
1938 IConsoleAliasRegister("dir", "ls");
1939 IConsoleAliasRegister("del", "rm %+");
1940 IConsoleAliasRegister("newmap", "newgame");
1941 IConsoleAliasRegister("patch", "setting %+");
1942 IConsoleAliasRegister("set", "setting %+");
1943 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
1944 IConsoleAliasRegister("list_patches", "list_settings %+");
1945 IConsoleAliasRegister("developer", "setting developer %+");
1947 IConsoleCmdRegister("list_ai_libs", ConListAILibs);
1948 IConsoleCmdRegister("list_ai", ConListAI);
1949 IConsoleCmdRegister("reload_ai", ConReloadAI);
1950 IConsoleCmdRegister("rescan_ai", ConRescanAI);
1951 IConsoleCmdRegister("start_ai", ConStartAI);
1952 IConsoleCmdRegister("stop_ai", ConStopAI);
1954 IConsoleCmdRegister("list_game", ConListGame);
1955 IConsoleCmdRegister("list_game_libs", ConListGameLibs);
1956 IConsoleCmdRegister("rescan_game", ConRescanGame);
1958 IConsoleCmdRegister("companies", ConCompanies);
1959 IConsoleAliasRegister("players", "companies");
1961 /* networking functions */
1962 #ifdef ENABLE_NETWORK
1963 /* Content downloading is only available with ZLIB */
1964 #if defined(WITH_ZLIB)
1965 IConsoleCmdRegister("content", ConContent);
1966 #endif /* defined(WITH_ZLIB) */
1968 /*** Networking commands ***/
1969 IConsoleCmdRegister("say", ConSay, ConHookNeedNetwork);
1970 IConsoleCmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
1971 IConsoleAliasRegister("say_player", "say_company %+");
1972 IConsoleCmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
1974 IConsoleCmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
1975 IConsoleCmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
1976 IConsoleCmdRegister("status", ConStatus, ConHookServerOnly);
1977 IConsoleCmdRegister("server_info", ConServerInfo, ConHookServerOnly);
1978 IConsoleAliasRegister("info", "server_info");
1979 IConsoleCmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
1980 IConsoleCmdRegister("rcon", ConRcon, ConHookNeedNetwork);
1982 IConsoleCmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
1983 IConsoleAliasRegister("spectate", "join 255");
1984 IConsoleCmdRegister("move", ConMoveClient, ConHookServerOnly);
1985 IConsoleCmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
1986 IConsoleAliasRegister("clean_company", "reset_company %A");
1987 IConsoleCmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
1988 IConsoleCmdRegister("kick", ConKick, ConHookServerOnly);
1989 IConsoleCmdRegister("ban", ConBan, ConHookServerOnly);
1990 IConsoleCmdRegister("unban", ConUnBan, ConHookServerOnly);
1991 IConsoleCmdRegister("banlist", ConBanList, ConHookServerOnly);
1993 IConsoleCmdRegister("pause", ConPauseGame, ConHookServerOnly);
1994 IConsoleCmdRegister("unpause", ConUnpauseGame, ConHookServerOnly);
1996 IConsoleCmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
1997 IConsoleAliasRegister("company_password", "company_pw %+");
1999 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2000 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2001 IConsoleAliasRegister("server_pw", "setting server_password %+");
2002 IConsoleAliasRegister("server_password", "setting server_password %+");
2003 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2004 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2005 IConsoleAliasRegister("name", "setting client_name %+");
2006 IConsoleAliasRegister("server_name", "setting server_name %+");
2007 IConsoleAliasRegister("server_port", "setting server_port %+");
2008 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2009 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2010 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2011 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2012 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2013 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2014 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2015 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2016 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2017 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2018 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2019 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2020 #endif /* ENABLE_NETWORK */
2022 /* debugging stuff */
2023 #ifdef _DEBUG
2024 IConsoleDebugLibRegister();
2025 #endif
2027 /* NewGRF development stuff */
2028 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);