UI.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CheckBox.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "Cursor.h"
  28. #include "DropDownList.h"
  29. #include "FileSelector.h"
  30. #include "Font.h"
  31. #include "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "Input.h"
  34. #include "InputEvents.h"
  35. #include "LineEdit.h"
  36. #include "ListView.h"
  37. #include "Log.h"
  38. #include "Matrix3x4.h"
  39. #include "Profiler.h"
  40. #include "Renderer.h"
  41. #include "ScrollBar.h"
  42. #include "Shader.h"
  43. #include "ShaderVariation.h"
  44. #include "Slider.h"
  45. #include "Text.h"
  46. #include "Texture2D.h"
  47. #include "UI.h"
  48. #include "UIEvents.h"
  49. #include "VertexBuffer.h"
  50. #include "Window.h"
  51. #include "Sort.h"
  52. #include "DebugNew.h"
  53. namespace Urho3D
  54. {
  55. OBJECTTYPESTATIC(UI);
  56. UI::UI(Context* context) :
  57. Object(context),
  58. mouseButtons_(0),
  59. qualifiers_(0),
  60. initialized_(false)
  61. {
  62. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  63. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  64. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  65. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  66. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  67. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  68. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  69. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  70. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  71. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  72. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  73. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  74. // Try to initialize right now, but skip if screen mode is not yet set
  75. Initialize();
  76. }
  77. UI::~UI()
  78. {
  79. }
  80. void UI::SetCursor(Cursor* cursor)
  81. {
  82. if (!rootElement_)
  83. return;
  84. // Remove old cursor (if any) and set new
  85. if (cursor_)
  86. {
  87. rootElement_->RemoveChild(cursor_);
  88. cursor_.Reset();
  89. }
  90. if (cursor)
  91. {
  92. rootElement_->AddChild(cursor);
  93. cursor_ = cursor;
  94. IntVector2 pos = cursor_->GetPosition();
  95. const IntVector2& rootSize = rootElement_->GetSize();
  96. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  97. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  98. cursor_->SetPosition(pos);
  99. }
  100. }
  101. void UI::SetFocusElement(UIElement* element)
  102. {
  103. if (!rootElement_)
  104. return;
  105. using namespace FocusChanged;
  106. VariantMap eventData;
  107. eventData[P_CLICKEDELEMENT] = (void*)element;
  108. if (element)
  109. {
  110. // Return if already has focus
  111. if (focusElement_ == element)
  112. return;
  113. // Search for an element in the hierarchy that can alter focus. If none found, exit
  114. element = GetFocusableElement(element);
  115. if (!element)
  116. return;
  117. }
  118. // Remove focus from the old element
  119. if (focusElement_)
  120. {
  121. UIElement* oldFocusElement = focusElement_;
  122. focusElement_.Reset();
  123. VariantMap focusEventData;
  124. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  125. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  126. }
  127. // Then set focus to the new
  128. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  129. {
  130. focusElement_ = element;
  131. VariantMap focusEventData;
  132. focusEventData[Focused::P_ELEMENT] = element;
  133. element->SendEvent(E_FOCUSED, focusEventData);
  134. }
  135. eventData[P_ELEMENT] = (void*)element;
  136. SendEvent(E_FOCUSCHANGED, eventData);
  137. }
  138. void UI::Clear()
  139. {
  140. if (!rootElement_)
  141. return;
  142. rootElement_->RemoveAllChildren();
  143. if (cursor_)
  144. rootElement_->AddChild(cursor_);
  145. }
  146. void UI::Update(float timeStep)
  147. {
  148. if (!rootElement_)
  149. return;
  150. PROFILE(UpdateUI);
  151. if (cursor_ && cursor_->IsVisible())
  152. {
  153. IntVector2 pos = cursor_->GetPosition();
  154. WeakPtr<UIElement> element(GetElementAt(pos));
  155. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  156. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  157. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  158. // Hover effect
  159. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  160. if (element)
  161. {
  162. if (!dragElement_ || dragElement_ == element || dragDropTest)
  163. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  164. }
  165. // Drag and drop test
  166. if (dragDropTest)
  167. {
  168. bool accept = element->OnDragDropTest(dragElement_);
  169. if (accept)
  170. {
  171. using namespace DragDropTest;
  172. VariantMap eventData;
  173. eventData[P_SOURCE] = (void*)dragElement_.Get();
  174. eventData[P_TARGET] = (void*)element.Get();
  175. eventData[P_ACCEPT] = accept;
  176. SendEvent(E_DRAGDROPTEST, eventData);
  177. accept = eventData[P_ACCEPT].GetBool();
  178. }
  179. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  180. }
  181. else if (dragSource)
  182. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  183. }
  184. // Touch hover
  185. Input* input = GetSubsystem<Input>();
  186. if (input)
  187. {
  188. unsigned numTouches = input->GetNumTouches();
  189. for (unsigned i = 0; i < numTouches; ++i)
  190. {
  191. TouchState* touch = input->GetTouch(i);
  192. WeakPtr<UIElement> element(GetElementAt(touch->position_));
  193. if (element)
  194. element->OnHover(element->ScreenToElement(touch->position_), touch->position_, MOUSEB_LEFT, 0, 0);
  195. }
  196. }
  197. Update(timeStep, rootElement_);
  198. }
  199. void UI::RenderUpdate()
  200. {
  201. if (!rootElement_ || !graphics_)
  202. return;
  203. PROFILE(GetUIBatches);
  204. // If the OS cursor is visible, do not render the UI's own cursor
  205. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  206. bool uiCursorVisible = false;
  207. if (osCursorVisible && cursor_)
  208. {
  209. uiCursorVisible = cursor_->IsVisible();
  210. cursor_->SetTempVisible(false);
  211. }
  212. // Get batches & quads from the UI elements
  213. batches_.Clear();
  214. quads_.Clear();
  215. const IntVector2& rootSize = rootElement_->GetSize();
  216. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  217. // If no drag, reset cursor shape for next frame
  218. if (cursor_ && !dragElement_)
  219. cursor_->SetShape(CS_NORMAL);
  220. // Restore UI cursor visibility state
  221. if (osCursorVisible && cursor_)
  222. cursor_->SetTempVisible(uiCursorVisible);
  223. }
  224. void UI::Render()
  225. {
  226. PROFILE(RenderUI);
  227. if (!graphics_ || graphics_->IsDeviceLost() || !quads_.Size())
  228. return;
  229. // Update quad geometry into the vertex buffer
  230. unsigned numVertices = quads_.Size() * 6;
  231. // Resize the vertex buffer if too small or much too large
  232. if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
  233. vertexBuffer_->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  234. unsigned vertexSize = vertexBuffer_->GetVertexSize();
  235. void* dest = vertexBuffer_->Lock(0, numVertices, true);
  236. if (!dest)
  237. return;
  238. for (unsigned i = 0; i < batches_.Size(); ++i)
  239. batches_[i].UpdateGeometry(graphics_, ((unsigned char*)dest) + batches_[i].quadStart_ * vertexSize * 6);
  240. vertexBuffer_->Unlock();
  241. Vector2 scale(2.0f, -2.0f);
  242. Vector2 offset(-1.0f, 1.0f);
  243. Matrix4 projection(Matrix4::IDENTITY);
  244. projection.m00_ = scale.x_;
  245. projection.m03_ = offset.x_;
  246. projection.m11_ = scale.y_;
  247. projection.m13_ = offset.y_;
  248. projection.m22_ = 1.0f;
  249. projection.m23_ = 0.0f;
  250. projection.m33_ = 1.0f;
  251. graphics_->ClearParameterSources();
  252. graphics_->SetCullMode(CULL_CCW);
  253. graphics_->SetDepthTest(CMP_ALWAYS);
  254. graphics_->SetDepthWrite(false);
  255. graphics_->SetStencilTest(false);
  256. graphics_->ResetRenderTargets();
  257. ShaderVariation* ps = 0;
  258. ShaderVariation* vs = 0;
  259. unsigned alphaFormat = Graphics::GetAlphaFormat();
  260. for (unsigned i = 0; i < batches_.Size(); ++i)
  261. {
  262. const UIBatch& batch = batches_[i];
  263. if (!batch.quadCount_)
  264. continue;
  265. if (!batch.texture_)
  266. {
  267. ps = noTexturePS_;
  268. vs = noTextureVS_;
  269. }
  270. else
  271. {
  272. // If texture contains only an alpha channel, use alpha shader (for fonts)
  273. vs = diffTextureVS_;
  274. if (batch.texture_->GetFormat() == alphaFormat)
  275. ps = alphaTexturePS_;
  276. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  277. ps = diffMaskTexturePS_;
  278. else
  279. ps = diffTexturePS_;
  280. }
  281. graphics_->SetShaders(vs, ps);
  282. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  283. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  284. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  285. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  286. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  287. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  288. graphics_->SetBlendMode(batch.blendMode_);
  289. graphics_->SetScissorTest(true, batch.scissor_);
  290. graphics_->SetTexture(0, batch.texture_);
  291. graphics_->SetVertexBuffer(vertexBuffer_);
  292. graphics_->Draw(TRIANGLE_LIST, batch.quadStart_ * 6, batch.quadCount_ * 6);
  293. }
  294. }
  295. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  296. {
  297. PROFILE(LoadUILayout);
  298. SharedPtr<UIElement> root;
  299. if (!file)
  300. {
  301. LOGERROR("Null UI layout XML file");
  302. return root;
  303. }
  304. LOGDEBUG("Loading UI layout " + file->GetName());
  305. XMLElement rootElem = file->GetRoot("element");
  306. if (!rootElem)
  307. {
  308. LOGERROR("No root UI element in " + file->GetName());
  309. return root;
  310. }
  311. String type = rootElem.GetAttribute("type");
  312. if (type.Empty())
  313. type = "UIElement";
  314. root = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  315. if (!root)
  316. {
  317. LOGERROR("Could not create unknown UI element " + type);
  318. return root;
  319. }
  320. root->SetName(rootElem.GetAttribute("name"));
  321. String styleName = rootElem.HasAttribute("style") ? rootElem.GetAttribute("style") : rootElem.GetAttribute("type");
  322. // First set the base style from the style file if exists, then apply UI layout overrides
  323. if (styleFile)
  324. root->SetStyle(styleFile, styleName);
  325. root->SetStyle(rootElem);
  326. // Load rest of the elements recursively
  327. LoadLayout(root, rootElem, styleFile);
  328. return root;
  329. }
  330. void UI::SetClipBoardText(const String& text)
  331. {
  332. clipBoard_ = text;
  333. }
  334. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  335. {
  336. if (!rootElement_)
  337. return 0;
  338. UIElement* result = 0;
  339. GetElementAt(result, rootElement_, position, activeOnly);
  340. return result;
  341. }
  342. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  343. {
  344. return GetElementAt(IntVector2(x, y), activeOnly);
  345. }
  346. UIElement* UI::GetFocusElement() const
  347. {
  348. return focusElement_;
  349. }
  350. UIElement* UI::GetFrontElement() const
  351. {
  352. if (!rootElement_)
  353. return 0;
  354. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  355. int maxPriority = M_MIN_INT;
  356. UIElement* front = 0;
  357. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  358. {
  359. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  360. if (!rootChildren[i]->IsActive() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  361. continue;
  362. int priority = rootChildren[i]->GetPriority();
  363. if (priority > maxPriority)
  364. {
  365. maxPriority = priority;
  366. front = rootChildren[i];
  367. }
  368. }
  369. return front;
  370. }
  371. IntVector2 UI::GetCursorPosition()
  372. {
  373. if (!cursor_)
  374. return IntVector2::ZERO;
  375. else
  376. return cursor_->GetPosition();
  377. }
  378. void UI::Initialize()
  379. {
  380. Graphics* graphics = GetSubsystem<Graphics>();
  381. Renderer* renderer = GetSubsystem<Renderer>();
  382. if (!graphics || !graphics->IsInitialized() || !renderer)
  383. return;
  384. PROFILE(InitUI);
  385. graphics_ = graphics;
  386. rootElement_ = new UIElement(context_);
  387. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  388. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  389. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  390. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  391. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  392. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  393. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  394. vertexBuffer_ = new VertexBuffer(context_);
  395. LOGINFO("Initialized user interface");
  396. initialized_ = true;
  397. }
  398. void UI::Update(float timeStep, UIElement* element)
  399. {
  400. element->Update(timeStep);
  401. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  402. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  403. Update(timeStep, *i);
  404. }
  405. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  406. {
  407. // Set clipping scissor for child elements. No need to draw if zero size
  408. element->AdjustScissor(currentScissor);
  409. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  410. return;
  411. element->SortChildren();
  412. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  413. if (children.Empty())
  414. return;
  415. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  416. // same renderstate
  417. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  418. if (element != rootElement_)
  419. {
  420. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  421. int currentPriority = children.Front()->GetPriority();
  422. while (i != children.End())
  423. {
  424. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  425. {
  426. if (IsVisible(*j, currentScissor))
  427. (*j)->GetBatches(batches_, quads_, currentScissor);
  428. ++j;
  429. }
  430. // Now recurse into the children
  431. while (i != j)
  432. {
  433. if (IsVisible(*i, currentScissor))
  434. GetBatches(*i, currentScissor);
  435. ++i;
  436. }
  437. if (i != children.End())
  438. currentPriority = (*i)->GetPriority();
  439. }
  440. }
  441. // On the root level draw each element and its children immediately after to avoid artifacts
  442. else
  443. {
  444. while (i != children.End())
  445. {
  446. if ((*i)->IsVisible())
  447. {
  448. if (IsVisible(*i, currentScissor))
  449. (*i)->GetBatches(batches_, quads_, currentScissor);
  450. GetBatches(*i, currentScissor);
  451. }
  452. ++i;
  453. }
  454. }
  455. }
  456. bool UI::IsVisible(UIElement* element, const IntRect& currentScissor)
  457. {
  458. // First check element's visibility
  459. if (!element->IsVisible())
  460. return false;
  461. // Then check element dimensions against the scissor rectangle
  462. const IntVector2& screenPos = element->GetScreenPosition();
  463. if (screenPos.x_ >= currentScissor.right_ || screenPos.x_ + element->GetWidth() <= currentScissor.left_ ||
  464. screenPos.y_ >= currentScissor.bottom_ || screenPos.y_ + element->GetHeight() <= currentScissor.top_)
  465. return false;
  466. else
  467. return true;
  468. }
  469. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  470. {
  471. if (!current)
  472. return;
  473. current->SortChildren();
  474. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  475. LayoutMode parentLayoutMode = current->GetLayoutMode();
  476. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  477. {
  478. UIElement* element = *i;
  479. bool hasChildren = element->GetNumChildren() > 0;
  480. if (element != cursor_.Get() && element->IsVisible())
  481. {
  482. if (element->IsInside(position, true))
  483. {
  484. // Store the current result, then recurse into its children. Because children
  485. // are sorted from lowest to highest priority, the topmost match should remain
  486. if (element->IsActive() || !activeOnly)
  487. result = element;
  488. if (hasChildren)
  489. GetElementAt(result, element, position, activeOnly);
  490. // Layout optimization: if the element has no children, can break out after the first match
  491. else if (parentLayoutMode != LM_FREE)
  492. break;
  493. }
  494. else
  495. {
  496. if (hasChildren)
  497. {
  498. if (element->IsInsideCombined(position, true))
  499. GetElementAt(result, element, position, activeOnly);
  500. }
  501. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  502. // or if we already passed all visible elements
  503. else if (parentLayoutMode != LM_FREE)
  504. {
  505. if (i == children.Begin())
  506. {
  507. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  508. element->GetScreenPosition().y_;
  509. int layoutMinSize = current->GetLayoutMinSize();
  510. if (screenPos < 0 && layoutMinSize > 0)
  511. {
  512. unsigned toSkip = -screenPos / layoutMinSize;
  513. if (toSkip > 0)
  514. {
  515. i += (toSkip - 1);
  516. if (i >= children.End())
  517. break;
  518. }
  519. }
  520. }
  521. else if (parentLayoutMode == LM_HORIZONTAL)
  522. {
  523. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  524. break;
  525. }
  526. else if (parentLayoutMode == LM_VERTICAL)
  527. {
  528. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  529. break;
  530. }
  531. }
  532. }
  533. }
  534. }
  535. }
  536. UIElement* UI::GetFocusableElement(UIElement* element)
  537. {
  538. while (element)
  539. {
  540. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  541. break;
  542. element = element->GetParent();
  543. }
  544. return element;
  545. }
  546. void UI::LoadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  547. {
  548. XMLElement childElem = elem.GetChild("element");
  549. while (childElem)
  550. {
  551. // Create element
  552. String type = childElem.GetAttribute("type");
  553. if (type.Empty())
  554. type = "UIElement";
  555. SharedPtr<UIElement> child = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  556. if (!child)
  557. {
  558. LOGERROR("Could not create unknown UI element " + type);
  559. childElem = childElem.GetNext("element");
  560. continue;
  561. }
  562. child->SetName(childElem.GetAttribute("name"));
  563. // Add to the hierarchy
  564. current->AddChild(child);
  565. // First set the base style from the style file if exists, then apply UI layout overrides
  566. String styleName = childElem.HasAttribute("style") ? childElem.GetAttribute("style") : childElem.GetAttribute("type");
  567. if (styleFile)
  568. child->SetStyle(styleFile, styleName);
  569. child->SetStyle(childElem);
  570. // Load the children recursively
  571. LoadLayout(child, childElem, styleFile);
  572. childElem = childElem.GetNext("element");
  573. }
  574. }
  575. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  576. {
  577. using namespace ScreenMode;
  578. if (!initialized_)
  579. Initialize();
  580. else
  581. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  582. }
  583. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  584. {
  585. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  586. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  587. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  588. if (cursor_ && cursor_->IsVisible())
  589. {
  590. IntVector2 pos = cursor_->GetPosition();
  591. WeakPtr<UIElement> element(GetElementAt(pos));
  592. if (element)
  593. {
  594. // Handle focusing & bringing to front
  595. if (button == MOUSEB_LEFT)
  596. {
  597. SetFocusElement(element);
  598. element->BringToFront();
  599. }
  600. // Handle click
  601. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  602. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  603. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  604. {
  605. dragElement_ = element;
  606. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  607. }
  608. }
  609. else
  610. {
  611. // If clicked over no element, or a disabled element, lose focus
  612. SetFocusElement(0);
  613. }
  614. using namespace UIMouseClick;
  615. VariantMap eventData;
  616. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  617. eventData[UIMouseClick::P_X] = pos.x_;
  618. eventData[UIMouseClick::P_Y] = pos.y_;
  619. eventData[UIMouseClick::P_BUTTON] = button;
  620. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  621. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  622. SendEvent(E_UIMOUSECLICK, eventData);
  623. }
  624. }
  625. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  626. {
  627. using namespace MouseButtonUp;
  628. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  629. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  630. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  631. {
  632. IntVector2 pos = cursor_->GetPosition();
  633. if (dragElement_ && !mouseButtons_)
  634. {
  635. if (dragElement_->IsActive() && dragElement_->IsVisible())
  636. {
  637. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  638. // Drag and drop finish
  639. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  640. if (dragSource)
  641. {
  642. WeakPtr<UIElement> target(GetElementAt(pos));
  643. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  644. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  645. if (dragDropFinish)
  646. {
  647. bool accept = target->OnDragDropFinish(dragElement_);
  648. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  649. if (accept && dragElement_ && target)
  650. {
  651. using namespace DragDropFinish;
  652. VariantMap eventData;
  653. eventData[P_SOURCE] = (void*)dragElement_.Get();
  654. eventData[P_TARGET] = (void*)target.Get();
  655. eventData[P_ACCEPT] = accept;
  656. SendEvent(E_DRAGDROPFINISH, eventData);
  657. }
  658. }
  659. }
  660. }
  661. dragElement_.Reset();
  662. }
  663. }
  664. }
  665. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  666. {
  667. using namespace MouseMove;
  668. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  669. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  670. if (cursor_)
  671. {
  672. Input* input = GetSubsystem<Input>();
  673. const IntVector2& rootSize = rootElement_->GetSize();
  674. if (!input->IsMouseVisible())
  675. {
  676. // Relative mouse motion: move cursor only when visible
  677. if (cursor_->IsVisible())
  678. {
  679. IntVector2 pos = cursor_->GetPosition();
  680. pos.x_ += eventData[P_DX].GetInt();
  681. pos.y_ += eventData[P_DY].GetInt();
  682. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  683. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  684. cursor_->SetPosition(pos);
  685. }
  686. }
  687. else
  688. {
  689. // Absolute mouse motion: move always
  690. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  691. }
  692. if (dragElement_ && mouseButtons_)
  693. {
  694. IntVector2 pos = cursor_->GetPosition();
  695. if (dragElement_->IsActive() && dragElement_->IsVisible())
  696. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  697. else
  698. {
  699. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  700. dragElement_.Reset();
  701. }
  702. }
  703. }
  704. }
  705. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  706. {
  707. using namespace MouseWheel;
  708. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  709. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  710. int delta = eventData[P_WHEEL].GetInt();
  711. UIElement* element = GetFocusElement();
  712. if (element)
  713. element->OnWheel(delta, mouseButtons_, qualifiers_);
  714. else
  715. {
  716. // If no element has actual focus, get the element at cursor
  717. if (cursor_)
  718. {
  719. IntVector2 pos = cursor_->GetPosition();
  720. UIElement* element = GetElementAt(pos);
  721. // If the element itself is not focusable, search for a focusable parent
  722. element = GetFocusableElement(element);
  723. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  724. element->OnWheel(delta, mouseButtons_, qualifiers_);
  725. }
  726. }
  727. }
  728. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  729. {
  730. using namespace TouchBegin;
  731. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  732. WeakPtr<UIElement> element(GetElementAt(pos));
  733. if (element)
  734. {
  735. // Handle focusing & bringing to front
  736. SetFocusElement(element);
  737. element->BringToFront();
  738. // Handle click
  739. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  740. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  741. if (element && !dragElement_ )
  742. {
  743. dragElement_ = element;
  744. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  745. }
  746. }
  747. else
  748. {
  749. // If clicked over no element, or a disabled element, lose focus
  750. SetFocusElement(0);
  751. }
  752. using namespace UIMouseClick;
  753. VariantMap clickEventData;
  754. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  755. clickEventData[UIMouseClick::P_X] = pos.x_;
  756. clickEventData[UIMouseClick::P_Y] = pos.y_;
  757. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  758. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  759. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  760. SendEvent(E_UIMOUSECLICK, clickEventData);
  761. }
  762. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  763. {
  764. using namespace TouchEnd;
  765. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  766. // Transmit hover end to the position where the finger was lifted
  767. WeakPtr<UIElement> element(GetElementAt(pos));
  768. if (element)
  769. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  770. if (dragElement_)
  771. {
  772. if (dragElement_->IsActive() && dragElement_->IsVisible())
  773. {
  774. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  775. // Drag and drop finish
  776. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  777. if (dragSource)
  778. {
  779. WeakPtr<UIElement> target(GetElementAt(pos));
  780. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  781. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  782. if (dragDropFinish)
  783. {
  784. bool accept = target->OnDragDropFinish(dragElement_);
  785. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  786. if (accept && dragElement_ && target)
  787. {
  788. using namespace DragDropFinish;
  789. VariantMap eventData;
  790. eventData[P_SOURCE] = (void*)dragElement_.Get();
  791. eventData[P_TARGET] = (void*)target.Get();
  792. eventData[P_ACCEPT] = accept;
  793. SendEvent(E_DRAGDROPFINISH, eventData);
  794. }
  795. }
  796. }
  797. }
  798. dragElement_.Reset();
  799. }
  800. }
  801. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  802. {
  803. using namespace TouchMove;
  804. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  805. if (dragElement_)
  806. {
  807. if (dragElement_->IsActive() && dragElement_->IsVisible())
  808. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  809. else
  810. {
  811. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  812. dragElement_.Reset();
  813. }
  814. }
  815. }
  816. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  817. {
  818. using namespace KeyDown;
  819. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  820. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  821. int key = eventData[P_KEY].GetInt();
  822. UIElement* element = GetFocusElement();
  823. if (element)
  824. {
  825. // Switch focus between focusable elements in the same top level window
  826. if (key == KEY_TAB)
  827. {
  828. UIElement* topLevel = element->GetParent();
  829. while (topLevel && topLevel->GetParent() != rootElement_)
  830. topLevel = topLevel->GetParent();
  831. if (topLevel)
  832. {
  833. topLevel->GetChildren(tempElements_, true);
  834. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  835. {
  836. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  837. i = tempElements_.Erase(i);
  838. else
  839. ++i;
  840. }
  841. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  842. {
  843. if (tempElements_[i] == element)
  844. {
  845. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  846. SetFocusElement(next);
  847. return;
  848. }
  849. }
  850. }
  851. }
  852. // Defocus the element
  853. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  854. element->SetFocus(false);
  855. // If none of the special keys, pass the key to the focused element
  856. else
  857. element->OnKey(key, mouseButtons_, qualifiers_);
  858. }
  859. }
  860. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  861. {
  862. using namespace Char;
  863. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  864. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  865. UIElement* element = GetFocusElement();
  866. if (element)
  867. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  868. }
  869. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  870. {
  871. if (initialized_)
  872. {
  873. using namespace PostUpdate;
  874. Update(eventData[P_TIMESTEP].GetFloat());
  875. }
  876. }
  877. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  878. {
  879. if (initialized_)
  880. RenderUpdate();
  881. }
  882. void RegisterUILibrary(Context* context)
  883. {
  884. Font::RegisterObject(context);
  885. UIElement::RegisterObject(context);
  886. BorderImage::RegisterObject(context);
  887. Button::RegisterObject(context);
  888. CheckBox::RegisterObject(context);
  889. Cursor::RegisterObject(context);
  890. Text::RegisterObject(context);
  891. Window::RegisterObject(context);
  892. LineEdit::RegisterObject(context);
  893. Slider::RegisterObject(context);
  894. ScrollBar::RegisterObject(context);
  895. ScrollView::RegisterObject(context);
  896. ListView::RegisterObject(context);
  897. Menu::RegisterObject(context);
  898. DropDownList::RegisterObject(context);
  899. FileSelector::RegisterObject(context);
  900. }
  901. }