UI.cpp 31 KB

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