UI.cpp 31 KB

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