Debian Codegraph @

src/engine/localevent.cpp

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2025 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2008 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #include "localevent.h"
25
26 #include <cassert>
27 #include <cmath>
28 #include <cstdlib>
29 #include <map>
30 #include <ostream>
31 #include <set>
32 #include <utility>
33
34 // Managing compiler warnings for SDL headers
35 #if defined( __GNUC__ )
36 #pragma GCC diagnostic push
37
38 #pragma GCC diagnostic ignored "-Wdouble-promotion"
39 #pragma GCC diagnostic ignored "-Wold-style-cast"
40 #pragma GCC diagnostic ignored "-Wswitch-default"
41 #endif
42
43 #include <SDL_error.h>
44 #include <SDL_events.h>
45 #include <SDL_gamecontroller.h>
46 #include <SDL_hints.h>
47 #include <SDL_joystick.h>
48 #include <SDL_keyboard.h>
49 #include <SDL_keycode.h>
50 #include <SDL_mouse.h>
51 #include <SDL_stdinc.h>
52 #include <SDL_timer.h>
53 #include <SDL_touch.h>
54 #include <SDL_version.h>
55 #include <SDL_video.h>
56
57 // Managing compiler warnings for SDL headers
58 #if defined( __GNUC__ )
59 #pragma GCC diagnostic pop
60 #endif
61
62 #include "audio.h"
63 #include "image.h"
64 #include "logging.h"
65 #include "render_processor.h"
66 #include "screen.h"
67
68 namespace
69 {
70 const uint32_t globalLoopSleepTime{ 1 };
71
72 // If such or more ms has passed after pressing the mouse button, then this is a long press.
73 const uint32_t mouseButtonLongPressTimeout{ 850 };
74
75 char getCharacterFromPressedKey( const fheroes2::Key key, int32_t mod )
76 {
77 if ( ( mod & fheroes2::KeyModifier::KEY_MODIFIER_SHIFT ) && ( mod & fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) ) {
78 mod = mod & ~( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS );
79 }
80
81 switch ( key ) {
82 case fheroes2::Key::KEY_1:
83 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '!' : '1' );
84 case fheroes2::Key::KEY_2:
85 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '@' : '2' );
86 case fheroes2::Key::KEY_3:
87 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '#' : '3' );
88 case fheroes2::Key::KEY_4:
89 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '$' : '4' );
90 case fheroes2::Key::KEY_5:
91 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '%' : '5' );
92 case fheroes2::Key::KEY_6:
93 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '^' : '6' );
94 case fheroes2::Key::KEY_7:
95 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '&' : '7' );
96 case fheroes2::Key::KEY_8:
97 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '*' : '8' );
98 case fheroes2::Key::KEY_9:
99 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '(' : '9' );
100 case fheroes2::Key::KEY_0:
101 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? ')' : '0' );
102 case fheroes2::Key::KEY_KP_0:
103 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
104 return '0';
105 break;
106 case fheroes2::Key::KEY_KP_1:
107 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
108 return '1';
109 break;
110 case fheroes2::Key::KEY_KP_2:
111 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
112 return '2';
113 break;
114 case fheroes2::Key::KEY_KP_3:
115 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
116 return '3';
117 break;
118 case fheroes2::Key::KEY_KP_4:
119 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
120 return '4';
121 break;
122 case fheroes2::Key::KEY_KP_5:
123 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
124 return '5';
125 break;
126 case fheroes2::Key::KEY_KP_6:
127 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
128 return '6';
129 break;
130 case fheroes2::Key::KEY_KP_7:
131 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
132 return '7';
133 break;
134 case fheroes2::Key::KEY_KP_8:
135 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
136 return '8';
137 break;
138 case fheroes2::Key::KEY_KP_9:
139 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
140 return '9';
141 break;
142 case fheroes2::Key::KEY_KP_PERIOD:
143 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
144 return '.';
145 break;
146 case fheroes2::Key::KEY_KP_DIVIDE:
147 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
148 return '/';
149 break;
150 case fheroes2::Key::KEY_KP_MULTIPLY:
151 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
152 return '*';
153 break;
154 case fheroes2::Key::KEY_KP_MINUS:
155 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
156 return '-';
157 break;
158 case fheroes2::Key::KEY_KP_PLUS:
159 if ( fheroes2::KeyModifier::KEY_MODIFIER_NUM & mod )
160 return '+';
161 break;
162 case fheroes2::Key::KEY_MINUS:
163 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '_' : '-' );
164 case fheroes2::Key::KEY_EQUALS:
165 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '+' : '=' );
166 case fheroes2::Key::KEY_BACKSLASH:
167 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '|' : '\\' );
168 case fheroes2::Key::KEY_LEFT_BRACKET:
169 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '{' : '[' );
170 case fheroes2::Key::KEY_RIGHT_BRACKET:
171 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '}' : ']' );
172 case fheroes2::Key::KEY_SEMICOLON:
173 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? ':' : ';' );
174 case fheroes2::Key::KEY_QUOTE:
175 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '"' : '\'' );
176 case fheroes2::Key::KEY_COMMA:
177 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '<' : ',' );
178 case fheroes2::Key::KEY_PERIOD:
179 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '>' : '.' );
180 case fheroes2::Key::KEY_SLASH:
181 return ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT & mod ? '?' : '/' );
182 case fheroes2::Key::KEY_EXCLAIM:
183 return '!';
184 case fheroes2::Key::KEY_AT:
185 return '@';
186 case fheroes2::Key::KEY_HASH:
187 return '#';
188 case fheroes2::Key::KEY_DOLLAR:
189 return '$';
190 case fheroes2::Key::KEY_AMPERSAND:
191 return '&';
192 case fheroes2::Key::KEY_ASTERISK:
193 return '*';
194 case fheroes2::Key::KEY_LEFT_PARENTHESIS:
195 return '(';
196 case fheroes2::Key::KEY_RIGHT_PARENTHESIS:
197 return ')';
198 case fheroes2::Key::KEY_DOUBLE_QUOTE:
199 return '"';
200 case fheroes2::Key::KEY_PLUS:
201 return '+';
202 case fheroes2::Key::KEY_COLON:
203 return ':';
204 case fheroes2::Key::KEY_LESS:
205 return '<';
206 case fheroes2::Key::KEY_GREATER:
207 return '>';
208 case fheroes2::Key::KEY_QUESTION:
209 return '?';
210 case fheroes2::Key::KEY_CARET:
211 return '^';
212 case fheroes2::Key::KEY_UNDERSCORE:
213 return '_';
214 case fheroes2::Key::KEY_SPACE:
215 return ' ';
216 case fheroes2::Key::KEY_A:
217 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'A' : 'a' );
218 case fheroes2::Key::KEY_B:
219 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'B' : 'b' );
220 case fheroes2::Key::KEY_C:
221 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'C' : 'c' );
222 case fheroes2::Key::KEY_D:
223 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'D' : 'd' );
224 case fheroes2::Key::KEY_E:
225 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'E' : 'e' );
226 case fheroes2::Key::KEY_F:
227 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'F' : 'f' );
228 case fheroes2::Key::KEY_G:
229 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'G' : 'g' );
230 case fheroes2::Key::KEY_H:
231 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'H' : 'h' );
232 case fheroes2::Key::KEY_I:
233 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'I' : 'i' );
234 case fheroes2::Key::KEY_J:
235 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'J' : 'j' );
236 case fheroes2::Key::KEY_K:
237 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'K' : 'k' );
238 case fheroes2::Key::KEY_L:
239 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'L' : 'l' );
240 case fheroes2::Key::KEY_M:
241 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'M' : 'm' );
242 case fheroes2::Key::KEY_N:
243 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'N' : 'n' );
244 case fheroes2::Key::KEY_O:
245 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'O' : 'o' );
246 case fheroes2::Key::KEY_P:
247 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'P' : 'p' );
248 case fheroes2::Key::KEY_Q:
249 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'Q' : 'q' );
250 case fheroes2::Key::KEY_R:
251 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'R' : 'r' );
252 case fheroes2::Key::KEY_S:
253 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'S' : 's' );
254 case fheroes2::Key::KEY_T:
255 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'T' : 't' );
256 case fheroes2::Key::KEY_U:
257 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'U' : 'u' );
258 case fheroes2::Key::KEY_V:
259 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'V' : 'v' );
260 case fheroes2::Key::KEY_W:
261 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'W' : 'w' );
262 case fheroes2::Key::KEY_X:
263 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'X' : 'x' );
264 case fheroes2::Key::KEY_Y:
265 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'Y' : 'y' );
266 case fheroes2::Key::KEY_Z:
267 return ( ( fheroes2::KeyModifier::KEY_MODIFIER_SHIFT | fheroes2::KeyModifier::KEY_MODIFIER_CAPS ) & mod ? 'Z' : 'z' );
268 default:
269 break;
270 }
271
272 return 0;
273 }
274 }
275
276 namespace EventProcessing
277 {
278 std::set<uint32_t> eventTypeStatus;
279
280 class EventEngine
281 {
282 public:
283 static void initEvents()
284 {
285 // The list below is based on event types which require SDL >= 2.0.5. Is there a reason why you want to compile with an older SDL version?
286 #if !SDL_VERSION_ATLEAST( 2, 0, 5 )
287 #error The event types used require at least SDL 2.0.5
288 #endif
289
290 // Full list of events and their requirements can be found at https://wiki.libsdl.org/SDL_EventType
291 setEventProcessingState( SDL_QUIT, true );
292 // This is a very serious situation and we should handle it.
293 setEventProcessingState( SDL_APP_LOWMEMORY, true );
294 setEventProcessingState( SDL_WINDOWEVENT, true );
295 setEventProcessingState( SDL_KEYDOWN, true );
296 setEventProcessingState( SDL_KEYUP, true );
297 // SDL_TEXTINPUT and SDL_TEXTEDITING are enabled and disabled by SDL_StartTextInput() and SDL_StopTextInput() functions.
298 // Do not enable them here.
299 setEventProcessingState( SDL_TEXTEDITING, false );
300 setEventProcessingState( SDL_TEXTINPUT, false );
301 setEventProcessingState( SDL_KEYMAPCHANGED, false ); // supported from SDL 2.0.4
302 setEventProcessingState( SDL_MOUSEMOTION, true );
303 setEventProcessingState( SDL_MOUSEBUTTONDOWN, true );
304 setEventProcessingState( SDL_MOUSEBUTTONUP, true );
305 setEventProcessingState( SDL_MOUSEWHEEL, true );
306 setEventProcessingState( SDL_JOYAXISMOTION, true );
307 setEventProcessingState( SDL_JOYBALLMOTION, true );
308 setEventProcessingState( SDL_JOYHATMOTION, true );
309 setEventProcessingState( SDL_JOYBUTTONDOWN, true );
310 setEventProcessingState( SDL_JOYBUTTONUP, true );
311 setEventProcessingState( SDL_JOYDEVICEADDED, true );
312 setEventProcessingState( SDL_JOYDEVICEREMOVED, true );
313 setEventProcessingState( SDL_CONTROLLERAXISMOTION, true );
314 setEventProcessingState( SDL_CONTROLLERBUTTONDOWN, true );
315 setEventProcessingState( SDL_CONTROLLERBUTTONUP, true );
316 setEventProcessingState( SDL_CONTROLLERDEVICEADDED, true );
317 setEventProcessingState( SDL_CONTROLLERDEVICEREMOVED, true );
318 setEventProcessingState( SDL_CONTROLLERDEVICEREMAPPED, true );
319 setEventProcessingState( SDL_FINGERDOWN, true );
320 setEventProcessingState( SDL_FINGERUP, true );
321 setEventProcessingState( SDL_FINGERMOTION, true );
322 // We do not support clipboard within the engine.
323 setEventProcessingState( SDL_CLIPBOARDUPDATE, false );
324 // We do not support drag and drop capability for the application.
325 setEventProcessingState( SDL_DROPFILE, false );
326 setEventProcessingState( SDL_DROPTEXT, false );
327 setEventProcessingState( SDL_DROPBEGIN, false ); // supported from SDL 2.0.5
328 setEventProcessingState( SDL_DROPCOMPLETE, false ); // supported from SDL 2.0.5
329 setEventProcessingState( SDL_RENDER_TARGETS_RESET, true ); // supported from SDL 2.0.2
330 setEventProcessingState( SDL_RENDER_DEVICE_RESET, true ); // supported from SDL 2.0.4
331 // We do not support custom user events as of now.
332 setEventProcessingState( SDL_USEREVENT, false );
333
334 // TODO: verify why we disabled processing of these events.
335 setEventProcessingState( SDL_SYSWMEVENT, false );
336 setEventProcessingState( SDL_DOLLARGESTURE, false );
337 setEventProcessingState( SDL_DOLLARRECORD, false );
338 setEventProcessingState( SDL_MULTIGESTURE, false );
339 setEventProcessingState( SDL_AUDIODEVICEADDED, false ); // supported from SDL 2.0.4
340 setEventProcessingState( SDL_AUDIODEVICEREMOVED, false ); // supported from SDL 2.0.4
341 setEventProcessingState( SDL_SENSORUPDATE, false );
342
343 // TODO: we don't process these events. Add the logic.
344 setEventProcessingState( SDL_APP_TERMINATING, false );
345 setEventProcessingState( SDL_APP_WILLENTERBACKGROUND, false );
346 setEventProcessingState( SDL_APP_DIDENTERBACKGROUND, false );
347 setEventProcessingState( SDL_APP_WILLENTERFOREGROUND, false );
348 setEventProcessingState( SDL_APP_DIDENTERFOREGROUND, false );
349 setEventProcessingState( SDL_DISPLAYEVENT, false );
350
351 // SDL_LOCALECHANGED is supported from SDL 2.0.14
352 // SDL_CONTROLLERTOUCHPADDOWN is supported from SDL 2.0.14
353 // SDL_CONTROLLERTOUCHPADMOTION is supported from SDL 2.0.14
354 // SDL_CONTROLLERTOUCHPADUP is supported from SDL 2.0.14
355 // SDL_CONTROLLERSENSORUPDATE is supported from SDL 2.0.14
356 // SDL_TEXTEDITING_EXT is supported only from SDL 2.0.22
357 // SDL_POLLSENTINEL is supported from SDL 2.0.?
358 }
359
360 static int32_t getCurrentKeyModifiers()
361 {
362 return getKeyModifierFromSDL( SDL_GetModState() );
363 }
364
365 static void initTouchpad()
366 {
367 #if SDL_VERSION_ATLEAST( 2, 0, 10 )
368 if ( SDL_SetHint( SDL_HINT_MOUSE_TOUCH_EVENTS, "0" ) != SDL_TRUE ) {
369 ERROR_LOG( "Failed to set the " SDL_HINT_MOUSE_TOUCH_EVENTS " hint." )
370 }
371 #endif
372 #if SDL_VERSION_ATLEAST( 2, 0, 6 )
373 if ( SDL_SetHint( SDL_HINT_TOUCH_MOUSE_EVENTS, "0" ) != SDL_TRUE ) {
374 ERROR_LOG( "Failed to set the " SDL_HINT_TOUCH_MOUSE_EVENTS " hint." )
375 }
376 #endif
377
378 if ( SDL_GetNumTouchDevices() <= 0 ) {
379 return;
380 }
381
382 // On devices with touchpad/touchscreen the software-rendered mouse cursor is mandatory
383 // to properly convert touch events to mouse events and render the cursor especially
384 // if no hardware mouse device is present and the hardware cursor is disabled by OS.
385 fheroes2::cursor().enableSoftwareEmulation( true );
386 }
387
388 void initController()
389 {
390 const int joystickNumber = SDL_NumJoysticks();
391 if ( joystickNumber < 0 ) {
392 ERROR_LOG( "Failed to get the number of joysticks. The error value: " << joystickNumber << ", description: " << SDL_GetError() )
393 return;
394 }
395
396 for ( int i = 0; i < joystickNumber; ++i ) {
397 if ( SDL_IsGameController( i ) == SDL_TRUE ) {
398 _gameController = SDL_GameControllerOpen( i );
399 if ( _gameController != nullptr ) {
400 // We force enable the software-rendered mouse cursor to properly convert controller events to mouse events
401 // and render the cursor especially if no hardware mouse device is present and the hardware cursor is disabled by OS.
402 fheroes2::cursor().enableSoftwareEmulation( true );
403 break;
404 }
405
406 ERROR_LOG( "Failed to open a controller with ID " << i << ". Error description: " << SDL_GetError() )
407 }
408 }
409 }
410
411 void closeController()
412 {
413 if ( SDL_GameControllerGetAttached( _gameController ) == SDL_TRUE ) {
414 SDL_GameControllerClose( _gameController );
415 _gameController = nullptr;
416 }
417 }
418
419 bool isControllerValid() const
420 {
421 return _gameController != nullptr;
422 }
423
424 static void sleep( const uint32_t milliseconds )
425 {
426 SDL_Delay( milliseconds );
427 }
428
429 bool handleEvents( LocalEvent & eventHandler, const bool allowExit, bool & updateDisplay )
430 {
431 updateDisplay = false;
432
433 SDL_Event event;
434
435 while ( SDL_PollEvent( &event ) ) {
436 // Most SDL events should be processed sequentially one event at a time, but for some
437 // event types, the processing of intermediate events may be skipped in order to gain
438 // overall event processing speed.
439 bool processImmediately = true;
440
441 switch ( event.type ) {
442 case SDL_WINDOWEVENT:
443 if ( event.window.event == SDL_WINDOWEVENT_CLOSE ) {
444 if ( allowExit ) {
445 // Try to perform clear exit to catch all memory leaks, for example.
446 return false;
447 }
448 processImmediately = false;
449 break;
450 }
451 if ( onWindowEvent( event.window ) ) {
452 updateDisplay = true;
453 }
454 else {
455 processImmediately = false;
456 }
457 break;
458 case SDL_KEYDOWN:
459 case SDL_KEYUP:
460 onKeyboardEvent( eventHandler, event.key );
461 break;
462 case SDL_MOUSEMOTION:
463 onMouseMotionEvent( eventHandler, event.motion );
464 processImmediately = false;
465 break;
466 case SDL_MOUSEBUTTONDOWN:
467 case SDL_MOUSEBUTTONUP:
468 onMouseButtonEvent( eventHandler, event.button );
469 break;
470 case SDL_MOUSEWHEEL:
471 onMouseWheelEvent( eventHandler, event.wheel );
472 break;
473 case SDL_CONTROLLERDEVICEREMOVED:
474 onControllerRemovedEvent( event.jdevice );
475 break;
476 case SDL_CONTROLLERDEVICEADDED:
477 onControllerAddedEvent( event.jdevice );
478 break;
479 case SDL_JOYAXISMOTION:
480 case SDL_JOYBALLMOTION:
481 case SDL_JOYHATMOTION:
482 case SDL_JOYBUTTONDOWN:
483 case SDL_JOYBUTTONUP:
484 case SDL_JOYDEVICEADDED:
485 case SDL_JOYDEVICEREMOVED:
486 case SDL_CONTROLLERDEVICEREMAPPED:
487 // SDL requires joystick events to be enabled in order to handle controller events.
488 // This is because the controller related code depends on the joystick related code.
489 // See SDL_gamecontroller.c within SDL source code for implementation details.
490 processImmediately = false;
491 break;
492 case SDL_CONTROLLERAXISMOTION:
493 onControllerAxisEvent( eventHandler, event.caxis );
494 processImmediately = false;
495 break;
496 case SDL_CONTROLLERBUTTONDOWN:
497 case SDL_CONTROLLERBUTTONUP:
498 onControllerButtonEvent( eventHandler, event.cbutton );
499 break;
500 case SDL_FINGERDOWN:
501 case SDL_FINGERUP:
502 case SDL_FINGERMOTION:
503 onTouchEvent( eventHandler, event.tfinger );
504 if ( event.type == SDL_FINGERMOTION ) {
505 processImmediately = false;
506 }
507 break;
508 case SDL_RENDER_TARGETS_RESET:
509 // We need to just update the screen. This event usually happens when we switch between fullscreen and windowed modes.
510 updateDisplay = true;
511 break;
512 case SDL_RENDER_DEVICE_RESET:
513 onRenderDeviceResetEvent();
514 updateDisplay = true;
515 break;
516 case SDL_TEXTINPUT:
517 // Keyboard events on Android should be processed here. Use event.text.text to extract text input.
518 break;
519 case SDL_TEXTEDITING:
520 // An event when a user pressed a button on a keyboard. Not all buttons are supported. This event should be used mainly on Android devices.
521 break;
522 case SDL_QUIT:
523 if ( allowExit ) {
524 // Try to perform clear exit to catch all memory leaks, for example.
525 return false;
526 }
527 processImmediately = false;
528 break;
529 case SDL_APP_LOWMEMORY:
530 // According to SDL this event can only happen on Android or iOS.
531 // We need to deallocate some memory but we need to be careful not to deallocate images that are in use at the moment.
532 // As of now we have no logic for this so we at least log this event.
533 DEBUG_LOG( DBG_ENGINE, DBG_WARN, "OS indicates low memory. Release some resources." )
534 break;
535 default:
536 // If this assertion blows up then we included an event type but we didn't add logic for it.
537 assert( eventTypeStatus.count( event.type ) == 0 );
538
539 // This is a new event type which we do not handle. It might have been added in a newer version of SDL.
540 processImmediately = false;
541 break;
542 }
543
544 // If the current event does require immediate processing, then we need to return immediately.
545 if ( processImmediately ) {
546 break;
547 }
548
549 // Otherwise, we can process it later along with the newly received events, if any.
550 }
551
552 return true;
553 }
554
555 static const char * getKeyName( const fheroes2::Key key )
556 {
557 if ( key == fheroes2::Key::KEY_MOUSE_BUTTON_BACKWARD ) {
558 return "Mouse Backward";
559 }
560
561 if ( key == fheroes2::Key::KEY_MOUSE_BUTTON_FORWARD ) {
562 return "Mouse Forward";
563 }
564
565 return SDL_GetKeyName( static_cast<SDL_Keycode>( getSDLKey( key ) ) );
566 }
567
568 private:
569 SDL_GameController * _gameController{ nullptr };
570
571 static void setEventProcessingState( const uint32_t eventType, const bool enable )
572 {
573 if ( const auto [dummy, inserted] = eventTypeStatus.emplace( eventType ); !inserted ) {
574 assert( 0 );
575 }
576
577 SDL_EventState( eventType, ( enable ? SDL_ENABLE : SDL_IGNORE ) );
578 }
579
580 static int32_t getKeyModifierFromSDL( const int sdlModifier )
581 {
582 int32_t modifier = fheroes2::KeyModifier::KEY_MODIFIER_NONE;
583 if ( sdlModifier & KMOD_CTRL ) {
584 modifier |= fheroes2::KeyModifier::KEY_MODIFIER_CTRL;
585 }
586 if ( sdlModifier & KMOD_SHIFT ) {
587 modifier |= fheroes2::KeyModifier::KEY_MODIFIER_SHIFT;
588 }
589 if ( sdlModifier & KMOD_ALT ) {
590 modifier |= fheroes2::KeyModifier::KEY_MODIFIER_ALT;
591 }
592 if ( sdlModifier & KMOD_CAPS ) {
593 modifier |= fheroes2::KeyModifier::KEY_MODIFIER_CAPS;
594 }
595 if ( sdlModifier & KMOD_NUM ) {
596 modifier |= fheroes2::KeyModifier::KEY_MODIFIER_NUM;
597 }
598
599 return modifier;
600 }
601
602 static int getSDLKey( const fheroes2::Key key )
603 {
604 switch ( key ) {
605 case fheroes2::Key::NONE:
606 case fheroes2::Key::LAST_KEY:
607 return SDLK_UNKNOWN;
608 case fheroes2::Key::KEY_BACKSPACE:
609 return SDLK_BACKSPACE;
610 case fheroes2::Key::KEY_ENTER:
611 return SDLK_RETURN;
612 case fheroes2::Key::KEY_ESCAPE:
613 return SDLK_ESCAPE;
614 case fheroes2::Key::KEY_SPACE:
615 return SDLK_SPACE;
616 case fheroes2::Key::KEY_EXCLAIM:
617 return SDLK_EXCLAIM;
618 case fheroes2::Key::KEY_DOUBLE_QUOTE:
619 return SDLK_QUOTEDBL;
620 case fheroes2::Key::KEY_HASH:
621 return SDLK_HASH;
622 case fheroes2::Key::KEY_DOLLAR:
623 return SDLK_DOLLAR;
624 case fheroes2::Key::KEY_AMPERSAND:
625 return SDLK_AMPERSAND;
626 case fheroes2::Key::KEY_QUOTE:
627 return SDLK_QUOTE;
628 case fheroes2::Key::KEY_BACKQUOTE:
629 return SDLK_BACKQUOTE;
630 case fheroes2::Key::KEY_LEFT_PARENTHESIS:
631 return SDLK_LEFTPAREN;
632 case fheroes2::Key::KEY_RIGHT_PARENTHESIS:
633 return SDLK_RIGHTPAREN;
634 case fheroes2::Key::KEY_ASTERISK:
635 return SDLK_ASTERISK;
636 case fheroes2::Key::KEY_PLUS:
637 return SDLK_PLUS;
638 case fheroes2::Key::KEY_COMMA:
639 return SDLK_COMMA;
640 case fheroes2::Key::KEY_MINUS:
641 return SDLK_MINUS;
642 case fheroes2::Key::KEY_PERIOD:
643 return SDLK_PERIOD;
644 case fheroes2::Key::KEY_SLASH:
645 return SDLK_SLASH;
646 case fheroes2::Key::KEY_COLON:
647 return SDLK_COLON;
648 case fheroes2::Key::KEY_SEMICOLON:
649 return SDLK_SEMICOLON;
650 case fheroes2::Key::KEY_LESS:
651 return SDLK_LESS;
652 case fheroes2::Key::KEY_EQUALS:
653 return SDLK_EQUALS;
654 case fheroes2::Key::KEY_GREATER:
655 return SDLK_GREATER;
656 case fheroes2::Key::KEY_QUESTION:
657 return SDLK_QUESTION;
658 case fheroes2::Key::KEY_AT:
659 return SDLK_AT;
660 case fheroes2::Key::KEY_LEFT_BRACKET:
661 return SDLK_LEFTBRACKET;
662 case fheroes2::Key::KEY_BACKSLASH:
663 return SDLK_BACKSLASH;
664 case fheroes2::Key::KEY_RIGHT_BRACKET:
665 return SDLK_RIGHTBRACKET;
666 case fheroes2::Key::KEY_CARET:
667 return SDLK_CARET;
668 case fheroes2::Key::KEY_UNDERSCORE:
669 return SDLK_UNDERSCORE;
670 case fheroes2::Key::KEY_LEFT_ALT:
671 return SDLK_LALT;
672 case fheroes2::Key::KEY_RIGHT_ALT:
673 return SDLK_RALT;
674 case fheroes2::Key::KEY_LEFT_CONTROL:
675 return SDLK_LCTRL;
676 case fheroes2::Key::KEY_RIGHT_CONTROL:
677 return SDLK_RCTRL;
678 case fheroes2::Key::KEY_LEFT_SHIFT:
679 return SDLK_LSHIFT;
680 case fheroes2::Key::KEY_RIGHT_SHIFT:
681 return SDLK_RSHIFT;
682 case fheroes2::Key::KEY_TAB:
683 return SDLK_TAB;
684 case fheroes2::Key::KEY_DELETE:
685 return SDLK_DELETE;
686 case fheroes2::Key::KEY_PAGE_UP:
687 return SDLK_PAGEUP;
688 case fheroes2::Key::KEY_PAGE_DOWN:
689 return SDLK_PAGEDOWN;
690 case fheroes2::Key::KEY_F1:
691 return SDLK_F1;
692 case fheroes2::Key::KEY_F2:
693 return SDLK_F2;
694 case fheroes2::Key::KEY_F3:
695 return SDLK_F3;
696 case fheroes2::Key::KEY_F4:
697 return SDLK_F4;
698 case fheroes2::Key::KEY_F5:
699 return SDLK_F5;
700 case fheroes2::Key::KEY_F6:
701 return SDLK_F6;
702 case fheroes2::Key::KEY_F7:
703 return SDLK_F7;
704 case fheroes2::Key::KEY_F8:
705 return SDLK_F8;
706 case fheroes2::Key::KEY_F9:
707 return SDLK_F9;
708 case fheroes2::Key::KEY_F10:
709 return SDLK_F10;
710 case fheroes2::Key::KEY_F11:
711 return SDLK_F11;
712 case fheroes2::Key::KEY_F12:
713 return SDLK_F12;
714 case fheroes2::Key::KEY_LEFT:
715 return SDLK_LEFT;
716 case fheroes2::Key::KEY_RIGHT:
717 return SDLK_RIGHT;
718 case fheroes2::Key::KEY_UP:
719 return SDLK_UP;
720 case fheroes2::Key::KEY_DOWN:
721 return SDLK_DOWN;
722 case fheroes2::Key::KEY_0:
723 return SDLK_0;
724 case fheroes2::Key::KEY_1:
725 return SDLK_1;
726 case fheroes2::Key::KEY_2:
727 return SDLK_2;
728 case fheroes2::Key::KEY_3:
729 return SDLK_3;
730 case fheroes2::Key::KEY_4:
731 return SDLK_4;
732 case fheroes2::Key::KEY_5:
733 return SDLK_5;
734 case fheroes2::Key::KEY_6:
735 return SDLK_6;
736 case fheroes2::Key::KEY_7:
737 return SDLK_7;
738 case fheroes2::Key::KEY_8:
739 return SDLK_8;
740 case fheroes2::Key::KEY_9:
741 return SDLK_9;
742 case fheroes2::Key::KEY_A:
743 return SDLK_a;
744 case fheroes2::Key::KEY_B:
745 return SDLK_b;
746 case fheroes2::Key::KEY_C:
747 return SDLK_c;
748 case fheroes2::Key::KEY_D:
749 return SDLK_d;
750 case fheroes2::Key::KEY_E:
751 return SDLK_e;
752 case fheroes2::Key::KEY_F:
753 return SDLK_f;
754 case fheroes2::Key::KEY_G:
755 return SDLK_g;
756 case fheroes2::Key::KEY_H:
757 return SDLK_h;
758 case fheroes2::Key::KEY_I:
759 return SDLK_i;
760 case fheroes2::Key::KEY_J:
761 return SDLK_j;
762 case fheroes2::Key::KEY_K:
763 return SDLK_k;
764 case fheroes2::Key::KEY_L:
765 return SDLK_l;
766 case fheroes2::Key::KEY_M:
767 return SDLK_m;
768 case fheroes2::Key::KEY_N:
769 return SDLK_n;
770 case fheroes2::Key::KEY_O:
771 return SDLK_o;
772 case fheroes2::Key::KEY_P:
773 return SDLK_p;
774 case fheroes2::Key::KEY_Q:
775 return SDLK_q;
776 case fheroes2::Key::KEY_R:
777 return SDLK_r;
778 case fheroes2::Key::KEY_S:
779 return SDLK_s;
780 case fheroes2::Key::KEY_T:
781 return SDLK_t;
782 case fheroes2::Key::KEY_U:
783 return SDLK_u;
784 case fheroes2::Key::KEY_V:
785 return SDLK_v;
786 case fheroes2::Key::KEY_W:
787 return SDLK_w;
788 case fheroes2::Key::KEY_X:
789 return SDLK_x;
790 case fheroes2::Key::KEY_Y:
791 return SDLK_y;
792 case fheroes2::Key::KEY_Z:
793 return SDLK_z;
794 case fheroes2::Key::KEY_PRINT:
795 return SDLK_PRINTSCREEN;
796 case fheroes2::Key::KEY_KP_0:
797 return SDLK_KP_0;
798 case fheroes2::Key::KEY_KP_1:
799 return SDLK_KP_1;
800 case fheroes2::Key::KEY_KP_2:
801 return SDLK_KP_2;
802 case fheroes2::Key::KEY_KP_3:
803 return SDLK_KP_3;
804 case fheroes2::Key::KEY_KP_4:
805 return SDLK_KP_4;
806 case fheroes2::Key::KEY_KP_5:
807 return SDLK_KP_5;
808 case fheroes2::Key::KEY_KP_6:
809 return SDLK_KP_6;
810 case fheroes2::Key::KEY_KP_7:
811 return SDLK_KP_7;
812 case fheroes2::Key::KEY_KP_8:
813 return SDLK_KP_8;
814 case fheroes2::Key::KEY_KP_9:
815 return SDLK_KP_9;
816 case fheroes2::Key::KEY_KP_PERIOD:
817 return SDLK_KP_PERIOD;
818 case fheroes2::Key::KEY_KP_DIVIDE:
819 return SDLK_KP_DIVIDE;
820 case fheroes2::Key::KEY_KP_MULTIPLY:
821 return SDLK_KP_MULTIPLY;
822 case fheroes2::Key::KEY_KP_MINUS:
823 return SDLK_KP_MINUS;
824 case fheroes2::Key::KEY_KP_PLUS:
825 return SDLK_KP_PLUS;
826 case fheroes2::Key::KEY_KP_ENTER:
827 return SDLK_KP_ENTER;
828 case fheroes2::Key::KEY_KP_EQUALS:
829 return SDLK_KP_EQUALS;
830 case fheroes2::Key::KEY_HOME:
831 return SDLK_HOME;
832 case fheroes2::Key::KEY_END:
833 return SDLK_END;
834 case fheroes2::Key::KEY_MOUSE_BUTTON_BACKWARD:
835 return SDL_BUTTON_X1;
836 case fheroes2::Key::KEY_MOUSE_BUTTON_FORWARD:
837 return SDL_BUTTON_X2;
838 default:
839 // Did you add a new key? Add the logic above!
840 assert( 0 );
841 break;
842 }
843
844 return SDLK_UNKNOWN;
845 }
846
847 static fheroes2::Key getKeyFromSDL( int sdlKey )
848 {
849 // SDL interprets keyboard Numpad Enter as a separate key. However, in the game we should handle it in the same way as the normal Enter.
850 if ( sdlKey == SDLK_KP_ENTER ) {
851 sdlKey = SDLK_RETURN;
852 }
853
854 static std::map<int, fheroes2::Key> sdlValueToKey;
855 if ( sdlValueToKey.empty() ) {
856 // The map is empty let's populate it.
857 for ( int32_t i = static_cast<int32_t>( fheroes2::Key::NONE ); i < static_cast<int32_t>( fheroes2::Key::LAST_KEY ); ++i ) {
858 const fheroes2::Key key = static_cast<fheroes2::Key>( i );
859 const auto [dummy, isEmplaced] = sdlValueToKey.try_emplace( getSDLKey( key ), key );
860 if ( !isEmplaced ) {
861 assert( 0 );
862 }
863 }
864 }
865
866 auto iter = sdlValueToKey.find( sdlKey );
867 if ( iter == sdlValueToKey.end() ) {
868 return fheroes2::Key::NONE;
869 }
870
871 return iter->second;
872 }
873
874 // Returns true if frame rendering is required.
875 static bool onWindowEvent( const SDL_WindowEvent & event )
876 {
877 if ( event.event == SDL_WINDOWEVENT_FOCUS_LOST ) {
878 LocalEvent::StopSounds();
879 return false;
880 }
881
882 if ( event.event == SDL_WINDOWEVENT_FOCUS_GAINED ) {
883 LocalEvent::ResumeSounds();
884 return true;
885 }
886
887 return ( event.event == SDL_WINDOWEVENT_RESIZED );
888 }
889
890 static void onMouseMotionEvent( LocalEvent & eventHandler, const SDL_MouseMotionEvent & motion )
891 {
892 eventHandler.onMouseMotionEvent( { motion.x, motion.y } );
893 }
894
895 static void onMouseButtonEvent( LocalEvent & eventHandler, const SDL_MouseButtonEvent & button )
896 {
897 // Not sure how it is possible to have something else for a button.
898 assert( ( button.state == SDL_PRESSED ) || ( button.state == SDL_RELEASED ) );
899
900 LocalEvent::MouseButtonType buttonType = LocalEvent::MouseButtonType::MOUSE_BUTTON_UNKNOWN;
901 switch ( button.button ) {
902 case SDL_BUTTON_LEFT:
903 buttonType = LocalEvent::MouseButtonType::MOUSE_BUTTON_LEFT;
904 break;
905 case SDL_BUTTON_MIDDLE:
906 buttonType = LocalEvent::MouseButtonType::MOUSE_BUTTON_MIDDLE;
907 break;
908 case SDL_BUTTON_RIGHT:
909 buttonType = LocalEvent::MouseButtonType::MOUSE_BUTTON_RIGHT;
910 break;
911 case SDL_BUTTON_X1:
912 // We treat the Backward mouse button as a normal keyboard button to allow to use it for hot-key mapping.
913 eventHandler.onKeyboardEvent( fheroes2::Key::KEY_MOUSE_BUTTON_BACKWARD, 0,
914 ( button.state == SDL_PRESSED ) ? LocalEvent::KeyboardEventState::KEY_DOWN : LocalEvent::KeyboardEventState::KEY_UP );
915 return;
916 case SDL_BUTTON_X2:
917 // We treat the Forward mouse button as a normal keyboard button to allow to use it for hot-key mapping.
918 eventHandler.onKeyboardEvent( fheroes2::Key::KEY_MOUSE_BUTTON_FORWARD, 0,
919 ( button.state == SDL_PRESSED ) ? LocalEvent::KeyboardEventState::KEY_DOWN : LocalEvent::KeyboardEventState::KEY_UP );
920 return;
921 default:
922 VERBOSE_LOG( "Unknown mouse button " << static_cast<int>( button.button ) )
923 return;
924 }
925
926 eventHandler.onMouseButtonEvent( button.state == SDL_PRESSED, buttonType, { button.x, button.y } );
927 }
928
929 static void onKeyboardEvent( LocalEvent & eventHandler, const SDL_KeyboardEvent & event )
930 {
931 const fheroes2::Key key = getKeyFromSDL( event.keysym.sym );
932 if ( key == fheroes2::Key::NONE ) {
933 // We do not process this key.
934 return;
935 }
936
937 LocalEvent::KeyboardEventState state = LocalEvent::KeyboardEventState::KEY_UNKNOWN;
938 switch ( event.type ) {
939 case SDL_KEYDOWN:
940 state = LocalEvent::KeyboardEventState::KEY_DOWN;
941 break;
942 case SDL_KEYUP:
943 state = LocalEvent::KeyboardEventState::KEY_UP;
944 break;
945 default:
946 // We don't handle other events for now.
947 break;
948 }
949
950 eventHandler.onKeyboardEvent( key, getKeyModifierFromSDL( event.keysym.mod ), state );
951 }
952
953 static void onMouseWheelEvent( LocalEvent & eventHandler, const SDL_MouseWheelEvent & wheel )
954 {
955 eventHandler.onMouseWheelEvent( { wheel.x, wheel.y } );
956 }
957
958 static void onControllerAxisEvent( LocalEvent & eventHandler, const SDL_ControllerAxisEvent & motion )
959 {
960 LocalEvent::ControllerAxisType axisType = LocalEvent::ControllerAxisType::CONTROLLER_AXIS_UNKNOWN;
961 switch ( motion.axis ) {
962 case SDL_CONTROLLER_AXIS_LEFTX:
963 axisType = LocalEvent::ControllerAxisType::CONTROLLER_AXIS_LEFT_X;
964 break;
965 case SDL_CONTROLLER_AXIS_LEFTY:
966 axisType = LocalEvent::ControllerAxisType::CONTROLLER_AXIS_LEFT_Y;
967 break;
968 case SDL_CONTROLLER_AXIS_RIGHTX:
969 axisType = LocalEvent::ControllerAxisType::CONTROLLER_AXIS_RIGHT_X;
970 break;
971 case SDL_CONTROLLER_AXIS_RIGHTY:
972 axisType = LocalEvent::ControllerAxisType::CONTROLLER_AXIS_RIGHT_Y;
973 break;
974 default:
975 // We don't process other axes.
976 break;
977 }
978
979 eventHandler.onControllerAxisEvent( axisType, motion.value );
980 }
981
982 static void onControllerButtonEvent( LocalEvent & eventHandler, const SDL_ControllerButtonEvent & button )
983 {
984 // Not sure how it is possible to have something else for a button.
985 assert( ( button.state == SDL_PRESSED ) || ( button.state == SDL_RELEASED ) );
986
987 LocalEvent::ControllerButtonType buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_UNKNOWN;
988
989 switch ( button.button ) {
990 case SDL_CONTROLLER_BUTTON_A:
991 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_A;
992 break;
993 case SDL_CONTROLLER_BUTTON_B:
994 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_B;
995 break;
996 case SDL_CONTROLLER_BUTTON_X:
997 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_X;
998 break;
999 case SDL_CONTROLLER_BUTTON_Y:
1000 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_Y;
1001 break;
1002 case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER:
1003 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_RIGHT_SHOULDER;
1004 break;
1005 case SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
1006 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_LEFT_SHOULDER;
1007 break;
1008 case SDL_CONTROLLER_BUTTON_DPAD_UP:
1009 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_UP;
1010 break;
1011 case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
1012 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_DOWN;
1013 break;
1014 case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
1015 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_RIGHT;
1016 break;
1017 case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
1018 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_LEFT;
1019 break;
1020 case SDL_CONTROLLER_BUTTON_BACK:
1021 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_BACK;
1022 break;
1023 case SDL_CONTROLLER_BUTTON_START:
1024 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_START;
1025 break;
1026 case SDL_CONTROLLER_BUTTON_GUIDE:
1027 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_GUIDE;
1028 break;
1029 default:
1030 // We don't handle other buttons for now.
1031 break;
1032 }
1033
1034 #if defined( TARGET_NINTENDO_SWITCH )
1035 // Custom button mapping for Nintendo Switch
1036 if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_A ) {
1037 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_B;
1038 }
1039 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_B ) {
1040 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_A;
1041 }
1042 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_X ) {
1043 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_START;
1044 }
1045 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_Y ) {
1046 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_GUIDE;
1047 }
1048 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_RIGHT_SHOULDER ) {
1049 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_RIGHT;
1050 }
1051 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_LEFT_SHOULDER ) {
1052 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_LEFT;
1053 }
1054 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_BACK ) {
1055 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_X;
1056 }
1057 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_START ) {
1058 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_Y;
1059 }
1060 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_GUIDE ) {
1061 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_BACK;
1062 }
1063 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_LEFT ) {
1064 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_LEFT_SHOULDER;
1065 }
1066 else if ( buttonType == LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_DPAD_RIGHT ) {
1067 buttonType = LocalEvent::ControllerButtonType::CONTROLLER_BUTTON_RIGHT_SHOULDER;
1068 }
1069 #endif
1070
1071 eventHandler.onControllerButtonEvent( button.state == SDL_PRESSED, buttonType );
1072 }
1073
1074 static void onTouchEvent( LocalEvent & eventHandler, const SDL_TouchFingerEvent & event )
1075 {
1076 #if defined( TARGET_PS_VITA )
1077 {
1078 // PS Vita has two touchpads: front and rear. The ID of the front touchpad must match the value of
1079 // 'SDL_TouchID' used in the 'SDL_AddTouch()' call in the 'VITA_InitTouch()' function in this SDL2
1080 // source file: video/vita/SDL_vitatouch.c.
1081 constexpr SDL_TouchID frontTouchpadDeviceID
1082 {
1083 #if SDL_VERSION_ATLEAST( 2, 30, 7 )
1084 1
1085 #else
1086 0
1087 #endif
1088 };
1089
1090 // Use only front touchpad on PS Vita.
1091 if ( event.touchId != frontTouchpadDeviceID ) {
1092 return;
1093 }
1094 }
1095 #endif
1096
1097 LocalEvent::TouchFingerEventType fingerEventType = LocalEvent::TouchFingerEventType::FINGER_EVENT_UNKNOWN;
1098
1099 switch ( event.type ) {
1100 case SDL_FINGERDOWN:
1101 fingerEventType = LocalEvent::TouchFingerEventType::FINGER_EVENT_DOWN;
1102 break;
1103 case SDL_FINGERUP:
1104 fingerEventType = LocalEvent::TouchFingerEventType::FINGER_EVENT_UP;
1105 break;
1106 case SDL_FINGERMOTION:
1107 fingerEventType = LocalEvent::TouchFingerEventType::FINGER_EVENT_MOTION;
1108 break;
1109 default:
1110 // We don't handle any other events.
1111 break;
1112 }
1113
1114 eventHandler.onTouchFingerEvent( fingerEventType, event.touchId, event.fingerId, { event.x, event.y } );
1115 }
1116
1117 static void onRenderDeviceResetEvent()
1118 {
1119 LocalEvent::onRenderDeviceResetEvent();
1120 }
1121
1122 void onControllerRemovedEvent( const SDL_JoyDeviceEvent & event )
1123 {
1124 if ( _gameController == nullptr ) {
1125 // Nothing to handle.
1126 return;
1127 }
1128
1129 const SDL_GameController * removedController = SDL_GameControllerFromInstanceID( event.which );
1130 if ( removedController == nullptr ) {
1131 ERROR_LOG( "Failed to remove a controller with ID " << event.which << ". Error description: " << SDL_GetError() )
1132 return;
1133 }
1134
1135 if ( removedController == _gameController ) {
1136 SDL_GameControllerClose( _gameController );
1137 _gameController = nullptr;
1138 }
1139 }
1140
1141 void onControllerAddedEvent( const SDL_JoyDeviceEvent & event )
1142 {
1143 if ( _gameController == nullptr ) {
1144 _gameController = SDL_GameControllerOpen( event.which );
1145 if ( _gameController != nullptr ) {
1146 // We force enable the software-rendered mouse cursor to properly convert controller events to mouse events
1147 // and render the cursor especially if no hardware mouse device is present and the hardware cursor is disabled by OS.
1148 fheroes2::cursor().enableSoftwareEmulation( true );
1149 }
1150 else {
1151 ERROR_LOG( "Failed to open a controller with ID " << event.which << ". Error description: " << SDL_GetError() )
1152 }
1153 }
1154 }
1155 };
1156 }
1157
1158 namespace fheroes2
1159 {
1160 const char * KeySymGetName( const Key key )
1161 {
1162 return EventProcessing::EventEngine::getKeyName( key );
1163 }
1164
1165 size_t InsertKeySym( std::string & res, size_t pos, const Key key, const int32_t mod )
1166 {
1167 switch ( key ) {
1168 case fheroes2::Key::KEY_BACKSPACE:
1169 if ( !res.empty() && pos ) {
1170 if ( pos >= res.size() )
1171 res.resize( res.size() - 1 );
1172 else
1173 res.erase( pos - 1, 1 );
1174 --pos;
1175 }
1176 break;
1177 case fheroes2::Key::KEY_DELETE:
1178 if ( pos < res.size() ) {
1179 res.erase( pos, 1 );
1180 }
1181 break;
1182
1183 case fheroes2::Key::KEY_LEFT:
1184 if ( pos )
1185 --pos;
1186 break;
1187 case fheroes2::Key::KEY_RIGHT:
1188 if ( pos < res.size() )
1189 ++pos;
1190 break;
1191 case fheroes2::Key::KEY_HOME:
1192 pos = 0;
1193 break;
1194 case fheroes2::Key::KEY_END:
1195 pos = res.size();
1196 break;
1197
1198 default: {
1199 char c = getCharacterFromPressedKey( key, mod );
1200
1201 if ( c ) {
1202 res.insert( pos, 1, c );
1203 ++pos;
1204 }
1205 }
1206 }
1207
1208 return pos;
1209 }
1210 }
1211
1212 LocalEvent::LocalEvent()
1213 : _engine( std::make_unique<EventProcessing::EventEngine>() )
1214 , _mouseButtonLongPressDelay( mouseButtonLongPressTimeout )
1215 {
1216 // Do nothing.
1217 }
1218
1219 void LocalEvent::initController()
1220 {
1221 _engine->initController();
1222 }
1223
1224 void LocalEvent::CloseController()
1225 {
1226 _engine->closeController();
1227 }
1228
1229 LocalEvent & LocalEvent::Get()
1230 {
1231 static LocalEvent le;
1232
1233 return le;
1234 }
1235
1236 bool LocalEvent::HandleEvents( const bool sleepAfterEventProcessing /* = true */, const bool allowExit /* = false */ )
1237 {
1238 // Event processing might be computationally heavy.
1239 // We want to make sure that we do not slow down by going into sleep mode when it is not needed.
1240 const fheroes2::Time eventProcessingTimer;
1241
1242 // Mouse area must be updated only once so we will use only the latest area for rendering.
1243 _mouseCursorRenderArea = {};
1244
1245 // We shouldn't reset the MOUSE_PRESSED and KEY_HOLD here because these are "ongoing" states
1246 resetStates( KEY_PRESSED );
1247 resetStates( MOUSE_MOTION );
1248 resetStates( MOUSE_RELEASED );
1249 resetStates( MOUSE_WHEEL );
1250
1251 // MOUSE_PRESSED is an "ongoing" state, so we shouldn't reset the MOUSE_TOUCH while that state is active
1252 if ( !( _actionStates & MOUSE_PRESSED ) ) {
1253 resetStates( MOUSE_TOUCH );
1254 }
1255
1256 bool isDisplayRefreshRequired = false;
1257
1258 if ( !_engine->handleEvents( *this, allowExit, isDisplayRefreshRequired ) ) {
1259 return false;
1260 }
1261
1262 if ( _engine->isControllerValid() ) {
1263 ProcessControllerAxisMotion();
1264 }
1265
1266 // We can have more than one event which requires rendering. We must render only once and only when sleeping is expected.
1267 fheroes2::Rect renderRoi;
1268
1269 fheroes2::Display & display = fheroes2::Display::instance();
1270
1271 // To maintain color cycling animation we need to render the whole frame with an updated palette.
1272 if ( isDisplayRefreshRequired || fheroes2::RenderProcessor::instance().isCyclingUpdateRequired() ) {
1273 renderRoi = { 0, 0, display.width(), display.height() };
1274 }
1275 else {
1276 renderRoi = _mouseCursorRenderArea;
1277 }
1278
1279 static_assert( globalLoopSleepTime == 1, "Since you have changed the sleep time, make sure that the sleep does not last too long." );
1280
1281 if ( sleepAfterEventProcessing ) {
1282 if ( renderRoi != fheroes2::Rect() ) {
1283 display.render( renderRoi );
1284 }
1285
1286 #ifndef __EMSCRIPTEN__
1287 // Make sure not to delay any further if the processing time within this function was more than the expected waiting time.
1288 if ( eventProcessingTimer.getMs() < globalLoopSleepTime ) {
1289 EventProcessing::EventEngine::sleep( globalLoopSleepTime );
1290 }
1291 #endif
1292 }
1293 else {
1294 // Since rendering is going to be just after the call of this method we need to update rendering area only.
1295 if ( renderRoi != fheroes2::Rect() ) {
1296 display.updateNextRenderRoi( renderRoi );
1297 }
1298 }
1299
1300 #ifdef __EMSCRIPTEN__
1301 // When a WebAssembly app is running in a browser, the sleep time is used to perform various "background" operations on the main thread (such
1302 // as feeding the audio streams) by yielding to the browser's event loop using the Emscripten Asyncify mechanism. Therefore, it is preferable
1303 // to always force the main thread to fall asleep, otherwise, for example, the following deadlock is possible: the main thread waits in a loop
1304 // for an audio playback to finish, but it never finishes because new chunks are not feeded to it, because the main thread never goes to sleep.
1305 EventProcessing::EventEngine::sleep( globalLoopSleepTime );
1306 #endif
1307
1308 return true;
1309 }
1310
1311 void LocalEvent::StopSounds()
1312 {
1313 Audio::Mute();
1314 }
1315
1316 void LocalEvent::ResumeSounds()
1317 {
1318 Audio::Unmute();
1319 }
1320
1321 void LocalEvent::onMouseWheelEvent( fheroes2::Point position )
1322 {
1323 setStates( MOUSE_WHEEL );
1324 _mouseReleaseMiddlePos = _mouseCursorPos;
1325 _mouseWheelMovementOffset = position;
1326 }
1327
1328 void LocalEvent::onTouchFingerEvent( const TouchFingerEventType eventType, const int64_t touchId, const int64_t fingerId, fheroes2::PointBase2D<float> position )
1329 {
1330 // ID of a finger here is a composite thing, and consists of a touch device id and a finger id. This
1331 // should allow gestures to be handled correctly even when using different touchpads for different
1332 // fingers.
1333 const auto eventFingerId = std::make_pair( touchId, fingerId );
1334
1335 switch ( eventType ) {
1336 case TouchFingerEventType::FINGER_EVENT_DOWN:
1337 if ( !_fingerIds.first ) {
1338 _fingerIds.first = eventFingerId;
1339 }
1340 else if ( !_fingerIds.second ) {
1341 _fingerIds.second = eventFingerId;
1342 }
1343 else {
1344 // Gestures of more than two fingers are not supported, ignore
1345 return;
1346 }
1347
1348 break;
1349 case TouchFingerEventType::FINGER_EVENT_UP:
1350 case TouchFingerEventType::FINGER_EVENT_MOTION:
1351 if ( eventFingerId != _fingerIds.first && eventFingerId != _fingerIds.second ) {
1352 // An event from an unknown finger, ignore
1353 return;
1354 }
1355
1356 break;
1357 default:
1358 // Unknown event, this should never happen
1359 assert( 0 );
1360 return;
1361 }
1362
1363 if ( eventFingerId == _fingerIds.first ) {
1364 const fheroes2::Display & display = fheroes2::Display::instance();
1365
1366 #if defined( TARGET_PS_VITA ) || defined( TARGET_NINTENDO_SWITCH )
1367 // TODO: verify where it is even needed to do such weird woodoo magic for these targets.
1368 const fheroes2::Size screenResolution = fheroes2::engine().getCurrentScreenResolution(); // current resolution of screen
1369 const fheroes2::Rect windowRect = fheroes2::engine().getActiveWindowROI(); // scaled (logical) resolution
1370 assert( windowRect.width > 0 );
1371
1372 _emulatedPointerPos.x = static_cast<double>( screenResolution.width * position.x - windowRect.x ) * ( static_cast<double>( display.width() ) / windowRect.width );
1373 _emulatedPointerPos.y
1374 = static_cast<double>( screenResolution.height * position.y - windowRect.y ) * ( static_cast<double>( display.height() ) / windowRect.height );
1375 #else
1376 _emulatedPointerPos.x = static_cast<double>( position.x ) * display.width();
1377 _emulatedPointerPos.y = static_cast<double>( position.y ) * display.height();
1378 #endif
1379
1380 _mouseCursorPos.x = static_cast<int32_t>( _emulatedPointerPos.x );
1381 _mouseCursorPos.y = static_cast<int32_t>( _emulatedPointerPos.y );
1382
1383 setStates( MOUSE_MOTION );
1384 setStates( MOUSE_TOUCH );
1385
1386 if ( _globalMouseMotionEventHook ) {
1387 _mouseCursorRenderArea = _globalMouseMotionEventHook( _mouseCursorPos.x, _mouseCursorPos.y );
1388 }
1389
1390 // If there is a two-finger gesture in progress, the first finger is only used to move the cursor.
1391 // The operation of the left mouse button is not simulated.
1392 if ( !_isTwoFingerGestureInProgress ) {
1393 if ( eventType == TouchFingerEventType::FINGER_EVENT_DOWN ) {
1394 _mousePressLeftPos = _mouseCursorPos;
1395
1396 _mouseButtonLongPressDelay.reset();
1397
1398 setStates( MOUSE_PRESSED );
1399 }
1400 else if ( eventType == TouchFingerEventType::FINGER_EVENT_UP ) {
1401 _mouseReleaseLeftPos = _mouseCursorPos;
1402
1403 resetStates( MOUSE_PRESSED );
1404 resetStates( DRAG_ONGOING );
1405
1406 setStates( MOUSE_RELEASED );
1407 }
1408
1409 _currentMouseButton = MouseButtonType::MOUSE_BUTTON_LEFT;
1410 }
1411 }
1412 else if ( eventFingerId == _fingerIds.second ) {
1413 if ( eventType == TouchFingerEventType::FINGER_EVENT_DOWN ) {
1414 _mousePressRightPos = _mouseCursorPos;
1415
1416 _mouseButtonLongPressDelay.reset();
1417
1418 setStates( MOUSE_PRESSED );
1419 setStates( MOUSE_TOUCH );
1420
1421 // When the second finger touches the screen, the two-finger gesture processing begins. This
1422 // gesture simulates the operation of the right mouse button and ends when both fingers are
1423 // removed from the screen.
1424 _isTwoFingerGestureInProgress = true;
1425 }
1426 else if ( eventType == TouchFingerEventType::FINGER_EVENT_UP ) {
1427 _mouseReleaseRightPos = _mouseCursorPos;
1428
1429 resetStates( MOUSE_PRESSED );
1430 resetStates( DRAG_ONGOING );
1431
1432 setStates( MOUSE_RELEASED );
1433 setStates( MOUSE_TOUCH );
1434 }
1435
1436 _currentMouseButton = MouseButtonType::MOUSE_BUTTON_RIGHT;
1437 }
1438
1439 // The finger no longer touches the screen, reset its state
1440 if ( eventType == TouchFingerEventType::FINGER_EVENT_UP ) {
1441 if ( eventFingerId == _fingerIds.first ) {
1442 _fingerIds.first.reset();
1443 }
1444 else if ( eventFingerId == _fingerIds.second ) {
1445 _fingerIds.second.reset();
1446 }
1447 else {
1448 // An event from an unknown finger, this should never happen
1449 assert( 0 );
1450 }
1451
1452 // Both fingers are removed from the screen, cancel the two-finger gesture
1453 if ( !_fingerIds.first && !_fingerIds.second ) {
1454 _isTwoFingerGestureInProgress = false;
1455 }
1456 }
1457 }
1458
1459 void LocalEvent::onControllerAxisEvent( const ControllerAxisType axisType, const int16_t value )
1460 {
1461 if ( axisType == ControllerAxisType::CONTROLLER_AXIS_LEFT_X ) {
1462 if ( std::abs( value ) > CONTROLLER_L_DEADZONE ) {
1463 _controllerLeftXAxis = value;
1464 }
1465 else {
1466 _controllerLeftXAxis = 0;
1467 }
1468 }
1469 else if ( axisType == ControllerAxisType::CONTROLLER_AXIS_LEFT_Y ) {
1470 if ( std::abs( value ) > CONTROLLER_L_DEADZONE ) {
1471 _controllerLeftYAxis = value;
1472 }
1473 else {
1474 _controllerLeftYAxis = 0;
1475 }
1476 }
1477 else if ( axisType == ControllerAxisType::CONTROLLER_AXIS_RIGHT_X ) {
1478 if ( std::abs( value ) > CONTROLLER_R_DEADZONE ) {
1479 _controllerRightXAxis = value;
1480 }
1481 else {
1482 _controllerRightXAxis = 0;
1483 }
1484 }
1485 else if ( axisType == ControllerAxisType::CONTROLLER_AXIS_RIGHT_Y ) {
1486 if ( std::abs( value ) > CONTROLLER_R_DEADZONE ) {
1487 _controllerRightYAxis = value;
1488 }
1489 else {
1490 _controllerRightYAxis = 0;
1491 }
1492 }
1493 }
1494
1495 void LocalEvent::onControllerButtonEvent( const bool isPressed, const ControllerButtonType buttonType )
1496 {
1497 if ( isPressed ) {
1498 setStates( KEY_PRESSED );
1499 }
1500 else {
1501 resetStates( KEY_PRESSED );
1502 }
1503
1504 if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_A || buttonType == ControllerButtonType::CONTROLLER_BUTTON_B ) {
1505 if ( isAnyKeyPressed() ) {
1506 _mouseButtonLongPressDelay.reset();
1507
1508 setStates( MOUSE_PRESSED );
1509 }
1510 else {
1511 resetStates( MOUSE_PRESSED );
1512 resetStates( DRAG_ONGOING );
1513
1514 setStates( MOUSE_RELEASED );
1515 }
1516
1517 if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_A ) {
1518 if ( isAnyKeyPressed() ) {
1519 _mousePressLeftPos = _mouseCursorPos;
1520 }
1521 else {
1522 _mouseReleaseLeftPos = _mouseCursorPos;
1523 }
1524
1525 _currentMouseButton = MouseButtonType::MOUSE_BUTTON_LEFT;
1526 }
1527 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_B ) {
1528 if ( isAnyKeyPressed() ) {
1529 _mousePressRightPos = _mouseCursorPos;
1530 }
1531 else {
1532 _mouseReleaseRightPos = _mouseCursorPos;
1533 }
1534
1535 _currentMouseButton = MouseButtonType::MOUSE_BUTTON_RIGHT;
1536 }
1537
1538 resetStates( KEY_PRESSED );
1539 }
1540 else if ( isAnyKeyPressed() ) {
1541 if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_RIGHT_SHOULDER ) {
1542 _controllerPointerSpeed *= _controllerTriggerCursorSpeedup;
1543 _currentKeyboardValue = fheroes2::Key::NONE;
1544 }
1545 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_GUIDE ) {
1546 _currentKeyboardValue = fheroes2::Key::KEY_ESCAPE;
1547 }
1548 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_DPAD_DOWN ) {
1549 _currentKeyboardValue = fheroes2::Key::KEY_SPACE;
1550 }
1551 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_DPAD_LEFT ) {
1552 _currentKeyboardValue = fheroes2::Key::KEY_H;
1553 }
1554 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_DPAD_RIGHT ) {
1555 _currentKeyboardValue = fheroes2::Key::KEY_T;
1556 }
1557 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_X ) {
1558 _currentKeyboardValue = fheroes2::Key::KEY_E;
1559 }
1560 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_Y ) {
1561 _currentKeyboardValue = fheroes2::Key::KEY_C;
1562 }
1563 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_BACK ) {
1564 _currentKeyboardValue = fheroes2::Key::KEY_F;
1565 }
1566 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_START ) {
1567 _currentKeyboardValue = fheroes2::Key::KEY_ENTER;
1568 }
1569 else {
1570 _currentKeyboardValue = fheroes2::Key::NONE;
1571 }
1572 }
1573 else if ( buttonType == ControllerButtonType::CONTROLLER_BUTTON_RIGHT_SHOULDER ) {
1574 _controllerPointerSpeed /= _controllerTriggerCursorSpeedup;
1575 }
1576 }
1577
1578 void LocalEvent::ProcessControllerAxisMotion()
1579 {
1580 const double deltaTime = _controllerTimer.getS() * 1000.0;
1581 _controllerTimer.reset();
1582
1583 if ( _controllerLeftXAxis != 0 || _controllerLeftYAxis != 0 ) {
1584 setStates( MOUSE_MOTION );
1585
1586 const int32_t xSign = ( _controllerLeftXAxis < 0 ) ? -1 : 1;
1587 const int32_t ySign = ( _controllerLeftYAxis < 0 ) ? -1 : 1;
1588
1589 _emulatedPointerPos.x += pow( std::abs( _controllerLeftXAxis ), _controllerAxisSpeedup ) * xSign * deltaTime * _controllerPointerSpeed;
1590 _emulatedPointerPos.y += pow( std::abs( _controllerLeftYAxis ), _controllerAxisSpeedup ) * ySign * deltaTime * _controllerPointerSpeed;
1591
1592 const fheroes2::Display & display = fheroes2::Display::instance();
1593
1594 if ( _emulatedPointerPos.x < 0 )
1595 _emulatedPointerPos.x = 0;
1596 else if ( _emulatedPointerPos.x >= display.width() )
1597 _emulatedPointerPos.x = display.width() - 1;
1598
1599 if ( _emulatedPointerPos.y < 0 )
1600 _emulatedPointerPos.y = 0;
1601 else if ( _emulatedPointerPos.y >= display.height() )
1602 _emulatedPointerPos.y = display.height() - 1;
1603
1604 _mouseCursorPos.x = static_cast<int32_t>( _emulatedPointerPos.x );
1605 _mouseCursorPos.y = static_cast<int32_t>( _emulatedPointerPos.y );
1606
1607 if ( _globalMouseMotionEventHook ) {
1608 _mouseCursorRenderArea = _globalMouseMotionEventHook( _mouseCursorPos.x, _mouseCursorPos.y );
1609 }
1610 }
1611
1612 // map scroll with right stick
1613 if ( _controllerRightXAxis != 0 || _controllerRightYAxis != 0 ) {
1614 _controllerScrollActive = true;
1615 setStates( KEY_PRESSED );
1616
1617 if ( _controllerRightXAxis < 0 ) {
1618 _currentKeyboardValue = fheroes2::Key::KEY_LEFT;
1619 }
1620 else if ( _controllerRightXAxis > 0 ) {
1621 _currentKeyboardValue = fheroes2::Key::KEY_RIGHT;
1622 }
1623 else if ( _controllerRightYAxis < 0 ) {
1624 _currentKeyboardValue = fheroes2::Key::KEY_UP;
1625 }
1626 else if ( _controllerRightYAxis > 0 ) {
1627 _currentKeyboardValue = fheroes2::Key::KEY_DOWN;
1628 }
1629 }
1630 else if ( _controllerScrollActive ) {
1631 resetStates( KEY_PRESSED );
1632 _controllerScrollActive = false;
1633 }
1634 }
1635
1636 void LocalEvent::onRenderDeviceResetEvent()
1637 {
1638 // All textures has to be recreated. The only way to do it is to reset everything and render it back.
1639 fheroes2::Display & display = fheroes2::Display::instance();
1640 fheroes2::Image temp;
1641
1642 assert( display.singleLayer() );
1643
1644 temp._disableTransformLayer();
1645
1646 fheroes2::Copy( display, temp );
1647 display.release();
1648 fheroes2::Copy( temp, display );
1649 }
1650
1651 void LocalEvent::onKeyboardEvent( const fheroes2::Key key, const int32_t keyModifier, const KeyboardEventState keyState )
1652 {
1653 if ( keyState == KeyboardEventState::KEY_DOWN ) {
1654 setStates( KEY_PRESSED );
1655 setStates( KEY_HOLD );
1656
1657 if ( _globalKeyDownEventHook ) {
1658 _globalKeyDownEventHook( key, keyModifier );
1659 }
1660 }
1661 else if ( keyState == KeyboardEventState::KEY_UP ) {
1662 resetStates( KEY_PRESSED );
1663 resetStates( KEY_HOLD );
1664 }
1665
1666 _currentKeyboardValue = key;
1667 }
1668
1669 void LocalEvent::onMouseMotionEvent( fheroes2::Point position )
1670 {
1671 setStates( MOUSE_MOTION );
1672 _mouseCursorPos = position;
1673 _emulatedPointerPos.x = _mouseCursorPos.x;
1674 _emulatedPointerPos.y = _mouseCursorPos.y;
1675
1676 if ( _globalMouseMotionEventHook ) {
1677 _mouseCursorRenderArea = _globalMouseMotionEventHook( position.x, position.y );
1678 }
1679 }
1680
1681 void LocalEvent::onMouseButtonEvent( const bool isPressed, const MouseButtonType buttonType, fheroes2::Point position )
1682 {
1683 if ( isPressed ) {
1684 _mouseButtonLongPressDelay.reset();
1685
1686 setStates( MOUSE_PRESSED );
1687 }
1688 else {
1689 resetStates( MOUSE_PRESSED );
1690 resetStates( DRAG_ONGOING );
1691
1692 setStates( MOUSE_RELEASED );
1693 }
1694
1695 _currentMouseButton = buttonType;
1696
1697 _mouseCursorPos = position;
1698 _emulatedPointerPos.x = _mouseCursorPos.x;
1699 _emulatedPointerPos.y = _mouseCursorPos.y;
1700
1701 if ( _actionStates & MOUSE_PRESSED ) {
1702 switch ( buttonType ) {
1703 case MouseButtonType::MOUSE_BUTTON_LEFT:
1704 _mousePressLeftPos = _mouseCursorPos;
1705 break;
1706
1707 case MouseButtonType::MOUSE_BUTTON_MIDDLE:
1708 _mousePressMiddlePos = _mouseCursorPos;
1709 break;
1710
1711 case MouseButtonType::MOUSE_BUTTON_RIGHT:
1712 _mousePressRightPos = _mouseCursorPos;
1713 break;
1714
1715 default:
1716 assert( 0 );
1717 break;
1718 }
1719 }
1720 // Mouse button has been released
1721 else {
1722 switch ( buttonType ) {
1723 case MouseButtonType::MOUSE_BUTTON_LEFT:
1724 _mouseReleaseLeftPos = _mouseCursorPos;
1725 break;
1726
1727 case MouseButtonType::MOUSE_BUTTON_MIDDLE:
1728 _mouseReleaseMiddlePos = _mouseCursorPos;
1729 break;
1730
1731 case MouseButtonType::MOUSE_BUTTON_RIGHT:
1732 _mouseReleaseRightPos = _mouseCursorPos;
1733 break;
1734
1735 default:
1736 assert( 0 );
1737 break;
1738 }
1739 }
1740 }
1741
1742 bool LocalEvent::MouseClickLeft()
1743 {
1744 if ( !( _actionStates & MOUSE_RELEASED ) ) {
1745 return false;
1746 }
1747
1748 if ( _currentMouseButton != MouseButtonType::MOUSE_BUTTON_LEFT ) {
1749 return false;
1750 }
1751
1752 if ( _mouseButtonLongPressDelay.isTriggered() ) {
1753 return false;
1754 }
1755
1756 resetStates( MOUSE_RELEASED );
1757
1758 return true;
1759 }
1760
1761 bool LocalEvent::MouseClickLeft( const fheroes2::Rect & area )
1762 {
1763 if ( !( _actionStates & MOUSE_RELEASED ) ) {
1764 return false;
1765 }
1766
1767 if ( _currentMouseButton != MouseButtonType::MOUSE_BUTTON_LEFT ) {
1768 return false;
1769 }
1770
1771 if ( !( area & _mousePressLeftPos ) || !( area & _mouseReleaseLeftPos ) ) {
1772 return false;
1773 }
1774
1775 if ( _mouseButtonLongPressDelay.isTriggered() ) {
1776 return false;
1777 }
1778
1779 resetStates( MOUSE_RELEASED );
1780
1781 return true;
1782 }
1783
1784 bool LocalEvent::MouseClickMiddle()
1785 {
1786 if ( !( _actionStates & MOUSE_RELEASED ) ) {
1787 return false;
1788 }
1789
1790 if ( _currentMouseButton != MouseButtonType::MOUSE_BUTTON_MIDDLE ) {
1791 return false;
1792 }
1793
1794 if ( _mouseButtonLongPressDelay.isTriggered() ) {
1795 return false;
1796 }
1797
1798 resetStates( MOUSE_RELEASED );
1799
1800 return true;
1801 }
1802
1803 bool LocalEvent::MouseClickRight()
1804 {
1805 if ( !( _actionStates & MOUSE_RELEASED ) ) {
1806 return false;
1807 }
1808
1809 if ( _currentMouseButton != MouseButtonType::MOUSE_BUTTON_RIGHT ) {
1810 return false;
1811 }
1812
1813 if ( _mouseButtonLongPressDelay.isTriggered() ) {
1814 return false;
1815 }
1816
1817 resetStates( MOUSE_RELEASED );
1818
1819 return true;
1820 }
1821
1822 bool LocalEvent::MouseClickRight( const fheroes2::Rect & area )
1823 {
1824 if ( !( _actionStates & MOUSE_RELEASED ) ) {
1825 return false;
1826 }
1827
1828 if ( _currentMouseButton != MouseButtonType::MOUSE_BUTTON_RIGHT ) {
1829 return false;
1830 }
1831
1832 if ( !( area & _mousePressRightPos ) || !( area & _mouseReleaseRightPos ) ) {
1833 return false;
1834 }
1835
1836 if ( _mouseButtonLongPressDelay.isTriggered() ) {
1837 return false;
1838 }
1839
1840 resetStates( MOUSE_RELEASED );
1841
1842 return true;
1843 }
1844
1845 bool LocalEvent::MouseLongPressLeft( const fheroes2::Rect & rt )
1846 {
1847 if ( !( _actionStates & MOUSE_PRESSED ) ) {
1848 return false;
1849 }
1850
1851 if ( _currentMouseButton != MouseButtonType::MOUSE_BUTTON_LEFT ) {
1852 return false;
1853 }
1854
1855 if ( !( rt & _mousePressLeftPos ) ) {
1856 return false;
1857 }
1858
1859 if ( !_mouseButtonLongPressDelay.isPassed() ) {
1860 return false;
1861 }
1862
1863 if ( _mouseButtonLongPressDelay.isTriggered() ) {
1864 return false;
1865 }
1866
1867 _mouseButtonLongPressDelay.setTriggered();
1868
1869 return true;
1870 }
1871
1872 int32_t LocalEvent::getCurrentKeyModifiers()
1873 {
1874 return EventProcessing::EventEngine::getCurrentKeyModifiers();
1875 }
1876
1877 void LocalEvent::initEventEngine()
1878 {
1879 EventProcessing::EventEngine::initEvents();
1880
1881 EventProcessing::EventEngine::initTouchpad();
1882 }