UI.cpp 35 KB

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