Debian Codegraph @

engine/ui/interface.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name interface.cpp - The interface. */
11 //
12 // (c) Copyright 1998-2008 by Lutz Sammer and Jimmy Salmon
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 //@{
30
31 /*----------------------------------------------------------------------------
32 -- Includes
33 ----------------------------------------------------------------------------*/
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #include "stratagus.h"
40 #include "video.h"
41 #include "sound.h"
42 #include "sound_server.h"
43 #include "unittype.h"
44 #include "player.h"
45 #include "unit.h"
46 #include "interface.h"
47 #include "cursor.h"
48 #include "ui.h"
49 #include "menus.h"
50 #include "script.h"
51 #include "map.h"
52 #include "minimap.h"
53 #include "network.h"
54 #include "font.h"
55 #include "results.h"
56 #include "video.h"
57 #include "iolib.h"
58 #include "replay.h"
59 #include "ai.h"
60 #include "widgets.h"
61 #include "particle.h"
62
63 /*----------------------------------------------------------------------------
64 -- Defines
65 ----------------------------------------------------------------------------*/
66
67 /// Scrolling area (<= 15 y)
68 #define SCROLL_UP 15
69 /// Scrolling area (>= VideoHeight - 16 y)
70 #define SCROLL_DOWN (Video.Height - 16)
71 /// Scrolling area (<= 15 y)
72 #define SCROLL_LEFT 15
73 /// Scrolling area (>= VideoWidth - 16 x)
74 #define SCROLL_RIGHT (Video.Width - 16)
75
76 /*----------------------------------------------------------------------------
77 -- Variables
78 ----------------------------------------------------------------------------*/
79
80 static char Input[80]; /// line input for messages/long commands
81 static int InputIndex; /// current index into input
82 static char InputStatusLine[99]; /// Last input status line
83 std::string DefaultGroupKeys = "0123456789`";/// Default group keys
84 std::string UiGroupKeys = DefaultGroupKeys;/// Up to 11 keys, last unselect. Default for qwerty
85 bool GameRunning; /// Current running state
86 bool GamePaused; /// Current pause state
87 bool GameObserve; /// Observe mode
88 char SkipGameCycle; /// Skip the next game cycle
89 char BigMapMode; /// Show only the map
90 enum _iface_state_ InterfaceState; /// Current interface state
91 bool GodMode; /// Invincibility cheat
92 enum _key_state_ KeyState; /// current key state
93
94 /*----------------------------------------------------------------------------
95 -- Functions
96 ----------------------------------------------------------------------------*/
97
98 /**
99 ** Show input.
100 */
101 static void ShowInput(void)
102 {
103 char *input;
104
105 sprintf_s(InputStatusLine, sizeof(InputStatusLine), _("MESSAGE:%s~!_"), Input);
106 input = InputStatusLine;
107 // FIXME: This is slow!
108 while (UI.StatusLine.Font->Width(input) > UI.StatusLine.Width) {
109 ++input;
110 }
111 KeyState = KeyStateCommand;
112 UI.StatusLine.Clear();
113 UI.StatusLine.Set(input);
114 KeyState = KeyStateInput;
115 }
116
117 /**
118 ** Begin input.
119 */
120 static void UiBeginInput(void)
121 {
122 KeyState = KeyStateInput;
123 Input[0] = '\0';
124 InputIndex = 0;
125 ClearCosts();
126 ShowInput();
127 }
128
129 //-----------------------------------------------------------------------------
130 // User interface group commands
131 //-----------------------------------------------------------------------------
132
133 /**
134 ** Unselect all currently selected units.
135 */
136 static void UiUnselectAll(void)
137 {
138 UnSelectAll();
139 NetworkSendSelection(NULL, 0);
140 SelectionChanged();
141 }
142
143 /**
144 ** Center on group.
145 **
146 ** @param group Group number to center on.
147 **
148 ** @todo Improve this function, try to show all selected units
149 ** or the most possible units.
150 */
151 static void UiCenterOnGroup(unsigned group)
152 {
153 CUnit **units;
154 int n;
155 int x;
156 int y;
157
158 n = GetNumberUnitsOfGroup(group);
159 if (n--) {
160 units = GetUnitsOfGroup(group);
161 // FIXME: what should we do with the removed units? ignore?
162
163 x = units[n]->X;
164 y = units[n]->Y;
165 while (n--) {
166 x += (units[n]->X - x) / 2;
167 y += (units[n]->Y - y) / 2;
168 }
169 UI.SelectedViewport->Center(x, y, TileSizeX / 2, TileSizeY / 2);
170 }
171 }
172
173 /**
174 ** Select group.
175 **
176 ** @param group Group number to select.
177 */
178 static void UiSelectGroup(unsigned group)
179 {
180 SelectGroup(group);
181 SelectionChanged();
182 }
183
184 /**
185 ** Add group to current selection.
186 **
187 ** @param group Group number to add.
188 */
189 static void UiAddGroupToSelection(unsigned group)
190 {
191 CUnit **units;
192 int n;
193
194 if (!(n = GetNumberUnitsOfGroup(group))) {
195 return;
196 }
197
198 //
199 // Don't allow to mix units and buildings
200 //
201 if (NumUnits && Selected[0]->Type->Building) {
202 return;
203 }
204
205 units = GetUnitsOfGroup(group);
206 if (units[0]->Type->Building) {
207 return;
208 }
209
210 while (n--) {
211 if (!units[n]->Removed) {
212 SelectUnit(units[n]);
213 }
214 }
215
216 SelectionChanged();
217 }
218
219 /**
220 ** Define a group. The current selected units become a new group.
221 **
222 ** @param group Group number to create.
223 */
224 static void UiDefineGroup(unsigned group)
225 {
226 SetGroup(Selected, NumSelected, group);
227 }
228
229 /**
230 ** Add to group. The current selected units are added to the group.
231 **
232 ** @param group Group number to be expanded.
233 */
234 static void UiAddToGroup(unsigned group)
235 {
236 AddToGroup(Selected, NumSelected, group);
237 }
238
239 /**
240 ** Toggle sound on / off.
241 */
242 static void UiToggleSound(void)
243 {
244 if (SoundEnabled()) {
245 if (IsEffectsEnabled()) {
246 SetEffectsEnabled(false);
247 SetMusicEnabled(false);
248 } else {
249 SetEffectsEnabled(true);
250 SetMusicEnabled(true);
251 CheckMusicFinished(true);
252 }
253 }
254
255 if (SoundEnabled()) {
256 if (IsEffectsEnabled()) {
257 UI.StatusLine.Set(_("Sound is on."));
258 } else {
259 UI.StatusLine.Set(_("Sound is off."));
260 }
261 }
262 }
263
264 /**
265 ** Toggle music on / off.
266 */
267 static void UiToggleMusic(void)
268 {
269 static int vol;
270 if (SoundEnabled()) {
271 if (GetMusicVolume()) {
272 vol = GetMusicVolume();
273 SetMusicVolume(0);
274 UI.StatusLine.Set(_("Music is off."));
275 } else {
276 SetMusicVolume(vol);
277 UI.StatusLine.Set(_("Music is on."));
278 }
279 }
280 }
281
282 /**
283 ** Toggle pause on / off.
284 */
285 void UiTogglePause(void)
286 {
287 if (!IsNetworkGame()) {
288 GamePaused = !GamePaused;
289 if (GamePaused) {
290 UI.StatusLine.Set(_("Game Paused"));
291 } else {
292 UI.StatusLine.Set(_("Game Resumed"));
293 }
294 }
295 }
296
297 /**
298 ** Toggle big map mode.
299 **
300 ** @todo FIXME: We should try to keep the same view, if possible
301 */
302 static void UiToggleBigMap(void)
303 {
304 static int mapx;
305 static int mapy;
306 static int mapex;
307 static int mapey;
308
309 BigMapMode ^= 1;
310 if (BigMapMode) {
311 mapx = UI.MapArea.X;
312 mapy = UI.MapArea.Y;
313 mapex = UI.MapArea.EndX;
314 mapey = UI.MapArea.EndY;
315
316 UI.MapArea.X = 0;
317 UI.MapArea.Y = 0;
318 UI.MapArea.EndX = Video.Width - 1;
319 UI.MapArea.EndY = Video.Height - 1;
320
321 SetViewportMode(UI.ViewportMode);
322
323 UI.StatusLine.Set(_("Big map enabled"));
324 } else {
325 UI.MapArea.X = mapx;
326 UI.MapArea.Y = mapy;
327 UI.MapArea.EndX = mapex;
328 UI.MapArea.EndY = mapey;
329
330 SetViewportMode(UI.ViewportMode);
331
332 UI.StatusLine.Set(_("Returning to old map"));
333 }
334 }
335
336 /**
337 ** Increase game speed.
338 */
339 static void UiIncreaseGameSpeed(void)
340 {
341 if (FastForwardCycle >= GameCycle) {
342 return;
343 }
344 VideoSyncSpeed += 10;
345 SetVideoSync();
346 UI.StatusLine.Set(_("Faster"));
347 }
348
349 /**
350 ** Decrease game speed.
351 */
352 static void UiDecreaseGameSpeed(void)
353 {
354 if (FastForwardCycle >= GameCycle) {
355 return;
356 }
357 if (VideoSyncSpeed <= 10) {
358 if (VideoSyncSpeed > 1) {
359 --VideoSyncSpeed;
360 }
361 } else {
362 VideoSyncSpeed -= 10;
363 }
364 SetVideoSync();
365 UI.StatusLine.Set(_("Slower"));
366 }
367
368 /**
369 ** Center on the selected units.
370 **
371 ** @todo Improve this function, try to show all selected units
372 ** or the most possible units.
373 */
374 static void UiCenterOnSelected(void)
375 {
376 int x;
377 int y;
378 int n;
379
380 if ((n = NumSelected)) {
381 x = Selected[--n]->X;
382 y = Selected[n]->Y;
383 while (n--) {
384 x += (Selected[n]->X - x) / 2;
385 y += (Selected[n]->Y - y) / 2;
386 }
387 UI.SelectedViewport->Center(x, y, TileSizeX / 2, TileSizeY / 2);
388 }
389 }
390
391 /**
392 ** Toggle terrain display on/off.
393 */
394 static void UiToggleTerrain(void)
395 {
396 UI.Minimap.WithTerrain ^= 1;
397 if (UI.Minimap.WithTerrain) {
398 UI.StatusLine.Set(_("Terrain displayed."));
399 } else {
400 UI.StatusLine.Set(_("Terrain hidden."));
401 }
402 }
403
404 /**
405 ** Find the next idle worker, select it, and center on it
406 */
407 static void UiFindIdleWorker(void)
408 {
409 CUnit *unit;
410
411 unit = FindIdleWorker(ThisPlayer);
412 if (unit != NoUnitP) {
413 SelectSingleUnit(unit);
414 UI.StatusLine.Clear();
415 ClearCosts();
416 CurrentButtonLevel = 0;
417 PlayUnitSound(Selected[0], VoiceSelected);
418 SelectionChanged();
419 UI.SelectedViewport->Center(unit->X, unit->Y, TileSizeX / 2, TileSizeY / 2);
420 }
421 }
422
423 /**
424 ** Toggle grab mouse on/off.
425 */
426 static void UiToggleGrabMouse(void)
427 {
428 DebugPrint("%x\n" _C_ KeyModifiers);
429 ToggleGrabMouse(0);
430 UI.StatusLine.Set(_("Grab mouse toggled."));
431 }
432
433 /**
434 ** Track unit, the viewport follows the unit.
435 */
436 static void UiTrackUnit(void)
437 {
438 if (UI.SelectedViewport->Unit == Selected[0]) {
439 UI.SelectedViewport->Unit = NULL;
440 } else {
441 UI.SelectedViewport->Unit = Selected[0];
442 }
443 }
444
445 /**
446 ** Call the lua function HandleCommandKey
447 */
448 bool HandleCommandKey(int key)
449 {
450 bool ret;
451 int base = lua_gettop(Lua);
452
453 lua_pushstring(Lua, "HandleCommandKey");
454 lua_gettable(Lua, LUA_GLOBALSINDEX);
455 if (!lua_isfunction(Lua, -1)) {
456 DebugPrint("No HandleCommandKey function in lua.\n");
457 return false;
458 }
459 lua_pushstring(Lua, SdlKey2Str(key));
460 lua_pushboolean(Lua, (KeyModifiers & ModifierControl));
461 lua_pushboolean(Lua, (KeyModifiers & ModifierAlt));
462 lua_pushboolean(Lua, (KeyModifiers & ModifierShift));
463 LuaCall(4, 0);
464 if (lua_gettop(Lua) - base == 1) {
465 ret = LuaToBoolean(Lua, base + 1);
466 lua_pop(Lua, 1);
467 } else {
468 LuaError(Lua, "HandleCommandKey must return a boolean");
469 ret = false;
470 }
471 return ret;
472 }
473
474 /**
475 ** Handle keys in command mode.
476 **
477 ** @param key Key scancode.
478 **
479 ** @return True, if key is handled; otherwise false.
480 */
481 static bool CommandKey(int key)
482 {
483 size_t p;
484
485 // FIXME: don't handle unicode well. Should work on all latin keyboard.
486 if ((p = UiGroupKeys.find(key)) != std::string::npos) {
487 key = '0' + p;
488 if (key > '9') {
489 key = SDLK_BACKQUOTE;
490 }
491 }
492
493 switch (key) {
494 // Return enters chat/input mode.
495 case SDLK_RETURN:
496 case SDLK_KP_ENTER: // RETURN
497 UiBeginInput();
498 return true;
499
500 // Unselect everything
501 case SDLK_ESCAPE:
502 case SDLK_CARET:
503 case SDLK_BACKQUOTE:
504 UiUnselectAll();
505 break;
506
507 // Group selection
508 case '0': case '1': case '2':
509 case '3': case '4': case '5':
510 case '6': case '7': case '8':
511 case '9':
512 if (KeyModifiers & ModifierShift) {
513 if (KeyModifiers & (ModifierAlt | ModifierDoublePress)) {
514 UiCenterOnGroup(key - '0');
515 } else if (KeyModifiers & ModifierControl) {
516 UiAddToGroup(key - '0');
517 } else {
518 UiAddGroupToSelection(key - '0');
519 }
520 } else {
521 if (KeyModifiers & (ModifierAlt | ModifierDoublePress)) {
522 UiCenterOnGroup(key - '0');
523 } else if (KeyModifiers & ModifierControl) {
524 UiDefineGroup(key - '0');
525 } else {
526 UiSelectGroup(key - '0');
527 }
528 }
529 break;
530
531 case SDLK_F2:
532 case SDLK_F3:
533 case SDLK_F4: // Set/Goto place
534 if (KeyModifiers & ModifierShift) {
535 SetSavedMapPosition(key - SDLK_F2, UI.SelectedViewport->MapX, UI.SelectedViewport->MapY);
536 } else {
537 RecallSavedMapPosition(key - SDLK_F2);
538 }
539 break;
540
541 case SDLK_SPACE: // center on last action
542 CenterOnMessage();
543 break;
544
545 case SDLK_EQUALS: // plus is shift-equals.
546 case SDLK_KP_PLUS:
547 UiIncreaseGameSpeed();
548 break;
549
550 case SDLK_MINUS: // - Slower
551 case SDLK_KP_MINUS:
552 UiDecreaseGameSpeed();
553 break;
554
555 case 'b': // ALT+B, CTRL+B Toggle big map
556 if (!(KeyModifiers & (ModifierAlt | ModifierControl))) {
557 break;
558 }
559 UiToggleBigMap();
560 break;
561
562 case 'c': // ALT+C, CTRL+C C center on units
563 UiCenterOnSelected();
564 break;
565
566 case 'f': // ALT+F, CTRL+F toggle fullscreen
567 if (!(KeyModifiers & (ModifierAlt | ModifierControl))) {
568 break;
569 }
570 ToggleFullScreen();
571 SavePreferences();
572 break;
573
574 case 'g': // ALT+G, CTRL+G grab mouse pointer
575 if (!(KeyModifiers & (ModifierAlt | ModifierControl))) {
576 break;
577 }
578 UiToggleGrabMouse();
579 break;
580
581 case 'i':
582 if (!(KeyModifiers & (ModifierAlt | ModifierControl))) {
583 break;
584 }
585 // FALL THROUGH
586 case SDLK_PERIOD: // ., ALT+I, CTRL+I: Find idle worker
587 UiFindIdleWorker();
588 break;
589
590 case 'm': // CTRL+M Turn music on / off
591 if (KeyModifiers & ModifierControl) {
592 UiToggleMusic();
593 SavePreferences();
594 break;
595 }
596 break;
597
598 case 'p': // CTRL+P, ALT+P Toggle pause
599 if (!(KeyModifiers & (ModifierAlt | ModifierControl))) {
600 break;
601 }
602 // FALL THROUGH (CTRL+P, ALT+P)
603 case SDLK_PAUSE:
604 UiTogglePause();
605 break;
606
607 case 's': // CTRL+S - Turn sound on / off
608 if (KeyModifiers & ModifierControl) {
609 UiToggleSound();
610 SavePreferences();
611 break;
612 }
613 break;
614
615 case 't': // ALT+T, CTRL+T Track unit
616 if (!(KeyModifiers & (ModifierAlt | ModifierControl))) {
617 break;
618 }
619 UiTrackUnit();
620 break;
621
622 case 'v': // ALT+V, CTRL+V: Viewport
623 if (KeyModifiers & ModifierControl) {
624 CycleViewportMode(-1);
625 } else if (KeyModifiers & ModifierAlt) {
626 CycleViewportMode(1);
627 }
628 break;
629
630 case SDLK_TAB: // TAB toggles minimap.
631 // FIXME: more...
632 // FIXME: shift+TAB
633 if (KeyModifiers & ModifierAlt) {
634 break;
635 }
636 UiToggleTerrain();
637 break;
638
639 case SDLK_UP:
640 case SDLK_KP8:
641 KeyScrollState |= ScrollUp;
642 break;
643 case SDLK_DOWN:
644 case SDLK_KP2:
645 KeyScrollState |= ScrollDown;
646 break;
647 case SDLK_LEFT:
648 case SDLK_KP4:
649 KeyScrollState |= ScrollLeft;
650 break;
651 case SDLK_RIGHT:
652 case SDLK_KP6:
653 KeyScrollState |= ScrollRight;
654 break;
655
656 default:
657 if (HandleCommandKey(key)) {
658 break;
659 }
660 return false;
661 }
662 return true;
663 }
664
665 /**
666 ** Handle cheats
667 **
668 ** @return 1 if a cheat was handled, 0 otherwise
669 */
670 int HandleCheats(const std::string &input)
671 {
672 int ret = 0;
673
674 #ifdef DEBUG
675 if (input == "ai me") {
676 if (ThisPlayer->AiEnabled) {
677 // FIXME: UnitGoesUnderFog and UnitGoesOutOfFog change unit refs
678 // for human players. We can't switch back to a human player or
679 // we'll be using the wrong ref counts.
680 #if 0
681 ThisPlayer->AiEnabled = 0;
682 ThisPlayer->Type = PlayerPerson;
683 SetMessage("AI is off, Normal Player");
684 #else
685 SetMessage("Cannot disable 'ai me' cheat");
686 #endif
687 } else {
688 ThisPlayer->AiEnabled = 1;
689 ThisPlayer->Type = PlayerComputer;
690 if (!ThisPlayer->Ai) {
691 AiInit(ThisPlayer);
692 }
693 SetMessage("I'm the BORG, resistance is futile!");
694 }
695 return 1;
696 }
697 #endif
698 int base = lua_gettop(Lua);
699 lua_pushstring(Lua, "HandleCheats");
700 lua_gettable(Lua, LUA_GLOBALSINDEX);
701 if (!lua_isfunction(Lua, -1)) {
702 DebugPrint("No HandleCheats function in lua.\n");
703 } else {
704 lua_pushstring(Lua, input.c_str());
705 if (LuaCall(1, 0, false)) {
706 // A Lua error occurred within HandleCheats,
707 // and LuaCall already reported it.
708 } else if (lua_gettop(Lua) - base != 1) {
709 DebugPrint("HandleCheats must return a boolean\n");
710 } else {
711 ret = LuaToBoolean(Lua, -1);
712 }
713 }
714 lua_settop(Lua, base);
715 return ret;
716 }
717
718 /**
719 ** Handle keys in input mode.
720 **
721 ** @param key Key scancode.
722 ** @return True input finished.
723 */
724 static int InputKey(int key)
725 {
726 char ChatMessage[sizeof(Input) + 40];
727 char *namestart;
728 char *p;
729 char *q;
730
731 switch (key) {
732 case SDLK_RETURN:
733 case SDLK_KP_ENTER: // RETURN
734 // Replace ~~ with ~
735 for (p = q = Input; *p;) {
736 if (*p == '~') {
737 ++p;
738 }
739 *q++ = *p++;
740 }
741 *q = '\0';
742 #ifdef DEBUG
743 if (Input[0] == '-') {
744 if (!GameObserve && !GamePaused) {
745 CommandLog("input", NoUnitP, FlushCommands, -1, -1, NoUnitP, Input, -1);
746 CclCommand(Input + 1, false);
747 }
748 } else
749 #endif
750 if (!IsNetworkGame()) {
751 if (!GameObserve && !GamePaused) {
752 if (HandleCheats(Input)) {
753 CommandLog("input", NoUnitP, FlushCommands, -1, -1, NoUnitP, Input, -1);
754 }
755 }
756 }
757
758 // Check for Replay and ffw x
759 #ifdef DEBUG
760 if (strncmp(Input, "ffw ", 4) == 0) {
761 #else
762 if (strncmp(Input, "ffw ", 4) == 0 && ReplayGameType != ReplayNone) {
763 #endif
764 FastForwardCycle = atol(&Input[4]);
765 }
766
767 if (Input[0]) {
768 // Replace ~ with ~~
769 for (p = Input; *p; ++p) {
770 if (*p == '~') {
771 q = p + strlen(p);
772 q[1] = '\0';
773 while (q > p) {
774 *q = *(q - 1);
775 --q;
776 }
777 ++p;
778 }
779 }
780 sprintf_s(ChatMessage, sizeof(ChatMessage), "~%s~<%s>~> %s",
781 PlayerColorNames[ThisPlayer->Index].c_str(),
782 ThisPlayer->Name.c_str(), Input);
783 // FIXME: only to selected players ...
784 NetworkChatMessage(ChatMessage);
785 }
786 // FALL THROUGH
787 case SDLK_ESCAPE:
788 KeyState = KeyStateCommand;
789 UI.StatusLine.Clear();
790 return 1;
791
792 case SDLK_BACKSPACE:
793 if (InputIndex) {
794 if (Input[InputIndex - 1] == '~') {
795 Input[--InputIndex] = '\0';
796 }
797 InputIndex = UTF8GetPrev(Input, InputIndex);
798 if (InputIndex >= 0) {
799 Input[InputIndex] = '\0';
800 ShowInput();
801 }
802 }
803 return 1;
804
805 case SDLK_TAB:
806 namestart = strrchr(Input, ' ');
807 if (namestart) {
808 ++namestart;
809 } else {
810 namestart = Input;
811 }
812 if (!strlen(namestart)) {
813 return 1;
814 }
815 for (int i = 0; i < PlayerMax; ++i) {
816 if (Players[i].Type != PlayerPerson) {
817 continue;
818 }
819 if (!strncasecmp(namestart, Players[i].Name.c_str(), strlen(namestart))) {
820 InputIndex += strlen(Players[i].Name.c_str()) - strlen(namestart);
821 strcpy_s(namestart, sizeof(Input) - (namestart - Input), Players[i].Name.c_str());
822 if (namestart == Input) {
823 InputIndex += 2;
824 strcat_s(namestart, sizeof(Input) - (namestart - Input), ": ");
825 }
826 ShowInput();
827 }
828 }
829 return 1;
830
831 default:
832 if (key >= ' ') {
833 gcn::Key k(key);
834 std::string kstr = k.toString();
835 if (key == '~') {
836 if (InputIndex < (int)sizeof(Input) - 2) {
837 Input[InputIndex++] = key;
838 Input[InputIndex++] = key;
839 Input[InputIndex] = '\0';
840 ShowInput();
841 }
842 } else if (InputIndex < (int)(sizeof(Input) - kstr.size())) {
843 for (size_t i = 0; i < kstr.size(); ++i) {
844 Input[InputIndex++] = kstr[i];
845 }
846 Input[InputIndex] = '\0';
847 ShowInput();
848 }
849 return 1;
850 }
851 break;
852 }
853 return 0;
854 }
855
856 /**
857 ** Save a screenshot.
858 */
859 static void Screenshot(void)
860 {
861 CFile fd;
862 char filename[30];
863 int i;
864
865 for (i = 1; i <= 99; ++i) {
866 // FIXME: what if we can't write to this directory?
867 sprintf_s(filename, sizeof(filename), "screen%02d.png", i);
868 if (fd.open(filename, CL_OPEN_READ) == -1) {
869 break;
870 }
871 fd.close();
872 }
873 SaveScreenshotPNG(filename);
874 }
875
876 /**
877 ** Update KeyModifiers if a key is pressed.
878 **
879 ** @param key Key scancode.
880 ** @param keychar Character code.
881 **
882 ** @return 1 if modifier found, 0 otherwise
883 */
884 int HandleKeyModifiersDown(unsigned key, unsigned keychar)
885 {
886 switch (key) {
887 case SDLK_LSHIFT:
888 case SDLK_RSHIFT:
889 KeyModifiers |= ModifierShift;
890 return 1;
891 case SDLK_LCTRL:
892 case SDLK_RCTRL:
893 KeyModifiers |= ModifierControl;
894 return 1;
895 case SDLK_LALT:
896 case SDLK_RALT:
897 case SDLK_LMETA:
898 case SDLK_RMETA:
899 KeyModifiers |= ModifierAlt;
900 // maxy: disabled
901 if (InterfaceState == IfaceStateNormal) {
902 SelectedUnitChanged(); // VLADI: to allow alt-buttons
903 }
904 return 1;
905 case SDLK_LSUPER:
906 case SDLK_RSUPER:
907 KeyModifiers |= ModifierSuper;
908 return 1;
909 case SDLK_SYSREQ:
910 case SDLK_PRINT:
911 Screenshot();
912 if (GameRunning) {
913 SetMessage("%s", _("Screenshot made."));
914 }
915 return 1;
916 default:
917 break;
918 }
919 return 0;
920 }
921
922 /**
923 ** Update KeyModifiers if a key is released.
924 **
925 ** @param key Key scancode.
926 ** @param keychar Character code.
927 **
928 ** @return 1 if modifier found, 0 otherwise
929 */
930 int HandleKeyModifiersUp(unsigned key, unsigned keychar)
931 {
932 switch (key) {
933 case SDLK_LSHIFT:
934 case SDLK_RSHIFT:
935 KeyModifiers &= ~ModifierShift;
936 return 1;
937 case SDLK_LCTRL:
938 case SDLK_RCTRL:
939 KeyModifiers &= ~ModifierControl;
940 return 1;
941 case SDLK_LALT:
942 case SDLK_RALT:
943 case SDLK_LMETA:
944 case SDLK_RMETA:
945 KeyModifiers &= ~ModifierAlt;
946 // maxy: disabled
947 if (InterfaceState == IfaceStateNormal) {
948 SelectedUnitChanged(); // VLADI: to allow alt-buttons
949 }
950 return 1;
951 case SDLK_LSUPER:
952 case SDLK_RSUPER:
953 KeyModifiers &= ~ModifierSuper;
954 return 1;
955 }
956 return 0;
957 }
958
959 /**
960 ** Check if a key is from the keypad and convert to ascii
961 */
962 static bool IsKeyPad(unsigned key, unsigned *kp)
963 {
964 if (key >= SDLK_KP0 && key <= SDLK_KP9) {
965 *kp = SDLK_0 + (key - SDLK_KP0);
966 } else if (key == SDLK_KP_PERIOD) {
967 *kp = SDLK_PERIOD;
968 } else if (key == SDLK_KP_DIVIDE) {
969 *kp = SDLK_SLASH;
970 } else if (key == SDLK_KP_MULTIPLY) {
971 *kp = SDLK_ASTERISK;
972 } else if (key == SDLK_KP_MINUS) {
973 *kp = SDLK_MINUS;
974 } else if (key == SDLK_KP_PLUS) {
975 *kp = SDLK_PLUS;
976 } else if (key == SDLK_KP_ENTER) {
977 *kp = SDLK_RETURN;
978 } else if (key == SDLK_KP_EQUALS) {
979 *kp = SDLK_EQUALS;
980 } else {
981 *kp = SDLK_UNKNOWN;
982 return false;
983 }
984 return true;
985 }
986
987 /**
988 ** Handle key down.
989 **
990 ** @param key Key scancode.
991 ** @param keychar Character code.
992 */
993 void HandleKeyDown(unsigned key, unsigned keychar)
994 {
995 if (HandleKeyModifiersDown(key, keychar)) {
996 return;
997 }
998
999 // Handle All other keys
1000
1001 // Command line input: for message or cheat
1002 unsigned kp = 0;
1003 if (KeyState == KeyStateInput && (keychar || IsKeyPad(key, &kp))) {
1004 InputKey(kp ? kp : keychar);
1005 } else {
1006 // If no modifier look if button bound
1007 if (!(KeyModifiers & (ModifierControl | ModifierAlt |
1008 ModifierSuper))) {
1009 if (!GameObserve && !GamePaused) {
1010 if (UI.ButtonPanel.DoKey(key)) {
1011 return;
1012 }
1013 }
1014 }
1015 CommandKey(key);
1016 }
1017 }
1018
1019 /**
1020 ** Handle key up.
1021 **
1022 ** @param key Key scancode.
1023 ** @param keychar Character code.
1024 */
1025 void HandleKeyUp(unsigned key, unsigned keychar)
1026 {
1027 if (HandleKeyModifiersUp(key, keychar)) {
1028 return;
1029 }
1030
1031 switch (key) {
1032 case SDLK_UP:
1033 case SDLK_KP8:
1034 KeyScrollState &= ~ScrollUp;
1035 break;
1036 case SDLK_DOWN:
1037 case SDLK_KP2:
1038 KeyScrollState &= ~ScrollDown;
1039 break;
1040 case SDLK_LEFT:
1041 case SDLK_KP4:
1042 KeyScrollState &= ~ScrollLeft;
1043 break;
1044 case SDLK_RIGHT:
1045 case SDLK_KP6:
1046 KeyScrollState &= ~ScrollRight;
1047 break;
1048 default:
1049 break;
1050 }
1051 }
1052
1053 /**
1054 ** Handle key up.
1055 **
1056 ** @param key Key scancode.
1057 ** @param keychar Character code.
1058 */
1059 void HandleKeyRepeat(unsigned key, unsigned keychar)
1060 {
1061 if (KeyState == KeyStateInput && keychar) {
1062 InputKey(keychar);
1063 }
1064 }
1065
1066 /**
1067 ** Handle the mouse in scroll area
1068 **
1069 ** @param x Screen X position.
1070 ** @param y Screen Y position.
1071 **
1072 ** @return 1 if the mouse is in the scroll area, 0 otherwise
1073 */
1074 int HandleMouseScrollArea(int x, int y)
1075 {
1076 if (x < SCROLL_LEFT) {
1077 if (y < SCROLL_UP) {
1078 CursorOn = CursorOnScrollLeftUp;
1079 MouseScrollState = ScrollLeftUp;
1080 GameCursor = UI.ArrowNW.Cursor;
1081 } else if (y > SCROLL_DOWN) {
1082 CursorOn = CursorOnScrollLeftDown;
1083 MouseScrollState = ScrollLeftDown;
1084 GameCursor = UI.ArrowSW.Cursor;
1085 } else {
1086 CursorOn = CursorOnScrollLeft;
1087 MouseScrollState = ScrollLeft;
1088 GameCursor = UI.ArrowW.Cursor;
1089 }
1090 } else if (x > SCROLL_RIGHT) {
1091 if (y < SCROLL_UP) {
1092 CursorOn = CursorOnScrollRightUp;
1093 MouseScrollState = ScrollRightUp;
1094 GameCursor = UI.ArrowNE.Cursor;
1095 } else if (y > SCROLL_DOWN) {
1096 CursorOn = CursorOnScrollRightDown;
1097 MouseScrollState = ScrollRightDown;
1098 GameCursor = UI.ArrowSE.Cursor;
1099 } else {
1100 CursorOn = CursorOnScrollRight;
1101 MouseScrollState = ScrollRight;
1102 GameCursor = UI.ArrowE.Cursor;
1103 }
1104 } else if (y < SCROLL_UP) {
1105 CursorOn = CursorOnScrollUp;
1106 MouseScrollState = ScrollUp;
1107 GameCursor = UI.ArrowN.Cursor;
1108 } else if (y > SCROLL_DOWN) {
1109 CursorOn = CursorOnScrollDown;
1110 MouseScrollState = ScrollDown;
1111 GameCursor = UI.ArrowS.Cursor;
1112 } else {
1113 return 0;
1114 }
1115 return 1;
1116 }
1117
1118 /**
1119 ** Keep coordinates in window and update cursor position
1120 **
1121 ** @param x screen pixel X position.
1122 ** @param y screen pixel Y position.
1123 */
1124 void HandleCursorMove(int *x, int *y)
1125 {
1126 //
1127 // Reduce coordinates to window-size.
1128 //
1129 if (*x < 0) {
1130 *x = 0;
1131 } else if (*x >= Video.Width) {
1132 *x = Video.Width - 1;
1133 }
1134 if (*y < 0) {
1135 *y = 0;
1136 } else if (*y >= Video.Height) {
1137 *y = Video.Height - 1;
1138 }
1139
1140 CursorX = *x;
1141 CursorY = *y;
1142 }
1143
1144 /**
1145 ** Handle movement of the cursor.
1146 **
1147 ** @param x screen pixel X position.
1148 ** @param y screen pixel Y position.
1149 */
1150 void HandleMouseMove(int x, int y)
1151 {
1152 HandleCursorMove(&x, &y);
1153 UIHandleMouseMove(x, y);
1154 }
1155
1156 /**
1157 ** Called if mouse button pressed down.
1158 **
1159 ** @param button Mouse button number (0 left, 1 middle, 2 right)
1160 */
1161 void HandleButtonDown(unsigned button)
1162 {
1163 UIHandleButtonDown(button);
1164 }
1165
1166 /**
1167 ** Called if mouse button released.
1168 **
1169 ** @todo FIXME: the mouse handling should be complete rewritten
1170 ** @todo FIXME: this is needed for double click, long click,...
1171 **
1172 ** @param button Mouse button number (0 left, 1 middle, 2 right)
1173 */
1174 void HandleButtonUp(unsigned button)
1175 {
1176 UIHandleButtonUp(button);
1177 }
1178
1179 /*----------------------------------------------------------------------------
1180 -- Lowlevel input functions
1181 ----------------------------------------------------------------------------*/
1182
1183 int DoubleClickDelay = 300; /// Time to detect double clicks.
1184 int HoldClickDelay = 1000; /// Time to detect hold clicks.
1185
1186 static enum {
1187 InitialMouseState, /// start state
1188 ClickedMouseState, /// button is clicked
1189 } MouseState; /// Current state of mouse
1190
1191 static int MouseX; /// Last mouse X position
1192 static int MouseY; /// Last mouse Y position
1193 static unsigned LastMouseButton; /// last mouse button handled
1194 static unsigned StartMouseTicks; /// Ticks of first click
1195 static unsigned LastMouseTicks; /// Ticks of last mouse event
1196
1197 /**
1198 ** Called if any mouse button is pressed down
1199 **
1200 ** Handles event conversion to double click, dragging, hold.
1201 **
1202 ** FIXME: dragging is not supported.
1203 **
1204 ** @param callbacks Callback structure for events.
1205 ** @param ticks Denotes time-stamp of video-system
1206 ** @param button Mouse button pressed.
1207 */
1208 void InputMouseButtonPress(const EventCallback *callbacks,
1209 unsigned ticks, unsigned button)
1210 {
1211 //
1212 // Button new pressed.
1213 //
1214 if (!(MouseButtons & (1 << button))) {
1215 MouseButtons |= (1 << button);
1216 //
1217 // Detect double click
1218 //
1219 if (MouseState == ClickedMouseState && button == LastMouseButton &&
1220 ticks < StartMouseTicks + DoubleClickDelay) {
1221 MouseButtons |= (1 << button) << MouseDoubleShift;
1222 button |= button << MouseDoubleShift;
1223 } else {
1224 MouseState = InitialMouseState;
1225 StartMouseTicks = ticks;
1226 LastMouseButton = button;
1227 }
1228 }
1229 LastMouseTicks = ticks;
1230
1231 callbacks->ButtonPressed(button);
1232 }
1233
1234 /**
1235 ** Called if any mouse button is released up
1236 **
1237 ** @param callbacks Callback structure for events.
1238 ** @param ticks Denotes time-stamp of video-system
1239 ** @param button Mouse button released.
1240 */
1241 void InputMouseButtonRelease(const EventCallback *callbacks,
1242 unsigned ticks, unsigned button)
1243 {
1244 unsigned mask;
1245
1246 //
1247 // Same button before pressed.
1248 //
1249 if (button == LastMouseButton && MouseState == InitialMouseState) {
1250 MouseState = ClickedMouseState;
1251 } else {
1252 LastMouseButton = 0;
1253 MouseState = InitialMouseState;
1254 }
1255 LastMouseTicks = ticks;
1256
1257 mask = 0;
1258 if (MouseButtons & ((1 << button) << MouseDoubleShift)) {
1259 mask |= button << MouseDoubleShift;
1260 }
1261 if (MouseButtons & ((1 << button) << MouseDragShift)) {
1262 mask |= button << MouseDragShift;
1263 }
1264 if (MouseButtons & ((1 << button) << MouseHoldShift)) {
1265 mask |= button << MouseHoldShift;
1266 }
1267 MouseButtons &= ~(0x01010101 << button);
1268
1269 callbacks->ButtonReleased(button | mask);
1270 }
1271
1272 /**
1273 ** Called if the mouse is moved
1274 **
1275 ** @param callbacks Callback structure for events.
1276 ** @param ticks Denotes time-stamp of video-system
1277 ** @param x X movement
1278 ** @param y Y movement
1279 */
1280 void InputMouseMove(const EventCallback *callbacks,
1281 unsigned ticks, int x, int y)
1282 {
1283 // Don't reset the mouse state unless we really moved
1284 if (MouseX != x || MouseY != y) {
1285 MouseState = InitialMouseState;
1286 LastMouseTicks = ticks;
1287 MouseX = x;
1288 MouseY = y;
1289 }
1290 callbacks->MouseMoved(x, y);
1291 }
1292
1293 /**
1294 ** Called if the mouse exits the game window (when supported by videomode)
1295 **
1296 ** @param callbacks Callback structure for events.
1297 ** @param ticks Denotes time-stamp of video-system
1298 **
1299 */
1300 void InputMouseExit(const EventCallback *callbacks, unsigned ticks)
1301 {
1302 // FIXME: should we do anything here with ticks? don't know, but conform others
1303 // JOHNS: called by callback HandleMouseExit();
1304 callbacks->MouseExit();
1305 }
1306
1307 /**
1308 ** Called each frame to handle mouse timeouts.
1309 **
1310 ** @param callbacks Callback structure for events.
1311 ** @param ticks Denotes time-stamp of video-system
1312 */
1313 void InputMouseTimeout(const EventCallback *callbacks, unsigned ticks)
1314 {
1315 if (MouseButtons & (1 << LastMouseButton)) {
1316 if (ticks > StartMouseTicks + DoubleClickDelay) {
1317 MouseState = InitialMouseState;
1318 }
1319 if (ticks > LastMouseTicks + HoldClickDelay) {
1320 LastMouseTicks = ticks;
1321 MouseButtons |= (1 << LastMouseButton) << MouseHoldShift;
1322 callbacks->ButtonPressed(LastMouseButton |
1323 (LastMouseButton << MouseHoldShift));
1324 }
1325 }
1326 }
1327
1328
1329 static int HoldKeyDelay = 250; /// Time to detect hold key
1330 static int HoldKeyAdditionalDelay = 50; /// Time to detect additional hold key
1331
1332 static unsigned LastIKey; /// last key handled
1333 static unsigned LastIKeyChar; /// last keychar handled
1334 static unsigned LastKeyTicks; /// Ticks of last key
1335 static unsigned DoubleKey; /// last key pressed
1336
1337 /**
1338 ** Handle keyboard key press.
1339 **
1340 ** @param callbacks Callback structure for events.
1341 ** @param ticks Denotes time-stamp of video-system
1342 ** @param ikey Key scancode.
1343 ** @param ikeychar Character code.
1344 */
1345 void InputKeyButtonPress(const EventCallback *callbacks,
1346 unsigned ticks, unsigned ikey, unsigned ikeychar)
1347 {
1348 if (!LastIKey && DoubleKey == ikey &&
1349 ticks < LastKeyTicks + DoubleClickDelay) {
1350 KeyModifiers |= ModifierDoublePress;
1351 }
1352 DoubleKey = ikey;
1353 LastIKey = ikey;
1354 LastIKeyChar = ikeychar;
1355 LastKeyTicks = ticks;
1356 callbacks->KeyPressed(ikey, ikeychar);
1357 KeyModifiers &= ~ModifierDoublePress;
1358 }
1359
1360 /**
1361 ** Handle keyboard key release.
1362 **
1363 ** @param callbacks Callback structure for events.
1364 ** @param ticks Denotes time-stamp of video-system
1365 ** @param ikey Key scancode.
1366 ** @param ikeychar Character code.
1367 */
1368 void InputKeyButtonRelease(const EventCallback *callbacks,
1369 unsigned ticks, unsigned ikey, unsigned ikeychar)
1370 {
1371 if (ikey == LastIKey) {
1372 LastIKey = 0;
1373 }
1374 LastKeyTicks = ticks;
1375 callbacks->KeyReleased(ikey, ikeychar);
1376 }
1377
1378 /**
1379 ** Called each frame to handle keyboard timeouts.
1380 **
1381 ** @param callbacks Callback structure for events.
1382 ** @param ticks Denotes time-stamp of video-system
1383 */
1384 void InputKeyTimeout(const EventCallback *callbacks, unsigned ticks)
1385 {
1386 if (LastIKey && ticks > LastKeyTicks + HoldKeyDelay) {
1387 LastKeyTicks = ticks - (HoldKeyDelay - HoldKeyAdditionalDelay);
1388 callbacks->KeyRepeated(LastIKey, LastIKeyChar);
1389 }
1390 }
1391
1392 /**
1393 ** Get double click delay
1394 */
1395 int GetDoubleClickDelay(void)
1396 {
1397 return DoubleClickDelay;
1398 }
1399
1400 /**
1401 ** Set double click delay
1402 **
1403 ** @param delay Double click delay
1404 */
1405 void SetDoubleClickDelay(int delay)
1406 {
1407 DoubleClickDelay = delay;
1408 }
1409
1410 /**
1411 ** Get hold click delay
1412 */
1413 int GetHoldClickDelay(void)
1414 {
1415 return HoldClickDelay;
1416 }
1417
1418 /**
1419 ** Set hold click delay
1420 **
1421 ** @param delay Hold click delay
1422 */
1423 void SetHoldClickDelay(int delay)
1424 {
1425 HoldClickDelay = delay;
1426 }
1427
1428 //@}