UI.cpp 31 KB

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