Input.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. //
  2. // Copyright (c) 2008-2014 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 "Context.h"
  24. #include "CoreEvents.h"
  25. #include "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "GraphicsEvents.h"
  28. #include "GraphicsImpl.h"
  29. #include "Input.h"
  30. #include "Log.h"
  31. #include "Mutex.h"
  32. #include "ProcessUtils.h"
  33. #include "Profiler.h"
  34. #include "ResourceCache.h"
  35. #include "RWOpsWrapper.h"
  36. #include "StringUtils.h"
  37. #include "Text.h"
  38. #include "UI.h"
  39. #include <cstring>
  40. #include <SDL.h>
  41. #include "DebugNew.h"
  42. extern "C" int SDL_AddTouch(SDL_TouchID touchID, const char *name);
  43. // Require a click inside window before re-hiding mouse cursor on OSX, otherwise dragging the window
  44. // can be incorrectly interpreted as mouse movement inside the window
  45. #if defined(__APPLE__) && !defined(IOS)
  46. #define REQUIRE_CLICK_TO_FOCUS
  47. #endif
  48. namespace Urho3D
  49. {
  50. const int SCREEN_JOYSTICK_START_ID = 0x40000000;
  51. const ShortStringHash VAR_BUTTON_KEY_BINDING("VAR_BUTTON_KEY_BINDING");
  52. const ShortStringHash VAR_BUTTON_MOUSE_BUTTON_BINDING("VAR_BUTTON_MOUSE_BUTTON_BINDING");
  53. const ShortStringHash VAR_LAST_KEYSYM("VAR_LAST_KEYSYM");
  54. const ShortStringHash VAR_SCREEN_JOYSTICK_ID("VAR_SCREEN_JOYSTICK_ID");
  55. /// Convert SDL keycode if necessary.
  56. int ConvertSDLKeyCode(int keySym, int scanCode)
  57. {
  58. if (scanCode == SCANCODE_AC_BACK)
  59. return KEY_ESC;
  60. else
  61. return SDL_toupper(keySym);
  62. }
  63. void JoystickState::Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats)
  64. {
  65. buttons_.Resize(numButtons);
  66. buttonPress_.Resize(numButtons);
  67. axes_.Resize(numAxes);
  68. hats_.Resize(numHats);
  69. Reset();
  70. }
  71. void JoystickState::Reset()
  72. {
  73. for (unsigned i = 0; i < buttons_.Size(); ++i)
  74. {
  75. buttons_[i] = false;
  76. buttonPress_[i] = false;
  77. }
  78. for (unsigned i = 0; i < axes_.Size(); ++i)
  79. axes_[i] = 0.0f;
  80. for (unsigned i = 0; i < hats_.Size(); ++i)
  81. hats_[i] = HAT_CENTER;
  82. }
  83. Input::Input(Context* context) :
  84. Object(context),
  85. mouseButtonDown_(0),
  86. mouseButtonPress_(0),
  87. mouseMoveWheel_(0),
  88. windowID_(0),
  89. toggleFullscreen_(true),
  90. mouseVisible_(false),
  91. mouseGrabbed_(false),
  92. touchEmulation_(false),
  93. inputFocus_(false),
  94. minimized_(false),
  95. focusedThisFrame_(false),
  96. suppressNextMouseMove_(false),
  97. initialized_(false)
  98. {
  99. SubscribeToEvent(E_SCREENMODE, HANDLER(Input, HandleScreenMode));
  100. // Try to initialize right now, but skip if screen mode is not yet set
  101. Initialize();
  102. }
  103. Input::~Input()
  104. {
  105. }
  106. void Input::Update()
  107. {
  108. assert(initialized_);
  109. PROFILE(UpdateInput);
  110. // Reset input accumulation for this frame
  111. keyPress_.Clear();
  112. scancodePress_.Clear();
  113. mouseButtonPress_ = 0;
  114. mouseMove_ = IntVector2::ZERO;
  115. mouseMoveWheel_ = 0;
  116. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  117. {
  118. for (unsigned j = 0; j < i->second_.buttonPress_.Size(); ++j)
  119. i->second_.buttonPress_[j] = false;
  120. }
  121. // Reset touch delta movement
  122. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  123. {
  124. TouchState& state = i->second_;
  125. state.lastPosition_ = state.position_;
  126. state.delta_ = IntVector2::ZERO;
  127. }
  128. // Check and handle SDL events
  129. SDL_PumpEvents();
  130. SDL_Event evt;
  131. while (SDL_PeepEvents(&evt, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) > 0)
  132. HandleSDLEvent(&evt);
  133. // Check for activation and inactivation from SDL window flags. Must nullcheck the window pointer because it may have
  134. // been closed due to input events
  135. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  136. unsigned flags = window ? SDL_GetWindowFlags(window) & (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS) : 0;
  137. if (window)
  138. {
  139. #ifdef REQUIRE_CLICK_TO_FOCUS
  140. if (!inputFocus_ && (graphics_->GetFullscreen() || mouseVisible_) && flags == (SDL_WINDOW_INPUT_FOCUS |
  141. SDL_WINDOW_MOUSE_FOCUS))
  142. #else
  143. if (!inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS))
  144. #endif
  145. focusedThisFrame_ = true;
  146. if (focusedThisFrame_)
  147. GainFocus();
  148. if (inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  149. LoseFocus();
  150. }
  151. else
  152. return;
  153. // Check for relative mode mouse move
  154. if (!touchEmulation_ && (graphics_->GetExternalWindow() || (!mouseVisible_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  155. {
  156. IntVector2 mousePosition = GetMousePosition();
  157. mouseMove_ = mousePosition - lastMousePosition_;
  158. if (graphics_->GetExternalWindow())
  159. lastMousePosition_ = mousePosition;
  160. else
  161. {
  162. // Recenter the mouse cursor manually after move
  163. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  164. if (mousePosition != center)
  165. {
  166. SetMousePosition(center);
  167. lastMousePosition_ = center;
  168. }
  169. }
  170. // Send mouse move event if necessary
  171. if (mouseMove_ != IntVector2::ZERO)
  172. {
  173. if (suppressNextMouseMove_)
  174. {
  175. mouseMove_ = IntVector2::ZERO;
  176. suppressNextMouseMove_ = false;
  177. }
  178. else
  179. {
  180. using namespace MouseMove;
  181. VariantMap& eventData = GetEventDataMap();
  182. if (mouseVisible_)
  183. {
  184. eventData[P_X] = mousePosition.x_;
  185. eventData[P_Y] = mousePosition.y_;
  186. }
  187. eventData[P_DX] = mouseMove_.x_;
  188. eventData[P_DY] = mouseMove_.y_;
  189. eventData[P_BUTTONS] = mouseButtonDown_;
  190. eventData[P_QUALIFIERS] = GetQualifiers();
  191. SendEvent(E_MOUSEMOVE, eventData);
  192. }
  193. }
  194. }
  195. }
  196. void Input::SetMouseVisible(bool enable)
  197. {
  198. // In touch emulation mode only enabled mouse is allowed
  199. if (touchEmulation_)
  200. enable = true;
  201. // SDL Raspberry Pi "video driver" does not have proper OS mouse support yet, so no-op for now
  202. #ifndef RASPI
  203. if (enable != mouseVisible_)
  204. {
  205. mouseVisible_ = enable;
  206. if (initialized_)
  207. {
  208. // External windows can only support visible mouse cursor
  209. if (graphics_->GetExternalWindow())
  210. {
  211. mouseVisible_ = true;
  212. return;
  213. }
  214. if (!mouseVisible_ && inputFocus_)
  215. {
  216. SDL_ShowCursor(SDL_FALSE);
  217. // Recenter the mouse cursor manually when hiding it to avoid erratic mouse move for one frame
  218. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  219. SetMousePosition(center);
  220. lastMousePosition_ = center;
  221. }
  222. else
  223. SDL_ShowCursor(SDL_TRUE);
  224. }
  225. using namespace MouseVisibleChanged;
  226. VariantMap& eventData = GetEventDataMap();
  227. eventData[P_VISIBLE] = mouseVisible_;
  228. SendEvent(E_MOUSEVISIBLECHANGED, eventData);
  229. }
  230. #endif
  231. }
  232. void Input::SetMouseGrabbed(bool grab)
  233. {
  234. mouseGrabbed_ = grab;
  235. }
  236. void Input::SetToggleFullscreen(bool enable)
  237. {
  238. toggleFullscreen_ = enable;
  239. }
  240. static void PopulateKeyBindingMap(HashMap<String, int>& keyBindingMap)
  241. {
  242. if (keyBindingMap.Empty())
  243. {
  244. keyBindingMap.Insert(MakePair<String, int>("SPACE", KEY_SPACE));
  245. keyBindingMap.Insert(MakePair<String, int>("LCTRL", KEY_LCTRL));
  246. keyBindingMap.Insert(MakePair<String, int>("RCTRL", KEY_RCTRL));
  247. keyBindingMap.Insert(MakePair<String, int>("LSHIFT", KEY_LSHIFT));
  248. keyBindingMap.Insert(MakePair<String, int>("RSHIFT", KEY_RSHIFT));
  249. keyBindingMap.Insert(MakePair<String, int>("LALT", KEY_LALT));
  250. keyBindingMap.Insert(MakePair<String, int>("RALT", KEY_RALT));
  251. keyBindingMap.Insert(MakePair<String, int>("LGUI", KEY_LGUI));
  252. keyBindingMap.Insert(MakePair<String, int>("RGUI", KEY_RGUI));
  253. keyBindingMap.Insert(MakePair<String, int>("TAB", KEY_TAB));
  254. keyBindingMap.Insert(MakePair<String, int>("RETURN", KEY_RETURN));
  255. keyBindingMap.Insert(MakePair<String, int>("RETURN2", KEY_RETURN2));
  256. keyBindingMap.Insert(MakePair<String, int>("ENTER", KEY_KP_ENTER));
  257. keyBindingMap.Insert(MakePair<String, int>("SELECT", KEY_SELECT));
  258. keyBindingMap.Insert(MakePair<String, int>("LEFT", KEY_LEFT));
  259. keyBindingMap.Insert(MakePair<String, int>("RIGHT", KEY_RIGHT));
  260. keyBindingMap.Insert(MakePair<String, int>("UP", KEY_UP));
  261. keyBindingMap.Insert(MakePair<String, int>("DOWN", KEY_DOWN));
  262. keyBindingMap.Insert(MakePair<String, int>("PAGEUP", KEY_PAGEUP));
  263. keyBindingMap.Insert(MakePair<String, int>("PAGEDOWN", KEY_PAGEDOWN));
  264. keyBindingMap.Insert(MakePair<String, int>("F1", KEY_F1));
  265. keyBindingMap.Insert(MakePair<String, int>("F2", KEY_F2));
  266. keyBindingMap.Insert(MakePair<String, int>("F3", KEY_F3));
  267. keyBindingMap.Insert(MakePair<String, int>("F4", KEY_F4));
  268. keyBindingMap.Insert(MakePair<String, int>("F5", KEY_F5));
  269. keyBindingMap.Insert(MakePair<String, int>("F6", KEY_F6));
  270. keyBindingMap.Insert(MakePair<String, int>("F7", KEY_F7));
  271. keyBindingMap.Insert(MakePair<String, int>("F8", KEY_F8));
  272. keyBindingMap.Insert(MakePair<String, int>("F9", KEY_F9));
  273. keyBindingMap.Insert(MakePair<String, int>("F10", KEY_F10));
  274. keyBindingMap.Insert(MakePair<String, int>("F11", KEY_F11));
  275. keyBindingMap.Insert(MakePair<String, int>("F12", KEY_F12));
  276. }
  277. }
  278. static void PopulateMouseButtonBindingMap(HashMap<String, int>& mouseButtonBindingMap)
  279. {
  280. if (mouseButtonBindingMap.Empty())
  281. {
  282. mouseButtonBindingMap.Insert(MakePair<String, int>("LEFT", SDL_BUTTON_LEFT));
  283. mouseButtonBindingMap.Insert(MakePair<String, int>("MIDDLE", SDL_BUTTON_MIDDLE));
  284. mouseButtonBindingMap.Insert(MakePair<String, int>("RIGHT", SDL_BUTTON_RIGHT));
  285. mouseButtonBindingMap.Insert(MakePair<String, int>("X1", SDL_BUTTON_X1));
  286. mouseButtonBindingMap.Insert(MakePair<String, int>("X2", SDL_BUTTON_X2));
  287. }
  288. }
  289. SDL_JoystickID Input::AddScreenJoystick(XMLFile* layoutFile, XMLFile* styleFile)
  290. {
  291. static HashMap<String, int> keyBindingMap;
  292. static HashMap<String, int> mouseButtonBindingMap;
  293. if (!graphics_)
  294. {
  295. LOGWARNING("Cannot add screen joystick in headless mode");
  296. return -1;
  297. }
  298. // If layout file is not given, use the default screen joystick layout
  299. if (!layoutFile)
  300. {
  301. ResourceCache* cache = GetSubsystem<ResourceCache>();
  302. layoutFile = cache->GetResource<XMLFile>("UI/ScreenJoystick.xml");
  303. if (!layoutFile) // Error is already logged
  304. return -1;
  305. }
  306. UI* ui = GetSubsystem<UI>();
  307. SharedPtr<UIElement> screenJoystick = ui->LoadLayout(layoutFile, styleFile);
  308. if (!screenJoystick) // Error is already logged
  309. return -1;
  310. screenJoystick->SetSize(ui->GetRoot()->GetSize());
  311. ui->GetRoot()->AddChild(screenJoystick);
  312. // Get an unused ID for the screen joystick
  313. /// \todo After a real joystick has been plugged in 1073741824 times, the ranges will overlap
  314. SDL_JoystickID joystickID = SCREEN_JOYSTICK_START_ID;
  315. while (joysticks_.Contains(joystickID))
  316. ++joystickID;
  317. JoystickState& state = joysticks_[joystickID];
  318. state.joystickID_ = joystickID;
  319. state.name_ = screenJoystick->GetName();
  320. state.screenJoystick_ = screenJoystick;
  321. unsigned numButtons = 0;
  322. unsigned numAxes = 0;
  323. unsigned numHats = 0;
  324. const Vector<SharedPtr<UIElement> >& children = state.screenJoystick_->GetChildren();
  325. for (Vector<SharedPtr<UIElement> >::ConstIterator iter = children.Begin(); iter != children.End(); ++iter)
  326. {
  327. UIElement* element = iter->Get();
  328. String name = element->GetName();
  329. if (name.StartsWith("Button"))
  330. {
  331. ++numButtons;
  332. // Check whether the button has key binding
  333. Text* text = dynamic_cast<Text*>(element->GetChild("KeyBinding", false));
  334. if (text)
  335. {
  336. text->SetVisible(false);
  337. const String& key = text->GetText();
  338. int keyBinding;
  339. if (key.Length() == 1)
  340. keyBinding = key[0];
  341. else
  342. {
  343. PopulateKeyBindingMap(keyBindingMap);
  344. HashMap<String, int>::Iterator i = keyBindingMap.Find(key);
  345. if (i != keyBindingMap.End())
  346. keyBinding = i->second_;
  347. else
  348. {
  349. LOGERRORF("Unsupported key binding: %s", key.CString());
  350. keyBinding = M_MAX_INT;
  351. }
  352. }
  353. if (keyBinding != M_MAX_INT)
  354. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  355. }
  356. // Check whether the button has mouse button binding
  357. text = dynamic_cast<Text*>(element->GetChild("MouseButtonBinding", false));
  358. if (text)
  359. {
  360. text->SetVisible(false);
  361. const String& mouseButton = text->GetText();
  362. PopulateMouseButtonBindingMap(mouseButtonBindingMap);
  363. HashMap<String, int>::Iterator i = mouseButtonBindingMap.Find(mouseButton);
  364. if (i != mouseButtonBindingMap.End())
  365. element->SetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING, i->second_);
  366. else
  367. LOGERRORF("Unsupported mouse button binding: %s", mouseButton.CString());
  368. }
  369. }
  370. else if (name.StartsWith("Axis"))
  371. {
  372. ++numAxes;
  373. ///\todo Axis emulation for screen joystick is not fully supported yet.
  374. LOGWARNING("Axis emulation for screen joystick is not fully supported yet");
  375. }
  376. else if (name.StartsWith("Hat"))
  377. {
  378. ++numHats;
  379. Text* text = dynamic_cast<Text*>(element->GetChild("KeyBinding", false));
  380. if (text)
  381. {
  382. text->SetVisible(false);
  383. String keyBinding = text->GetText();
  384. if (keyBinding.Contains(' ')) // e.g.: "UP DOWN LEFT RIGHT"
  385. {
  386. // Attempt to split the text using ' ' as separator
  387. Vector<String>keyBindings(keyBinding.Split(' '));
  388. String mappedKeyBinding;
  389. if (keyBindings.Size() == 4)
  390. {
  391. PopulateKeyBindingMap(keyBindingMap);
  392. for (unsigned j = 0; j < 4; ++j)
  393. {
  394. if (keyBindings[j].Length() == 1)
  395. mappedKeyBinding.Append(keyBindings[j][0]);
  396. else
  397. {
  398. HashMap<String, int>::Iterator i = keyBindingMap.Find(keyBindings[j]);
  399. if (i != keyBindingMap.End())
  400. mappedKeyBinding.Append(i->second_);
  401. else
  402. break;
  403. }
  404. }
  405. }
  406. if (mappedKeyBinding.Length() != 4)
  407. {
  408. LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  409. keyBinding = "WSAD";
  410. }
  411. else
  412. keyBinding = mappedKeyBinding;
  413. }
  414. else if (keyBinding.Length() != 4)
  415. {
  416. LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  417. keyBinding = "WSAD";
  418. }
  419. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  420. }
  421. }
  422. element->SetVar(VAR_SCREEN_JOYSTICK_ID, joystickID);
  423. }
  424. // Make sure all the children are non-focusable so they do not mistakenly to be considered as active UI input controls by application
  425. PODVector<UIElement*> allChildren;
  426. state.screenJoystick_->GetChildren(allChildren, true);
  427. for (PODVector<UIElement*>::Iterator iter = allChildren.Begin(); iter != allChildren.End(); ++iter)
  428. (*iter)->SetFocusMode(FM_NOTFOCUSABLE);
  429. state.Initialize(numButtons, numAxes, numHats);
  430. // There could be potentially more than one screen joystick, however they all will be handled by a same handler method
  431. // So there is no harm to replace the old handler with the new handler in each call to SubscribeToEvent()
  432. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(Input, HandleScreenJoystickTouch));
  433. SubscribeToEvent(E_TOUCHMOVE, HANDLER(Input, HandleScreenJoystickTouch));
  434. SubscribeToEvent(E_TOUCHEND, HANDLER(Input, HandleScreenJoystickTouch));
  435. return joystickID;
  436. }
  437. bool Input::RemoveScreenJoystick(SDL_JoystickID id)
  438. {
  439. if (!joysticks_.Contains(id))
  440. {
  441. LOGERRORF("Failed to remove non-existing screen joystick ID #%d", id);
  442. return false;
  443. }
  444. JoystickState& state = joysticks_[id];
  445. if (!state.screenJoystick_)
  446. {
  447. LOGERRORF("Failed to remove joystick with ID #%d which is not a screen joystick", id);
  448. return false;
  449. }
  450. state.screenJoystick_->Remove();
  451. joysticks_.Erase(id);
  452. return true;
  453. }
  454. void Input::SetScreenJoystickVisible(SDL_JoystickID id, bool enable)
  455. {
  456. if (joysticks_.Contains(id))
  457. {
  458. JoystickState& state = joysticks_[id];
  459. if (state.screenJoystick_)
  460. state.screenJoystick_->SetVisible(enable);
  461. }
  462. }
  463. void Input::SetScreenKeyboardVisible(bool enable)
  464. {
  465. if (!graphics_)
  466. return;
  467. if (enable != IsScreenKeyboardVisible())
  468. {
  469. if (enable)
  470. SDL_StartTextInput();
  471. else
  472. SDL_StopTextInput();
  473. }
  474. }
  475. void Input::SetTouchEmulation(bool enable)
  476. {
  477. #if !defined(ANDROID) && !defined(IOS)
  478. if (enable != touchEmulation_)
  479. {
  480. // Touch emulation needs the mouse visible
  481. if (enable)
  482. {
  483. if (!mouseVisible_)
  484. SetMouseVisible(true);
  485. // Add a virtual touch device the first time we are enabling emulated touch
  486. if (enable && !SDL_GetNumTouchDevices())
  487. SDL_AddTouch(0, "Emulated Touch");
  488. }
  489. else
  490. ResetTouches();
  491. touchEmulation_ = enable;
  492. }
  493. #endif
  494. }
  495. bool Input::RecordGesture()
  496. {
  497. // If have no touch devices, fail
  498. if (!SDL_GetNumTouchDevices())
  499. {
  500. LOGERROR("Can not record gesture: no touch devices");
  501. return false;
  502. }
  503. return SDL_RecordGesture(-1);
  504. }
  505. bool Input::SaveGestures(Serializer& dest)
  506. {
  507. RWOpsWrapper<Serializer> wrapper(dest);
  508. return SDL_SaveAllDollarTemplates(wrapper.GetRWOps());
  509. }
  510. bool Input::SaveGesture(Serializer& dest, unsigned gestureID)
  511. {
  512. RWOpsWrapper<Serializer> wrapper(dest);
  513. return SDL_SaveDollarTemplate(gestureID, wrapper.GetRWOps());
  514. }
  515. unsigned Input::LoadGestures(Deserializer& source)
  516. {
  517. // If have no touch devices, fail
  518. if (!SDL_GetNumTouchDevices())
  519. {
  520. LOGERROR("Can not load gestures: no touch devices");
  521. return 0;
  522. }
  523. RWOpsWrapper<Deserializer> wrapper(source);
  524. return SDL_LoadDollarTemplates(-1, wrapper.GetRWOps());
  525. }
  526. SDL_JoystickID Input::OpenJoystick(unsigned index)
  527. {
  528. SDL_Joystick* joystick = SDL_JoystickOpen(index);
  529. if (!joystick)
  530. {
  531. LOGERRORF("Cannot open joystick #%d", index);
  532. return -1;
  533. }
  534. // Create joystick state for the new joystick
  535. int joystickID = SDL_JoystickInstanceID(joystick);
  536. JoystickState& state = joysticks_[joystickID];
  537. state.joystick_ = joystick;
  538. state.joystickID_ = joystickID;
  539. state.name_ = SDL_JoystickName(joystick);
  540. if (SDL_IsGameController(index))
  541. state.controller_ = SDL_GameControllerOpen(index);
  542. unsigned numButtons = SDL_JoystickNumButtons(joystick);
  543. unsigned numAxes = SDL_JoystickNumAxes(joystick);
  544. unsigned numHats = SDL_JoystickNumHats(joystick);
  545. // When the joystick is a controller, make sure there's enough axes & buttons for the standard controller mappings
  546. if (state.controller_)
  547. {
  548. if (numButtons < SDL_CONTROLLER_BUTTON_MAX)
  549. numButtons = SDL_CONTROLLER_BUTTON_MAX;
  550. if (numAxes < SDL_CONTROLLER_AXIS_MAX)
  551. numAxes = SDL_CONTROLLER_AXIS_MAX;
  552. }
  553. state.Initialize(numButtons, numAxes, numHats);
  554. return joystickID;
  555. }
  556. int Input::GetKeyFromName(const String& name) const
  557. {
  558. return SDL_GetKeyFromName(name.CString());
  559. }
  560. int Input::GetKeyFromScancode(int scancode) const
  561. {
  562. return SDL_GetKeyFromScancode((SDL_Scancode)scancode);
  563. }
  564. String Input::GetKeyName(int key) const
  565. {
  566. return String(SDL_GetKeyName(key));
  567. }
  568. int Input::GetScancodeFromKey(int key) const
  569. {
  570. return SDL_GetScancodeFromKey(key);
  571. }
  572. int Input::GetScancodeFromName(const String& name) const
  573. {
  574. return SDL_GetScancodeFromName(name.CString());
  575. }
  576. String Input::GetScancodeName(int scancode) const
  577. {
  578. return SDL_GetScancodeName((SDL_Scancode)scancode);
  579. }
  580. bool Input::GetKeyDown(int key) const
  581. {
  582. return keyDown_.Contains(SDL_toupper(key));
  583. }
  584. bool Input::GetKeyPress(int key) const
  585. {
  586. return keyPress_.Contains(SDL_toupper(key));
  587. }
  588. bool Input::GetScancodeDown(int scancode) const
  589. {
  590. return scancodeDown_.Contains(scancode);
  591. }
  592. bool Input::GetScancodePress(int scancode) const
  593. {
  594. return scancodePress_.Contains(scancode);
  595. }
  596. bool Input::GetMouseButtonDown(int button) const
  597. {
  598. return (mouseButtonDown_ & button) != 0;
  599. }
  600. bool Input::GetMouseButtonPress(int button) const
  601. {
  602. return (mouseButtonPress_ & button) != 0;
  603. }
  604. bool Input::GetQualifierDown(int qualifier) const
  605. {
  606. if (qualifier == QUAL_SHIFT)
  607. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  608. if (qualifier == QUAL_CTRL)
  609. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  610. if (qualifier == QUAL_ALT)
  611. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  612. return false;
  613. }
  614. bool Input::GetQualifierPress(int qualifier) const
  615. {
  616. if (qualifier == QUAL_SHIFT)
  617. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  618. if (qualifier == QUAL_CTRL)
  619. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  620. if (qualifier == QUAL_ALT)
  621. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  622. return false;
  623. }
  624. int Input::GetQualifiers() const
  625. {
  626. int ret = 0;
  627. if (GetQualifierDown(QUAL_SHIFT))
  628. ret |= QUAL_SHIFT;
  629. if (GetQualifierDown(QUAL_CTRL))
  630. ret |= QUAL_CTRL;
  631. if (GetQualifierDown(QUAL_ALT))
  632. ret |= QUAL_ALT;
  633. return ret;
  634. }
  635. IntVector2 Input::GetMousePosition() const
  636. {
  637. IntVector2 ret = IntVector2::ZERO;
  638. if (!initialized_)
  639. return ret;
  640. SDL_GetMouseState(&ret.x_, &ret.y_);
  641. return ret;
  642. }
  643. TouchState* Input::GetTouch(unsigned index) const
  644. {
  645. if (index >= touches_.Size())
  646. return 0;
  647. HashMap<int, TouchState>::ConstIterator i = touches_.Begin();
  648. while (index--)
  649. ++i;
  650. return const_cast<TouchState*>(&i->second_);
  651. }
  652. JoystickState* Input::GetJoystickByIndex(unsigned index)
  653. {
  654. unsigned compare = 0;
  655. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  656. {
  657. if (compare++ == index)
  658. return &(i->second_);
  659. }
  660. return 0;
  661. }
  662. JoystickState* Input::GetJoystick(SDL_JoystickID id)
  663. {
  664. HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Find(id);
  665. return i != joysticks_.End() ? &(i->second_) : 0;
  666. }
  667. bool Input::IsScreenJoystickVisible(SDL_JoystickID id) const
  668. {
  669. HashMap<SDL_JoystickID, JoystickState>::ConstIterator i = joysticks_.Find(id);
  670. return i != joysticks_.End() && i->second_.screenJoystick_ && i->second_.screenJoystick_->IsVisible();
  671. }
  672. bool Input::GetScreenKeyboardSupport() const
  673. {
  674. return graphics_ ? SDL_HasScreenKeyboardSupport() : false;
  675. }
  676. bool Input::IsScreenKeyboardVisible() const
  677. {
  678. if (graphics_)
  679. {
  680. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  681. return SDL_IsScreenKeyboardShown(window);
  682. }
  683. else
  684. return false;
  685. }
  686. bool Input::IsMinimized() const
  687. {
  688. // Return minimized state also when unfocused in fullscreen
  689. if (!inputFocus_ && graphics_ && graphics_->GetFullscreen())
  690. return true;
  691. else
  692. return minimized_;
  693. }
  694. void Input::Initialize()
  695. {
  696. Graphics* graphics = GetSubsystem<Graphics>();
  697. if (!graphics || !graphics->IsInitialized())
  698. return;
  699. graphics_ = graphics;
  700. // In external window mode only visible mouse is supported
  701. if (graphics_->GetExternalWindow())
  702. mouseVisible_ = true;
  703. // Set the initial activation
  704. focusedThisFrame_ = true;
  705. initialized_ = true;
  706. ResetJoysticks();
  707. ResetState();
  708. SubscribeToEvent(E_BEGINFRAME, HANDLER(Input, HandleBeginFrame));
  709. LOGINFO("Initialized input");
  710. }
  711. void Input::ResetJoysticks()
  712. {
  713. joysticks_.Clear();
  714. // Open each detected joystick automatically on startup
  715. int size = SDL_NumJoysticks();
  716. for (int i = 0; i < size; ++i)
  717. OpenJoystick(i);
  718. }
  719. void Input::GainFocus()
  720. {
  721. ResetState();
  722. inputFocus_ = true;
  723. focusedThisFrame_ = false;
  724. // Re-establish mouse cursor hiding as necessary
  725. if (!mouseVisible_)
  726. {
  727. SDL_ShowCursor(SDL_FALSE);
  728. suppressNextMouseMove_ = true;
  729. }
  730. else
  731. lastMousePosition_ = GetMousePosition();
  732. SendInputFocusEvent();
  733. }
  734. void Input::LoseFocus()
  735. {
  736. ResetState();
  737. inputFocus_ = false;
  738. focusedThisFrame_ = false;
  739. // Show the mouse cursor when inactive
  740. SDL_ShowCursor(SDL_TRUE);
  741. SendInputFocusEvent();
  742. }
  743. void Input::ResetState()
  744. {
  745. keyDown_.Clear();
  746. keyPress_.Clear();
  747. scancodeDown_.Clear();
  748. scancodePress_.Clear();
  749. /// \todo Check if resetting joystick state on input focus loss is even necessary
  750. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  751. i->second_.Reset();
  752. ResetTouches();
  753. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  754. SetMouseButton(MOUSEB_LEFT, false);
  755. SetMouseButton(MOUSEB_RIGHT, false);
  756. SetMouseButton(MOUSEB_MIDDLE, false);
  757. mouseMove_ = IntVector2::ZERO;
  758. mouseMoveWheel_ = 0;
  759. mouseButtonPress_ = 0;
  760. }
  761. void Input::ResetTouches()
  762. {
  763. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  764. {
  765. TouchState& state = i->second_;
  766. using namespace TouchEnd;
  767. VariantMap& eventData = GetEventDataMap();
  768. eventData[P_TOUCHID] = state.touchID_;
  769. eventData[P_X] = state.position_.x_;
  770. eventData[P_Y] = state.position_.y_;
  771. SendEvent(E_TOUCHEND, eventData);
  772. }
  773. touches_.Clear();
  774. }
  775. void Input::SendInputFocusEvent()
  776. {
  777. using namespace InputFocus;
  778. VariantMap& eventData = GetEventDataMap();
  779. eventData[P_FOCUS] = HasFocus();
  780. eventData[P_MINIMIZED] = IsMinimized();
  781. SendEvent(E_INPUTFOCUS, eventData);
  782. }
  783. void Input::SetMouseButton(int button, bool newState)
  784. {
  785. #ifdef REQUIRE_CLICK_TO_FOCUS
  786. if (!mouseVisible_ && !graphics_->GetFullscreen())
  787. {
  788. if (!inputFocus_ && newState && button == MOUSEB_LEFT)
  789. focusedThisFrame_ = true;
  790. }
  791. #endif
  792. // If we do not have focus yet, do not react to the mouse button down
  793. if (!graphics_->GetExternalWindow() && newState && !inputFocus_)
  794. return;
  795. if (newState)
  796. {
  797. if (!(mouseButtonDown_ & button))
  798. mouseButtonPress_ |= button;
  799. mouseButtonDown_ |= button;
  800. }
  801. else
  802. {
  803. if (!(mouseButtonDown_ & button))
  804. return;
  805. mouseButtonDown_ &= ~button;
  806. }
  807. using namespace MouseButtonDown;
  808. VariantMap& eventData = GetEventDataMap();
  809. eventData[P_BUTTON] = button;
  810. eventData[P_BUTTONS] = mouseButtonDown_;
  811. eventData[P_QUALIFIERS] = GetQualifiers();
  812. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  813. }
  814. void Input::SetKey(int key, int scancode, unsigned raw, bool newState)
  815. {
  816. // If we do not have focus yet, do not react to the key down
  817. if (!graphics_->GetExternalWindow() && newState && !inputFocus_)
  818. return;
  819. bool repeat = false;
  820. if (newState)
  821. {
  822. scancodeDown_.Insert(scancode);
  823. scancodePress_.Insert(scancode);
  824. if (!keyDown_.Contains(key))
  825. {
  826. keyDown_.Insert(key);
  827. keyPress_.Insert(key);
  828. }
  829. else
  830. repeat = true;
  831. }
  832. else
  833. {
  834. scancodeDown_.Erase(scancode);
  835. if (!keyDown_.Erase(key))
  836. return;
  837. }
  838. using namespace KeyDown;
  839. VariantMap& eventData = GetEventDataMap();
  840. eventData[P_KEY] = key;
  841. eventData[P_SCANCODE] = scancode;
  842. eventData[P_RAW] = raw;
  843. eventData[P_BUTTONS] = mouseButtonDown_;
  844. eventData[P_QUALIFIERS] = GetQualifiers();
  845. if (newState)
  846. eventData[P_REPEAT] = repeat;
  847. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  848. if ((key == KEY_RETURN || key == KEY_RETURN2 || key == KEY_KP_ENTER) && newState && !repeat && toggleFullscreen_ &&
  849. (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  850. graphics_->ToggleFullscreen();
  851. }
  852. void Input::SetMouseWheel(int delta)
  853. {
  854. // If we do not have focus yet, do not react to the wheel
  855. if (!graphics_->GetExternalWindow() && !inputFocus_)
  856. return;
  857. if (delta)
  858. {
  859. mouseMoveWheel_ += delta;
  860. using namespace MouseWheel;
  861. VariantMap& eventData = GetEventDataMap();
  862. eventData[P_WHEEL] = delta;
  863. eventData[P_BUTTONS] = mouseButtonDown_;
  864. eventData[P_QUALIFIERS] = GetQualifiers();
  865. SendEvent(E_MOUSEWHEEL, eventData);
  866. }
  867. }
  868. void Input::SetMousePosition(const IntVector2& position)
  869. {
  870. if (!graphics_)
  871. return;
  872. SDL_WarpMouseInWindow(graphics_->GetImpl()->GetWindow(), position.x_, position.y_);
  873. }
  874. void Input::HandleSDLEvent(void* sdlEvent)
  875. {
  876. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  877. switch (evt.type)
  878. {
  879. case SDL_KEYDOWN:
  880. // Convert to uppercase to match Win32 virtual key codes
  881. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, evt.key.keysym.raw, true);
  882. break;
  883. case SDL_KEYUP:
  884. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, evt.key.keysym.raw, false);
  885. break;
  886. case SDL_TEXTINPUT:
  887. {
  888. textInput_ = &evt.text.text[0];
  889. unsigned unicode = textInput_.AtUTF8(0);
  890. if (unicode)
  891. {
  892. using namespace TextInput;
  893. VariantMap textInputEventData;
  894. textInputEventData[P_TEXT] = textInput_;
  895. textInputEventData[P_BUTTONS] = mouseButtonDown_;
  896. textInputEventData[P_QUALIFIERS] = GetQualifiers();
  897. SendEvent(E_TEXTINPUT, textInputEventData);
  898. }
  899. }
  900. break;
  901. case SDL_MOUSEBUTTONDOWN:
  902. if (!touchEmulation_)
  903. SetMouseButton(1 << (evt.button.button - 1), true);
  904. else
  905. {
  906. int x, y;
  907. SDL_GetMouseState(&x, &y);
  908. SDL_Event event;
  909. event.type = SDL_FINGERDOWN;
  910. event.tfinger.touchId = 0;
  911. event.tfinger.fingerId = evt.button.button - 1;
  912. event.tfinger.pressure = 1.0f;
  913. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  914. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  915. event.tfinger.dx = 0;
  916. event.tfinger.dy = 0;
  917. SDL_PushEvent(&event);
  918. }
  919. break;
  920. case SDL_MOUSEBUTTONUP:
  921. if (!touchEmulation_)
  922. SetMouseButton(1 << (evt.button.button - 1), false);
  923. else
  924. {
  925. int x, y;
  926. SDL_GetMouseState(&x, &y);
  927. SDL_Event event;
  928. event.type = SDL_FINGERUP;
  929. event.tfinger.touchId = 0;
  930. event.tfinger.fingerId = evt.button.button - 1;;
  931. event.tfinger.pressure = 0.0f;
  932. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  933. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  934. event.tfinger.dx = 0;
  935. event.tfinger.dy = 0;
  936. SDL_PushEvent(&event);
  937. }
  938. break;
  939. case SDL_MOUSEMOTION:
  940. if (mouseVisible_ && !touchEmulation_)
  941. {
  942. mouseMove_.x_ += evt.motion.xrel;
  943. mouseMove_.y_ += evt.motion.yrel;
  944. using namespace MouseMove;
  945. VariantMap& eventData = GetEventDataMap();
  946. if (mouseVisible_)
  947. {
  948. eventData[P_X] = evt.motion.x;
  949. eventData[P_Y] = evt.motion.y;
  950. }
  951. eventData[P_DX] = evt.motion.xrel;
  952. eventData[P_DY] = evt.motion.yrel;
  953. eventData[P_BUTTONS] = mouseButtonDown_;
  954. eventData[P_QUALIFIERS] = GetQualifiers();
  955. SendEvent(E_MOUSEMOVE, eventData);
  956. }
  957. // Only the left mouse button "finger" moves along with the mouse movement
  958. else if (touchEmulation_ && touches_.Contains(0))
  959. {
  960. int x, y;
  961. SDL_GetMouseState(&x, &y);
  962. SDL_Event event;
  963. event.type = SDL_FINGERMOTION;
  964. event.tfinger.touchId = 0;
  965. event.tfinger.fingerId = 0;
  966. event.tfinger.pressure = 1.0f;
  967. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  968. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  969. event.tfinger.dx = (float)evt.motion.xrel / (float)graphics_->GetWidth();
  970. event.tfinger.dy = (float)evt.motion.yrel / (float)graphics_->GetHeight();
  971. SDL_PushEvent(&event);
  972. }
  973. break;
  974. case SDL_MOUSEWHEEL:
  975. if (!touchEmulation_)
  976. SetMouseWheel(evt.wheel.y);
  977. break;
  978. case SDL_FINGERDOWN:
  979. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  980. {
  981. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  982. TouchState& state = touches_[touchID];
  983. state.touchID_ = touchID;
  984. state.lastPosition_ = state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  985. (int)(evt.tfinger.y * graphics_->GetHeight()));
  986. state.delta_ = IntVector2::ZERO;
  987. state.pressure_ = evt.tfinger.pressure;
  988. using namespace TouchBegin;
  989. VariantMap& eventData = GetEventDataMap();
  990. eventData[P_TOUCHID] = touchID;
  991. eventData[P_X] = state.position_.x_;
  992. eventData[P_Y] = state.position_.y_;
  993. eventData[P_PRESSURE] = state.pressure_;
  994. SendEvent(E_TOUCHBEGIN, eventData);
  995. }
  996. break;
  997. case SDL_FINGERUP:
  998. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  999. {
  1000. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  1001. TouchState& state = touches_[touchID];
  1002. using namespace TouchEnd;
  1003. VariantMap& eventData = GetEventDataMap();
  1004. // Do not trust the position in the finger up event. Instead use the last position stored in the
  1005. // touch structure
  1006. eventData[P_TOUCHID] = touchID;
  1007. eventData[P_X] = state.position_.x_;
  1008. eventData[P_Y] = state.position_.y_;
  1009. SendEvent(E_TOUCHEND, eventData);
  1010. touches_.Erase(touchID);
  1011. }
  1012. break;
  1013. case SDL_FINGERMOTION:
  1014. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1015. {
  1016. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  1017. TouchState& state = touches_[touchID];
  1018. state.touchID_ = touchID;
  1019. state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1020. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1021. state.delta_ = state.position_ - state.lastPosition_;
  1022. state.pressure_ = evt.tfinger.pressure;
  1023. using namespace TouchMove;
  1024. VariantMap& eventData = GetEventDataMap();
  1025. eventData[P_TOUCHID] = touchID;
  1026. eventData[P_X] = state.position_.x_;
  1027. eventData[P_Y] = state.position_.y_;
  1028. eventData[P_DX] = (int)(evt.tfinger.dx * graphics_->GetWidth());
  1029. eventData[P_DY] = (int)(evt.tfinger.dy * graphics_->GetHeight());
  1030. eventData[P_PRESSURE] = state.pressure_;
  1031. SendEvent(E_TOUCHMOVE, eventData);
  1032. }
  1033. break;
  1034. case SDL_DOLLARRECORD:
  1035. {
  1036. using namespace GestureRecorded;
  1037. VariantMap& eventData = GetEventDataMap();
  1038. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1039. SendEvent(E_GESTURERECORDED, eventData);
  1040. }
  1041. break;
  1042. case SDL_DOLLARGESTURE:
  1043. {
  1044. using namespace GestureInput;
  1045. VariantMap& eventData = GetEventDataMap();
  1046. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1047. eventData[P_CENTERX] = (int)(evt.dgesture.x * graphics_->GetWidth());
  1048. eventData[P_CENTERY] = (int)(evt.dgesture.y * graphics_->GetHeight());
  1049. eventData[P_NUMFINGERS] = (int)evt.dgesture.numFingers;
  1050. eventData[P_ERROR] = evt.dgesture.error;
  1051. SendEvent(E_GESTUREINPUT, eventData);
  1052. }
  1053. break;
  1054. case SDL_MULTIGESTURE:
  1055. {
  1056. using namespace MultiGesture;
  1057. VariantMap& eventData = GetEventDataMap();
  1058. eventData[P_CENTERX] = (int)(evt.mgesture.x * graphics_->GetWidth());
  1059. eventData[P_CENTERY] = (int)(evt.mgesture.y * graphics_->GetHeight());
  1060. eventData[P_NUMFINGERS] = (int)evt.mgesture.numFingers;
  1061. eventData[P_DTHETA] = M_RADTODEG * evt.mgesture.dTheta;
  1062. eventData[P_DDIST] = evt.mgesture.dDist;
  1063. SendEvent(E_MULTIGESTURE, eventData);
  1064. }
  1065. break;
  1066. case SDL_JOYDEVICEADDED:
  1067. {
  1068. using namespace JoystickConnected;
  1069. SDL_JoystickID joystickID = OpenJoystick(evt.jdevice.which);
  1070. VariantMap& eventData = GetEventDataMap();
  1071. eventData[P_JOYSTICKID] = joystickID;
  1072. SendEvent(E_JOYSTICKCONNECTED, eventData);
  1073. }
  1074. break;
  1075. case SDL_JOYDEVICEREMOVED:
  1076. {
  1077. using namespace JoystickDisconnected;
  1078. joysticks_.Erase(evt.jdevice.which);
  1079. VariantMap& eventData = GetEventDataMap();
  1080. eventData[P_JOYSTICKID] = evt.jdevice.which;
  1081. SendEvent(E_JOYSTICKDISCONNECTED, eventData);
  1082. }
  1083. break;
  1084. case SDL_JOYBUTTONDOWN:
  1085. {
  1086. using namespace JoystickButtonDown;
  1087. unsigned button = evt.jbutton.button;
  1088. SDL_JoystickID joystickID = evt.jbutton.which;
  1089. JoystickState& state = joysticks_[joystickID];
  1090. // Skip ordinary joystick event for a controller
  1091. if (!state.controller_)
  1092. {
  1093. VariantMap& eventData = GetEventDataMap();
  1094. eventData[P_JOYSTICKID] = joystickID;
  1095. eventData[P_BUTTON] = button;
  1096. if (button < state.buttons_.Size())
  1097. {
  1098. state.buttons_[button] = true;
  1099. state.buttonPress_[button] = true;
  1100. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1101. }
  1102. }
  1103. }
  1104. break;
  1105. case SDL_JOYBUTTONUP:
  1106. {
  1107. using namespace JoystickButtonUp;
  1108. unsigned button = evt.jbutton.button;
  1109. SDL_JoystickID joystickID = evt.jbutton.which;
  1110. JoystickState& state = joysticks_[joystickID];
  1111. if (!state.controller_)
  1112. {
  1113. VariantMap& eventData = GetEventDataMap();
  1114. eventData[P_JOYSTICKID] = joystickID;
  1115. eventData[P_BUTTON] = button;
  1116. if (button < state.buttons_.Size())
  1117. {
  1118. if (!state.controller_)
  1119. state.buttons_[button] = false;
  1120. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1121. }
  1122. }
  1123. }
  1124. break;
  1125. case SDL_JOYAXISMOTION:
  1126. {
  1127. using namespace JoystickAxisMove;
  1128. SDL_JoystickID joystickID = evt.jaxis.which;
  1129. JoystickState& state = joysticks_[joystickID];
  1130. if (!state.controller_)
  1131. {
  1132. VariantMap& eventData = GetEventDataMap();
  1133. eventData[P_JOYSTICKID] = joystickID;
  1134. eventData[P_AXIS] = evt.jaxis.axis;
  1135. eventData[P_POSITION] = Clamp((float)evt.jaxis.value / 32767.0f, -1.0f, 1.0f);
  1136. if (evt.jaxis.axis < state.axes_.Size())
  1137. {
  1138. // If the joystick is a controller, only use the controller axis mappings
  1139. // (we'll also get the controller event)
  1140. if (!state.controller_)
  1141. state.axes_[evt.jaxis.axis] = eventData[P_POSITION].GetFloat();
  1142. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1143. }
  1144. }
  1145. }
  1146. break;
  1147. case SDL_JOYHATMOTION:
  1148. {
  1149. using namespace JoystickHatMove;
  1150. SDL_JoystickID joystickID = evt.jaxis.which;
  1151. JoystickState& state = joysticks_[joystickID];
  1152. VariantMap& eventData = GetEventDataMap();
  1153. eventData[P_JOYSTICKID] = joystickID;
  1154. eventData[P_HAT] = evt.jhat.hat;
  1155. eventData[P_POSITION] = evt.jhat.value;
  1156. if (evt.jhat.hat < state.hats_.Size())
  1157. {
  1158. state.hats_[evt.jhat.hat] = evt.jhat.value;
  1159. SendEvent(E_JOYSTICKHATMOVE, eventData);
  1160. }
  1161. }
  1162. break;
  1163. case SDL_CONTROLLERBUTTONDOWN:
  1164. {
  1165. using namespace JoystickButtonDown;
  1166. unsigned button = evt.cbutton.button;
  1167. SDL_JoystickID joystickID = evt.cbutton.which;
  1168. JoystickState& state = joysticks_[joystickID];
  1169. VariantMap& eventData = GetEventDataMap();
  1170. eventData[P_JOYSTICKID] = joystickID;
  1171. eventData[P_BUTTON] = button;
  1172. if (button < state.buttons_.Size())
  1173. {
  1174. state.buttons_[button] = true;
  1175. state.buttonPress_[button] = true;
  1176. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1177. }
  1178. }
  1179. break;
  1180. case SDL_CONTROLLERBUTTONUP:
  1181. {
  1182. using namespace JoystickButtonUp;
  1183. unsigned button = evt.cbutton.button;
  1184. SDL_JoystickID joystickID = evt.cbutton.which;
  1185. JoystickState& state = joysticks_[joystickID];
  1186. VariantMap& eventData = GetEventDataMap();
  1187. eventData[P_JOYSTICKID] = joystickID;
  1188. eventData[P_BUTTON] = button;
  1189. if (button < state.buttons_.Size())
  1190. {
  1191. state.buttons_[button] = false;
  1192. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1193. }
  1194. }
  1195. break;
  1196. case SDL_CONTROLLERAXISMOTION:
  1197. {
  1198. using namespace JoystickAxisMove;
  1199. SDL_JoystickID joystickID = evt.caxis.which;
  1200. JoystickState& state = joysticks_[joystickID];
  1201. VariantMap& eventData = GetEventDataMap();
  1202. eventData[P_JOYSTICKID] = joystickID;
  1203. eventData[P_AXIS] = evt.caxis.axis;
  1204. eventData[P_POSITION] = Clamp((float)evt.caxis.value / 32767.0f, -1.0f, 1.0f);
  1205. if (evt.caxis.axis < state.axes_.Size())
  1206. {
  1207. state.axes_[evt.caxis.axis] = eventData[P_POSITION].GetFloat();
  1208. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1209. }
  1210. }
  1211. break;
  1212. case SDL_WINDOWEVENT:
  1213. {
  1214. switch (evt.window.event)
  1215. {
  1216. case SDL_WINDOWEVENT_MINIMIZED:
  1217. minimized_ = true;
  1218. SendInputFocusEvent();
  1219. break;
  1220. case SDL_WINDOWEVENT_MAXIMIZED:
  1221. case SDL_WINDOWEVENT_RESTORED:
  1222. minimized_ = false;
  1223. SendInputFocusEvent();
  1224. #ifdef IOS
  1225. // On iOS we never lose the GL context, but may have done GPU object changes that could not be applied yet.
  1226. // Apply them now
  1227. graphics_->Restore();
  1228. #endif
  1229. break;
  1230. #ifdef ANDROID
  1231. case SDL_WINDOWEVENT_FOCUS_GAINED:
  1232. // Restore GPU objects to the new GL context
  1233. graphics_->Restore();
  1234. break;
  1235. #endif
  1236. case SDL_WINDOWEVENT_RESIZED:
  1237. graphics_->WindowResized();
  1238. break;
  1239. }
  1240. }
  1241. break;
  1242. case SDL_DROPFILE:
  1243. {
  1244. using namespace DropFile;
  1245. VariantMap& eventData = GetEventDataMap();
  1246. eventData[P_FILENAME] = GetInternalPath(String(evt.drop.file));
  1247. SDL_free(evt.drop.file);
  1248. SendEvent(E_DROPFILE, eventData);
  1249. }
  1250. break;
  1251. case SDL_QUIT:
  1252. SendEvent(E_EXITREQUESTED);
  1253. break;
  1254. }
  1255. }
  1256. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1257. {
  1258. // Reset input state on subsequent initializations
  1259. if (!initialized_)
  1260. Initialize();
  1261. else
  1262. ResetState();
  1263. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  1264. // mouse move event. Also get new window ID if it changed
  1265. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  1266. windowID_ = SDL_GetWindowID(window);
  1267. if (!mouseVisible_)
  1268. {
  1269. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  1270. SetMousePosition(center);
  1271. lastMousePosition_ = center;
  1272. }
  1273. focusedThisFrame_ = true;
  1274. // After setting a new screen mode we should not be minimized
  1275. minimized_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0;
  1276. }
  1277. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1278. {
  1279. // Update input right at the beginning of the frame
  1280. Update();
  1281. }
  1282. void Input::HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData)
  1283. {
  1284. using namespace TouchBegin;
  1285. // Only interested in events from screen joystick(s)
  1286. TouchState& state = touches_[eventData[P_TOUCHID].GetInt()];
  1287. IntVector2 position(state.position_.x_, state.position_.y_);
  1288. UIElement* element = eventType == E_TOUCHBEGIN ? GetSubsystem<UI>()->GetElementAt(position) : state.touchedElement_;
  1289. if (!element)
  1290. return;
  1291. Variant variant = element->GetVar(VAR_SCREEN_JOYSTICK_ID);
  1292. if (variant.IsEmpty())
  1293. return;
  1294. SDL_JoystickID joystickID = variant.GetInt();
  1295. if (eventType == E_TOUCHEND)
  1296. state.touchedElement_.Reset();
  1297. else
  1298. state.touchedElement_ = element;
  1299. // Prepare a fake SDL event
  1300. SDL_Event evt;
  1301. const String& name = element->GetName();
  1302. if (name.StartsWith("Button"))
  1303. {
  1304. if (eventType == E_TOUCHMOVE)
  1305. return;
  1306. // Determine whether to inject a joystick event or keyboard/mouse event
  1307. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  1308. Variant mouseButtonBindingVar = element->GetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING);
  1309. if (keyBindingVar.IsEmpty() && mouseButtonBindingVar.IsEmpty())
  1310. {
  1311. evt.type = eventType == E_TOUCHBEGIN ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
  1312. evt.jbutton.which = joystickID;
  1313. evt.jbutton.button = ToUInt(name.Substring(6));
  1314. }
  1315. else
  1316. {
  1317. if (!keyBindingVar.IsEmpty())
  1318. {
  1319. evt.type = eventType == E_TOUCHBEGIN ? SDL_KEYDOWN : SDL_KEYUP;
  1320. evt.key.keysym.sym = keyBindingVar.GetInt();
  1321. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  1322. }
  1323. if (!mouseButtonBindingVar.IsEmpty() && !touchEmulation_)
  1324. {
  1325. // Mouse button are sent as extra events besides key events
  1326. // Do not send mouse events in touch emulation mode, because those would in turn be re-interpreted as touch
  1327. SDL_Event evt;
  1328. evt.type = eventType == E_TOUCHBEGIN ? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP;
  1329. evt.button.button = mouseButtonBindingVar.GetInt();
  1330. HandleSDLEvent(&evt);
  1331. }
  1332. }
  1333. }
  1334. else if (name.StartsWith("Hat"))
  1335. {
  1336. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  1337. if (keyBindingVar.IsEmpty())
  1338. {
  1339. evt.type = SDL_JOYHATMOTION;
  1340. evt.jaxis.which = joystickID;
  1341. evt.jhat.hat = ToUInt(name.Substring(3));
  1342. evt.jhat.value = HAT_CENTER;
  1343. if (eventType != E_TOUCHEND)
  1344. {
  1345. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  1346. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1347. evt.jhat.value |= HAT_UP;
  1348. if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1349. evt.jhat.value |= HAT_DOWN;
  1350. if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1351. evt.jhat.value |= HAT_LEFT;
  1352. if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1353. evt.jhat.value |= HAT_RIGHT;
  1354. }
  1355. }
  1356. else
  1357. {
  1358. // Hat is binded by 4 keys, like 'WASD'
  1359. String keyBinding = keyBindingVar.GetString();
  1360. if (eventType == E_TOUCHEND)
  1361. {
  1362. evt.type = SDL_KEYUP;
  1363. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  1364. if (!evt.key.keysym.sym)
  1365. return;
  1366. element->SetVar(VAR_LAST_KEYSYM, 0);
  1367. }
  1368. else
  1369. {
  1370. evt.type = SDL_KEYDOWN;
  1371. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  1372. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1373. evt.key.keysym.sym = keyBinding[0];
  1374. else if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1375. evt.key.keysym.sym = keyBinding[1];
  1376. else if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1377. evt.key.keysym.sym = keyBinding[2];
  1378. else if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1379. evt.key.keysym.sym = keyBinding[3];
  1380. else
  1381. return;
  1382. if (eventType == E_TOUCHMOVE && evt.key.keysym.sym != element->GetVar(VAR_LAST_KEYSYM).GetInt())
  1383. {
  1384. // Dragging past the directional boundary will cause an additional key up event for previous key symbol
  1385. SDL_Event evt;
  1386. evt.type = SDL_KEYUP;
  1387. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  1388. if (evt.key.keysym.sym)
  1389. {
  1390. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  1391. HandleSDLEvent(&evt);
  1392. }
  1393. element->SetVar(VAR_LAST_KEYSYM, 0);
  1394. }
  1395. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  1396. element->SetVar(VAR_LAST_KEYSYM, evt.key.keysym.sym);
  1397. }
  1398. }
  1399. }
  1400. else
  1401. return;
  1402. // Handle the fake SDL event to turn it into Urho3D genuine event
  1403. HandleSDLEvent(&evt);
  1404. }
  1405. }