UI.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. // If the OS cursor is visible, do not render the UI's own cursor
  203. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  204. bool uiCursorVisible = false;
  205. if (osCursorVisible && cursor_)
  206. {
  207. uiCursorVisible = cursor_->IsVisible();
  208. cursor_->SetTempVisible(false);
  209. }
  210. // Get batches & quads from the UI elements
  211. batches_.Clear();
  212. quads_.Clear();
  213. const IntVector2& rootSize = rootElement_->GetSize();
  214. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  215. // If no drag, reset cursor shape for next frame
  216. if (cursor_ && !dragElement_)
  217. cursor_->SetShape(CS_NORMAL);
  218. // Restore UI cursor visibility state
  219. if (osCursorVisible && cursor_)
  220. cursor_->SetTempVisible(uiCursorVisible);
  221. }
  222. void UI::Render()
  223. {
  224. PROFILE(RenderUI);
  225. if (!graphics_ || graphics_->IsDeviceLost() || !quads_.Size())
  226. return;
  227. // Update quad geometry into the vertex buffer
  228. unsigned numVertices = quads_.Size() * 6;
  229. // Resize the vertex buffer if too small or much too large
  230. if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
  231. vertexBuffer_->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  232. unsigned vertexSize = vertexBuffer_->GetVertexSize();
  233. void* dest = vertexBuffer_->Lock(0, numVertices, true);
  234. if (!dest)
  235. return;
  236. for (unsigned i = 0; i < batches_.Size(); ++i)
  237. batches_[i].UpdateGeometry(graphics_, ((unsigned char*)dest) + batches_[i].quadStart_ * vertexSize * 6);
  238. vertexBuffer_->Unlock();
  239. Vector2 scale(2.0f, -2.0f);
  240. Vector2 offset(-1.0f, 1.0f);
  241. Matrix4 projection(Matrix4::IDENTITY);
  242. projection.m00_ = scale.x_;
  243. projection.m03_ = offset.x_;
  244. projection.m11_ = scale.y_;
  245. projection.m13_ = offset.y_;
  246. projection.m22_ = 1.0f;
  247. projection.m23_ = 0.0f;
  248. projection.m33_ = 1.0f;
  249. graphics_->ClearParameterSources();
  250. graphics_->SetCullMode(CULL_CCW);
  251. graphics_->SetDepthTest(CMP_ALWAYS);
  252. graphics_->SetDepthWrite(false);
  253. graphics_->SetStencilTest(false);
  254. graphics_->ResetRenderTargets();
  255. ShaderVariation* ps = 0;
  256. ShaderVariation* vs = 0;
  257. unsigned alphaFormat = Graphics::GetAlphaFormat();
  258. for (unsigned i = 0; i < batches_.Size(); ++i)
  259. {
  260. const UIBatch& batch = batches_[i];
  261. if (!batch.quadCount_)
  262. continue;
  263. if (!batch.texture_)
  264. {
  265. ps = noTexturePS_;
  266. vs = noTextureVS_;
  267. }
  268. else
  269. {
  270. // If texture contains only an alpha channel, use alpha shader (for fonts)
  271. vs = diffTextureVS_;
  272. if (batch.texture_->GetFormat() == alphaFormat)
  273. ps = alphaTexturePS_;
  274. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  275. ps = diffMaskTexturePS_;
  276. else
  277. ps = diffTexturePS_;
  278. }
  279. graphics_->SetShaders(vs, ps);
  280. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  281. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  282. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  283. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  284. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  285. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  286. graphics_->SetBlendMode(batch.blendMode_);
  287. graphics_->SetScissorTest(true, batch.scissor_);
  288. graphics_->SetTexture(0, batch.texture_);
  289. graphics_->SetVertexBuffer(vertexBuffer_);
  290. graphics_->Draw(TRIANGLE_LIST, batch.quadStart_ * 6, batch.quadCount_ * 6);
  291. }
  292. }
  293. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  294. {
  295. PROFILE(LoadUILayout);
  296. SharedPtr<UIElement> root;
  297. if (!file)
  298. {
  299. LOGERROR("Null UI layout XML file");
  300. return root;
  301. }
  302. LOGDEBUG("Loading UI layout " + file->GetName());
  303. XMLElement rootElem = file->GetRoot("element");
  304. if (!rootElem)
  305. {
  306. LOGERROR("No root UI element in " + file->GetName());
  307. return root;
  308. }
  309. String type = rootElem.GetAttribute("type");
  310. if (type.Empty())
  311. type = "UIElement";
  312. root = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  313. if (!root)
  314. {
  315. LOGERROR("Could not create UI element " + type);
  316. return root;
  317. }
  318. root->SetName(rootElem.GetAttribute("name"));
  319. String styleName = rootElem.HasAttribute("style") ? rootElem.GetAttribute("style") : rootElem.GetAttribute("type");
  320. // First set the base style from the style file if exists, then apply UI layout overrides
  321. if (styleFile)
  322. root->SetStyle(styleFile, styleName);
  323. root->SetStyle(rootElem);
  324. // Load rest of the elements recursively
  325. LoadLayout(root, rootElem, styleFile);
  326. return root;
  327. }
  328. void UI::SetClipBoardText(const String& text)
  329. {
  330. clipBoard_ = text;
  331. }
  332. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  333. {
  334. if (!rootElement_)
  335. return 0;
  336. UIElement* result = 0;
  337. GetElementAt(result, rootElement_, position, activeOnly);
  338. return result;
  339. }
  340. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  341. {
  342. return GetElementAt(IntVector2(x, y), activeOnly);
  343. }
  344. UIElement* UI::GetFocusElement() const
  345. {
  346. return focusElement_;
  347. }
  348. UIElement* UI::GetFrontElement() const
  349. {
  350. if (!rootElement_)
  351. return 0;
  352. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  353. int maxPriority = M_MIN_INT;
  354. UIElement* front = 0;
  355. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  356. {
  357. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  358. if (!rootChildren[i]->IsActive() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  359. continue;
  360. int priority = rootChildren[i]->GetPriority();
  361. if (priority > maxPriority)
  362. {
  363. maxPriority = priority;
  364. front = rootChildren[i];
  365. }
  366. }
  367. return front;
  368. }
  369. IntVector2 UI::GetCursorPosition()
  370. {
  371. if (!cursor_)
  372. return IntVector2::ZERO;
  373. else
  374. return cursor_->GetPosition();
  375. }
  376. void UI::Initialize()
  377. {
  378. Graphics* graphics = GetSubsystem<Graphics>();
  379. Renderer* renderer = GetSubsystem<Renderer>();
  380. if (!graphics || !graphics->IsInitialized() || !renderer)
  381. return;
  382. PROFILE(InitUI);
  383. graphics_ = graphics;
  384. rootElement_ = new UIElement(context_);
  385. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  386. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  387. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  388. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  389. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  390. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  391. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  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. Input* input = GetSubsystem<Input>();
  671. const IntVector2& rootSize = rootElement_->GetSize();
  672. if (!input->IsMouseVisible())
  673. {
  674. // Relative mouse motion: move cursor only when visible
  675. if (cursor_->IsVisible())
  676. {
  677. IntVector2 pos = cursor_->GetPosition();
  678. pos.x_ += eventData[P_DX].GetInt();
  679. pos.y_ += eventData[P_DY].GetInt();
  680. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  681. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  682. cursor_->SetPosition(pos);
  683. }
  684. }
  685. else
  686. {
  687. // Absolute mouse motion: move always
  688. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  689. }
  690. if (dragElement_ && mouseButtons_)
  691. {
  692. IntVector2 pos = cursor_->GetPosition();
  693. if (dragElement_->IsActive() && dragElement_->IsVisible())
  694. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  695. else
  696. {
  697. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  698. dragElement_.Reset();
  699. }
  700. }
  701. }
  702. }
  703. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  704. {
  705. using namespace MouseWheel;
  706. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  707. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  708. int delta = eventData[P_WHEEL].GetInt();
  709. UIElement* element = GetFocusElement();
  710. if (element)
  711. element->OnWheel(delta, mouseButtons_, qualifiers_);
  712. else
  713. {
  714. // If no element has actual focus, get the element at cursor
  715. if (cursor_)
  716. {
  717. IntVector2 pos = cursor_->GetPosition();
  718. UIElement* element = GetElementAt(pos);
  719. // If the element itself is not focusable, search for a focusable parent
  720. element = GetFocusableElement(element);
  721. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  722. element->OnWheel(delta, mouseButtons_, qualifiers_);
  723. }
  724. }
  725. }
  726. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  727. {
  728. using namespace TouchBegin;
  729. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  730. WeakPtr<UIElement> element(GetElementAt(pos));
  731. if (element)
  732. {
  733. // Handle focusing & bringing to front
  734. SetFocusElement(element);
  735. element->BringToFront();
  736. // Handle click
  737. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  738. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  739. if (element && !dragElement_ )
  740. {
  741. dragElement_ = element;
  742. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  743. }
  744. }
  745. else
  746. {
  747. // If clicked over no element, or a disabled element, lose focus
  748. SetFocusElement(0);
  749. }
  750. using namespace UIMouseClick;
  751. VariantMap clickEventData;
  752. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  753. clickEventData[UIMouseClick::P_X] = pos.x_;
  754. clickEventData[UIMouseClick::P_Y] = pos.y_;
  755. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  756. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  757. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  758. SendEvent(E_UIMOUSECLICK, clickEventData);
  759. }
  760. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  761. {
  762. using namespace TouchEnd;
  763. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  764. // Transmit hover end to the position where the finger was lifted
  765. WeakPtr<UIElement> element(GetElementAt(pos));
  766. if (element)
  767. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  768. if (dragElement_)
  769. {
  770. if (dragElement_->IsActive() && dragElement_->IsVisible())
  771. {
  772. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  773. // Drag and drop finish
  774. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  775. if (dragSource)
  776. {
  777. WeakPtr<UIElement> target(GetElementAt(pos));
  778. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  779. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  780. if (dragDropFinish)
  781. {
  782. bool accept = target->OnDragDropFinish(dragElement_);
  783. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  784. if (accept && dragElement_ && target)
  785. {
  786. using namespace DragDropFinish;
  787. VariantMap eventData;
  788. eventData[P_SOURCE] = (void*)dragElement_.Get();
  789. eventData[P_TARGET] = (void*)target.Get();
  790. eventData[P_ACCEPT] = accept;
  791. SendEvent(E_DRAGDROPFINISH, eventData);
  792. }
  793. }
  794. }
  795. }
  796. dragElement_.Reset();
  797. }
  798. }
  799. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  800. {
  801. using namespace TouchMove;
  802. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  803. if (dragElement_)
  804. {
  805. if (dragElement_->IsActive() && dragElement_->IsVisible())
  806. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  807. else
  808. {
  809. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  810. dragElement_.Reset();
  811. }
  812. }
  813. }
  814. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  815. {
  816. using namespace KeyDown;
  817. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  818. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  819. int key = eventData[P_KEY].GetInt();
  820. UIElement* element = GetFocusElement();
  821. if (element)
  822. {
  823. // Switch focus between focusable elements in the same top level window
  824. if (key == KEY_TAB)
  825. {
  826. UIElement* topLevel = element->GetParent();
  827. while (topLevel && topLevel->GetParent() != rootElement_)
  828. topLevel = topLevel->GetParent();
  829. if (topLevel)
  830. {
  831. topLevel->GetChildren(tempElements_, true);
  832. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  833. {
  834. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  835. i = tempElements_.Erase(i);
  836. else
  837. ++i;
  838. }
  839. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  840. {
  841. if (tempElements_[i] == element)
  842. {
  843. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  844. SetFocusElement(next);
  845. return;
  846. }
  847. }
  848. }
  849. }
  850. // Defocus the element
  851. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  852. element->SetFocus(false);
  853. // If none of the special keys, pass the key to the focused element
  854. else
  855. element->OnKey(key, mouseButtons_, qualifiers_);
  856. }
  857. }
  858. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  859. {
  860. using namespace Char;
  861. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  862. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  863. UIElement* element = GetFocusElement();
  864. if (element)
  865. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  866. }
  867. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  868. {
  869. if (initialized_)
  870. {
  871. using namespace PostUpdate;
  872. Update(eventData[P_TIMESTEP].GetFloat());
  873. }
  874. }
  875. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  876. {
  877. if (initialized_)
  878. RenderUpdate();
  879. }
  880. void RegisterUILibrary(Context* context)
  881. {
  882. Font::RegisterObject(context);
  883. UIElement::RegisterObject(context);
  884. BorderImage::RegisterObject(context);
  885. Button::RegisterObject(context);
  886. CheckBox::RegisterObject(context);
  887. Cursor::RegisterObject(context);
  888. Text::RegisterObject(context);
  889. Window::RegisterObject(context);
  890. LineEdit::RegisterObject(context);
  891. Slider::RegisterObject(context);
  892. ScrollBar::RegisterObject(context);
  893. ScrollView::RegisterObject(context);
  894. ListView::RegisterObject(context);
  895. Menu::RegisterObject(context);
  896. DropDownList::RegisterObject(context);
  897. FileSelector::RegisterObject(context);
  898. }