UI.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  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 "CheckBox.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "Cursor.h"
  27. #include "DropDownList.h"
  28. #include "FileSelector.h"
  29. #include "Font.h"
  30. #include "Graphics.h"
  31. #include "GraphicsEvents.h"
  32. #include "Input.h"
  33. #include "InputEvents.h"
  34. #include "LineEdit.h"
  35. #include "ListView.h"
  36. #include "Log.h"
  37. #include "Matrix3x4.h"
  38. #include "MessageBox.h"
  39. #include "Profiler.h"
  40. #include "ResourceCache.h"
  41. #include "ScrollBar.h"
  42. #include "Shader.h"
  43. #include "ShaderVariation.h"
  44. #include "Slider.h"
  45. #include "Sort.h"
  46. #include "Sprite.h"
  47. #include "Text.h"
  48. #include "Text3D.h"
  49. #include "Texture2D.h"
  50. #include "ToolTip.h"
  51. #include "UI.h"
  52. #include "UIEvents.h"
  53. #include "VertexBuffer.h"
  54. #include "Window.h"
  55. #include "View3D.h"
  56. #include <SDL.h>
  57. #include "DebugNew.h"
  58. namespace Urho3D
  59. {
  60. ShortStringHash VAR_ORIGIN("Origin");
  61. const ShortStringHash VAR_ORIGINAL_PARENT("OriginalParent");
  62. const ShortStringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex");
  63. const ShortStringHash VAR_PARENT_CHANGED("ParentChanged");
  64. const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f;
  65. const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f;
  66. const float DEFAULT_TOOLTIP_DELAY = 0.5f;
  67. const int DEFAULT_DRAGBEGIN_DISTANCE = 5;
  68. const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048;
  69. const char* UI_CATEGORY = "UI";
  70. UI::UI(Context* context) :
  71. Object(context),
  72. rootElement_(new UIElement(context)),
  73. rootModalElement_(new UIElement(context)),
  74. mouseButtons_(0),
  75. lastMouseButtons_(0),
  76. qualifiers_(0),
  77. maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE),
  78. doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL),
  79. dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL),
  80. dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE),
  81. defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY),
  82. initialized_(false),
  83. usingTouchInput_(false),
  84. #ifdef WIN32
  85. nonFocusedMouseWheel_(false), // Default MS Windows behaviour
  86. #else
  87. nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
  88. #endif
  89. useSystemClipBoard_(false),
  90. #if defined(ANDROID) || defined(IOS)
  91. useScreenKeyboard_(true),
  92. #else
  93. useScreenKeyboard_(false),
  94. #endif
  95. useMutableGlyphs_(false),
  96. forceAutoHint_(false),
  97. dragBeginPending_(false),
  98. nonModalBatchSize_(0)
  99. {
  100. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  101. rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
  102. // Register UI library object factories
  103. RegisterUILibrary(context_);
  104. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  105. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  106. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  107. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  108. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  109. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  110. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  111. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  112. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  113. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  114. SubscribeToEvent(E_DROPFILE, HANDLER(UI, HandleDropFile));
  115. // Try to initialize right now, but skip if screen mode is not yet set
  116. Initialize();
  117. }
  118. UI::~UI()
  119. {
  120. }
  121. void UI::SetCursor(Cursor* cursor)
  122. {
  123. // Remove old cursor (if any) and set new
  124. if (cursor_)
  125. {
  126. rootElement_->RemoveChild(cursor_);
  127. cursor_.Reset();
  128. }
  129. if (cursor)
  130. {
  131. rootElement_->AddChild(cursor);
  132. cursor_ = cursor;
  133. IntVector2 pos = cursor_->GetPosition();
  134. const IntVector2& rootSize = rootElement_->GetSize();
  135. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  136. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  137. cursor_->SetPosition(pos);
  138. }
  139. }
  140. void UI::SetFocusElement(UIElement* element, bool byKey)
  141. {
  142. using namespace FocusChanged;
  143. UIElement* originalElement = element;
  144. if (element)
  145. {
  146. // Return if already has focus
  147. if (focusElement_ == element)
  148. return;
  149. // Only allow child elements of the modal element to receive focus
  150. if (HasModalElement())
  151. {
  152. UIElement* topLevel = element->GetParent();
  153. while (topLevel && topLevel->GetParent() != rootElement_)
  154. topLevel = topLevel->GetParent();
  155. if (topLevel) // If parented to non-modal root then ignore
  156. return;
  157. }
  158. // Search for an element in the hierarchy that can alter focus. If none found, exit
  159. element = GetFocusableElement(element);
  160. if (!element)
  161. return;
  162. }
  163. // Remove focus from the old element
  164. if (focusElement_)
  165. {
  166. UIElement* oldFocusElement = focusElement_;
  167. focusElement_.Reset();
  168. VariantMap& focusEventData = GetEventDataMap();
  169. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  170. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  171. }
  172. // Then set focus to the new
  173. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  174. {
  175. focusElement_ = element;
  176. VariantMap& focusEventData = GetEventDataMap();
  177. focusEventData[Focused::P_ELEMENT] = element;
  178. focusEventData[Focused::P_BYKEY] = byKey;
  179. element->SendEvent(E_FOCUSED, focusEventData);
  180. }
  181. VariantMap& eventData = GetEventDataMap();
  182. eventData[P_CLICKEDELEMENT] = originalElement;
  183. eventData[P_ELEMENT] = element;
  184. SendEvent(E_FOCUSCHANGED, eventData);
  185. }
  186. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  187. {
  188. if (!modalElement)
  189. return false;
  190. // Currently only allow modal window
  191. if (modalElement->GetType() != Window::GetTypeStatic())
  192. return false;
  193. assert(rootModalElement_);
  194. UIElement* currParent = modalElement->GetParent();
  195. if (enable)
  196. {
  197. // Make sure it is not already the child of the root modal element
  198. if (currParent == rootModalElement_)
  199. return false;
  200. // Adopt modal root as parent
  201. modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent);
  202. modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED);
  203. modalElement->SetParent(rootModalElement_);
  204. // If it is a popup element, bring along its top-level parent
  205. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  206. if (originElement)
  207. {
  208. UIElement* element = originElement;
  209. while (element && element->GetParent() != rootElement_)
  210. element = element->GetParent();
  211. if (element)
  212. {
  213. originElement->SetVar(VAR_PARENT_CHANGED, element);
  214. UIElement* oriParent = element->GetParent();
  215. element->SetVar(VAR_ORIGINAL_PARENT, oriParent);
  216. element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED);
  217. element->SetParent(rootModalElement_);
  218. }
  219. }
  220. return true;
  221. }
  222. else
  223. {
  224. // Only the modal element can disable itself
  225. if (currParent != rootModalElement_)
  226. return false;
  227. // Revert back to original parent
  228. modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  229. modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  230. VariantMap& vars = const_cast<VariantMap&>(modalElement->GetVars());
  231. vars.Erase(VAR_ORIGINAL_PARENT);
  232. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  233. // If it is a popup element, revert back its top-level parent
  234. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  235. if (originElement)
  236. {
  237. UIElement* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
  238. if (element)
  239. {
  240. const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
  241. element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  242. element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  243. vars = const_cast<VariantMap&>(element->GetVars());
  244. vars.Erase(VAR_ORIGINAL_PARENT);
  245. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  246. }
  247. }
  248. return true;
  249. }
  250. }
  251. void UI::Clear()
  252. {
  253. rootElement_->RemoveAllChildren();
  254. rootModalElement_->RemoveAllChildren();
  255. if (cursor_)
  256. rootElement_->AddChild(cursor_);
  257. }
  258. void UI::Update(float timeStep)
  259. {
  260. assert(rootElement_ && rootModalElement_);
  261. PROFILE(UpdateUI);
  262. IntVector2 cursorPos;
  263. bool cursorVisible;
  264. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  265. // Drag begin based on time
  266. if (dragElement_ && dragBeginPending_)
  267. {
  268. if (dragBeginTimer_.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000))
  269. {
  270. dragBeginPending_ = false;
  271. if (!usingTouchInput_)
  272. {
  273. dragElement_->OnDragBegin(dragElement_->ScreenToElement(dragBeginPos_), dragBeginPos_, mouseButtons_, qualifiers_,
  274. cursor_);
  275. }
  276. else
  277. dragElement_->OnDragBegin(dragElement_->ScreenToElement(dragBeginPos_), dragBeginPos_, MOUSEB_LEFT, 0, 0);
  278. SendDragEvent(E_DRAGBEGIN, dragElement_, dragBeginPos_);
  279. }
  280. }
  281. // Mouse hover
  282. if (!usingTouchInput_ && cursorVisible)
  283. ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_);
  284. // Touch hover
  285. Input* input = GetSubsystem<Input>();
  286. unsigned numTouches = input->GetNumTouches();
  287. for (unsigned i = 0; i < numTouches; ++i)
  288. {
  289. TouchState* touch = input->GetTouch(i);
  290. ProcessHover(touch->position_, MOUSEB_LEFT, 0, 0);
  291. }
  292. Update(timeStep, rootElement_);
  293. Update(timeStep, rootModalElement_);
  294. }
  295. void UI::RenderUpdate()
  296. {
  297. assert(rootElement_ && rootModalElement_ && graphics_);
  298. PROFILE(GetUIBatches);
  299. // If the OS cursor is visible, do not render the UI's own cursor
  300. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  301. // Get rendering batches from the non-modal UI elements
  302. batches_.Clear();
  303. vertexData_.Clear();
  304. const IntVector2& rootSize = rootElement_->GetSize();
  305. IntRect currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  306. GetBatches(rootElement_, currentScissor);
  307. // Save the batch size of the non-modal batches for later use
  308. nonModalBatchSize_ = batches_.Size();
  309. // Get rendering batches from the modal UI elements
  310. GetBatches(rootModalElement_, currentScissor);
  311. // Get batches from the cursor (and its possible children) last to draw it on top of everything
  312. if (cursor_ && cursor_->IsVisible() && !osCursorVisible)
  313. {
  314. currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  315. cursor_->GetBatches(batches_, vertexData_, currentScissor);
  316. GetBatches(cursor_, currentScissor);
  317. }
  318. }
  319. void UI::Render()
  320. {
  321. PROFILE(RenderUI);
  322. // If the OS cursor is visible, apply its shape now if changed
  323. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  324. if (cursor_ && osCursorVisible)
  325. cursor_->ApplyOSCursorShape();
  326. SetVertexData(vertexBuffer_, vertexData_);
  327. SetVertexData(debugVertexBuffer_, debugVertexData_);
  328. // Render non-modal batches
  329. Render(vertexBuffer_, batches_, 0, nonModalBatchSize_);
  330. // Render debug draw
  331. Render(debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size());
  332. // Render modal batches
  333. Render(vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size());
  334. // Clear the debug draw batches and data
  335. debugDrawBatches_.Clear();
  336. debugVertexData_.Clear();
  337. }
  338. void UI::DebugDraw(UIElement* element)
  339. {
  340. if (element)
  341. {
  342. const IntVector2& rootSize = rootElement_->GetSize();
  343. element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  344. }
  345. }
  346. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  347. {
  348. SharedPtr<XMLFile> xml(new XMLFile(context_));
  349. if (!xml->Load(source))
  350. return SharedPtr<UIElement>();
  351. else
  352. return LoadLayout(xml, styleFile);
  353. }
  354. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  355. {
  356. PROFILE(LoadUILayout);
  357. SharedPtr<UIElement> root;
  358. if (!file)
  359. {
  360. LOGERROR("Null UI layout XML file");
  361. return root;
  362. }
  363. LOGDEBUG("Loading UI layout " + file->GetName());
  364. XMLElement rootElem = file->GetRoot("element");
  365. if (!rootElem)
  366. {
  367. LOGERROR("No root UI element in " + file->GetName());
  368. return root;
  369. }
  370. String typeName = rootElem.GetAttribute("type");
  371. if (typeName.Empty())
  372. typeName = "UIElement";
  373. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  374. if (!root)
  375. {
  376. LOGERROR("Could not create unknown UI element " + typeName);
  377. return root;
  378. }
  379. // Use default style file of the root element if it has one
  380. if (!styleFile)
  381. styleFile = rootElement_->GetDefaultStyle(false);
  382. // Set it as default for later use by children elements
  383. if (styleFile)
  384. root->SetDefaultStyle(styleFile);
  385. root->LoadXML(rootElem, styleFile);
  386. return root;
  387. }
  388. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  389. {
  390. PROFILE(SaveUILayout);
  391. return element && element->SaveXML(dest);
  392. }
  393. void UI::SetClipBoardText(const String& text)
  394. {
  395. clipBoard_ = text;
  396. if (useSystemClipBoard_)
  397. SDL_SetClipboardText(text.CString());
  398. }
  399. void UI::SetDoubleClickInterval(float interval)
  400. {
  401. doubleClickInterval_ = Max(interval, 0.0f);
  402. }
  403. void UI::SetDragBeginInterval(float interval)
  404. {
  405. dragBeginInterval_ = Max(interval, 0.0f);
  406. }
  407. void UI::SetDragBeginDistance(int pixels)
  408. {
  409. dragBeginDistance_ = Max(pixels, 0);
  410. }
  411. void UI::SetDefaultToolTipDelay(float delay)
  412. {
  413. defaultToolTipDelay_ = Max(delay, 0.0f);
  414. }
  415. void UI::SetMaxFontTextureSize(int size)
  416. {
  417. if (IsPowerOfTwo(size) && size >= FONT_TEXTURE_MIN_SIZE)
  418. {
  419. if (size != maxFontTextureSize_)
  420. {
  421. maxFontTextureSize_ = size;
  422. ReleaseFontFaces();
  423. }
  424. }
  425. }
  426. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  427. {
  428. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  429. }
  430. void UI::SetUseSystemClipBoard(bool enable)
  431. {
  432. useSystemClipBoard_ = enable;
  433. }
  434. void UI::SetUseScreenKeyboard(bool enable)
  435. {
  436. useScreenKeyboard_ = enable;
  437. }
  438. void UI::SetUseMutableGlyphs(bool enable)
  439. {
  440. if (enable != useMutableGlyphs_)
  441. {
  442. useMutableGlyphs_ = enable;
  443. ReleaseFontFaces();
  444. }
  445. }
  446. void UI::SetForceAutoHint(bool enable)
  447. {
  448. if (enable != forceAutoHint_)
  449. {
  450. forceAutoHint_ = enable;
  451. ReleaseFontFaces();
  452. }
  453. }
  454. IntVector2 UI::GetCursorPosition() const
  455. {
  456. return cursor_ ? cursor_->GetPosition() : GetSubsystem<Input>()->GetMousePosition();
  457. }
  458. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  459. {
  460. UIElement* result = 0;
  461. GetElementAt(result, HasModalElement() ? rootModalElement_ : rootElement_, position, enabledOnly);
  462. return result;
  463. }
  464. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  465. {
  466. return GetElementAt(IntVector2(x, y), enabledOnly);
  467. }
  468. UIElement* UI::GetFrontElement() const
  469. {
  470. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  471. int maxPriority = M_MIN_INT;
  472. UIElement* front = 0;
  473. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  474. {
  475. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  476. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  477. continue;
  478. int priority = rootChildren[i]->GetPriority();
  479. if (priority > maxPriority)
  480. {
  481. maxPriority = priority;
  482. front = rootChildren[i];
  483. }
  484. }
  485. return front;
  486. }
  487. UIElement* UI::GetDragElement() const
  488. {
  489. // Do not return the element until drag begin event has actually been posted
  490. return dragBeginPending_ ? (UIElement*)0 : dragElement_;
  491. }
  492. const String& UI::GetClipBoardText() const
  493. {
  494. if (useSystemClipBoard_)
  495. {
  496. char* text = SDL_GetClipboardText();
  497. clipBoard_ = String(text);
  498. if (text)
  499. SDL_free(text);
  500. }
  501. return clipBoard_;
  502. }
  503. bool UI::HasModalElement() const
  504. {
  505. return rootModalElement_->GetNumChildren() > 0;
  506. }
  507. void UI::Initialize()
  508. {
  509. Graphics* graphics = GetSubsystem<Graphics>();
  510. if (!graphics || !graphics->IsInitialized())
  511. return;
  512. PROFILE(InitUI);
  513. graphics_ = graphics;
  514. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  515. rootModalElement_->SetSize(rootElement_->GetSize());
  516. vertexBuffer_ = new VertexBuffer(context_);
  517. debugVertexBuffer_ = new VertexBuffer(context_);
  518. initialized_ = true;
  519. SubscribeToEvent(E_BEGINFRAME, HANDLER(UI, HandleBeginFrame));
  520. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  521. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  522. LOGINFO("Initialized user interface");
  523. }
  524. void UI::Update(float timeStep, UIElement* element)
  525. {
  526. // Keep a weak pointer to the element in case it destroys itself on update
  527. WeakPtr<UIElement> elementWeak(element);
  528. element->Update(timeStep);
  529. if (elementWeak.Expired())
  530. return;
  531. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  532. // Update of an element may modify its child vector. Use just index-based iteration to be safe
  533. for (unsigned i = 0; i < children.Size(); ++i)
  534. Update(timeStep, children[i]);
  535. }
  536. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  537. {
  538. if (vertexData.Empty())
  539. return;
  540. // Update quad geometry into the vertex buffer
  541. // Resize the vertex buffer first if too small or much too large
  542. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  543. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  544. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  545. dest->SetData(&vertexData[0]);
  546. }
  547. void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  548. {
  549. // Engine does not render when window is closed or device is lost
  550. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  551. if (batches.Empty())
  552. return;
  553. Vector2 invScreenSize(1.0f / (float)graphics_->GetWidth(), 1.0f / (float)graphics_->GetHeight());
  554. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  555. Vector2 offset(-1.0f, 1.0f);
  556. Matrix4 projection(Matrix4::IDENTITY);
  557. projection.m00_ = scale.x_;
  558. projection.m03_ = offset.x_;
  559. projection.m11_ = scale.y_;
  560. projection.m13_ = offset.y_;
  561. projection.m22_ = 1.0f;
  562. projection.m23_ = 0.0f;
  563. projection.m33_ = 1.0f;
  564. graphics_->ClearParameterSources();
  565. graphics_->SetCullMode(CULL_CCW);
  566. graphics_->SetDepthTest(CMP_ALWAYS);
  567. graphics_->SetDepthWrite(false);
  568. graphics_->SetStencilTest(false);
  569. graphics_->ResetRenderTargets();
  570. graphics_->SetVertexBuffer(buffer);
  571. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  572. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  573. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  574. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  575. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  576. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  577. unsigned alphaFormat = Graphics::GetAlphaFormat();
  578. for (unsigned i = batchStart; i < batchEnd; ++i)
  579. {
  580. const UIBatch& batch = batches[i];
  581. if (batch.vertexStart_ == batch.vertexEnd_)
  582. continue;
  583. ShaderVariation* ps;
  584. ShaderVariation* vs;
  585. if (!batch.texture_)
  586. {
  587. ps = noTexturePS;
  588. vs = noTextureVS;
  589. }
  590. else
  591. {
  592. // If texture contains only an alpha channel, use alpha shader (for fonts)
  593. vs = diffTextureVS;
  594. if (batch.texture_->GetFormat() == alphaFormat)
  595. ps = alphaTexturePS;
  596. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  597. ps = diffMaskTexturePS;
  598. else
  599. ps = diffTexturePS;
  600. }
  601. graphics_->SetShaders(vs, ps);
  602. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  603. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  604. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  605. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  606. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  607. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  608. graphics_->SetBlendMode(batch.blendMode_);
  609. graphics_->SetScissorTest(true, batch.scissor_);
  610. graphics_->SetTexture(0, batch.texture_);
  611. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  612. UI_VERTEX_SIZE);
  613. }
  614. }
  615. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  616. {
  617. // Set clipping scissor for child elements. No need to draw if zero size
  618. element->AdjustScissor(currentScissor);
  619. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  620. return;
  621. element->SortChildren();
  622. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  623. if (children.Empty())
  624. return;
  625. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  626. // same renderstate
  627. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  628. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  629. {
  630. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  631. while (i != children.End())
  632. {
  633. int currentPriority = (*i)->GetPriority();
  634. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  635. {
  636. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  637. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  638. ++j;
  639. }
  640. // Now recurse into the children
  641. while (i != j)
  642. {
  643. if ((*i)->IsVisible() && (*i) != cursor_)
  644. GetBatches(*i, currentScissor);
  645. ++i;
  646. }
  647. }
  648. }
  649. // On the root level draw each element and its children immediately after to avoid artifacts
  650. else
  651. {
  652. while (i != children.End())
  653. {
  654. if ((*i) != cursor_)
  655. {
  656. if ((*i)->IsWithinScissor(currentScissor))
  657. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  658. if ((*i)->IsVisible())
  659. GetBatches(*i, currentScissor);
  660. }
  661. ++i;
  662. }
  663. }
  664. }
  665. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  666. {
  667. if (!current)
  668. return;
  669. current->SortChildren();
  670. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  671. LayoutMode parentLayoutMode = current->GetLayoutMode();
  672. for (unsigned i = 0; i < children.Size(); ++i)
  673. {
  674. UIElement* element = children[i];
  675. bool hasChildren = element->GetNumChildren() > 0;
  676. if (element != cursor_.Get() && element->IsVisible())
  677. {
  678. if (element->IsInside(position, true))
  679. {
  680. // Store the current result, then recurse into its children. Because children
  681. // are sorted from lowest to highest priority, the topmost match should remain
  682. if (element->IsEnabled() || !enabledOnly)
  683. result = element;
  684. if (hasChildren)
  685. GetElementAt(result, element, position, enabledOnly);
  686. // Layout optimization: if the element has no children, can break out after the first match
  687. else if (parentLayoutMode != LM_FREE)
  688. break;
  689. }
  690. else
  691. {
  692. if (hasChildren)
  693. {
  694. if (element->IsInsideCombined(position, true))
  695. GetElementAt(result, element, position, enabledOnly);
  696. }
  697. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  698. // or if we already passed all visible elements
  699. else if (parentLayoutMode != LM_FREE)
  700. {
  701. if (!i)
  702. {
  703. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  704. element->GetScreenPosition().y_;
  705. int layoutMinSize = current->GetLayoutMinSize();
  706. if (screenPos < 0 && layoutMinSize > 0)
  707. {
  708. unsigned toSkip = -screenPos / layoutMinSize;
  709. if (toSkip > 0)
  710. i += (toSkip - 1);
  711. }
  712. }
  713. else if (parentLayoutMode == LM_HORIZONTAL)
  714. {
  715. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  716. break;
  717. }
  718. else if (parentLayoutMode == LM_VERTICAL)
  719. {
  720. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  721. break;
  722. }
  723. }
  724. }
  725. }
  726. }
  727. }
  728. UIElement* UI::GetFocusableElement(UIElement* element)
  729. {
  730. while (element)
  731. {
  732. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  733. break;
  734. element = element->GetParent();
  735. }
  736. return element;
  737. }
  738. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  739. {
  740. if (cursor_)
  741. {
  742. pos = cursor_->GetPosition();
  743. visible = cursor_->IsVisible();
  744. }
  745. else
  746. {
  747. Input* input = GetSubsystem<Input>();
  748. pos = input->GetMousePosition();
  749. visible = input->IsMouseVisible();
  750. }
  751. }
  752. void UI::SetCursorShape(CursorShape shape)
  753. {
  754. if (cursor_)
  755. cursor_->SetShape(shape);
  756. }
  757. void UI::ReleaseFontFaces()
  758. {
  759. LOGDEBUG("Reloading font faces");
  760. PODVector<Font*> fonts;
  761. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  762. for (unsigned i = 0; i < fonts.Size(); ++i)
  763. fonts[i]->ReleaseFaces();
  764. }
  765. void UI::ProcessHover(const IntVector2& cursorPos, int buttons, int qualifiers, Cursor* cursor)
  766. {
  767. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  768. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  769. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  770. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  771. // If drag start event has not been posted yet, do not do drag handling here
  772. if (dragBeginPending_)
  773. dragSource = dragTarget = dragDropTest = false;
  774. // Hover effect
  775. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  776. if (element && element->IsEnabled())
  777. {
  778. if (!dragElement_ || dragElement_ == element || dragDropTest)
  779. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  780. }
  781. // Drag and drop test
  782. if (dragDropTest)
  783. {
  784. bool accept = element->OnDragDropTest(dragElement_);
  785. if (accept)
  786. {
  787. using namespace DragDropTest;
  788. VariantMap& eventData = GetEventDataMap();
  789. eventData[P_SOURCE] = dragElement_.Get();
  790. eventData[P_TARGET] = element.Get();
  791. eventData[P_ACCEPT] = accept;
  792. SendEvent(E_DRAGDROPTEST, eventData);
  793. accept = eventData[P_ACCEPT].GetBool();
  794. }
  795. if (cursor)
  796. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  797. }
  798. else if (dragSource && cursor)
  799. cursor->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  800. }
  801. void UI::ProcessClickBegin(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  802. {
  803. if (cursorVisible)
  804. {
  805. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  806. if (element)
  807. {
  808. // Handle focusing & bringing to front
  809. if (button == MOUSEB_LEFT)
  810. {
  811. SetFocusElement(element);
  812. element->BringToFront();
  813. }
  814. // Handle click
  815. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  816. SendClickEvent(E_UIMOUSECLICK, element, cursorPos, button, buttons, qualifiers);
  817. // Remember element clicked on for the click end
  818. clickElement_ = element;
  819. // Fire double click event if element matches and is in time
  820. if (doubleClickElement_ && element == doubleClickElement_ && clickTimer_.GetMSec(true) <
  821. (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
  822. {
  823. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  824. doubleClickElement_.Reset();
  825. SendClickEvent(E_UIMOUSEDOUBLECLICK, element, cursorPos, button, buttons, qualifiers);
  826. }
  827. else
  828. {
  829. doubleClickElement_ = element;
  830. clickTimer_.Reset();
  831. }
  832. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  833. if (element && !dragElement_ && buttons == MOUSEB_LEFT)
  834. {
  835. dragElement_ = element;
  836. dragBeginPending_ = true;
  837. dragBeginPos_ = cursorPos;
  838. dragBeginTimer_.Reset();
  839. }
  840. }
  841. else
  842. {
  843. // If clicked over no element, or a disabled element, lose focus
  844. SetFocusElement(0);
  845. SendClickEvent(E_UIMOUSECLICK, element, cursorPos, button, buttons, qualifiers);
  846. }
  847. lastMouseButtons_ = buttons;
  848. }
  849. }
  850. void UI::ProcessClickEnd(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  851. {
  852. if (cursorVisible)
  853. {
  854. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  855. // Handle end of click
  856. if (element)
  857. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor, clickElement_);
  858. SendClickEvent(E_UIMOUSECLICKEND, element, cursorPos, button, buttons, qualifiers);
  859. // Handle end of drag
  860. if (dragElement_ && !buttons)
  861. {
  862. if (dragElement_->IsEnabled() && dragElement_->IsVisible() && !dragBeginPending_)
  863. {
  864. dragElement_->OnDragEnd(dragElement_->ScreenToElement(cursorPos), cursorPos, cursor);
  865. SendDragEvent(E_DRAGEND, dragElement_, cursorPos);
  866. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  867. if (dragSource)
  868. {
  869. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  870. bool dragDropFinish = dragSource && dragTarget && element != dragElement_;
  871. if (dragDropFinish)
  872. {
  873. bool accept = element->OnDragDropFinish(dragElement_);
  874. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  875. if (accept && dragElement_ && element)
  876. {
  877. using namespace DragDropFinish;
  878. VariantMap& eventData = GetEventDataMap();
  879. eventData[P_SOURCE] = dragElement_.Get();
  880. eventData[P_TARGET] = element.Get();
  881. eventData[P_ACCEPT] = accept;
  882. SendEvent(E_DRAGDROPFINISH, eventData);
  883. }
  884. }
  885. }
  886. }
  887. dragElement_.Reset();
  888. dragBeginPending_ = false;
  889. }
  890. clickElement_.Reset();
  891. }
  892. }
  893. void UI::ProcessMove(const IntVector2& cursorPos, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  894. {
  895. if (cursorVisible && dragElement_ && buttons)
  896. {
  897. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  898. {
  899. // Signal drag begin if distance threshold was exceeded
  900. if (dragBeginPending_)
  901. {
  902. IntVector2 offset = cursorPos - dragBeginPos_;
  903. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  904. {
  905. dragBeginPending_ = false;
  906. dragElement_->OnDragBegin(dragElement_->ScreenToElement(dragBeginPos_), dragBeginPos_, buttons, qualifiers, cursor);
  907. SendDragEvent(E_DRAGBEGIN, dragElement_, dragBeginPos_);
  908. }
  909. }
  910. if (!dragBeginPending_)
  911. {
  912. dragElement_->OnDragMove(dragElement_->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  913. SendDragEvent(E_DRAGMOVE, dragElement_, cursorPos);
  914. }
  915. }
  916. else
  917. {
  918. dragElement_->OnDragEnd(dragElement_->ScreenToElement(cursorPos), cursorPos, cursor);
  919. SendDragEvent(E_DRAGEND, dragElement_, cursorPos);
  920. dragElement_.Reset();
  921. }
  922. }
  923. }
  924. void UI::SendDragEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos)
  925. {
  926. if (!element)
  927. return;
  928. IntVector2 relativePos = element->ScreenToElement(screenPos);
  929. using namespace DragBegin;
  930. VariantMap& eventData = GetEventDataMap();
  931. eventData[P_ELEMENT] = element;
  932. eventData[P_X] = screenPos.x_;
  933. eventData[P_Y] = screenPos.y_;
  934. eventData[P_ELEMENTX] = relativePos.x_;
  935. eventData[P_ELEMENTY] = relativePos.y_;
  936. element->SendEvent(eventType, eventData);
  937. }
  938. void UI::SendClickEvent(StringHash eventType, UIElement* element, const IntVector2& pos, int button, int buttons, int qualifiers)
  939. {
  940. VariantMap& eventData = GetEventDataMap();
  941. eventData[UIMouseClick::P_ELEMENT] = element;
  942. eventData[UIMouseClick::P_X] = pos.x_;
  943. eventData[UIMouseClick::P_Y] = pos.y_;
  944. eventData[UIMouseClick::P_BUTTON] = button;
  945. eventData[UIMouseClick::P_BUTTONS] = buttons;
  946. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers;
  947. // For click end events, send also the element the click began on
  948. if (eventType == E_UIMOUSECLICKEND)
  949. eventData[UIMouseClickEnd::P_BEGINELEMENT] = clickElement_;
  950. SendEvent(eventType, eventData);
  951. }
  952. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  953. {
  954. using namespace ScreenMode;
  955. if (!initialized_)
  956. Initialize();
  957. else
  958. {
  959. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  960. rootModalElement_->SetSize(rootElement_->GetSize());
  961. }
  962. }
  963. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  964. {
  965. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  966. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  967. usingTouchInput_ = false;
  968. IntVector2 cursorPos;
  969. bool cursorVisible;
  970. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  971. ProcessClickBegin(cursorPos, eventData[MouseButtonDown::P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_,
  972. cursorVisible);
  973. }
  974. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  975. {
  976. using namespace MouseButtonUp;
  977. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  978. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  979. IntVector2 cursorPos;
  980. bool cursorVisible;
  981. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  982. ProcessClickEnd(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  983. }
  984. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  985. {
  986. using namespace MouseMove;
  987. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  988. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  989. usingTouchInput_ = false;
  990. Input* input = GetSubsystem<Input>();
  991. const IntVector2& rootSize = rootElement_->GetSize();
  992. if (cursor_)
  993. {
  994. if (!input->IsMouseVisible())
  995. {
  996. // Relative mouse motion: move cursor only when visible
  997. if (cursor_->IsVisible())
  998. {
  999. IntVector2 pos = cursor_->GetPosition();
  1000. pos.x_ += eventData[P_DX].GetInt();
  1001. pos.y_ += eventData[P_DY].GetInt();
  1002. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  1003. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  1004. cursor_->SetPosition(pos);
  1005. }
  1006. }
  1007. else
  1008. {
  1009. // Absolute mouse motion: move always
  1010. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  1011. }
  1012. }
  1013. IntVector2 cursorPos;
  1014. bool cursorVisible;
  1015. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1016. ProcessMove(cursorPos, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1017. }
  1018. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1019. {
  1020. using namespace MouseWheel;
  1021. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1022. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1023. int delta = eventData[P_WHEEL].GetInt();
  1024. usingTouchInput_ = false;
  1025. IntVector2 cursorPos;
  1026. bool cursorVisible;
  1027. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1028. UIElement* element;
  1029. if (!nonFocusedMouseWheel_&& (element = focusElement_))
  1030. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1031. else
  1032. {
  1033. // If no element has actual focus or in non-focused mode, get the element at cursor
  1034. if (cursorVisible)
  1035. {
  1036. element = GetElementAt(cursorPos);
  1037. if (nonFocusedMouseWheel_)
  1038. {
  1039. // Going up the hierarchy chain to find element that could handle mouse wheel
  1040. while (element)
  1041. {
  1042. if (element->GetType() == ListView::GetTypeStatic() ||
  1043. element->GetType() == ScrollView::GetTypeStatic())
  1044. break;
  1045. element = element->GetParent();
  1046. }
  1047. }
  1048. else
  1049. // If the element itself is not focusable, search for a focusable parent,
  1050. // although the focusable element may not actually handle mouse wheel
  1051. element = GetFocusableElement(element);
  1052. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1053. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1054. }
  1055. }
  1056. }
  1057. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1058. {
  1059. using namespace TouchBegin;
  1060. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1061. WeakPtr<UIElement> element(GetElementAt(pos));
  1062. usingTouchInput_ = true;
  1063. ProcessClickBegin(pos, MOUSEB_LEFT, MOUSEB_LEFT, 0, 0, true);
  1064. }
  1065. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1066. {
  1067. using namespace TouchEnd;
  1068. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1069. // Transmit hover end to the position where the finger was lifted
  1070. UIElement* element = GetElementAt(pos);
  1071. if (element && element->IsEnabled())
  1072. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  1073. ProcessClickEnd(pos, MOUSEB_LEFT, 0, 0, 0, true);
  1074. }
  1075. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1076. {
  1077. using namespace TouchMove;
  1078. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1079. usingTouchInput_ = true;
  1080. ProcessMove(pos, MOUSEB_LEFT, 0, 0, true);
  1081. }
  1082. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1083. {
  1084. using namespace KeyDown;
  1085. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1086. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1087. int key = eventData[P_KEY].GetInt();
  1088. // Dismiss modal element if any when ESC key is pressed
  1089. if (key == KEY_ESC && HasModalElement())
  1090. {
  1091. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1092. if (element->GetVars().Contains(VAR_ORIGIN))
  1093. // If it is a popup, dismiss by defocusing it
  1094. SetFocusElement(0);
  1095. else
  1096. {
  1097. // If it is a modal window, by resetting its modal flag
  1098. Window* window = dynamic_cast<Window*>(element);
  1099. if (window)
  1100. window->SetModal(false);
  1101. }
  1102. return;
  1103. }
  1104. UIElement* element = focusElement_;
  1105. if (element)
  1106. {
  1107. // Switch focus between focusable elements in the same top level window
  1108. if (key == KEY_TAB)
  1109. {
  1110. UIElement* topLevel = element->GetParent();
  1111. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1112. topLevel = topLevel->GetParent();
  1113. if (topLevel)
  1114. {
  1115. topLevel->GetChildren(tempElements_, true);
  1116. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1117. {
  1118. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1119. i = tempElements_.Erase(i);
  1120. else
  1121. ++i;
  1122. }
  1123. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1124. {
  1125. if (tempElements_[i] == element)
  1126. {
  1127. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1128. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1129. UIElement* next = tempElements_[nextIndex];
  1130. SetFocusElement(next, true);
  1131. return;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. // Defocus the element
  1137. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1138. element->SetFocus(false);
  1139. // If none of the special keys, pass the key to the focused element
  1140. else
  1141. element->OnKey(key, mouseButtons_, qualifiers_);
  1142. }
  1143. }
  1144. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  1145. {
  1146. using namespace Char;
  1147. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1148. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1149. UIElement* element = focusElement_;
  1150. if (element)
  1151. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  1152. }
  1153. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1154. {
  1155. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1156. // custom shapes can do it after this, but needs to do it each frame
  1157. if (cursor_ && !dragElement_)
  1158. cursor_->SetShape(CS_NORMAL);
  1159. }
  1160. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1161. {
  1162. using namespace PostUpdate;
  1163. Update(eventData[P_TIMESTEP].GetFloat());
  1164. }
  1165. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1166. {
  1167. RenderUpdate();
  1168. }
  1169. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1170. {
  1171. Input* input = GetSubsystem<Input>();
  1172. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1173. if (input->IsMouseVisible())
  1174. {
  1175. IntVector2 screenPos = input->GetMousePosition();
  1176. UIElement* element = GetElementAt(screenPos);
  1177. using namespace UIDropFile;
  1178. VariantMap uiEventData;
  1179. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1180. uiEventData[P_X] = screenPos.x_;
  1181. uiEventData[P_Y] = screenPos.y_;
  1182. uiEventData[P_ELEMENT] = element;
  1183. if (element)
  1184. {
  1185. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1186. uiEventData[P_ELEMENTX] = relativePos.x_;
  1187. uiEventData[P_ELEMENTY] = relativePos.y_;
  1188. }
  1189. SendEvent(E_UIDROPFILE, uiEventData);
  1190. }
  1191. }
  1192. void RegisterUILibrary(Context* context)
  1193. {
  1194. Font::RegisterObject(context);
  1195. UIElement::RegisterObject(context);
  1196. BorderImage::RegisterObject(context);
  1197. Sprite::RegisterObject(context);
  1198. Button::RegisterObject(context);
  1199. CheckBox::RegisterObject(context);
  1200. Cursor::RegisterObject(context);
  1201. Text::RegisterObject(context);
  1202. Text3D::RegisterObject(context);
  1203. Window::RegisterObject(context);
  1204. View3D::RegisterObject(context);
  1205. LineEdit::RegisterObject(context);
  1206. Slider::RegisterObject(context);
  1207. ScrollBar::RegisterObject(context);
  1208. ScrollView::RegisterObject(context);
  1209. ListView::RegisterObject(context);
  1210. Menu::RegisterObject(context);
  1211. DropDownList::RegisterObject(context);
  1212. FileSelector::RegisterObject(context);
  1213. MessageBox::RegisterObject(context);
  1214. ToolTip::RegisterObject(context);
  1215. }
  1216. }