UI.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. // Set clipping scissor for child elements. No need to draw if zero size
  537. element->AdjustScissor(currentScissor);
  538. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  539. return;
  540. element->SortChildren();
  541. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  542. if (children.Empty())
  543. return;
  544. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  545. // same renderstate
  546. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  547. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  548. {
  549. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  550. while (i != children.End())
  551. {
  552. int currentPriority = (*i)->GetPriority();
  553. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  554. {
  555. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  556. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  557. ++j;
  558. }
  559. // Now recurse into the children
  560. while (i != j)
  561. {
  562. if ((*i)->IsVisible() && (*i) != cursor_)
  563. GetBatches(*i, currentScissor);
  564. ++i;
  565. }
  566. }
  567. }
  568. // On the root level draw each element and its children immediately after to avoid artifacts
  569. else
  570. {
  571. while (i != children.End())
  572. {
  573. if ((*i) != cursor_)
  574. {
  575. if ((*i)->IsWithinScissor(currentScissor))
  576. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  577. if ((*i)->IsVisible())
  578. GetBatches(*i, currentScissor);
  579. }
  580. ++i;
  581. }
  582. }
  583. }
  584. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  585. {
  586. if (!current)
  587. return;
  588. current->SortChildren();
  589. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  590. LayoutMode parentLayoutMode = current->GetLayoutMode();
  591. for (unsigned i = 0; i < children.Size(); ++i)
  592. {
  593. UIElement* element = children[i];
  594. bool hasChildren = element->GetNumChildren() > 0;
  595. if (element != cursor_.Get() && element->IsVisible())
  596. {
  597. if (element->IsInside(position, true))
  598. {
  599. // Store the current result, then recurse into its children. Because children
  600. // are sorted from lowest to highest priority, the topmost match should remain
  601. if (element->IsEnabled() || !enabledOnly)
  602. result = element;
  603. if (hasChildren)
  604. GetElementAt(result, element, position, enabledOnly);
  605. // Layout optimization: if the element has no children, can break out after the first match
  606. else if (parentLayoutMode != LM_FREE)
  607. break;
  608. }
  609. else
  610. {
  611. if (hasChildren)
  612. {
  613. if (element->IsInsideCombined(position, true))
  614. GetElementAt(result, element, position, enabledOnly);
  615. }
  616. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  617. // or if we already passed all visible elements
  618. else if (parentLayoutMode != LM_FREE)
  619. {
  620. if (!i)
  621. {
  622. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  623. element->GetScreenPosition().y_;
  624. int layoutMinSize = current->GetLayoutMinSize();
  625. if (screenPos < 0 && layoutMinSize > 0)
  626. {
  627. unsigned toSkip = -screenPos / layoutMinSize;
  628. if (toSkip > 0)
  629. i += (toSkip - 1);
  630. }
  631. }
  632. else if (parentLayoutMode == LM_HORIZONTAL)
  633. {
  634. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  635. break;
  636. }
  637. else if (parentLayoutMode == LM_VERTICAL)
  638. {
  639. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  640. break;
  641. }
  642. }
  643. }
  644. }
  645. }
  646. }
  647. UIElement* UI::GetFocusableElement(UIElement* element)
  648. {
  649. while (element)
  650. {
  651. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  652. break;
  653. element = element->GetParent();
  654. }
  655. return element;
  656. }
  657. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  658. {
  659. if (cursor_)
  660. {
  661. pos = cursor_->GetPosition();
  662. visible = cursor_->IsVisible();
  663. }
  664. else
  665. {
  666. Input* input = GetSubsystem<Input>();
  667. pos = input->GetMousePosition();
  668. visible = input->IsMouseVisible();
  669. }
  670. }
  671. void UI::SetCursorShape(CursorShape shape)
  672. {
  673. if (cursor_)
  674. cursor_->SetShape(shape);
  675. }
  676. void UI::SendDragEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos)
  677. {
  678. if (!element)
  679. return;
  680. IntVector2 relativePos = element->ScreenToElement(screenPos);
  681. using namespace DragBegin;
  682. VariantMap eventData;
  683. eventData[P_ELEMENT] = (void*)element;
  684. eventData[P_X] = screenPos.x_;
  685. eventData[P_Y] = screenPos.y_;
  686. eventData[P_ELEMENTX] = relativePos.x_;
  687. eventData[P_ELEMENTY] = relativePos.y_;
  688. element->SendEvent(eventType, eventData);
  689. }
  690. void UI::SendClickEvent(StringHash eventType, UIElement* element, const IntVector2& pos, int button, int buttons, int qualifiers)
  691. {
  692. VariantMap eventData;
  693. eventData[UIMouseClick::P_ELEMENT] = (void*)element;
  694. eventData[UIMouseClick::P_X] = pos.x_;
  695. eventData[UIMouseClick::P_Y] = pos.y_;
  696. eventData[UIMouseClick::P_BUTTON] = button;
  697. eventData[UIMouseClick::P_BUTTONS] = buttons;
  698. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers;
  699. SendEvent(eventType, eventData);
  700. }
  701. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  702. {
  703. using namespace ScreenMode;
  704. if (!initialized_)
  705. Initialize();
  706. else
  707. {
  708. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  709. rootModalElement_->SetSize(rootElement_->GetSize());
  710. }
  711. }
  712. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  713. {
  714. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  715. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  716. usingTouchInput_ = false;
  717. IntVector2 cursorPos;
  718. bool cursorVisible;
  719. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  720. if (cursorVisible)
  721. {
  722. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  723. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  724. if (element)
  725. {
  726. // Handle focusing & bringing to front
  727. if (button == MOUSEB_LEFT)
  728. {
  729. SetFocusElement(element);
  730. element->BringToFront();
  731. }
  732. // Handle click
  733. element->OnClick(element->ScreenToElement(cursorPos), cursorPos, mouseButtons_, qualifiers_, cursor_);
  734. SendClickEvent(E_UIMOUSECLICK, element, cursorPos, button, mouseButtons_, qualifiers_);
  735. // Fire double click event if element matches and is in time
  736. if (doubleClickElement_ && element == doubleClickElement_ && clickTimer_->GetMSec(true) <
  737. (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == mouseButtons_)
  738. {
  739. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, mouseButtons_, qualifiers_, cursor_);
  740. doubleClickElement_.Reset();
  741. SendClickEvent(E_UIMOUSEDOUBLECLICK, element, cursorPos, button, mouseButtons_, qualifiers_);
  742. }
  743. else
  744. {
  745. doubleClickElement_ = element;
  746. clickTimer_->Reset();
  747. }
  748. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  749. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  750. {
  751. dragElement_ = element;
  752. element->OnDragBegin(element->ScreenToElement(cursorPos), cursorPos, mouseButtons_, qualifiers_, cursor_);
  753. SendDragEvent(E_DRAGBEGIN, element, cursorPos);
  754. }
  755. }
  756. else
  757. {
  758. // If clicked over no element, or a disabled element, lose focus
  759. SetFocusElement(0);
  760. SendClickEvent(E_UIMOUSECLICK, element, cursorPos, button, mouseButtons_, qualifiers_);
  761. }
  762. lastMouseButtons_ = mouseButtons_;
  763. }
  764. }
  765. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  766. {
  767. using namespace MouseButtonUp;
  768. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  769. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  770. IntVector2 cursorPos;
  771. bool cursorVisible;
  772. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  773. if (cursorVisible || dragElement_)
  774. {
  775. if (dragElement_ && !mouseButtons_)
  776. {
  777. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  778. {
  779. dragElement_->OnDragEnd(dragElement_->ScreenToElement(cursorPos), cursorPos, cursor_);
  780. SendDragEvent(E_DRAGEND, dragElement_, cursorPos);
  781. // Drag and drop finish
  782. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  783. if (dragSource)
  784. {
  785. WeakPtr<UIElement> target(GetElementAt(cursorPos));
  786. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  787. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  788. if (dragDropFinish)
  789. {
  790. bool accept = target->OnDragDropFinish(dragElement_);
  791. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  792. if (accept && dragElement_ && target)
  793. {
  794. using namespace DragDropFinish;
  795. VariantMap eventData;
  796. eventData[P_SOURCE] = (void*)dragElement_.Get();
  797. eventData[P_TARGET] = (void*)target.Get();
  798. eventData[P_ACCEPT] = accept;
  799. SendEvent(E_DRAGDROPFINISH, eventData);
  800. }
  801. }
  802. }
  803. }
  804. dragElement_.Reset();
  805. }
  806. }
  807. }
  808. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  809. {
  810. using namespace MouseMove;
  811. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  812. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  813. usingTouchInput_ = false;
  814. Input* input = GetSubsystem<Input>();
  815. const IntVector2& rootSize = rootElement_->GetSize();
  816. if (cursor_)
  817. {
  818. if (!input->IsMouseVisible())
  819. {
  820. // Relative mouse motion: move cursor only when visible
  821. if (cursor_->IsVisible())
  822. {
  823. IntVector2 pos = cursor_->GetPosition();
  824. pos.x_ += eventData[P_DX].GetInt();
  825. pos.y_ += eventData[P_DY].GetInt();
  826. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  827. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  828. cursor_->SetPosition(pos);
  829. }
  830. }
  831. else
  832. {
  833. // Absolute mouse motion: move always
  834. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  835. }
  836. }
  837. IntVector2 cursorPos;
  838. bool cursorVisible;
  839. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  840. if (cursorVisible && dragElement_ && mouseButtons_)
  841. {
  842. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  843. {
  844. dragElement_->OnDragMove(dragElement_->ScreenToElement(cursorPos), cursorPos, mouseButtons_, qualifiers_, cursor_);
  845. SendDragEvent(E_DRAGMOVE, dragElement_, cursorPos);
  846. }
  847. else
  848. {
  849. dragElement_->OnDragEnd(dragElement_->ScreenToElement(cursorPos), cursorPos, cursor_);
  850. SendDragEvent(E_DRAGEND, dragElement_, cursorPos);
  851. dragElement_.Reset();
  852. }
  853. }
  854. }
  855. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  856. {
  857. using namespace MouseWheel;
  858. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  859. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  860. int delta = eventData[P_WHEEL].GetInt();
  861. usingTouchInput_ = false;
  862. IntVector2 cursorPos;
  863. bool cursorVisible;
  864. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  865. UIElement* element;
  866. if (!nonFocusedMouseWheel_&& (element = focusElement_))
  867. element->OnWheel(delta, mouseButtons_, qualifiers_);
  868. else
  869. {
  870. // If no element has actual focus or in non-focused mode, get the element at cursor
  871. if (cursorVisible)
  872. {
  873. element = GetElementAt(cursorPos);
  874. if (nonFocusedMouseWheel_)
  875. {
  876. // Going up the hierarchy chain to find element that could handle mouse wheel
  877. while (element)
  878. {
  879. if (element->GetType() == ListView::GetTypeStatic() ||
  880. element->GetType() == ScrollView::GetTypeStatic())
  881. break;
  882. element = element->GetParent();
  883. }
  884. }
  885. else
  886. // If the element itself is not focusable, search for a focusable parent,
  887. // although the focusable element may not actually handle mouse wheel
  888. element = GetFocusableElement(element);
  889. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  890. element->OnWheel(delta, mouseButtons_, qualifiers_);
  891. }
  892. }
  893. }
  894. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  895. {
  896. using namespace TouchBegin;
  897. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  898. WeakPtr<UIElement> element(GetElementAt(pos));
  899. usingTouchInput_ = true;
  900. if (element)
  901. {
  902. // Handle focusing & bringing to front
  903. SetFocusElement(element);
  904. element->BringToFront();
  905. // Handle click
  906. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  907. SendClickEvent(E_UIMOUSECLICK, element, pos, MOUSEB_LEFT, MOUSEB_LEFT, 0);
  908. // Fire double click event if element matches and is in time
  909. if (doubleClickElement_ && element == doubleClickElement_ && clickTimer_->GetMSec(true) <
  910. (unsigned)(doubleClickInterval_ * 1000))
  911. {
  912. element->OnDoubleClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  913. doubleClickElement_.Reset();
  914. SendClickEvent(E_UIMOUSEDOUBLECLICK, element, pos, MOUSEB_LEFT, MOUSEB_LEFT, 0);
  915. }
  916. else
  917. {
  918. doubleClickElement_ = element;
  919. clickTimer_->Reset();
  920. }
  921. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  922. if (element && !dragElement_ )
  923. {
  924. dragElement_ = element;
  925. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  926. SendDragEvent(E_DRAGBEGIN, element, pos);
  927. }
  928. }
  929. else
  930. {
  931. // If clicked over no element, or a disabled element, lose focus
  932. SetFocusElement(0);
  933. SendClickEvent(E_UIMOUSECLICK, element, pos, MOUSEB_LEFT, MOUSEB_LEFT, 0);
  934. }
  935. }
  936. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  937. {
  938. using namespace TouchEnd;
  939. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  940. // Transmit hover end to the position where the finger was lifted
  941. UIElement* element = GetElementAt(pos);
  942. if (element && element->IsEnabled())
  943. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  944. if (dragElement_)
  945. {
  946. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  947. {
  948. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  949. SendDragEvent(E_DRAGEND, dragElement_, pos);
  950. // Drag and drop finish
  951. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  952. if (dragSource)
  953. {
  954. WeakPtr<UIElement> target(GetElementAt(pos));
  955. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  956. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  957. if (dragDropFinish)
  958. {
  959. bool accept = target->OnDragDropFinish(dragElement_);
  960. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  961. if (accept && dragElement_ && target)
  962. {
  963. using namespace DragDropFinish;
  964. VariantMap eventData;
  965. eventData[P_SOURCE] = (void*)dragElement_.Get();
  966. eventData[P_TARGET] = (void*)target.Get();
  967. eventData[P_ACCEPT] = accept;
  968. SendEvent(E_DRAGDROPFINISH, eventData);
  969. }
  970. }
  971. }
  972. }
  973. dragElement_.Reset();
  974. }
  975. }
  976. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  977. {
  978. using namespace TouchMove;
  979. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  980. usingTouchInput_ = true;
  981. if (dragElement_)
  982. {
  983. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  984. {
  985. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  986. SendDragEvent(E_DRAGMOVE, dragElement_, pos);
  987. }
  988. else
  989. {
  990. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  991. SendDragEvent(E_DRAGEND, dragElement_, pos);
  992. dragElement_.Reset();
  993. }
  994. }
  995. }
  996. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  997. {
  998. using namespace KeyDown;
  999. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1000. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1001. int key = eventData[P_KEY].GetInt();
  1002. // Dismiss modal element if any when ESC key is pressed
  1003. if (key == KEY_ESC && HasModalElement())
  1004. {
  1005. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1006. if (element->GetVars().Contains(VAR_ORIGIN))
  1007. // If it is a popup, dismiss by defocusing it
  1008. SetFocusElement(0);
  1009. else
  1010. {
  1011. // If it is a modal window, by resetting its modal flag
  1012. Window* window = dynamic_cast<Window*>(element);
  1013. if (window)
  1014. window->SetModal(false);
  1015. }
  1016. return;
  1017. }
  1018. UIElement* element = focusElement_;
  1019. if (element)
  1020. {
  1021. // Switch focus between focusable elements in the same top level window
  1022. if (key == KEY_TAB)
  1023. {
  1024. UIElement* topLevel = element->GetParent();
  1025. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1026. topLevel = topLevel->GetParent();
  1027. if (topLevel)
  1028. {
  1029. topLevel->GetChildren(tempElements_, true);
  1030. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1031. {
  1032. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1033. i = tempElements_.Erase(i);
  1034. else
  1035. ++i;
  1036. }
  1037. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1038. {
  1039. if (tempElements_[i] == element)
  1040. {
  1041. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  1042. SetFocusElement(next);
  1043. return;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. // Defocus the element
  1049. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1050. element->SetFocus(false);
  1051. // If none of the special keys, pass the key to the focused element
  1052. else
  1053. element->OnKey(key, mouseButtons_, qualifiers_);
  1054. }
  1055. }
  1056. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  1057. {
  1058. using namespace Char;
  1059. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1060. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1061. UIElement* element = focusElement_;
  1062. if (element)
  1063. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  1064. }
  1065. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1066. {
  1067. using namespace PostUpdate;
  1068. Update(eventData[P_TIMESTEP].GetFloat());
  1069. }
  1070. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1071. {
  1072. RenderUpdate();
  1073. }
  1074. void RegisterUILibrary(Context* context)
  1075. {
  1076. Font::RegisterObject(context);
  1077. UIElement::RegisterObject(context);
  1078. BorderImage::RegisterObject(context);
  1079. Sprite::RegisterObject(context);
  1080. Button::RegisterObject(context);
  1081. CheckBox::RegisterObject(context);
  1082. Cursor::RegisterObject(context);
  1083. Text::RegisterObject(context);
  1084. Text3D::RegisterObject(context);
  1085. Window::RegisterObject(context);
  1086. LineEdit::RegisterObject(context);
  1087. Slider::RegisterObject(context);
  1088. ScrollBar::RegisterObject(context);
  1089. ScrollView::RegisterObject(context);
  1090. ListView::RegisterObject(context);
  1091. Menu::RegisterObject(context);
  1092. DropDownList::RegisterObject(context);
  1093. FileSelector::RegisterObject(context);
  1094. }
  1095. }