UI.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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. 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* dest = vertexBuffer_->Lock(0, numVertices, true);
  223. if (!dest)
  224. return;
  225. for (unsigned i = 0; i < batches_.Size(); ++i)
  226. batches_[i].UpdateGeometry(graphics_, ((unsigned char*)dest) + 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. Renderer* renderer = GetSubsystem<Renderer>();
  369. if (!graphics || !graphics->IsInitialized() || !renderer)
  370. return;
  371. PROFILE(InitUI);
  372. graphics_ = graphics;
  373. rootElement_ = new UIElement(context_);
  374. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  375. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  376. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  377. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  378. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  379. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  380. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  381. vertexBuffer_ = new VertexBuffer(context_);
  382. LOGINFO("Initialized user interface");
  383. initialized_ = true;
  384. }
  385. void UI::Update(float timeStep, UIElement* element)
  386. {
  387. element->Update(timeStep);
  388. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  389. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  390. Update(timeStep, *i);
  391. }
  392. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  393. {
  394. // Set clipping scissor for child elements. No need to draw if zero size
  395. element->AdjustScissor(currentScissor);
  396. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  397. return;
  398. element->SortChildren();
  399. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  400. if (children.Empty())
  401. return;
  402. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  403. // same renderstate
  404. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  405. if (element != rootElement_)
  406. {
  407. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  408. int currentPriority = children.Front()->GetPriority();
  409. while (i != children.End())
  410. {
  411. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  412. {
  413. if (IsVisible(*j, currentScissor))
  414. (*j)->GetBatches(batches_, quads_, currentScissor);
  415. ++j;
  416. }
  417. // Now recurse into the children
  418. while (i != j)
  419. {
  420. if (IsVisible(*i, currentScissor))
  421. GetBatches(*i, currentScissor);
  422. ++i;
  423. }
  424. if (i != children.End())
  425. currentPriority = (*i)->GetPriority();
  426. }
  427. }
  428. // On the root level draw each element and its children immediately after to avoid artifacts
  429. else
  430. {
  431. while (i != children.End())
  432. {
  433. if ((*i)->IsVisible())
  434. {
  435. if (IsVisible(*i, currentScissor))
  436. (*i)->GetBatches(batches_, quads_, currentScissor);
  437. GetBatches(*i, currentScissor);
  438. }
  439. ++i;
  440. }
  441. }
  442. }
  443. bool UI::IsVisible(UIElement* element, const IntRect& currentScissor)
  444. {
  445. // First check element's visibility
  446. if (!element->IsVisible())
  447. return false;
  448. // Then check element dimensions against the scissor rectangle
  449. const IntVector2& screenPos = element->GetScreenPosition();
  450. if (screenPos.x_ >= currentScissor.right_ || screenPos.x_ + element->GetWidth() <= currentScissor.left_ ||
  451. screenPos.y_ >= currentScissor.bottom_ || screenPos.y_ + element->GetHeight() <= currentScissor.top_)
  452. return false;
  453. else
  454. return true;
  455. }
  456. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  457. {
  458. if (!current)
  459. return;
  460. current->SortChildren();
  461. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  462. LayoutMode parentLayoutMode = current->GetLayoutMode();
  463. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  464. {
  465. UIElement* element = *i;
  466. bool hasChildren = element->GetNumChildren() > 0;
  467. if (element != cursor_.Get() && element->IsVisible())
  468. {
  469. if (element->IsInside(position, true))
  470. {
  471. // Store the current result, then recurse into its children. Because children
  472. // are sorted from lowest to highest priority, the topmost match should remain
  473. if (element->IsActive() || !activeOnly)
  474. result = element;
  475. if (hasChildren)
  476. GetElementAt(result, element, position, activeOnly);
  477. // Layout optimization: if the element has no children, can break out after the first match
  478. else if (parentLayoutMode != LM_FREE)
  479. break;
  480. }
  481. else
  482. {
  483. if (hasChildren)
  484. {
  485. if (element->IsInsideCombined(position, true))
  486. GetElementAt(result, element, position, activeOnly);
  487. }
  488. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  489. // or if we already passed all visible elements
  490. else if (parentLayoutMode != LM_FREE)
  491. {
  492. if (i == children.Begin())
  493. {
  494. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  495. element->GetScreenPosition().y_;
  496. int layoutMinSize = current->GetLayoutMinSize();
  497. if (screenPos < 0 && layoutMinSize > 0)
  498. {
  499. unsigned toSkip = -screenPos / layoutMinSize;
  500. if (toSkip > 0)
  501. {
  502. i += (toSkip - 1);
  503. if (i >= children.End())
  504. break;
  505. }
  506. }
  507. }
  508. else if (parentLayoutMode == LM_HORIZONTAL)
  509. {
  510. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  511. break;
  512. }
  513. else if (parentLayoutMode == LM_VERTICAL)
  514. {
  515. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  516. break;
  517. }
  518. }
  519. }
  520. }
  521. }
  522. }
  523. UIElement* UI::GetFocusableElement(UIElement* element)
  524. {
  525. while (element)
  526. {
  527. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  528. break;
  529. element = element->GetParent();
  530. }
  531. return element;
  532. }
  533. void UI::LoadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  534. {
  535. XMLElement childElem = elem.GetChild("element");
  536. while (childElem)
  537. {
  538. // Create element
  539. String type = childElem.GetAttribute("type");
  540. if (type.Empty())
  541. type = "UIElement";
  542. SharedPtr<UIElement> child = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  543. if (!child)
  544. {
  545. LOGERROR("Could not create UI element " + type);
  546. childElem = childElem.GetNext("element");
  547. continue;
  548. }
  549. child->SetName(childElem.GetAttribute("name"));
  550. // Add to the hierarchy
  551. current->AddChild(child);
  552. // First set the base style from the style file if exists, then apply UI layout overrides
  553. String styleName = childElem.HasAttribute("style") ? childElem.GetAttribute("style") : childElem.GetAttribute("type");
  554. if (styleFile)
  555. child->SetStyle(styleFile, styleName);
  556. child->SetStyle(childElem);
  557. // Load the children recursively
  558. LoadLayout(child, childElem, styleFile);
  559. childElem = childElem.GetNext("element");
  560. }
  561. }
  562. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  563. {
  564. using namespace ScreenMode;
  565. if (!initialized_)
  566. Initialize();
  567. else
  568. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  569. }
  570. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  571. {
  572. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  573. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  574. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  575. if (cursor_ && cursor_->IsVisible())
  576. {
  577. IntVector2 pos = cursor_->GetPosition();
  578. WeakPtr<UIElement> element(GetElementAt(pos));
  579. if (element)
  580. {
  581. // Handle focusing & bringing to front
  582. if (button == MOUSEB_LEFT)
  583. {
  584. SetFocusElement(element);
  585. element->BringToFront();
  586. }
  587. // Handle click
  588. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  589. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  590. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  591. {
  592. dragElement_ = element;
  593. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  594. }
  595. }
  596. else
  597. {
  598. // If clicked over no element, or a disabled element, lose focus
  599. SetFocusElement(0);
  600. }
  601. using namespace UIMouseClick;
  602. VariantMap eventData;
  603. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  604. eventData[UIMouseClick::P_X] = pos.x_;
  605. eventData[UIMouseClick::P_Y] = pos.y_;
  606. eventData[UIMouseClick::P_BUTTON] = button;
  607. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  608. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  609. SendEvent(E_UIMOUSECLICK, eventData);
  610. }
  611. }
  612. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  613. {
  614. using namespace MouseButtonUp;
  615. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  616. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  617. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  618. {
  619. IntVector2 pos = cursor_->GetPosition();
  620. if (dragElement_ && !mouseButtons_)
  621. {
  622. if (dragElement_->IsActive() && dragElement_->IsVisible())
  623. {
  624. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  625. // Drag and drop finish
  626. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  627. if (dragSource)
  628. {
  629. WeakPtr<UIElement> target(GetElementAt(pos));
  630. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  631. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  632. if (dragDropFinish)
  633. {
  634. bool accept = target->OnDragDropFinish(dragElement_);
  635. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  636. if (accept && dragElement_ && target)
  637. {
  638. using namespace DragDropFinish;
  639. VariantMap eventData;
  640. eventData[P_SOURCE] = (void*)dragElement_.Get();
  641. eventData[P_TARGET] = (void*)target.Get();
  642. eventData[P_ACCEPT] = accept;
  643. SendEvent(E_DRAGDROPFINISH, eventData);
  644. }
  645. }
  646. }
  647. }
  648. dragElement_.Reset();
  649. }
  650. }
  651. }
  652. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  653. {
  654. using namespace MouseMove;
  655. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  656. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  657. if (cursor_)
  658. {
  659. const IntVector2& rootSize = rootElement_->GetSize();
  660. // Move cursor only when visible
  661. if (cursor_->IsVisible())
  662. {
  663. IntVector2 pos = cursor_->GetPosition();
  664. pos.x_ += eventData[P_DX].GetInt();
  665. pos.y_ += eventData[P_DY].GetInt();
  666. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  667. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  668. cursor_->SetPosition(pos);
  669. }
  670. if (dragElement_ && mouseButtons_)
  671. {
  672. IntVector2 pos = cursor_->GetPosition();
  673. if (dragElement_->IsActive() && dragElement_->IsVisible())
  674. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  675. else
  676. {
  677. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  678. dragElement_.Reset();
  679. }
  680. }
  681. }
  682. }
  683. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  684. {
  685. using namespace MouseWheel;
  686. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  687. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  688. int delta = eventData[P_WHEEL].GetInt();
  689. UIElement* element = GetFocusElement();
  690. if (element)
  691. element->OnWheel(delta, mouseButtons_, qualifiers_);
  692. else
  693. {
  694. // If no element has actual focus, get the element at cursor
  695. if (cursor_)
  696. {
  697. IntVector2 pos = cursor_->GetPosition();
  698. UIElement* element = GetElementAt(pos);
  699. // If the element itself is not focusable, search for a focusable parent
  700. element = GetFocusableElement(element);
  701. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  702. element->OnWheel(delta, mouseButtons_, qualifiers_);
  703. }
  704. }
  705. }
  706. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  707. {
  708. using namespace TouchBegin;
  709. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  710. WeakPtr<UIElement> element(GetElementAt(pos));
  711. if (element)
  712. {
  713. // Handle focusing & bringing to front
  714. SetFocusElement(element);
  715. element->BringToFront();
  716. // Handle click
  717. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  718. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  719. if (element && !dragElement_ )
  720. {
  721. dragElement_ = element;
  722. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  723. }
  724. }
  725. else
  726. {
  727. // If clicked over no element, or a disabled element, lose focus
  728. SetFocusElement(0);
  729. }
  730. using namespace UIMouseClick;
  731. VariantMap clickEventData;
  732. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  733. clickEventData[UIMouseClick::P_X] = pos.x_;
  734. clickEventData[UIMouseClick::P_Y] = pos.y_;
  735. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  736. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  737. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  738. SendEvent(E_UIMOUSECLICK, clickEventData);
  739. }
  740. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  741. {
  742. using namespace TouchEnd;
  743. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  744. // Transmit hover end to the position where the finger was lifted
  745. WeakPtr<UIElement> element(GetElementAt(pos));
  746. if (element)
  747. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  748. if (dragElement_)
  749. {
  750. if (dragElement_->IsActive() && dragElement_->IsVisible())
  751. {
  752. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  753. // Drag and drop finish
  754. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  755. if (dragSource)
  756. {
  757. WeakPtr<UIElement> target(GetElementAt(pos));
  758. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  759. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  760. if (dragDropFinish)
  761. {
  762. bool accept = target->OnDragDropFinish(dragElement_);
  763. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  764. if (accept && dragElement_ && target)
  765. {
  766. using namespace DragDropFinish;
  767. VariantMap eventData;
  768. eventData[P_SOURCE] = (void*)dragElement_.Get();
  769. eventData[P_TARGET] = (void*)target.Get();
  770. eventData[P_ACCEPT] = accept;
  771. SendEvent(E_DRAGDROPFINISH, eventData);
  772. }
  773. }
  774. }
  775. }
  776. dragElement_.Reset();
  777. }
  778. }
  779. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  780. {
  781. using namespace TouchMove;
  782. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  783. if (dragElement_)
  784. {
  785. if (dragElement_->IsActive() && dragElement_->IsVisible())
  786. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  787. else
  788. {
  789. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  790. dragElement_.Reset();
  791. }
  792. }
  793. }
  794. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  795. {
  796. using namespace KeyDown;
  797. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  798. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  799. int key = eventData[P_KEY].GetInt();
  800. UIElement* element = GetFocusElement();
  801. if (element)
  802. {
  803. // Switch focus between focusable elements in the same top level window
  804. if (key == KEY_TAB)
  805. {
  806. UIElement* topLevel = element->GetParent();
  807. while (topLevel && topLevel->GetParent() != rootElement_)
  808. topLevel = topLevel->GetParent();
  809. if (topLevel)
  810. {
  811. topLevel->GetChildren(tempElements_, true);
  812. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  813. {
  814. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  815. i = tempElements_.Erase(i);
  816. else
  817. ++i;
  818. }
  819. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  820. {
  821. if (tempElements_[i] == element)
  822. {
  823. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  824. SetFocusElement(next);
  825. return;
  826. }
  827. }
  828. }
  829. }
  830. // Defocus the element
  831. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  832. element->SetFocus(false);
  833. // If none of the special keys, pass the key to the focused element
  834. else
  835. element->OnKey(key, mouseButtons_, qualifiers_);
  836. }
  837. }
  838. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  839. {
  840. using namespace Char;
  841. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  842. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  843. UIElement* element = GetFocusElement();
  844. if (element)
  845. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  846. }
  847. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  848. {
  849. if (initialized_)
  850. {
  851. using namespace PostUpdate;
  852. Update(eventData[P_TIMESTEP].GetFloat());
  853. }
  854. }
  855. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  856. {
  857. if (initialized_)
  858. RenderUpdate();
  859. }
  860. void RegisterUILibrary(Context* context)
  861. {
  862. Font::RegisterObject(context);
  863. UIElement::RegisterObject(context);
  864. BorderImage::RegisterObject(context);
  865. Button::RegisterObject(context);
  866. CheckBox::RegisterObject(context);
  867. Cursor::RegisterObject(context);
  868. Text::RegisterObject(context);
  869. Window::RegisterObject(context);
  870. LineEdit::RegisterObject(context);
  871. Slider::RegisterObject(context);
  872. ScrollBar::RegisterObject(context);
  873. ScrollView::RegisterObject(context);
  874. ListView::RegisterObject(context);
  875. Menu::RegisterObject(context);
  876. DropDownList::RegisterObject(context);
  877. FileSelector::RegisterObject(context);
  878. }