UI.cpp 31 KB

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