UI.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  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* scratch = graphics_->ReserveScratchBuffer(numVertices * vertexSize);
  223. for (unsigned i = 0; i < batches_.Size(); ++i)
  224. batches_[i].UpdateGeometry(graphics_, ((unsigned char*)scratch) + batches_[i].quadStart_ * vertexSize * 6);
  225. vertexBuffer_->SetDataRange(scratch, 0, numVertices, true);
  226. graphics_->FreeScratchBuffer(scratch);
  227. Vector2 scale(2.0f, -2.0f);
  228. Vector2 offset(-1.0f, 1.0f);
  229. Matrix4 projection(Matrix4::IDENTITY);
  230. projection.m00_ = scale.x_;
  231. projection.m03_ = offset.x_;
  232. projection.m11_ = scale.y_;
  233. projection.m13_ = offset.y_;
  234. projection.m22_ = 1.0f;
  235. projection.m23_ = 0.0f;
  236. projection.m33_ = 1.0f;
  237. graphics_->ClearParameterSources();
  238. graphics_->SetCullMode(CULL_CCW);
  239. graphics_->SetDepthTest(CMP_ALWAYS);
  240. graphics_->SetDepthWrite(false);
  241. graphics_->SetStencilTest(false);
  242. graphics_->ResetRenderTargets();
  243. ShaderVariation* ps = 0;
  244. ShaderVariation* vs = 0;
  245. unsigned alphaFormat = Graphics::GetAlphaFormat();
  246. for (unsigned i = 0; i < batches_.Size(); ++i)
  247. {
  248. const UIBatch& batch = batches_[i];
  249. if (!batch.quadCount_)
  250. continue;
  251. if (!batch.texture_)
  252. {
  253. ps = noTexturePS_;
  254. vs = noTextureVS_;
  255. }
  256. else
  257. {
  258. // If texture contains only an alpha channel, use alpha shader (for fonts)
  259. vs = diffTextureVS_;
  260. if (batch.texture_->GetFormat() == alphaFormat)
  261. ps = alphaTexturePS_;
  262. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  263. ps = diffMaskTexturePS_;
  264. else
  265. ps = diffTexturePS_;
  266. }
  267. graphics_->SetShaders(vs, ps);
  268. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  269. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  270. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  271. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  272. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  273. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  274. graphics_->SetBlendMode(batch.blendMode_);
  275. graphics_->SetScissorTest(true, batch.scissor_);
  276. graphics_->SetTexture(0, batch.texture_);
  277. graphics_->SetVertexBuffer(vertexBuffer_);
  278. graphics_->Draw(TRIANGLE_LIST, batch.quadStart_ * 6, batch.quadCount_ * 6);
  279. }
  280. }
  281. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  282. {
  283. PROFILE(LoadUILayout);
  284. SharedPtr<UIElement> root;
  285. if (!file)
  286. {
  287. LOGERROR("Null UI layout XML file");
  288. return root;
  289. }
  290. LOGDEBUG("Loading UI layout " + file->GetName());
  291. XMLElement rootElem = file->GetRoot("element");
  292. if (!rootElem)
  293. {
  294. LOGERROR("No root UI element in " + file->GetName());
  295. return root;
  296. }
  297. String type = rootElem.GetAttribute("type");
  298. if (type.Empty())
  299. type = "UIElement";
  300. root = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  301. if (!root)
  302. {
  303. LOGERROR("Could not create UI element " + type);
  304. return root;
  305. }
  306. root->SetName(rootElem.GetAttribute("name"));
  307. String styleName = rootElem.HasAttribute("style") ? rootElem.GetAttribute("style") : rootElem.GetAttribute("type");
  308. // First set the base style from the style file if exists, then apply UI layout overrides
  309. if (styleFile)
  310. root->SetStyle(styleFile, styleName);
  311. root->SetStyle(rootElem);
  312. // Load rest of the elements recursively
  313. LoadLayout(root, rootElem, styleFile);
  314. return root;
  315. }
  316. void UI::SetClipBoardText(const String& text)
  317. {
  318. clipBoard_ = text;
  319. }
  320. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  321. {
  322. if (!rootElement_)
  323. return 0;
  324. UIElement* result = 0;
  325. GetElementAt(result, rootElement_, position, activeOnly);
  326. return result;
  327. }
  328. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  329. {
  330. return GetElementAt(IntVector2(x, y), activeOnly);
  331. }
  332. UIElement* UI::GetFocusElement() const
  333. {
  334. return focusElement_;
  335. }
  336. UIElement* UI::GetFrontElement() const
  337. {
  338. if (!rootElement_)
  339. return 0;
  340. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  341. int maxPriority = M_MIN_INT;
  342. UIElement* front = 0;
  343. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  344. {
  345. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  346. if (!rootChildren[i]->IsActive() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  347. continue;
  348. int priority = rootChildren[i]->GetPriority();
  349. if (priority > maxPriority)
  350. {
  351. maxPriority = priority;
  352. front = rootChildren[i];
  353. }
  354. }
  355. return front;
  356. }
  357. IntVector2 UI::GetCursorPosition()
  358. {
  359. if (!cursor_)
  360. return IntVector2::ZERO;
  361. else
  362. return cursor_->GetPosition();
  363. }
  364. void UI::Initialize()
  365. {
  366. Graphics* graphics = GetSubsystem<Graphics>();
  367. Renderer* renderer = GetSubsystem<Renderer>();
  368. if (!graphics || !graphics->IsInitialized() || !renderer)
  369. return;
  370. PROFILE(InitUI);
  371. graphics_ = graphics;
  372. rootElement_ = new UIElement(context_);
  373. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  374. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  375. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  376. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  377. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  378. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  379. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  380. vertexBuffer_ = new VertexBuffer(context_);
  381. LOGINFO("Initialized user interface");
  382. initialized_ = true;
  383. }
  384. void UI::Update(float timeStep, UIElement* element)
  385. {
  386. element->Update(timeStep);
  387. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  388. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  389. Update(timeStep, *i);
  390. }
  391. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  392. {
  393. // Set clipping scissor for child elements. No need to draw if zero size
  394. element->AdjustScissor(currentScissor);
  395. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  396. return;
  397. element->SortChildren();
  398. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  399. if (children.Empty())
  400. return;
  401. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  402. // same renderstate
  403. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  404. if (element != rootElement_)
  405. {
  406. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  407. int currentPriority = children.Front()->GetPriority();
  408. while (i != children.End())
  409. {
  410. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  411. {
  412. if (IsVisible(*j, currentScissor))
  413. (*j)->GetBatches(batches_, quads_, currentScissor);
  414. ++j;
  415. }
  416. // Now recurse into the children
  417. while (i != j)
  418. {
  419. if (IsVisible(*i, currentScissor))
  420. GetBatches(*i, currentScissor);
  421. ++i;
  422. }
  423. if (i != children.End())
  424. currentPriority = (*i)->GetPriority();
  425. }
  426. }
  427. // On the root level draw each element and its children immediately after to avoid artifacts
  428. else
  429. {
  430. while (i != children.End())
  431. {
  432. if ((*i)->IsVisible())
  433. {
  434. if (IsVisible(*i, currentScissor))
  435. (*i)->GetBatches(batches_, quads_, currentScissor);
  436. GetBatches(*i, currentScissor);
  437. }
  438. ++i;
  439. }
  440. }
  441. }
  442. bool UI::IsVisible(UIElement* element, const IntRect& currentScissor)
  443. {
  444. // First check element's visibility
  445. if (!element->IsVisible())
  446. return false;
  447. // Then check element dimensions against the scissor rectangle
  448. const IntVector2& screenPos = element->GetScreenPosition();
  449. if (screenPos.x_ >= currentScissor.right_ || screenPos.x_ + element->GetWidth() <= currentScissor.left_ ||
  450. screenPos.y_ >= currentScissor.bottom_ || screenPos.y_ + element->GetHeight() <= currentScissor.top_)
  451. return false;
  452. else
  453. return true;
  454. }
  455. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  456. {
  457. if (!current)
  458. return;
  459. current->SortChildren();
  460. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  461. LayoutMode parentLayoutMode = current->GetLayoutMode();
  462. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  463. {
  464. UIElement* element = *i;
  465. bool hasChildren = element->GetNumChildren() > 0;
  466. if (element != cursor_.Get() && element->IsVisible())
  467. {
  468. if (element->IsInside(position, true))
  469. {
  470. // Store the current result, then recurse into its children. Because children
  471. // are sorted from lowest to highest priority, the topmost match should remain
  472. if (element->IsActive() || !activeOnly)
  473. result = element;
  474. if (hasChildren)
  475. GetElementAt(result, element, position, activeOnly);
  476. // Layout optimization: if the element has no children, can break out after the first match
  477. else if (parentLayoutMode != LM_FREE)
  478. break;
  479. }
  480. else
  481. {
  482. if (hasChildren)
  483. {
  484. if (element->IsInsideCombined(position, true))
  485. GetElementAt(result, element, position, activeOnly);
  486. }
  487. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  488. // or if we already passed all visible elements
  489. else if (parentLayoutMode != LM_FREE)
  490. {
  491. if (i == children.Begin())
  492. {
  493. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  494. element->GetScreenPosition().y_;
  495. int layoutMinSize = current->GetLayoutMinSize();
  496. if (screenPos < 0 && layoutMinSize > 0)
  497. {
  498. unsigned toSkip = -screenPos / layoutMinSize;
  499. if (toSkip > 0)
  500. {
  501. i += (toSkip - 1);
  502. if (i >= children.End())
  503. break;
  504. }
  505. }
  506. }
  507. else if (parentLayoutMode == LM_HORIZONTAL)
  508. {
  509. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  510. break;
  511. }
  512. else if (parentLayoutMode == LM_VERTICAL)
  513. {
  514. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  515. break;
  516. }
  517. }
  518. }
  519. }
  520. }
  521. }
  522. UIElement* UI::GetFocusableElement(UIElement* element)
  523. {
  524. while (element)
  525. {
  526. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  527. break;
  528. element = element->GetParent();
  529. }
  530. return element;
  531. }
  532. void UI::LoadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  533. {
  534. XMLElement childElem = elem.GetChild("element");
  535. while (childElem)
  536. {
  537. // Create element
  538. String type = childElem.GetAttribute("type");
  539. if (type.Empty())
  540. type = "UIElement";
  541. SharedPtr<UIElement> child = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  542. if (!child)
  543. {
  544. LOGERROR("Could not create UI element " + type);
  545. childElem = childElem.GetNext("element");
  546. continue;
  547. }
  548. child->SetName(childElem.GetAttribute("name"));
  549. // Add to the hierarchy
  550. current->AddChild(child);
  551. // First set the base style from the style file if exists, then apply UI layout overrides
  552. String styleName = childElem.HasAttribute("style") ? childElem.GetAttribute("style") : childElem.GetAttribute("type");
  553. if (styleFile)
  554. child->SetStyle(styleFile, styleName);
  555. child->SetStyle(childElem);
  556. // Load the children recursively
  557. LoadLayout(child, childElem, styleFile);
  558. childElem = childElem.GetNext("element");
  559. }
  560. }
  561. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  562. {
  563. using namespace ScreenMode;
  564. if (!initialized_)
  565. Initialize();
  566. else
  567. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  568. }
  569. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  570. {
  571. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  572. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  573. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  574. if (cursor_ && cursor_->IsVisible())
  575. {
  576. IntVector2 pos = cursor_->GetPosition();
  577. WeakPtr<UIElement> element(GetElementAt(pos));
  578. if (element)
  579. {
  580. // Handle focusing & bringing to front
  581. if (button == MOUSEB_LEFT)
  582. {
  583. SetFocusElement(element);
  584. element->BringToFront();
  585. }
  586. // Handle click
  587. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  588. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  589. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  590. {
  591. dragElement_ = element;
  592. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  593. }
  594. }
  595. else
  596. {
  597. // If clicked over no element, or a disabled element, lose focus
  598. SetFocusElement(0);
  599. }
  600. using namespace UIMouseClick;
  601. VariantMap eventData;
  602. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  603. eventData[UIMouseClick::P_X] = pos.x_;
  604. eventData[UIMouseClick::P_Y] = pos.y_;
  605. eventData[UIMouseClick::P_BUTTON] = button;
  606. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  607. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  608. SendEvent(E_UIMOUSECLICK, eventData);
  609. }
  610. }
  611. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  612. {
  613. using namespace MouseButtonUp;
  614. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  615. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  616. if (cursor_ && (cursor_->IsVisible()) || (dragElement_))
  617. {
  618. IntVector2 pos = cursor_->GetPosition();
  619. if (dragElement_ && !mouseButtons_)
  620. {
  621. if (dragElement_->IsActive() && dragElement_->IsVisible())
  622. {
  623. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  624. // Drag and drop finish
  625. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  626. if (dragSource)
  627. {
  628. WeakPtr<UIElement> target(GetElementAt(pos));
  629. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  630. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  631. if (dragDropFinish)
  632. {
  633. bool accept = target->OnDragDropFinish(dragElement_);
  634. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  635. if (accept && dragElement_ && target)
  636. {
  637. using namespace DragDropFinish;
  638. VariantMap eventData;
  639. eventData[P_SOURCE] = (void*)dragElement_.Get();
  640. eventData[P_TARGET] = (void*)target.Get();
  641. eventData[P_ACCEPT] = accept;
  642. SendEvent(E_DRAGDROPFINISH, eventData);
  643. }
  644. }
  645. }
  646. }
  647. dragElement_.Reset();
  648. }
  649. }
  650. }
  651. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  652. {
  653. using namespace MouseMove;
  654. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  655. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  656. if (cursor_)
  657. {
  658. const IntVector2& rootSize = rootElement_->GetSize();
  659. // Move cursor only when visible
  660. if (cursor_->IsVisible())
  661. {
  662. IntVector2 pos = cursor_->GetPosition();
  663. pos.x_ += eventData[P_DX].GetInt();
  664. pos.y_ += eventData[P_DY].GetInt();
  665. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  666. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  667. cursor_->SetPosition(pos);
  668. }
  669. if (dragElement_ && mouseButtons_)
  670. {
  671. IntVector2 pos = cursor_->GetPosition();
  672. if (dragElement_->IsActive() && dragElement_->IsVisible())
  673. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  674. else
  675. {
  676. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  677. dragElement_.Reset();
  678. }
  679. }
  680. }
  681. }
  682. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  683. {
  684. using namespace MouseWheel;
  685. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  686. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  687. int delta = eventData[P_WHEEL].GetInt();
  688. UIElement* element = GetFocusElement();
  689. if (element)
  690. element->OnWheel(delta, mouseButtons_, qualifiers_);
  691. else
  692. {
  693. // If no element has actual focus, get the element at cursor
  694. if (cursor_)
  695. {
  696. IntVector2 pos = cursor_->GetPosition();
  697. UIElement* element = GetElementAt(pos);
  698. // If the element itself is not focusable, search for a focusable parent
  699. element = GetFocusableElement(element);
  700. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  701. element->OnWheel(delta, mouseButtons_, qualifiers_);
  702. }
  703. }
  704. }
  705. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  706. {
  707. using namespace TouchBegin;
  708. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  709. WeakPtr<UIElement> element(GetElementAt(pos));
  710. if (element)
  711. {
  712. // Handle focusing & bringing to front
  713. SetFocusElement(element);
  714. element->BringToFront();
  715. // Handle click
  716. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  717. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  718. if (element && !dragElement_ )
  719. {
  720. dragElement_ = element;
  721. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  722. }
  723. }
  724. else
  725. {
  726. // If clicked over no element, or a disabled element, lose focus
  727. SetFocusElement(0);
  728. }
  729. using namespace UIMouseClick;
  730. VariantMap clickEventData;
  731. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  732. clickEventData[UIMouseClick::P_X] = pos.x_;
  733. clickEventData[UIMouseClick::P_Y] = pos.y_;
  734. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  735. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  736. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  737. SendEvent(E_UIMOUSECLICK, clickEventData);
  738. }
  739. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  740. {
  741. using namespace TouchEnd;
  742. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  743. // Transmit hover end to the position where the finger was lifted
  744. WeakPtr<UIElement> element(GetElementAt(pos));
  745. if (element)
  746. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  747. if (dragElement_)
  748. {
  749. if (dragElement_->IsActive() && dragElement_->IsVisible())
  750. {
  751. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  752. // Drag and drop finish
  753. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  754. if (dragSource)
  755. {
  756. WeakPtr<UIElement> target(GetElementAt(pos));
  757. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  758. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  759. if (dragDropFinish)
  760. {
  761. bool accept = target->OnDragDropFinish(dragElement_);
  762. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  763. if (accept && dragElement_ && target)
  764. {
  765. using namespace DragDropFinish;
  766. VariantMap eventData;
  767. eventData[P_SOURCE] = (void*)dragElement_.Get();
  768. eventData[P_TARGET] = (void*)target.Get();
  769. eventData[P_ACCEPT] = accept;
  770. SendEvent(E_DRAGDROPFINISH, eventData);
  771. }
  772. }
  773. }
  774. }
  775. dragElement_.Reset();
  776. }
  777. }
  778. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  779. {
  780. using namespace TouchMove;
  781. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  782. if (dragElement_)
  783. {
  784. if (dragElement_->IsActive() && dragElement_->IsVisible())
  785. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  786. else
  787. {
  788. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  789. dragElement_.Reset();
  790. }
  791. }
  792. }
  793. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  794. {
  795. using namespace KeyDown;
  796. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  797. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  798. int key = eventData[P_KEY].GetInt();
  799. UIElement* element = GetFocusElement();
  800. if (element)
  801. {
  802. // Switch focus between focusable elements in the same top level window
  803. if (key == KEY_TAB)
  804. {
  805. UIElement* topLevel = element->GetParent();
  806. while (topLevel && topLevel->GetParent() != rootElement_)
  807. topLevel = topLevel->GetParent();
  808. if (topLevel)
  809. {
  810. topLevel->GetChildren(tempElements_, true);
  811. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  812. {
  813. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  814. i = tempElements_.Erase(i);
  815. else
  816. ++i;
  817. }
  818. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  819. {
  820. if (tempElements_[i] == element)
  821. {
  822. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  823. SetFocusElement(next);
  824. return;
  825. }
  826. }
  827. }
  828. }
  829. // Defocus the element
  830. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  831. element->SetFocus(false);
  832. // If none of the special keys, pass the key to the focused element
  833. else
  834. element->OnKey(key, mouseButtons_, qualifiers_);
  835. }
  836. }
  837. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  838. {
  839. using namespace Char;
  840. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  841. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  842. UIElement* element = GetFocusElement();
  843. if (element)
  844. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  845. }
  846. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  847. {
  848. if (initialized_)
  849. {
  850. using namespace PostUpdate;
  851. Update(eventData[P_TIMESTEP].GetFloat());
  852. }
  853. }
  854. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  855. {
  856. if (initialized_)
  857. RenderUpdate();
  858. }
  859. void RegisterUILibrary(Context* context)
  860. {
  861. Font::RegisterObject(context);
  862. UIElement::RegisterObject(context);
  863. BorderImage::RegisterObject(context);
  864. Button::RegisterObject(context);
  865. CheckBox::RegisterObject(context);
  866. Cursor::RegisterObject(context);
  867. Text::RegisterObject(context);
  868. Window::RegisterObject(context);
  869. LineEdit::RegisterObject(context);
  870. Slider::RegisterObject(context);
  871. ScrollBar::RegisterObject(context);
  872. ScrollView::RegisterObject(context);
  873. ListView::RegisterObject(context);
  874. Menu::RegisterObject(context);
  875. DropDownList::RegisterObject(context);
  876. FileSelector::RegisterObject(context);
  877. }