Input.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Mutex.h"
  26. #include "../Core/ProcessUtils.h"
  27. #include "../Core/Profiler.h"
  28. #include "../Core/StringUtils.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/GraphicsEvents.h"
  31. #include "../Input/Input.h"
  32. #include "../IO/FileSystem.h"
  33. #include "../IO/Log.h"
  34. #include "../IO/RWOpsWrapper.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../UI/Text.h"
  37. #include "../UI/UI.h"
  38. #include <SDL/SDL.h>
  39. #ifdef __EMSCRIPTEN__
  40. #include <emscripten/html5.h>
  41. #endif
  42. #include "../DebugNew.h"
  43. extern "C" int SDL_AddTouch(SDL_TouchID touchID, const char* name);
  44. // Use a "click inside window to focus" mechanism on desktop platforms when the mouse cursor is hidden
  45. // TODO: For now, in this particular case only, treat all the ARM on Linux as "desktop" (e.g. RPI, odroid, etc), revisit this again when we support "mobile" ARM on Linux
  46. #if defined(_WIN32) || (defined(__APPLE__) && !defined(IOS)) || (defined(__linux__) && !defined(__ANDROID__))
  47. #define REQUIRE_CLICK_TO_FOCUS
  48. #endif
  49. namespace Urho3D
  50. {
  51. const int SCREEN_JOYSTICK_START_ID = 0x40000000;
  52. const StringHash VAR_BUTTON_KEY_BINDING("VAR_BUTTON_KEY_BINDING");
  53. const StringHash VAR_BUTTON_MOUSE_BUTTON_BINDING("VAR_BUTTON_MOUSE_BUTTON_BINDING");
  54. const StringHash VAR_LAST_KEYSYM("VAR_LAST_KEYSYM");
  55. const StringHash VAR_SCREEN_JOYSTICK_ID("VAR_SCREEN_JOYSTICK_ID");
  56. const unsigned TOUCHID_MAX = 32;
  57. /// Convert SDL keycode if necessary.
  58. int ConvertSDLKeyCode(int keySym, int scanCode)
  59. {
  60. if (scanCode == SCANCODE_AC_BACK)
  61. return KEY_ESCAPE;
  62. else
  63. return SDL_tolower(keySym);
  64. }
  65. UIElement* TouchState::GetTouchedElement()
  66. {
  67. return touchedElement_.Get();
  68. }
  69. #ifdef __EMSCRIPTEN__
  70. #define EM_TRUE 1
  71. #define EM_FALSE 0
  72. /// Glue between Urho Input and Emscripten HTML5
  73. /** HTML5 (Emscripten) is limited in the way it handles input. The EmscriptenInput class attempts to provide the glue between Urho3D Input behavior and HTML5, where SDL currently fails to do so.
  74. *
  75. * Mouse Input:
  76. * - The OS mouse cursor position can't be set.
  77. * - The mouse can be trapped within play area via 'PointerLock API', which requires a request and interaction between the user and browser.
  78. * - To request mouse lock, call SetMouseMode(MM_RELATIVE). The E_MOUSEMODECHANGED event will be sent if/when the user confirms the request.
  79. * NOTE: The request must be initiated by the user (eg: on mouse button down/up, key down/up).
  80. * - The user can press 'escape' key and browser will force user out of pointer lock. Urho will send the E_MOUSEMODECHANGED event.
  81. * - SetMouseMode(MM_ABSOLUTE) will leave pointer lock.
  82. * - MM_WRAP is unsupported.
  83. */
  84. /// % Emscripten Input glue. Intended to be used by the Input subsystem only.
  85. class EmscriptenInput
  86. {
  87. friend class Input;
  88. public:
  89. /// Constructor, expecting pointer to constructing Input instance.
  90. EmscriptenInput(Input* inputInst);
  91. /// Static callback method for Pointer Lock API. Handles change in Pointer Lock state and sends events for mouse mode change.
  92. static EM_BOOL HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent* keyEvent, void* userData);
  93. /// Static callback method for tracking focus change events.
  94. static EM_BOOL HandleFocusChange(int eventType, const EmscriptenFocusEvent* keyEvent, void* userData);
  95. /// Static callback method for suppressing mouse jump.
  96. static EM_BOOL HandleMouseJump(int eventType, const EmscriptenMouseEvent * mouseEvent, void* userData);
  97. /// Static callback method to handle SDL events.
  98. static int HandleSDLEvents(void* userData, SDL_Event* event);
  99. /// Send request to user to gain pointer lock. This requires a user-browser interaction on the first call.
  100. void RequestPointerLock(MouseMode mode, bool suppressEvent = false);
  101. /// Send request to exit pointer lock. This has the benefit of not requiring the user-browser interaction on the next pointer lock request.
  102. void ExitPointerLock(bool suppressEvent = false);
  103. /// Returns whether the page is visible.
  104. bool IsVisible();
  105. private:
  106. /// Instance of Input subsystem that constructed this instance.
  107. Input* inputInst_;
  108. /// The mouse mode being requested for pointer-lock.
  109. static MouseMode requestedMouseMode_;
  110. /// Flag indicating whether to suppress the next mouse mode change event.
  111. static bool suppressMouseModeEvent_;
  112. /// The mouse mode of the previous request for pointer-lock.
  113. static MouseMode invalidatedRequestedMouseMode_;
  114. /// Flag indicating the previous request to suppress the next mouse mode change event.
  115. static bool invalidatedSuppressMouseModeEvent_;
  116. };
  117. bool EmscriptenInput::suppressMouseModeEvent_ = false;
  118. MouseMode EmscriptenInput::requestedMouseMode_ = MM_INVALID;
  119. bool EmscriptenInput::invalidatedSuppressMouseModeEvent_ = false;
  120. MouseMode EmscriptenInput::invalidatedRequestedMouseMode_ = MM_INVALID;
  121. EmscriptenInput::EmscriptenInput(Input* inputInst) :
  122. inputInst_(inputInst)
  123. {
  124. void* vInputInst = (void*)inputInst;
  125. // Handle pointer lock
  126. emscripten_set_pointerlockchange_callback(NULL, vInputInst, false, EmscriptenInput::HandlePointerLockChange);
  127. // Handle mouse events to prevent mouse jumps
  128. emscripten_set_mousedown_callback(NULL, vInputInst, true, EmscriptenInput::HandleMouseJump);
  129. emscripten_set_mousemove_callback(NULL, vInputInst, true, EmscriptenInput::HandleMouseJump);
  130. // Handle focus changes
  131. emscripten_set_focusout_callback(NULL, vInputInst, false, EmscriptenInput::HandleFocusChange);
  132. emscripten_set_focus_callback(NULL, vInputInst, false, EmscriptenInput::HandleFocusChange);
  133. // Handle SDL events
  134. SDL_AddEventWatch(EmscriptenInput::HandleSDLEvents, vInputInst);
  135. }
  136. void EmscriptenInput::RequestPointerLock(MouseMode mode, bool suppressEvent)
  137. {
  138. requestedMouseMode_ = mode;
  139. suppressMouseModeEvent_ = suppressEvent;
  140. emscripten_request_pointerlock(NULL, true);
  141. }
  142. void EmscriptenInput::ExitPointerLock(bool suppressEvent)
  143. {
  144. if (requestedMouseMode_ != MM_INVALID)
  145. {
  146. invalidatedRequestedMouseMode_ = requestedMouseMode_;
  147. invalidatedSuppressMouseModeEvent_ = suppressMouseModeEvent_;
  148. }
  149. requestedMouseMode_ = MM_INVALID;
  150. suppressMouseModeEvent_ = suppressEvent;
  151. if (inputInst_->IsMouseLocked())
  152. {
  153. inputInst_->emscriptenExitingPointerLock_ = true;
  154. emscripten_exit_pointerlock();
  155. }
  156. }
  157. bool EmscriptenInput::IsVisible()
  158. {
  159. EmscriptenVisibilityChangeEvent visibilityStatus;
  160. if (emscripten_get_visibility_status(&visibilityStatus) >= EMSCRIPTEN_RESULT_SUCCESS)
  161. return visibilityStatus.hidden >= EM_TRUE ? false : true;
  162. // Assume visible
  163. URHO3D_LOGWARNING("Could not determine visibility status.");
  164. return true;
  165. }
  166. EM_BOOL EmscriptenInput::HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent* keyEvent, void* userData)
  167. {
  168. Input* const inputInst = (Input*)userData;
  169. bool invalid = false;
  170. const bool suppress = suppressMouseModeEvent_;
  171. if (requestedMouseMode_ == MM_INVALID && invalidatedRequestedMouseMode_ != MM_INVALID)
  172. {
  173. invalid = true;
  174. requestedMouseMode_ = invalidatedRequestedMouseMode_;
  175. suppressMouseModeEvent_ = invalidatedSuppressMouseModeEvent_;
  176. invalidatedRequestedMouseMode_ = MM_INVALID;
  177. invalidatedSuppressMouseModeEvent_ = false;
  178. }
  179. if (keyEvent->isActive >= EM_TRUE)
  180. {
  181. // Pointer Lock is now active
  182. inputInst->emscriptenPointerLock_ = true;
  183. inputInst->emscriptenEnteredPointerLock_ = true;
  184. inputInst->SetMouseModeEmscriptenFinal(requestedMouseMode_, suppressMouseModeEvent_);
  185. }
  186. else
  187. {
  188. // Pointer Lock is now inactive
  189. inputInst->emscriptenPointerLock_ = false;
  190. if (inputInst->mouseMode_ == MM_RELATIVE)
  191. inputInst->SetMouseModeEmscriptenFinal(MM_FREE, suppressMouseModeEvent_);
  192. else if (inputInst->mouseMode_ == MM_ABSOLUTE)
  193. inputInst->SetMouseModeEmscriptenFinal(MM_ABSOLUTE, suppressMouseModeEvent_);
  194. inputInst->emscriptenExitingPointerLock_ = false;
  195. }
  196. if (invalid)
  197. {
  198. if (keyEvent->isActive >= EM_TRUE)
  199. {
  200. // ExitPointerLock was called before the pointer-lock request was accepted.
  201. // Exit from pointer-lock to avoid unexpected behavior.
  202. invalidatedRequestedMouseMode_ = MM_INVALID;
  203. inputInst->emscriptenInput_->ExitPointerLock(suppress);
  204. return EM_TRUE;
  205. }
  206. }
  207. requestedMouseMode_ = MM_INVALID;
  208. suppressMouseModeEvent_ = false;
  209. invalidatedRequestedMouseMode_ = MM_INVALID;
  210. invalidatedSuppressMouseModeEvent_ = false;
  211. return EM_TRUE;
  212. }
  213. EM_BOOL EmscriptenInput::HandleFocusChange(int eventType, const EmscriptenFocusEvent* keyEvent, void* userData)
  214. {
  215. Input* const inputInst = (Input*)userData;
  216. inputInst->SuppressNextMouseMove();
  217. if (eventType == EMSCRIPTEN_EVENT_FOCUSOUT)
  218. inputInst->LoseFocus();
  219. else if (eventType == EMSCRIPTEN_EVENT_FOCUS)
  220. inputInst->GainFocus();
  221. return EM_TRUE;
  222. }
  223. EM_BOOL EmscriptenInput::HandleMouseJump(int eventType, const EmscriptenMouseEvent * mouseEvent, void* userData)
  224. {
  225. // Suppress mouse jump on pointer-lock change
  226. Input* const inputInst = (Input*)userData;
  227. bool suppress = false;
  228. if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN && inputInst->emscriptenEnteredPointerLock_)
  229. {
  230. suppress = true;
  231. inputInst->emscriptenEnteredPointerLock_ = false;
  232. }
  233. else if (eventType == EMSCRIPTEN_EVENT_MOUSEMOVE && inputInst->emscriptenExitingPointerLock_)
  234. {
  235. suppress = true;
  236. }
  237. if (suppress)
  238. inputInst->SuppressNextMouseMove();
  239. return EM_FALSE;
  240. }
  241. int EmscriptenInput::HandleSDLEvents(void* userData, SDL_Event* event)
  242. {
  243. Input* const inputInst = (Input*)userData;
  244. inputInst->HandleSDLEvent(event);
  245. return 0;
  246. }
  247. #endif
  248. void JoystickState::Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats)
  249. {
  250. buttons_.Resize(numButtons);
  251. buttonPress_.Resize(numButtons);
  252. axes_.Resize(numAxes);
  253. hats_.Resize(numHats);
  254. Reset();
  255. }
  256. void JoystickState::Reset()
  257. {
  258. for (unsigned i = 0; i < buttons_.Size(); ++i)
  259. {
  260. buttons_[i] = false;
  261. buttonPress_[i] = false;
  262. }
  263. for (unsigned i = 0; i < axes_.Size(); ++i)
  264. axes_[i] = 0.0f;
  265. for (unsigned i = 0; i < hats_.Size(); ++i)
  266. hats_[i] = HAT_CENTER;
  267. }
  268. Input::Input(Context* context) :
  269. Object(context),
  270. mouseButtonDown_(0),
  271. mouseButtonPress_(0),
  272. lastVisibleMousePosition_(MOUSE_POSITION_OFFSCREEN),
  273. mouseMoveWheel_(0),
  274. windowID_(0),
  275. toggleFullscreen_(true),
  276. mouseVisible_(false),
  277. lastMouseVisible_(false),
  278. mouseGrabbed_(false),
  279. lastMouseGrabbed_(false),
  280. mouseMode_(MM_ABSOLUTE),
  281. lastMouseMode_(MM_ABSOLUTE),
  282. #ifndef __EMSCRIPTEN__
  283. sdlMouseRelative_(false),
  284. #else
  285. emscriptenPointerLock_(false),
  286. emscriptenEnteredPointerLock_(false),
  287. emscriptenExitingPointerLock_(false),
  288. #endif
  289. touchEmulation_(false),
  290. inputFocus_(false),
  291. minimized_(false),
  292. focusedThisFrame_(false),
  293. suppressNextMouseMove_(false),
  294. inResize_(false),
  295. screenModeChanged_(false),
  296. initialized_(false)
  297. {
  298. for (int i = 0; i < TOUCHID_MAX; i++)
  299. availableTouchIDs_.Push(i);
  300. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(Input, HandleScreenMode));
  301. #if defined(__ANDROID__)
  302. SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1");
  303. #elif defined(__EMSCRIPTEN__)
  304. emscriptenInput_ = new EmscriptenInput(this);
  305. #endif
  306. // Try to initialize right now, but skip if screen mode is not yet set
  307. Initialize();
  308. }
  309. Input::~Input()
  310. {
  311. #ifdef __EMSCRIPTEN__
  312. delete emscriptenInput_;
  313. emscriptenInput_ = 0;
  314. #endif
  315. }
  316. void Input::Update()
  317. {
  318. assert(initialized_);
  319. URHO3D_PROFILE(UpdateInput);
  320. #ifndef __EMSCRIPTEN__
  321. bool mouseMoved = false;
  322. if (mouseMove_ != IntVector2::ZERO)
  323. mouseMoved = true;
  324. ResetInputAccumulation();
  325. SDL_Event evt;
  326. while (SDL_PollEvent(&evt))
  327. HandleSDLEvent(&evt);
  328. if (suppressNextMouseMove_ && (mouseMove_ != IntVector2::ZERO || mouseMoved))
  329. UnsuppressMouseMove();
  330. #endif
  331. // Check for focus change this frame
  332. SDL_Window* window = graphics_->GetWindow();
  333. unsigned flags = window ? SDL_GetWindowFlags(window) & (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS) : 0;
  334. #ifndef __EMSCRIPTEN__
  335. if (window)
  336. {
  337. #ifdef REQUIRE_CLICK_TO_FOCUS
  338. // When using the "click to focus" mechanism, only focus automatically in fullscreen or non-hidden mouse mode
  339. if (!inputFocus_ && ((mouseVisible_ || mouseMode_ == MM_FREE) || graphics_->GetFullscreen() || screenModeChanged_) && (flags & SDL_WINDOW_INPUT_FOCUS))
  340. #else
  341. if (!inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS))
  342. #endif
  343. {
  344. screenModeChanged_ = false;
  345. focusedThisFrame_ = true;
  346. }
  347. if (focusedThisFrame_)
  348. GainFocus();
  349. // Check for losing focus. The window flags are not reliable when using an external window, so prevent losing focus in that case
  350. if (inputFocus_ && !graphics_->GetExternalWindow() && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  351. LoseFocus();
  352. }
  353. else
  354. return;
  355. // Handle mouse mode MM_WRAP
  356. if (mouseVisible_ && mouseMode_ == MM_WRAP)
  357. {
  358. IntVector2 windowPos = graphics_->GetWindowPosition();
  359. IntVector2 mpos;
  360. SDL_GetGlobalMouseState(&mpos.x_, &mpos.y_);
  361. mpos -= windowPos;
  362. const int buffer = 5;
  363. const int width = graphics_->GetWidth() - buffer * 2;
  364. const int height = graphics_->GetHeight() - buffer * 2;
  365. bool warp = false;
  366. if (mpos.x_ < buffer)
  367. {
  368. warp = true;
  369. mpos.x_ += width;
  370. }
  371. if (mpos.x_ > buffer + width)
  372. {
  373. warp = true;
  374. mpos.x_ -= width;
  375. }
  376. if (mpos.y_ < buffer)
  377. {
  378. warp = true;
  379. mpos.y_ += height;
  380. }
  381. if (mpos.y_ > buffer + height)
  382. {
  383. warp = true;
  384. mpos.y_ -= height;
  385. }
  386. if (warp)
  387. {
  388. SetMousePosition(mpos);
  389. SuppressNextMouseMove();
  390. }
  391. }
  392. #else
  393. if (!window)
  394. return;
  395. #endif
  396. #ifndef __EMSCRIPTEN__
  397. if (!touchEmulation_ && (graphics_->GetExternalWindow() || ((!sdlMouseRelative_ && !mouseVisible_ && mouseMode_ != MM_FREE) && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  398. #else
  399. if (!touchEmulation_ && !emscriptenPointerLock_ && (graphics_->GetExternalWindow() || (!mouseVisible_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  400. #endif
  401. {
  402. const IntVector2 mousePosition = GetMousePosition();
  403. mouseMove_ = mousePosition - lastMousePosition_;
  404. #ifndef __EMSCRIPTEN__
  405. if (graphics_->GetExternalWindow())
  406. lastMousePosition_ = mousePosition;
  407. else
  408. {
  409. // Recenter the mouse cursor manually after move
  410. CenterMousePosition();
  411. }
  412. #else
  413. if (mouseMode_ == MM_ABSOLUTE || mouseMode_ == MM_FREE)
  414. lastMousePosition_ = mousePosition;
  415. if (emscriptenExitingPointerLock_)
  416. SuppressNextMouseMove();
  417. #endif
  418. // Send mouse move event if necessary
  419. if (mouseMove_ != IntVector2::ZERO)
  420. {
  421. if (!suppressNextMouseMove_)
  422. {
  423. using namespace MouseMove;
  424. VariantMap& eventData = GetEventDataMap();
  425. eventData[P_X] = mousePosition.x_;
  426. eventData[P_Y] = mousePosition.y_;
  427. eventData[P_DX] = mouseMove_.x_;
  428. eventData[P_DY] = mouseMove_.y_;
  429. eventData[P_BUTTONS] = mouseButtonDown_;
  430. eventData[P_QUALIFIERS] = GetQualifiers();
  431. SendEvent(E_MOUSEMOVE, eventData);
  432. }
  433. }
  434. }
  435. #ifndef __EMSCRIPTEN__
  436. else if (!touchEmulation_ && !mouseVisible_ && sdlMouseRelative_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))
  437. {
  438. // Keep the cursor trapped in window.
  439. CenterMousePosition();
  440. }
  441. #endif
  442. }
  443. void Input::SetMouseVisible(bool enable, bool suppressEvent)
  444. {
  445. const bool startMouseVisible = mouseVisible_;
  446. // In touch emulation mode only enabled mouse is allowed
  447. if (touchEmulation_)
  448. enable = true;
  449. // In mouse mode relative, the mouse should be invisible
  450. if (mouseMode_ == MM_RELATIVE)
  451. {
  452. if (!suppressEvent)
  453. lastMouseVisible_ = enable;
  454. enable = false;
  455. }
  456. // SDL Raspberry Pi "video driver" does not have proper OS mouse support yet, so no-op for now
  457. #ifndef RPI
  458. if (enable != mouseVisible_)
  459. {
  460. if (initialized_)
  461. {
  462. // External windows can only support visible mouse cursor
  463. if (graphics_->GetExternalWindow())
  464. {
  465. mouseVisible_ = true;
  466. if (!suppressEvent)
  467. lastMouseVisible_ = true;
  468. return;
  469. }
  470. if (!enable && inputFocus_)
  471. {
  472. #ifndef __EMSCRIPTEN__
  473. if (mouseVisible_)
  474. lastVisibleMousePosition_ = GetMousePosition();
  475. if (mouseMode_ == MM_ABSOLUTE)
  476. SetMouseModeAbsolute(SDL_TRUE);
  477. #else
  478. if (mouseMode_ == MM_ABSOLUTE && !emscriptenPointerLock_)
  479. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  480. #endif
  481. SDL_ShowCursor(SDL_FALSE);
  482. mouseVisible_ = false;
  483. }
  484. else if (mouseMode_ != MM_RELATIVE)
  485. {
  486. SetMouseGrabbed(false, suppressEvent);
  487. SDL_ShowCursor(SDL_TRUE);
  488. mouseVisible_ = true;
  489. #ifndef __EMSCRIPTEN__
  490. if (mouseMode_ == MM_ABSOLUTE)
  491. SetMouseModeAbsolute(SDL_FALSE);
  492. // Update cursor position
  493. UI* ui = GetSubsystem<UI>();
  494. Cursor* cursor = ui->GetCursor();
  495. // If the UI Cursor was visible, use that position instead of last visible OS cursor position
  496. if (cursor && cursor->IsVisible())
  497. {
  498. IntVector2 pos = cursor->GetScreenPosition();
  499. if (pos != MOUSE_POSITION_OFFSCREEN)
  500. {
  501. SetMousePosition(pos);
  502. lastMousePosition_ = pos;
  503. }
  504. }
  505. else
  506. {
  507. if (lastVisibleMousePosition_ != MOUSE_POSITION_OFFSCREEN)
  508. {
  509. SetMousePosition(lastVisibleMousePosition_);
  510. lastMousePosition_ = lastVisibleMousePosition_;
  511. }
  512. }
  513. #else
  514. if (mouseMode_ == MM_ABSOLUTE && emscriptenPointerLock_)
  515. emscriptenInput_->ExitPointerLock(suppressEvent);
  516. #endif
  517. }
  518. }
  519. if (mouseVisible_ != startMouseVisible)
  520. {
  521. SuppressNextMouseMove();
  522. if (!suppressEvent)
  523. {
  524. lastMouseVisible_ = mouseVisible_;
  525. using namespace MouseVisibleChanged;
  526. VariantMap& eventData = GetEventDataMap();
  527. eventData[P_VISIBLE] = mouseVisible_;
  528. SendEvent(E_MOUSEVISIBLECHANGED, eventData);
  529. }
  530. }
  531. }
  532. #endif
  533. }
  534. void Input::ResetMouseVisible()
  535. {
  536. #ifndef __EMSCRIPTEN__
  537. SetMouseVisible(lastMouseVisible_, false);
  538. #else
  539. SetMouseVisibleEmscripten(lastMouseVisible_, false);
  540. #endif
  541. }
  542. #ifdef __EMSCRIPTEN__
  543. void Input::SetMouseVisibleEmscripten(bool enable, bool suppressEvent)
  544. {
  545. if (enable != mouseVisible_)
  546. {
  547. if (mouseMode_ == MM_ABSOLUTE)
  548. {
  549. if (enable)
  550. {
  551. mouseVisible_ = true;
  552. SDL_ShowCursor(SDL_TRUE);
  553. emscriptenInput_->ExitPointerLock(suppressEvent);
  554. }
  555. else
  556. {
  557. if (emscriptenPointerLock_)
  558. {
  559. mouseVisible_ = false;
  560. SDL_ShowCursor(SDL_FALSE);
  561. }
  562. else
  563. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  564. }
  565. }
  566. else
  567. {
  568. mouseVisible_ = enable;
  569. SDL_ShowCursor(enable ? SDL_TRUE : SDL_FALSE);
  570. }
  571. }
  572. if (!suppressEvent)
  573. lastMouseVisible_ = mouseVisible_;
  574. }
  575. void Input::SetMouseModeEmscriptenFinal(MouseMode mode, bool suppressEvent)
  576. {
  577. if (!suppressEvent)
  578. lastMouseMode_ = mode;
  579. mouseMode_ = mode;
  580. if (mode == MM_ABSOLUTE)
  581. {
  582. if (emscriptenPointerLock_)
  583. {
  584. SetMouseVisibleEmscripten(false, suppressEvent);
  585. }
  586. else
  587. {
  588. SetMouseVisibleEmscripten(true, suppressEvent);
  589. }
  590. UI* const ui = GetSubsystem<UI>();
  591. Cursor* const cursor = ui->GetCursor();
  592. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  593. }
  594. else if (mode == MM_RELATIVE && emscriptenPointerLock_)
  595. {
  596. SetMouseGrabbed(true, suppressEvent);
  597. SetMouseVisibleEmscripten(false, suppressEvent);
  598. }
  599. else
  600. {
  601. SetMouseGrabbed(false, suppressEvent);
  602. }
  603. SuppressNextMouseMove();
  604. if (!suppressEvent)
  605. {
  606. VariantMap& eventData = GetEventDataMap();
  607. eventData[MouseModeChanged::P_MODE] = mode;
  608. eventData[MouseModeChanged::P_MOUSELOCKED] = IsMouseLocked();
  609. SendEvent(E_MOUSEMODECHANGED, eventData);
  610. }
  611. }
  612. void Input::SetMouseModeEmscripten(MouseMode mode, bool suppressEvent)
  613. {
  614. if (mode != mouseMode_)
  615. SuppressNextMouseMove();
  616. const MouseMode previousMode = mouseMode_;
  617. mouseMode_ = mode;
  618. UI* const ui = GetSubsystem<UI>();
  619. Cursor* const cursor = ui->GetCursor();
  620. // Handle changing from previous mode
  621. if (previousMode == MM_RELATIVE)
  622. ResetMouseVisible();
  623. // Handle changing to new mode
  624. if (mode == MM_FREE)
  625. {
  626. // Attempt to cancel pending pointer-lock requests
  627. emscriptenInput_->ExitPointerLock(suppressEvent);
  628. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  629. }
  630. else if (mode == MM_ABSOLUTE)
  631. {
  632. if (!mouseVisible_)
  633. {
  634. if (emscriptenPointerLock_)
  635. {
  636. SetMouseVisibleEmscripten(false, suppressEvent);
  637. }
  638. else
  639. {
  640. if (!cursor)
  641. SetMouseVisible(true, suppressEvent);
  642. // Deferred mouse mode change to pointer-lock callback
  643. mouseMode_ = previousMode;
  644. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  645. }
  646. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  647. }
  648. }
  649. else if (mode == MM_RELATIVE)
  650. {
  651. if (emscriptenPointerLock_)
  652. {
  653. SetMouseVisibleEmscripten(false, true);
  654. SetMouseGrabbed(!(cursor && cursor->IsVisible()), suppressEvent);
  655. }
  656. else
  657. {
  658. // Defer mouse mode change to pointer-lock callback
  659. SetMouseGrabbed(false, true);
  660. mouseMode_ = previousMode;
  661. emscriptenInput_->RequestPointerLock(MM_RELATIVE, suppressEvent);
  662. }
  663. }
  664. }
  665. #endif
  666. void Input::SetMouseGrabbed(bool grab, bool suppressEvent)
  667. {
  668. // To not interfere with touch UI operation, never report the mouse as grabbed on Android / iOS
  669. #if !defined(__ANDROID__) && !defined(IOS)
  670. mouseGrabbed_ = grab;
  671. if (!suppressEvent)
  672. lastMouseGrabbed_ = grab;
  673. #endif
  674. }
  675. void Input::ResetMouseGrabbed()
  676. {
  677. SetMouseGrabbed(lastMouseGrabbed_, true);
  678. }
  679. #ifndef __EMSCRIPTEN__
  680. void Input::SetMouseModeAbsolute(SDL_bool enable)
  681. {
  682. SDL_Window* const window = graphics_->GetWindow();
  683. SDL_SetWindowGrab(window, enable);
  684. }
  685. void Input::SetMouseModeRelative(SDL_bool enable)
  686. {
  687. SDL_Window* const window = graphics_->GetWindow();
  688. int result = SDL_SetRelativeMouseMode(enable);
  689. sdlMouseRelative_ = enable && (result == 0);
  690. if (result == -1)
  691. SDL_SetWindowGrab(window, enable);
  692. }
  693. #endif
  694. void Input::SetMouseMode(MouseMode mode, bool suppressEvent)
  695. {
  696. const MouseMode previousMode = mouseMode_;
  697. #ifdef __EMSCRIPTEN__
  698. SetMouseModeEmscripten(mode, suppressEvent);
  699. #else
  700. if (mode != mouseMode_)
  701. {
  702. SuppressNextMouseMove();
  703. mouseMode_ = mode;
  704. SDL_Window* const window = graphics_->GetWindow();
  705. UI* const ui = GetSubsystem<UI>();
  706. Cursor* const cursor = ui->GetCursor();
  707. // Handle changing from previous mode
  708. if (previousMode == MM_ABSOLUTE)
  709. {
  710. if (!mouseVisible_)
  711. SetMouseModeAbsolute(SDL_FALSE);
  712. }
  713. if (previousMode == MM_RELATIVE)
  714. {
  715. SetMouseModeRelative(SDL_FALSE);
  716. ResetMouseVisible();
  717. }
  718. else if (previousMode == MM_WRAP)
  719. SDL_SetWindowGrab(window, SDL_FALSE);
  720. // Handle changing to new mode
  721. if (mode == MM_ABSOLUTE)
  722. {
  723. if (!mouseVisible_)
  724. SetMouseModeAbsolute(SDL_TRUE);
  725. }
  726. else if (mode == MM_RELATIVE)
  727. {
  728. SetMouseVisible(false, true);
  729. SetMouseModeRelative(SDL_TRUE);
  730. }
  731. else if (mode == MM_WRAP)
  732. {
  733. SetMouseGrabbed(true, suppressEvent);
  734. SDL_SetWindowGrab(window, SDL_TRUE);
  735. }
  736. if (mode != MM_WRAP)
  737. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  738. }
  739. #endif
  740. if (!suppressEvent)
  741. {
  742. lastMouseMode_ = mode;
  743. if (mouseMode_ != previousMode)
  744. {
  745. VariantMap& eventData = GetEventDataMap();
  746. eventData[MouseModeChanged::P_MODE] = mode;
  747. eventData[MouseModeChanged::P_MOUSELOCKED] = IsMouseLocked();
  748. SendEvent(E_MOUSEMODECHANGED, eventData);
  749. }
  750. }
  751. }
  752. void Input::ResetMouseMode()
  753. {
  754. SetMouseMode(lastMouseMode_, false);
  755. }
  756. void Input::SetToggleFullscreen(bool enable)
  757. {
  758. toggleFullscreen_ = enable;
  759. }
  760. static void PopulateKeyBindingMap(HashMap<String, int>& keyBindingMap)
  761. {
  762. if (keyBindingMap.Empty())
  763. {
  764. keyBindingMap.Insert(MakePair<String, int>("SPACE", KEY_SPACE));
  765. keyBindingMap.Insert(MakePair<String, int>("LCTRL", KEY_LCTRL));
  766. keyBindingMap.Insert(MakePair<String, int>("RCTRL", KEY_RCTRL));
  767. keyBindingMap.Insert(MakePair<String, int>("LSHIFT", KEY_LSHIFT));
  768. keyBindingMap.Insert(MakePair<String, int>("RSHIFT", KEY_RSHIFT));
  769. keyBindingMap.Insert(MakePair<String, int>("LALT", KEY_LALT));
  770. keyBindingMap.Insert(MakePair<String, int>("RALT", KEY_RALT));
  771. keyBindingMap.Insert(MakePair<String, int>("LGUI", KEY_LGUI));
  772. keyBindingMap.Insert(MakePair<String, int>("RGUI", KEY_RGUI));
  773. keyBindingMap.Insert(MakePair<String, int>("TAB", KEY_TAB));
  774. keyBindingMap.Insert(MakePair<String, int>("RETURN", KEY_RETURN));
  775. keyBindingMap.Insert(MakePair<String, int>("RETURN2", KEY_RETURN2));
  776. keyBindingMap.Insert(MakePair<String, int>("ENTER", KEY_KP_ENTER));
  777. keyBindingMap.Insert(MakePair<String, int>("SELECT", KEY_SELECT));
  778. keyBindingMap.Insert(MakePair<String, int>("LEFT", KEY_LEFT));
  779. keyBindingMap.Insert(MakePair<String, int>("RIGHT", KEY_RIGHT));
  780. keyBindingMap.Insert(MakePair<String, int>("UP", KEY_UP));
  781. keyBindingMap.Insert(MakePair<String, int>("DOWN", KEY_DOWN));
  782. keyBindingMap.Insert(MakePair<String, int>("PAGEUP", KEY_PAGEUP));
  783. keyBindingMap.Insert(MakePair<String, int>("PAGEDOWN", KEY_PAGEDOWN));
  784. keyBindingMap.Insert(MakePair<String, int>("F1", KEY_F1));
  785. keyBindingMap.Insert(MakePair<String, int>("F2", KEY_F2));
  786. keyBindingMap.Insert(MakePair<String, int>("F3", KEY_F3));
  787. keyBindingMap.Insert(MakePair<String, int>("F4", KEY_F4));
  788. keyBindingMap.Insert(MakePair<String, int>("F5", KEY_F5));
  789. keyBindingMap.Insert(MakePair<String, int>("F6", KEY_F6));
  790. keyBindingMap.Insert(MakePair<String, int>("F7", KEY_F7));
  791. keyBindingMap.Insert(MakePair<String, int>("F8", KEY_F8));
  792. keyBindingMap.Insert(MakePair<String, int>("F9", KEY_F9));
  793. keyBindingMap.Insert(MakePair<String, int>("F10", KEY_F10));
  794. keyBindingMap.Insert(MakePair<String, int>("F11", KEY_F11));
  795. keyBindingMap.Insert(MakePair<String, int>("F12", KEY_F12));
  796. }
  797. }
  798. static void PopulateMouseButtonBindingMap(HashMap<String, int>& mouseButtonBindingMap)
  799. {
  800. if (mouseButtonBindingMap.Empty())
  801. {
  802. mouseButtonBindingMap.Insert(MakePair<String, int>("LEFT", SDL_BUTTON_LEFT));
  803. mouseButtonBindingMap.Insert(MakePair<String, int>("MIDDLE", SDL_BUTTON_MIDDLE));
  804. mouseButtonBindingMap.Insert(MakePair<String, int>("RIGHT", SDL_BUTTON_RIGHT));
  805. mouseButtonBindingMap.Insert(MakePair<String, int>("X1", SDL_BUTTON_X1));
  806. mouseButtonBindingMap.Insert(MakePair<String, int>("X2", SDL_BUTTON_X2));
  807. }
  808. }
  809. SDL_JoystickID Input::AddScreenJoystick(XMLFile* layoutFile, XMLFile* styleFile)
  810. {
  811. static HashMap<String, int> keyBindingMap;
  812. static HashMap<String, int> mouseButtonBindingMap;
  813. if (!graphics_)
  814. {
  815. URHO3D_LOGWARNING("Cannot add screen joystick in headless mode");
  816. return -1;
  817. }
  818. // If layout file is not given, use the default screen joystick layout
  819. if (!layoutFile)
  820. {
  821. ResourceCache* cache = GetSubsystem<ResourceCache>();
  822. layoutFile = cache->GetResource<XMLFile>("UI/ScreenJoystick.xml");
  823. if (!layoutFile) // Error is already logged
  824. return -1;
  825. }
  826. UI* ui = GetSubsystem<UI>();
  827. SharedPtr<UIElement> screenJoystick = ui->LoadLayout(layoutFile, styleFile);
  828. if (!screenJoystick) // Error is already logged
  829. return -1;
  830. screenJoystick->SetSize(ui->GetRoot()->GetSize());
  831. ui->GetRoot()->AddChild(screenJoystick);
  832. // Get an unused ID for the screen joystick
  833. /// \todo After a real joystick has been plugged in 1073741824 times, the ranges will overlap
  834. SDL_JoystickID joystickID = SCREEN_JOYSTICK_START_ID;
  835. while (joysticks_.Contains(joystickID))
  836. ++joystickID;
  837. JoystickState& state = joysticks_[joystickID];
  838. state.joystickID_ = joystickID;
  839. state.name_ = screenJoystick->GetName();
  840. state.screenJoystick_ = screenJoystick;
  841. unsigned numButtons = 0;
  842. unsigned numAxes = 0;
  843. unsigned numHats = 0;
  844. const Vector<SharedPtr<UIElement> >& children = state.screenJoystick_->GetChildren();
  845. for (Vector<SharedPtr<UIElement> >::ConstIterator iter = children.Begin(); iter != children.End(); ++iter)
  846. {
  847. UIElement* element = iter->Get();
  848. String name = element->GetName();
  849. if (name.StartsWith("Button"))
  850. {
  851. ++numButtons;
  852. // Check whether the button has key binding
  853. Text* text = element->GetChildDynamicCast<Text>("KeyBinding", false);
  854. if (text)
  855. {
  856. text->SetVisible(false);
  857. const String& key = text->GetText();
  858. int keyBinding;
  859. if (key.Length() == 1)
  860. keyBinding = key[0];
  861. else
  862. {
  863. PopulateKeyBindingMap(keyBindingMap);
  864. HashMap<String, int>::Iterator i = keyBindingMap.Find(key);
  865. if (i != keyBindingMap.End())
  866. keyBinding = i->second_;
  867. else
  868. {
  869. URHO3D_LOGERRORF("Unsupported key binding: %s", key.CString());
  870. keyBinding = M_MAX_INT;
  871. }
  872. }
  873. if (keyBinding != M_MAX_INT)
  874. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  875. }
  876. // Check whether the button has mouse button binding
  877. text = element->GetChildDynamicCast<Text>("MouseButtonBinding", false);
  878. if (text)
  879. {
  880. text->SetVisible(false);
  881. const String& mouseButton = text->GetText();
  882. PopulateMouseButtonBindingMap(mouseButtonBindingMap);
  883. HashMap<String, int>::Iterator i = mouseButtonBindingMap.Find(mouseButton);
  884. if (i != mouseButtonBindingMap.End())
  885. element->SetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING, i->second_);
  886. else
  887. URHO3D_LOGERRORF("Unsupported mouse button binding: %s", mouseButton.CString());
  888. }
  889. }
  890. else if (name.StartsWith("Axis"))
  891. {
  892. ++numAxes;
  893. ///\todo Axis emulation for screen joystick is not fully supported yet.
  894. URHO3D_LOGWARNING("Axis emulation for screen joystick is not fully supported yet");
  895. }
  896. else if (name.StartsWith("Hat"))
  897. {
  898. ++numHats;
  899. Text* text = element->GetChildDynamicCast<Text>("KeyBinding", false);
  900. if (text)
  901. {
  902. text->SetVisible(false);
  903. String keyBinding = text->GetText();
  904. int mappedKeyBinding[4] = {KEY_W, KEY_S, KEY_A, KEY_D};
  905. Vector<String> keyBindings;
  906. if (keyBinding.Contains(' ')) // e.g.: "UP DOWN LEFT RIGHT"
  907. keyBindings = keyBinding.Split(' '); // Attempt to split the text using ' ' as separator
  908. else if (keyBinding.Length() == 4)
  909. {
  910. keyBindings.Resize(4); // e.g.: "WSAD"
  911. for (unsigned i = 0; i < 4; ++i)
  912. keyBindings[i] = keyBinding.Substring(i, 1);
  913. }
  914. if (keyBindings.Size() == 4)
  915. {
  916. PopulateKeyBindingMap(keyBindingMap);
  917. for (unsigned j = 0; j < 4; ++j)
  918. {
  919. if (keyBindings[j].Length() == 1)
  920. mappedKeyBinding[j] = keyBindings[j][0];
  921. else
  922. {
  923. HashMap<String, int>::Iterator i = keyBindingMap.Find(keyBindings[j]);
  924. if (i != keyBindingMap.End())
  925. mappedKeyBinding[j] = i->second_;
  926. else
  927. URHO3D_LOGERRORF("%s - %s cannot be mapped, fallback to '%c'", name.CString(), keyBindings[j].CString(),
  928. mappedKeyBinding[j]);
  929. }
  930. }
  931. }
  932. else
  933. URHO3D_LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  934. element->SetVar(VAR_BUTTON_KEY_BINDING, IntRect(mappedKeyBinding));
  935. }
  936. }
  937. element->SetVar(VAR_SCREEN_JOYSTICK_ID, joystickID);
  938. }
  939. // Make sure all the children are non-focusable so they do not mistakenly to be considered as active UI input controls by application
  940. PODVector<UIElement*> allChildren;
  941. state.screenJoystick_->GetChildren(allChildren, true);
  942. for (PODVector<UIElement*>::Iterator iter = allChildren.Begin(); iter != allChildren.End(); ++iter)
  943. (*iter)->SetFocusMode(FM_NOTFOCUSABLE);
  944. state.Initialize(numButtons, numAxes, numHats);
  945. // There could be potentially more than one screen joystick, however they all will be handled by a same handler method
  946. // So there is no harm to replace the old handler with the new handler in each call to SubscribeToEvent()
  947. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  948. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  949. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  950. return joystickID;
  951. }
  952. bool Input::RemoveScreenJoystick(SDL_JoystickID id)
  953. {
  954. if (!joysticks_.Contains(id))
  955. {
  956. URHO3D_LOGERRORF("Failed to remove non-existing screen joystick ID #%d", id);
  957. return false;
  958. }
  959. JoystickState& state = joysticks_[id];
  960. if (!state.screenJoystick_)
  961. {
  962. URHO3D_LOGERRORF("Failed to remove joystick with ID #%d which is not a screen joystick", id);
  963. return false;
  964. }
  965. state.screenJoystick_->Remove();
  966. joysticks_.Erase(id);
  967. return true;
  968. }
  969. void Input::SetScreenJoystickVisible(SDL_JoystickID id, bool enable)
  970. {
  971. if (joysticks_.Contains(id))
  972. {
  973. JoystickState& state = joysticks_[id];
  974. if (state.screenJoystick_)
  975. state.screenJoystick_->SetVisible(enable);
  976. }
  977. }
  978. void Input::SetScreenKeyboardVisible(bool enable)
  979. {
  980. if (!graphics_)
  981. return;
  982. if (enable != IsScreenKeyboardVisible())
  983. {
  984. if (enable)
  985. SDL_StartTextInput();
  986. else
  987. SDL_StopTextInput();
  988. }
  989. }
  990. void Input::SetTouchEmulation(bool enable)
  991. {
  992. #if !defined(__ANDROID__) && !defined(IOS)
  993. if (enable != touchEmulation_)
  994. {
  995. if (enable)
  996. {
  997. // Touch emulation needs the mouse visible
  998. if (!mouseVisible_)
  999. SetMouseVisible(true);
  1000. // Add a virtual touch device the first time we are enabling emulated touch
  1001. if (!SDL_GetNumTouchDevices())
  1002. SDL_AddTouch(0, "Emulated Touch");
  1003. }
  1004. else
  1005. ResetTouches();
  1006. touchEmulation_ = enable;
  1007. }
  1008. #endif
  1009. }
  1010. bool Input::RecordGesture()
  1011. {
  1012. // If have no touch devices, fail
  1013. if (!SDL_GetNumTouchDevices())
  1014. {
  1015. URHO3D_LOGERROR("Can not record gesture: no touch devices");
  1016. return false;
  1017. }
  1018. return SDL_RecordGesture(-1) != 0;
  1019. }
  1020. bool Input::SaveGestures(Serializer& dest)
  1021. {
  1022. RWOpsWrapper<Serializer> wrapper(dest);
  1023. return SDL_SaveAllDollarTemplates(wrapper.GetRWOps()) != 0;
  1024. }
  1025. bool Input::SaveGesture(Serializer& dest, unsigned gestureID)
  1026. {
  1027. RWOpsWrapper<Serializer> wrapper(dest);
  1028. return SDL_SaveDollarTemplate(gestureID, wrapper.GetRWOps()) != 0;
  1029. }
  1030. unsigned Input::LoadGestures(Deserializer& source)
  1031. {
  1032. // If have no touch devices, fail
  1033. if (!SDL_GetNumTouchDevices())
  1034. {
  1035. URHO3D_LOGERROR("Can not load gestures: no touch devices");
  1036. return 0;
  1037. }
  1038. RWOpsWrapper<Deserializer> wrapper(source);
  1039. return (unsigned)SDL_LoadDollarTemplates(-1, wrapper.GetRWOps());
  1040. }
  1041. bool Input::RemoveGesture(unsigned gestureID)
  1042. {
  1043. #ifdef __EMSCRIPTEN__
  1044. return false;
  1045. #else
  1046. return SDL_RemoveDollarTemplate(gestureID) != 0;
  1047. #endif
  1048. }
  1049. void Input::RemoveAllGestures()
  1050. {
  1051. #ifndef __EMSCRIPTEN__
  1052. SDL_RemoveAllDollarTemplates();
  1053. #endif
  1054. }
  1055. SDL_JoystickID Input::OpenJoystick(unsigned index)
  1056. {
  1057. SDL_Joystick* joystick = SDL_JoystickOpen(index);
  1058. if (!joystick)
  1059. {
  1060. URHO3D_LOGERRORF("Cannot open joystick #%d", index);
  1061. return -1;
  1062. }
  1063. // Create joystick state for the new joystick
  1064. int joystickID = SDL_JoystickInstanceID(joystick);
  1065. JoystickState& state = joysticks_[joystickID];
  1066. state.joystick_ = joystick;
  1067. state.joystickID_ = joystickID;
  1068. state.name_ = SDL_JoystickName(joystick);
  1069. if (SDL_IsGameController(index))
  1070. state.controller_ = SDL_GameControllerOpen(index);
  1071. unsigned numButtons = (unsigned)SDL_JoystickNumButtons(joystick);
  1072. unsigned numAxes = (unsigned)SDL_JoystickNumAxes(joystick);
  1073. unsigned numHats = (unsigned)SDL_JoystickNumHats(joystick);
  1074. // When the joystick is a controller, make sure there's enough axes & buttons for the standard controller mappings
  1075. if (state.controller_)
  1076. {
  1077. if (numButtons < SDL_CONTROLLER_BUTTON_MAX)
  1078. numButtons = SDL_CONTROLLER_BUTTON_MAX;
  1079. if (numAxes < SDL_CONTROLLER_AXIS_MAX)
  1080. numAxes = SDL_CONTROLLER_AXIS_MAX;
  1081. }
  1082. state.Initialize(numButtons, numAxes, numHats);
  1083. return joystickID;
  1084. }
  1085. int Input::GetKeyFromName(const String& name) const
  1086. {
  1087. return SDL_GetKeyFromName(name.CString());
  1088. }
  1089. int Input::GetKeyFromScancode(int scancode) const
  1090. {
  1091. return SDL_GetKeyFromScancode((SDL_Scancode)scancode);
  1092. }
  1093. String Input::GetKeyName(int key) const
  1094. {
  1095. return String(SDL_GetKeyName(key));
  1096. }
  1097. int Input::GetScancodeFromKey(int key) const
  1098. {
  1099. return SDL_GetScancodeFromKey(key);
  1100. }
  1101. int Input::GetScancodeFromName(const String& name) const
  1102. {
  1103. return SDL_GetScancodeFromName(name.CString());
  1104. }
  1105. String Input::GetScancodeName(int scancode) const
  1106. {
  1107. return SDL_GetScancodeName((SDL_Scancode)scancode);
  1108. }
  1109. bool Input::GetKeyDown(int key) const
  1110. {
  1111. return keyDown_.Contains(SDL_tolower(key));
  1112. }
  1113. bool Input::GetKeyPress(int key) const
  1114. {
  1115. return keyPress_.Contains(SDL_tolower(key));
  1116. }
  1117. bool Input::GetScancodeDown(int scancode) const
  1118. {
  1119. return scancodeDown_.Contains(scancode);
  1120. }
  1121. bool Input::GetScancodePress(int scancode) const
  1122. {
  1123. return scancodePress_.Contains(scancode);
  1124. }
  1125. bool Input::GetMouseButtonDown(int button) const
  1126. {
  1127. return (mouseButtonDown_ & button) != 0;
  1128. }
  1129. bool Input::GetMouseButtonPress(int button) const
  1130. {
  1131. return (mouseButtonPress_ & button) != 0;
  1132. }
  1133. bool Input::GetQualifierDown(int qualifier) const
  1134. {
  1135. if (qualifier == QUAL_SHIFT)
  1136. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  1137. if (qualifier == QUAL_CTRL)
  1138. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  1139. if (qualifier == QUAL_ALT)
  1140. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  1141. return false;
  1142. }
  1143. bool Input::GetQualifierPress(int qualifier) const
  1144. {
  1145. if (qualifier == QUAL_SHIFT)
  1146. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  1147. if (qualifier == QUAL_CTRL)
  1148. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  1149. if (qualifier == QUAL_ALT)
  1150. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  1151. return false;
  1152. }
  1153. int Input::GetQualifiers() const
  1154. {
  1155. int ret = 0;
  1156. if (GetQualifierDown(QUAL_SHIFT))
  1157. ret |= QUAL_SHIFT;
  1158. if (GetQualifierDown(QUAL_CTRL))
  1159. ret |= QUAL_CTRL;
  1160. if (GetQualifierDown(QUAL_ALT))
  1161. ret |= QUAL_ALT;
  1162. return ret;
  1163. }
  1164. IntVector2 Input::GetMousePosition() const
  1165. {
  1166. IntVector2 ret = IntVector2::ZERO;
  1167. if (!initialized_)
  1168. return ret;
  1169. SDL_GetMouseState(&ret.x_, &ret.y_);
  1170. return ret;
  1171. }
  1172. const IntVector2& Input::GetMouseMove() const
  1173. {
  1174. if (!suppressNextMouseMove_)
  1175. return mouseMove_;
  1176. else
  1177. return IntVector2::ZERO;
  1178. }
  1179. int Input::GetMouseMoveX() const
  1180. {
  1181. if (!suppressNextMouseMove_)
  1182. return mouseMove_.x_;
  1183. else
  1184. return 0;
  1185. }
  1186. int Input::GetMouseMoveY() const
  1187. {
  1188. if (!suppressNextMouseMove_)
  1189. return mouseMove_.y_;
  1190. else
  1191. return 0;
  1192. }
  1193. TouchState* Input::GetTouch(unsigned index) const
  1194. {
  1195. if (index >= touches_.Size())
  1196. return 0;
  1197. HashMap<int, TouchState>::ConstIterator i = touches_.Begin();
  1198. while (index--)
  1199. ++i;
  1200. return const_cast<TouchState*>(&i->second_);
  1201. }
  1202. JoystickState* Input::GetJoystickByIndex(unsigned index)
  1203. {
  1204. unsigned compare = 0;
  1205. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1206. {
  1207. if (compare++ == index)
  1208. return &(i->second_);
  1209. }
  1210. return 0;
  1211. }
  1212. JoystickState* Input::GetJoystickByName(const String& name)
  1213. {
  1214. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1215. {
  1216. if (i->second_.name_ == name)
  1217. return &(i->second_);
  1218. }
  1219. return 0;
  1220. }
  1221. JoystickState* Input::GetJoystick(SDL_JoystickID id)
  1222. {
  1223. HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Find(id);
  1224. return i != joysticks_.End() ? &(i->second_) : 0;
  1225. }
  1226. bool Input::IsScreenJoystickVisible(SDL_JoystickID id) const
  1227. {
  1228. HashMap<SDL_JoystickID, JoystickState>::ConstIterator i = joysticks_.Find(id);
  1229. return i != joysticks_.End() && i->second_.screenJoystick_ && i->second_.screenJoystick_->IsVisible();
  1230. }
  1231. bool Input::GetScreenKeyboardSupport() const
  1232. {
  1233. return graphics_ ? SDL_HasScreenKeyboardSupport() != 0 : false;
  1234. }
  1235. bool Input::IsScreenKeyboardVisible() const
  1236. {
  1237. if (graphics_)
  1238. {
  1239. SDL_Window* window = graphics_->GetWindow();
  1240. return SDL_IsScreenKeyboardShown(window) != SDL_FALSE;
  1241. }
  1242. else
  1243. return false;
  1244. }
  1245. bool Input::IsMouseLocked() const
  1246. {
  1247. #ifdef __EMSCRIPTEN__
  1248. return emscriptenPointerLock_;
  1249. #else
  1250. return !((mouseMode_ == MM_ABSOLUTE && mouseVisible_) || mouseMode_ == MM_FREE);
  1251. #endif
  1252. }
  1253. bool Input::IsMinimized() const
  1254. {
  1255. // Return minimized state also when unfocused in fullscreen
  1256. if (!inputFocus_ && graphics_ && graphics_->GetFullscreen())
  1257. return true;
  1258. else
  1259. return minimized_;
  1260. }
  1261. void Input::Initialize()
  1262. {
  1263. Graphics* graphics = GetSubsystem<Graphics>();
  1264. if (!graphics || !graphics->IsInitialized())
  1265. return;
  1266. graphics_ = graphics;
  1267. // In external window mode only visible mouse is supported
  1268. if (graphics_->GetExternalWindow())
  1269. mouseVisible_ = true;
  1270. // Set the initial activation
  1271. initialized_ = true;
  1272. #ifndef __EMSCRIPTEN__
  1273. GainFocus();
  1274. #else
  1275. // Note: Page visibility and focus are slightly different, however we can't query last focus with Emscripten (1.29.0)
  1276. if (emscriptenInput_->IsVisible())
  1277. GainFocus();
  1278. else
  1279. LoseFocus();
  1280. #endif
  1281. ResetJoysticks();
  1282. ResetState();
  1283. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(Input, HandleBeginFrame));
  1284. #ifdef __EMSCRIPTEN__
  1285. SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Input, HandleEndFrame));
  1286. #endif
  1287. URHO3D_LOGINFO("Initialized input");
  1288. }
  1289. void Input::ResetJoysticks()
  1290. {
  1291. joysticks_.Clear();
  1292. // Open each detected joystick automatically on startup
  1293. unsigned size = static_cast<unsigned>(SDL_NumJoysticks());
  1294. for (unsigned i = 0; i < size; ++i)
  1295. OpenJoystick(i);
  1296. }
  1297. void Input::ResetInputAccumulation()
  1298. {
  1299. // Reset input accumulation for this frame
  1300. keyPress_.Clear();
  1301. scancodePress_.Clear();
  1302. mouseButtonPress_ = 0;
  1303. mouseMove_ = IntVector2::ZERO;
  1304. mouseMoveWheel_ = 0;
  1305. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1306. {
  1307. for (unsigned j = 0; j < i->second_.buttonPress_.Size(); ++j)
  1308. i->second_.buttonPress_[j] = false;
  1309. }
  1310. // Reset touch delta movement
  1311. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  1312. {
  1313. TouchState& state = i->second_;
  1314. state.lastPosition_ = state.position_;
  1315. state.delta_ = IntVector2::ZERO;
  1316. }
  1317. }
  1318. void Input::GainFocus()
  1319. {
  1320. ResetState();
  1321. inputFocus_ = true;
  1322. focusedThisFrame_ = false;
  1323. // Restore mouse mode
  1324. #ifndef __EMSCRIPTEN__
  1325. const MouseMode mm = mouseMode_;
  1326. mouseMode_ = MM_FREE;
  1327. SetMouseMode(mm, true);
  1328. #endif
  1329. SuppressNextMouseMove();
  1330. // Re-establish mouse cursor hiding as necessary
  1331. if (!mouseVisible_)
  1332. SDL_ShowCursor(SDL_FALSE);
  1333. SendInputFocusEvent();
  1334. }
  1335. void Input::LoseFocus()
  1336. {
  1337. ResetState();
  1338. inputFocus_ = false;
  1339. focusedThisFrame_ = false;
  1340. // Show the mouse cursor when inactive
  1341. SDL_ShowCursor(SDL_TRUE);
  1342. // Change mouse mode -- removing any cursor grabs, etc.
  1343. #ifndef __EMSCRIPTEN__
  1344. const MouseMode mm = mouseMode_;
  1345. SetMouseMode(MM_FREE, true);
  1346. // Restore flags to reflect correct mouse state.
  1347. mouseMode_ = mm;
  1348. #endif
  1349. SendInputFocusEvent();
  1350. }
  1351. void Input::ResetState()
  1352. {
  1353. keyDown_.Clear();
  1354. keyPress_.Clear();
  1355. scancodeDown_.Clear();
  1356. scancodePress_.Clear();
  1357. /// \todo Check if resetting joystick state on input focus loss is even necessary
  1358. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1359. i->second_.Reset();
  1360. ResetTouches();
  1361. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  1362. SetMouseButton(MOUSEB_LEFT, false);
  1363. SetMouseButton(MOUSEB_RIGHT, false);
  1364. SetMouseButton(MOUSEB_MIDDLE, false);
  1365. mouseMove_ = IntVector2::ZERO;
  1366. mouseMoveWheel_ = 0;
  1367. mouseButtonPress_ = 0;
  1368. }
  1369. void Input::ResetTouches()
  1370. {
  1371. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  1372. {
  1373. TouchState& state = i->second_;
  1374. using namespace TouchEnd;
  1375. VariantMap& eventData = GetEventDataMap();
  1376. eventData[P_TOUCHID] = state.touchID_;
  1377. eventData[P_X] = state.position_.x_;
  1378. eventData[P_Y] = state.position_.y_;
  1379. SendEvent(E_TOUCHEND, eventData);
  1380. }
  1381. touches_.Clear();
  1382. touchIDMap_.Clear();
  1383. availableTouchIDs_.Clear();
  1384. for (int i = 0; i < TOUCHID_MAX; i++)
  1385. availableTouchIDs_.Push(i);
  1386. }
  1387. unsigned Input::GetTouchIndexFromID(int touchID)
  1388. {
  1389. HashMap<int, int>::ConstIterator i = touchIDMap_.Find(touchID);
  1390. if (i != touchIDMap_.End())
  1391. {
  1392. return (unsigned)i->second_;
  1393. }
  1394. unsigned index = PopTouchIndex();
  1395. touchIDMap_[touchID] = index;
  1396. return index;
  1397. }
  1398. unsigned Input::PopTouchIndex()
  1399. {
  1400. if (availableTouchIDs_.Empty())
  1401. return 0;
  1402. unsigned index = (unsigned)availableTouchIDs_.Front();
  1403. availableTouchIDs_.PopFront();
  1404. return index;
  1405. }
  1406. void Input::PushTouchIndex(int touchID)
  1407. {
  1408. HashMap<int, int>::ConstIterator ci = touchIDMap_.Find(touchID);
  1409. if (ci == touchIDMap_.End())
  1410. return;
  1411. int index = touchIDMap_[touchID];
  1412. touchIDMap_.Erase(touchID);
  1413. // Sorted insertion
  1414. bool inserted = false;
  1415. for (List<int>::Iterator i = availableTouchIDs_.Begin(); i != availableTouchIDs_.End(); ++i)
  1416. {
  1417. if (*i == index)
  1418. {
  1419. // This condition can occur when TOUCHID_MAX is reached.
  1420. inserted = true;
  1421. break;
  1422. }
  1423. if (*i > index)
  1424. {
  1425. availableTouchIDs_.Insert(i, index);
  1426. inserted = true;
  1427. break;
  1428. }
  1429. }
  1430. // If empty, or the lowest value then insert at end.
  1431. if (!inserted)
  1432. availableTouchIDs_.Push(index);
  1433. }
  1434. void Input::SendInputFocusEvent()
  1435. {
  1436. using namespace InputFocus;
  1437. VariantMap& eventData = GetEventDataMap();
  1438. eventData[P_FOCUS] = HasFocus();
  1439. eventData[P_MINIMIZED] = IsMinimized();
  1440. SendEvent(E_INPUTFOCUS, eventData);
  1441. }
  1442. void Input::SetMouseButton(int button, bool newState)
  1443. {
  1444. if (newState)
  1445. {
  1446. if (!(mouseButtonDown_ & button))
  1447. mouseButtonPress_ |= button;
  1448. mouseButtonDown_ |= button;
  1449. }
  1450. else
  1451. {
  1452. if (!(mouseButtonDown_ & button))
  1453. return;
  1454. mouseButtonDown_ &= ~button;
  1455. }
  1456. using namespace MouseButtonDown;
  1457. VariantMap& eventData = GetEventDataMap();
  1458. eventData[P_BUTTON] = button;
  1459. eventData[P_BUTTONS] = mouseButtonDown_;
  1460. eventData[P_QUALIFIERS] = GetQualifiers();
  1461. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  1462. }
  1463. void Input::SetKey(int key, int scancode, bool newState)
  1464. {
  1465. bool repeat = false;
  1466. if (newState)
  1467. {
  1468. scancodeDown_.Insert(scancode);
  1469. scancodePress_.Insert(scancode);
  1470. if (!keyDown_.Contains(key))
  1471. {
  1472. keyDown_.Insert(key);
  1473. keyPress_.Insert(key);
  1474. }
  1475. else
  1476. repeat = true;
  1477. }
  1478. else
  1479. {
  1480. scancodeDown_.Erase(scancode);
  1481. if (!keyDown_.Erase(key))
  1482. return;
  1483. }
  1484. using namespace KeyDown;
  1485. VariantMap& eventData = GetEventDataMap();
  1486. eventData[P_KEY] = key;
  1487. eventData[P_SCANCODE] = scancode;
  1488. eventData[P_BUTTONS] = mouseButtonDown_;
  1489. eventData[P_QUALIFIERS] = GetQualifiers();
  1490. if (newState)
  1491. eventData[P_REPEAT] = repeat;
  1492. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  1493. if ((key == KEY_RETURN || key == KEY_RETURN2 || key == KEY_KP_ENTER) && newState && !repeat && toggleFullscreen_ &&
  1494. (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  1495. graphics_->ToggleFullscreen();
  1496. }
  1497. void Input::SetMouseWheel(int delta)
  1498. {
  1499. if (delta)
  1500. {
  1501. mouseMoveWheel_ += delta;
  1502. using namespace MouseWheel;
  1503. VariantMap& eventData = GetEventDataMap();
  1504. eventData[P_WHEEL] = delta;
  1505. eventData[P_BUTTONS] = mouseButtonDown_;
  1506. eventData[P_QUALIFIERS] = GetQualifiers();
  1507. SendEvent(E_MOUSEWHEEL, eventData);
  1508. }
  1509. }
  1510. void Input::SetMousePosition(const IntVector2& position)
  1511. {
  1512. if (!graphics_)
  1513. return;
  1514. SDL_WarpMouseInWindow(graphics_->GetWindow(), position.x_, position.y_);
  1515. }
  1516. void Input::CenterMousePosition()
  1517. {
  1518. const IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  1519. if (GetMousePosition() != center)
  1520. {
  1521. SetMousePosition(center);
  1522. lastMousePosition_ = center;
  1523. }
  1524. }
  1525. void Input::SuppressNextMouseMove()
  1526. {
  1527. suppressNextMouseMove_ = true;
  1528. mouseMove_ = IntVector2::ZERO;
  1529. }
  1530. void Input::UnsuppressMouseMove()
  1531. {
  1532. suppressNextMouseMove_ = false;
  1533. mouseMove_ = IntVector2::ZERO;
  1534. lastMousePosition_ = GetMousePosition();
  1535. }
  1536. void Input::HandleSDLEvent(void* sdlEvent)
  1537. {
  1538. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  1539. // While not having input focus, skip key/mouse/touch/joystick events, except for the "click to focus" mechanism
  1540. if (!inputFocus_ && evt.type >= SDL_KEYDOWN && evt.type <= SDL_MULTIGESTURE)
  1541. {
  1542. #ifdef REQUIRE_CLICK_TO_FOCUS
  1543. // Require the click to be at least 1 pixel inside the window to disregard clicks in the title bar
  1544. if (evt.type == SDL_MOUSEBUTTONDOWN && evt.button.x > 0 && evt.button.y > 0 && evt.button.x < graphics_->GetWidth() - 1 &&
  1545. evt.button.y < graphics_->GetHeight() - 1)
  1546. {
  1547. focusedThisFrame_ = true;
  1548. // Do not cause the click to actually go throughfin
  1549. return;
  1550. }
  1551. else if (evt.type == SDL_FINGERDOWN)
  1552. {
  1553. // When focusing by touch, call GainFocus() immediately as it resets the state; a touch has sustained state
  1554. // which should be kept
  1555. GainFocus();
  1556. }
  1557. else
  1558. #endif
  1559. return;
  1560. }
  1561. switch (evt.type)
  1562. {
  1563. case SDL_KEYDOWN:
  1564. #ifdef __EMSCRIPTEN__
  1565. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, true);
  1566. #else
  1567. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, true);
  1568. #endif
  1569. break;
  1570. case SDL_KEYUP:
  1571. #ifdef __EMSCRIPTEN__
  1572. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, false);
  1573. #else
  1574. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, false);
  1575. #endif
  1576. break;
  1577. case SDL_TEXTINPUT:
  1578. {
  1579. textInput_ = &evt.text.text[0];
  1580. unsigned unicode = textInput_.AtUTF8(0);
  1581. if (unicode)
  1582. {
  1583. using namespace TextInput;
  1584. VariantMap textInputEventData;
  1585. textInputEventData[P_TEXT] = textInput_;
  1586. textInputEventData[P_BUTTONS] = mouseButtonDown_;
  1587. textInputEventData[P_QUALIFIERS] = GetQualifiers();
  1588. SendEvent(E_TEXTINPUT, textInputEventData);
  1589. }
  1590. }
  1591. break;
  1592. case SDL_MOUSEBUTTONDOWN:
  1593. if (!touchEmulation_)
  1594. SetMouseButton(1 << (evt.button.button - 1), true);
  1595. else
  1596. {
  1597. int x, y;
  1598. SDL_GetMouseState(&x, &y);
  1599. SDL_Event event;
  1600. event.type = SDL_FINGERDOWN;
  1601. event.tfinger.touchId = 0;
  1602. event.tfinger.fingerId = evt.button.button - 1;
  1603. event.tfinger.pressure = 1.0f;
  1604. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1605. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1606. event.tfinger.dx = 0;
  1607. event.tfinger.dy = 0;
  1608. SDL_PushEvent(&event);
  1609. }
  1610. break;
  1611. case SDL_MOUSEBUTTONUP:
  1612. if (!touchEmulation_)
  1613. SetMouseButton(1 << (evt.button.button - 1), false);
  1614. else
  1615. {
  1616. int x, y;
  1617. SDL_GetMouseState(&x, &y);
  1618. SDL_Event event;
  1619. event.type = SDL_FINGERUP;
  1620. event.tfinger.touchId = 0;
  1621. event.tfinger.fingerId = evt.button.button - 1;
  1622. event.tfinger.pressure = 0.0f;
  1623. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1624. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1625. event.tfinger.dx = 0;
  1626. event.tfinger.dy = 0;
  1627. SDL_PushEvent(&event);
  1628. }
  1629. break;
  1630. case SDL_MOUSEMOTION:
  1631. #ifndef __EMSCRIPTEN__
  1632. if ((sdlMouseRelative_ || mouseVisible_ || mouseMode_ == MM_FREE) && !touchEmulation_)
  1633. #else
  1634. if ((mouseVisible_ || emscriptenPointerLock_ || mouseMode_ == MM_FREE) && !touchEmulation_)
  1635. #endif
  1636. {
  1637. #ifdef __EMSCRIPTEN__
  1638. if (emscriptenExitingPointerLock_)
  1639. {
  1640. SuppressNextMouseMove();
  1641. break;
  1642. }
  1643. #endif
  1644. mouseMove_.x_ += evt.motion.xrel;
  1645. mouseMove_.y_ += evt.motion.yrel;
  1646. if (!suppressNextMouseMove_)
  1647. {
  1648. using namespace MouseMove;
  1649. VariantMap& eventData = GetEventDataMap();
  1650. eventData[P_X] = evt.motion.x;
  1651. eventData[P_Y] = evt.motion.y;
  1652. eventData[P_DX] = evt.motion.xrel;
  1653. eventData[P_DY] = evt.motion.yrel;
  1654. eventData[P_BUTTONS] = mouseButtonDown_;
  1655. eventData[P_QUALIFIERS] = GetQualifiers();
  1656. SendEvent(E_MOUSEMOVE, eventData);
  1657. }
  1658. }
  1659. // Only the left mouse button "finger" moves along with the mouse movement
  1660. else if (touchEmulation_ && touches_.Contains(0))
  1661. {
  1662. int x, y;
  1663. SDL_GetMouseState(&x, &y);
  1664. SDL_Event event;
  1665. event.type = SDL_FINGERMOTION;
  1666. event.tfinger.touchId = 0;
  1667. event.tfinger.fingerId = 0;
  1668. event.tfinger.pressure = 1.0f;
  1669. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1670. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1671. event.tfinger.dx = (float)evt.motion.xrel / (float)graphics_->GetWidth();
  1672. event.tfinger.dy = (float)evt.motion.yrel / (float)graphics_->GetHeight();
  1673. SDL_PushEvent(&event);
  1674. }
  1675. break;
  1676. case SDL_MOUSEWHEEL:
  1677. if (!touchEmulation_)
  1678. SetMouseWheel(evt.wheel.y);
  1679. break;
  1680. case SDL_FINGERDOWN:
  1681. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1682. {
  1683. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffff);
  1684. TouchState& state = touches_[touchID];
  1685. state.touchID_ = touchID;
  1686. state.lastPosition_ = state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1687. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1688. state.delta_ = IntVector2::ZERO;
  1689. state.pressure_ = evt.tfinger.pressure;
  1690. using namespace TouchBegin;
  1691. VariantMap& eventData = GetEventDataMap();
  1692. eventData[P_TOUCHID] = touchID;
  1693. eventData[P_X] = state.position_.x_;
  1694. eventData[P_Y] = state.position_.y_;
  1695. eventData[P_PRESSURE] = state.pressure_;
  1696. SendEvent(E_TOUCHBEGIN, eventData);
  1697. // Finger touch may move the mouse cursor. Suppress next mouse move when cursor hidden to prevent jumps
  1698. if (!mouseVisible_)
  1699. SuppressNextMouseMove();
  1700. }
  1701. break;
  1702. case SDL_FINGERUP:
  1703. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1704. {
  1705. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffff);
  1706. TouchState& state = touches_[touchID];
  1707. using namespace TouchEnd;
  1708. VariantMap& eventData = GetEventDataMap();
  1709. // Do not trust the position in the finger up event. Instead use the last position stored in the
  1710. // touch structure
  1711. eventData[P_TOUCHID] = touchID;
  1712. eventData[P_X] = state.position_.x_;
  1713. eventData[P_Y] = state.position_.y_;
  1714. SendEvent(E_TOUCHEND, eventData);
  1715. // Add touch index back to list of available touch Ids
  1716. PushTouchIndex(evt.tfinger.fingerId & 0x7ffffff);
  1717. touches_.Erase(touchID);
  1718. }
  1719. break;
  1720. case SDL_FINGERMOTION:
  1721. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1722. {
  1723. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffff);
  1724. // We don't want this event to create a new touches_ event if it doesn't exist (touchEmulation)
  1725. if (touchEmulation_ && !touches_.Contains(touchID))
  1726. break;
  1727. TouchState& state = touches_[touchID];
  1728. state.touchID_ = touchID;
  1729. state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1730. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1731. state.delta_ = state.position_ - state.lastPosition_;
  1732. state.pressure_ = evt.tfinger.pressure;
  1733. using namespace TouchMove;
  1734. VariantMap& eventData = GetEventDataMap();
  1735. eventData[P_TOUCHID] = touchID;
  1736. eventData[P_X] = state.position_.x_;
  1737. eventData[P_Y] = state.position_.y_;
  1738. eventData[P_DX] = (int)(evt.tfinger.dx * graphics_->GetWidth());
  1739. eventData[P_DY] = (int)(evt.tfinger.dy * graphics_->GetHeight());
  1740. eventData[P_PRESSURE] = state.pressure_;
  1741. SendEvent(E_TOUCHMOVE, eventData);
  1742. // Finger touch may move the mouse cursor. Suppress next mouse move when cursor hidden to prevent jumps
  1743. if (!mouseVisible_)
  1744. SuppressNextMouseMove();
  1745. }
  1746. break;
  1747. case SDL_DOLLARRECORD:
  1748. {
  1749. using namespace GestureRecorded;
  1750. VariantMap& eventData = GetEventDataMap();
  1751. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1752. SendEvent(E_GESTURERECORDED, eventData);
  1753. }
  1754. break;
  1755. case SDL_DOLLARGESTURE:
  1756. {
  1757. using namespace GestureInput;
  1758. VariantMap& eventData = GetEventDataMap();
  1759. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1760. eventData[P_CENTERX] = (int)(evt.dgesture.x * graphics_->GetWidth());
  1761. eventData[P_CENTERY] = (int)(evt.dgesture.y * graphics_->GetHeight());
  1762. eventData[P_NUMFINGERS] = (int)evt.dgesture.numFingers;
  1763. eventData[P_ERROR] = evt.dgesture.error;
  1764. SendEvent(E_GESTUREINPUT, eventData);
  1765. }
  1766. break;
  1767. case SDL_MULTIGESTURE:
  1768. {
  1769. using namespace MultiGesture;
  1770. VariantMap& eventData = GetEventDataMap();
  1771. eventData[P_CENTERX] = (int)(evt.mgesture.x * graphics_->GetWidth());
  1772. eventData[P_CENTERY] = (int)(evt.mgesture.y * graphics_->GetHeight());
  1773. eventData[P_NUMFINGERS] = (int)evt.mgesture.numFingers;
  1774. eventData[P_DTHETA] = M_RADTODEG * evt.mgesture.dTheta;
  1775. eventData[P_DDIST] = evt.mgesture.dDist;
  1776. SendEvent(E_MULTIGESTURE, eventData);
  1777. }
  1778. break;
  1779. case SDL_JOYDEVICEADDED:
  1780. {
  1781. using namespace JoystickConnected;
  1782. SDL_JoystickID joystickID = OpenJoystick((unsigned)evt.jdevice.which);
  1783. VariantMap& eventData = GetEventDataMap();
  1784. eventData[P_JOYSTICKID] = joystickID;
  1785. SendEvent(E_JOYSTICKCONNECTED, eventData);
  1786. }
  1787. break;
  1788. case SDL_JOYDEVICEREMOVED:
  1789. {
  1790. using namespace JoystickDisconnected;
  1791. joysticks_.Erase(evt.jdevice.which);
  1792. VariantMap& eventData = GetEventDataMap();
  1793. eventData[P_JOYSTICKID] = evt.jdevice.which;
  1794. SendEvent(E_JOYSTICKDISCONNECTED, eventData);
  1795. }
  1796. break;
  1797. case SDL_JOYBUTTONDOWN:
  1798. {
  1799. using namespace JoystickButtonDown;
  1800. unsigned button = evt.jbutton.button;
  1801. SDL_JoystickID joystickID = evt.jbutton.which;
  1802. JoystickState& state = joysticks_[joystickID];
  1803. // Skip ordinary joystick event for a controller
  1804. if (!state.controller_)
  1805. {
  1806. VariantMap& eventData = GetEventDataMap();
  1807. eventData[P_JOYSTICKID] = joystickID;
  1808. eventData[P_BUTTON] = button;
  1809. if (button < state.buttons_.Size())
  1810. {
  1811. state.buttons_[button] = true;
  1812. state.buttonPress_[button] = true;
  1813. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1814. }
  1815. }
  1816. }
  1817. break;
  1818. case SDL_JOYBUTTONUP:
  1819. {
  1820. using namespace JoystickButtonUp;
  1821. unsigned button = evt.jbutton.button;
  1822. SDL_JoystickID joystickID = evt.jbutton.which;
  1823. JoystickState& state = joysticks_[joystickID];
  1824. if (!state.controller_)
  1825. {
  1826. VariantMap& eventData = GetEventDataMap();
  1827. eventData[P_JOYSTICKID] = joystickID;
  1828. eventData[P_BUTTON] = button;
  1829. if (button < state.buttons_.Size())
  1830. {
  1831. if (!state.controller_)
  1832. state.buttons_[button] = false;
  1833. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1834. }
  1835. }
  1836. }
  1837. break;
  1838. case SDL_JOYAXISMOTION:
  1839. {
  1840. using namespace JoystickAxisMove;
  1841. SDL_JoystickID joystickID = evt.jaxis.which;
  1842. JoystickState& state = joysticks_[joystickID];
  1843. if (!state.controller_)
  1844. {
  1845. VariantMap& eventData = GetEventDataMap();
  1846. eventData[P_JOYSTICKID] = joystickID;
  1847. eventData[P_AXIS] = evt.jaxis.axis;
  1848. eventData[P_POSITION] = Clamp((float)evt.jaxis.value / 32767.0f, -1.0f, 1.0f);
  1849. if (evt.jaxis.axis < state.axes_.Size())
  1850. {
  1851. // If the joystick is a controller, only use the controller axis mappings
  1852. // (we'll also get the controller event)
  1853. if (!state.controller_)
  1854. state.axes_[evt.jaxis.axis] = eventData[P_POSITION].GetFloat();
  1855. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1856. }
  1857. }
  1858. }
  1859. break;
  1860. case SDL_JOYHATMOTION:
  1861. {
  1862. using namespace JoystickHatMove;
  1863. SDL_JoystickID joystickID = evt.jaxis.which;
  1864. JoystickState& state = joysticks_[joystickID];
  1865. VariantMap& eventData = GetEventDataMap();
  1866. eventData[P_JOYSTICKID] = joystickID;
  1867. eventData[P_HAT] = evt.jhat.hat;
  1868. eventData[P_POSITION] = evt.jhat.value;
  1869. if (evt.jhat.hat < state.hats_.Size())
  1870. {
  1871. state.hats_[evt.jhat.hat] = evt.jhat.value;
  1872. SendEvent(E_JOYSTICKHATMOVE, eventData);
  1873. }
  1874. }
  1875. break;
  1876. case SDL_CONTROLLERBUTTONDOWN:
  1877. {
  1878. using namespace JoystickButtonDown;
  1879. unsigned button = evt.cbutton.button;
  1880. SDL_JoystickID joystickID = evt.cbutton.which;
  1881. JoystickState& state = joysticks_[joystickID];
  1882. VariantMap& eventData = GetEventDataMap();
  1883. eventData[P_JOYSTICKID] = joystickID;
  1884. eventData[P_BUTTON] = button;
  1885. if (button < state.buttons_.Size())
  1886. {
  1887. state.buttons_[button] = true;
  1888. state.buttonPress_[button] = true;
  1889. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1890. }
  1891. }
  1892. break;
  1893. case SDL_CONTROLLERBUTTONUP:
  1894. {
  1895. using namespace JoystickButtonUp;
  1896. unsigned button = evt.cbutton.button;
  1897. SDL_JoystickID joystickID = evt.cbutton.which;
  1898. JoystickState& state = joysticks_[joystickID];
  1899. VariantMap& eventData = GetEventDataMap();
  1900. eventData[P_JOYSTICKID] = joystickID;
  1901. eventData[P_BUTTON] = button;
  1902. if (button < state.buttons_.Size())
  1903. {
  1904. state.buttons_[button] = false;
  1905. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1906. }
  1907. }
  1908. break;
  1909. case SDL_CONTROLLERAXISMOTION:
  1910. {
  1911. using namespace JoystickAxisMove;
  1912. SDL_JoystickID joystickID = evt.caxis.which;
  1913. JoystickState& state = joysticks_[joystickID];
  1914. VariantMap& eventData = GetEventDataMap();
  1915. eventData[P_JOYSTICKID] = joystickID;
  1916. eventData[P_AXIS] = evt.caxis.axis;
  1917. eventData[P_POSITION] = Clamp((float)evt.caxis.value / 32767.0f, -1.0f, 1.0f);
  1918. if (evt.caxis.axis < state.axes_.Size())
  1919. {
  1920. state.axes_[evt.caxis.axis] = eventData[P_POSITION].GetFloat();
  1921. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1922. }
  1923. }
  1924. break;
  1925. case SDL_WINDOWEVENT:
  1926. {
  1927. switch (evt.window.event)
  1928. {
  1929. case SDL_WINDOWEVENT_MINIMIZED:
  1930. minimized_ = true;
  1931. SendInputFocusEvent();
  1932. break;
  1933. case SDL_WINDOWEVENT_MAXIMIZED:
  1934. case SDL_WINDOWEVENT_RESTORED:
  1935. #if defined(IOS) || defined (__ANDROID__)
  1936. // On iOS we never lose the GL context, but may have done GPU object changes that could not be applied yet. Apply them now
  1937. // On Android the old GL context may be lost already, restore GPU objects to the new GL context
  1938. graphics_->Restore();
  1939. #endif
  1940. minimized_ = false;
  1941. SendInputFocusEvent();
  1942. break;
  1943. case SDL_WINDOWEVENT_RESIZED:
  1944. inResize_ = true;
  1945. graphics_->OnWindowResized();
  1946. inResize_ = false;
  1947. break;
  1948. case SDL_WINDOWEVENT_MOVED:
  1949. graphics_->OnWindowMoved();
  1950. break;
  1951. default: break;
  1952. }
  1953. }
  1954. break;
  1955. case SDL_DROPFILE:
  1956. {
  1957. using namespace DropFile;
  1958. VariantMap& eventData = GetEventDataMap();
  1959. eventData[P_FILENAME] = GetInternalPath(String(evt.drop.file));
  1960. SDL_free(evt.drop.file);
  1961. SendEvent(E_DROPFILE, eventData);
  1962. }
  1963. break;
  1964. case SDL_QUIT:
  1965. SendEvent(E_EXITREQUESTED);
  1966. break;
  1967. default: break;
  1968. }
  1969. }
  1970. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1971. {
  1972. if (!initialized_)
  1973. Initialize();
  1974. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  1975. // mouse move event. Also get new window ID if it changed
  1976. SDL_Window* window = graphics_->GetWindow();
  1977. windowID_ = SDL_GetWindowID(window);
  1978. // If screen mode happens due to mouse drag resize, do not recenter the mouse as that would lead to erratic window sizes
  1979. if (!mouseVisible_ && mouseMode_ != MM_FREE && !inResize_)
  1980. {
  1981. CenterMousePosition();
  1982. focusedThisFrame_ = true;
  1983. }
  1984. else
  1985. lastMousePosition_ = GetMousePosition();
  1986. // Resize screen joysticks to new screen size
  1987. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1988. {
  1989. UIElement* screenjoystick = i->second_.screenJoystick_;
  1990. if (screenjoystick)
  1991. screenjoystick->SetSize(graphics_->GetWidth(), graphics_->GetHeight());
  1992. }
  1993. if (graphics_->GetFullscreen())
  1994. focusedThisFrame_ = true;
  1995. // After setting a new screen mode we should not be minimized
  1996. minimized_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0;
  1997. // Remember that screen mode changed in case we lose focus (needed on Linux)
  1998. if (!inResize_)
  1999. screenModeChanged_ = true;
  2000. }
  2001. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  2002. {
  2003. // Update input right at the beginning of the frame
  2004. Update();
  2005. }
  2006. #ifdef __EMSCRIPTEN__
  2007. void Input::HandleEndFrame(StringHash eventType, VariantMap& eventData)
  2008. {
  2009. if (suppressNextMouseMove_ && mouseMove_ != IntVector2::ZERO)
  2010. UnsuppressMouseMove();
  2011. ResetInputAccumulation();
  2012. }
  2013. #endif
  2014. void Input::HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData)
  2015. {
  2016. using namespace TouchBegin;
  2017. // Only interested in events from screen joystick(s)
  2018. TouchState& state = touches_[eventData[P_TOUCHID].GetInt()];
  2019. IntVector2 position(int(state.position_.x_ / GetSubsystem<UI>()->GetScale()), int(state.position_.y_ / GetSubsystem<UI>()->GetScale()));
  2020. UIElement* element = eventType == E_TOUCHBEGIN ? GetSubsystem<UI>()->GetElementAt(position) : state.touchedElement_;
  2021. if (!element)
  2022. return;
  2023. Variant variant = element->GetVar(VAR_SCREEN_JOYSTICK_ID);
  2024. if (variant.IsEmpty())
  2025. return;
  2026. SDL_JoystickID joystickID = variant.GetInt();
  2027. if (eventType == E_TOUCHEND)
  2028. state.touchedElement_.Reset();
  2029. else
  2030. state.touchedElement_ = element;
  2031. // Prepare a fake SDL event
  2032. SDL_Event evt;
  2033. const String& name = element->GetName();
  2034. if (name.StartsWith("Button"))
  2035. {
  2036. if (eventType == E_TOUCHMOVE)
  2037. return;
  2038. // Determine whether to inject a joystick event or keyboard/mouse event
  2039. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  2040. Variant mouseButtonBindingVar = element->GetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING);
  2041. if (keyBindingVar.IsEmpty() && mouseButtonBindingVar.IsEmpty())
  2042. {
  2043. evt.type = eventType == E_TOUCHBEGIN ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
  2044. evt.jbutton.which = joystickID;
  2045. evt.jbutton.button = (Uint8)ToUInt(name.Substring(6));
  2046. }
  2047. else
  2048. {
  2049. if (!keyBindingVar.IsEmpty())
  2050. {
  2051. evt.type = eventType == E_TOUCHBEGIN ? SDL_KEYDOWN : SDL_KEYUP;
  2052. evt.key.keysym.sym = ToLower(keyBindingVar.GetInt());
  2053. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2054. }
  2055. if (!mouseButtonBindingVar.IsEmpty())
  2056. {
  2057. // Mouse button are sent as extra events besides key events
  2058. // Disable touch emulation handling during this to prevent endless loop
  2059. bool oldTouchEmulation = touchEmulation_;
  2060. touchEmulation_ = false;
  2061. SDL_Event mouseEvent;
  2062. mouseEvent.type = eventType == E_TOUCHBEGIN ? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP;
  2063. mouseEvent.button.button = (Uint8)mouseButtonBindingVar.GetInt();
  2064. HandleSDLEvent(&mouseEvent);
  2065. touchEmulation_ = oldTouchEmulation;
  2066. }
  2067. }
  2068. }
  2069. else if (name.StartsWith("Hat"))
  2070. {
  2071. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  2072. if (keyBindingVar.IsEmpty())
  2073. {
  2074. evt.type = SDL_JOYHATMOTION;
  2075. evt.jaxis.which = joystickID;
  2076. evt.jhat.hat = (Uint8)ToUInt(name.Substring(3));
  2077. evt.jhat.value = HAT_CENTER;
  2078. if (eventType != E_TOUCHEND)
  2079. {
  2080. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  2081. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2082. evt.jhat.value |= HAT_UP;
  2083. if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2084. evt.jhat.value |= HAT_DOWN;
  2085. if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2086. evt.jhat.value |= HAT_LEFT;
  2087. if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2088. evt.jhat.value |= HAT_RIGHT;
  2089. }
  2090. }
  2091. else
  2092. {
  2093. // Hat is binded by 4 integers representing keysyms for 'w', 's', 'a', 'd' or something similar
  2094. IntRect keyBinding = keyBindingVar.GetIntRect();
  2095. if (eventType == E_TOUCHEND)
  2096. {
  2097. evt.type = SDL_KEYUP;
  2098. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  2099. if (!evt.key.keysym.sym)
  2100. return;
  2101. element->SetVar(VAR_LAST_KEYSYM, 0);
  2102. }
  2103. else
  2104. {
  2105. evt.type = SDL_KEYDOWN;
  2106. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  2107. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2108. evt.key.keysym.sym = keyBinding.left_; // The integers are encoded in WSAD order to l-t-r-b
  2109. else if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2110. evt.key.keysym.sym = keyBinding.top_;
  2111. else if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2112. evt.key.keysym.sym = keyBinding.right_;
  2113. else if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2114. evt.key.keysym.sym = keyBinding.bottom_;
  2115. else
  2116. return;
  2117. if (eventType == E_TOUCHMOVE && evt.key.keysym.sym != element->GetVar(VAR_LAST_KEYSYM).GetInt())
  2118. {
  2119. // Dragging past the directional boundary will cause an additional key up event for previous key symbol
  2120. SDL_Event keyEvent;
  2121. keyEvent.type = SDL_KEYUP;
  2122. keyEvent.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  2123. if (keyEvent.key.keysym.sym)
  2124. {
  2125. keyEvent.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2126. HandleSDLEvent(&keyEvent);
  2127. }
  2128. element->SetVar(VAR_LAST_KEYSYM, 0);
  2129. }
  2130. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2131. element->SetVar(VAR_LAST_KEYSYM, evt.key.keysym.sym);
  2132. }
  2133. }
  2134. }
  2135. else
  2136. return;
  2137. // Handle the fake SDL event to turn it into Urho3D genuine event
  2138. HandleSDLEvent(&evt);
  2139. }
  2140. }