UI.cpp 43 KB

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