UI.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CheckBox.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "Cursor.h"
  28. #include "DropDownList.h"
  29. #include "FileSelector.h"
  30. #include "Font.h"
  31. #include "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "Input.h"
  34. #include "InputEvents.h"
  35. #include "LineEdit.h"
  36. #include "ListView.h"
  37. #include "Log.h"
  38. #include "Matrix3x4.h"
  39. #include "Profiler.h"
  40. #include "Renderer.h"
  41. #include "ScrollBar.h"
  42. #include "Shader.h"
  43. #include "ShaderVariation.h"
  44. #include "Slider.h"
  45. #include "Text.h"
  46. #include "Texture2D.h"
  47. #include "UI.h"
  48. #include "UIEvents.h"
  49. #include "VertexBuffer.h"
  50. #include "Window.h"
  51. #include "Sort.h"
  52. #include "DebugNew.h"
  53. namespace Urho3D
  54. {
  55. OBJECTTYPESTATIC(UI);
  56. UI::UI(Context* context) :
  57. Object(context),
  58. mouseButtons_(0),
  59. qualifiers_(0),
  60. initialized_(false)
  61. {
  62. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  63. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  64. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  65. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  66. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  67. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  68. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  69. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  70. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  71. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  72. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  73. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  74. // Try to initialize right now, but skip if screen mode is not yet set
  75. Initialize();
  76. }
  77. UI::~UI()
  78. {
  79. }
  80. void UI::SetCursor(Cursor* cursor)
  81. {
  82. if (!rootElement_)
  83. return;
  84. // Remove old cursor (if any) and set new
  85. if (cursor_)
  86. {
  87. rootElement_->RemoveChild(cursor_);
  88. cursor_.Reset();
  89. }
  90. if (cursor)
  91. {
  92. rootElement_->AddChild(cursor);
  93. cursor_ = cursor;
  94. IntVector2 pos = cursor_->GetPosition();
  95. const IntVector2& rootSize = rootElement_->GetSize();
  96. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  97. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  98. cursor_->SetPosition(pos);
  99. }
  100. }
  101. void UI::SetFocusElement(UIElement* element)
  102. {
  103. if (!rootElement_)
  104. return;
  105. using namespace FocusChanged;
  106. VariantMap eventData;
  107. eventData[P_CLICKEDELEMENT] = (void*)element;
  108. if (element)
  109. {
  110. // Return if already has focus
  111. if (focusElement_ == element)
  112. return;
  113. // Search for an element in the hierarchy that can alter focus. If none found, exit
  114. element = GetFocusableElement(element);
  115. if (!element)
  116. return;
  117. }
  118. // Remove focus from the old element
  119. if (focusElement_)
  120. {
  121. UIElement* oldFocusElement = focusElement_;
  122. focusElement_.Reset();
  123. VariantMap focusEventData;
  124. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  125. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  126. }
  127. // Then set focus to the new
  128. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  129. {
  130. focusElement_ = element;
  131. VariantMap focusEventData;
  132. focusEventData[Focused::P_ELEMENT] = element;
  133. element->SendEvent(E_FOCUSED, focusEventData);
  134. }
  135. eventData[P_ELEMENT] = (void*)element;
  136. SendEvent(E_FOCUSCHANGED, eventData);
  137. }
  138. void UI::Clear()
  139. {
  140. if (!rootElement_)
  141. return;
  142. rootElement_->RemoveAllChildren();
  143. if (cursor_)
  144. rootElement_->AddChild(cursor_);
  145. }
  146. void UI::Update(float timeStep)
  147. {
  148. if (!rootElement_)
  149. return;
  150. PROFILE(UpdateUI);
  151. if (cursor_ && cursor_->IsVisible())
  152. {
  153. IntVector2 pos = cursor_->GetPosition();
  154. WeakPtr<UIElement> element(GetElementAt(pos));
  155. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  156. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  157. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  158. // Hover effect
  159. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  160. if (element)
  161. {
  162. if (!dragElement_ || dragElement_ == element || dragDropTest)
  163. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  164. }
  165. // Drag and drop test
  166. if (dragDropTest)
  167. {
  168. bool accept = element->OnDragDropTest(dragElement_);
  169. if (accept)
  170. {
  171. using namespace DragDropTest;
  172. VariantMap eventData;
  173. eventData[P_SOURCE] = (void*)dragElement_.Get();
  174. eventData[P_TARGET] = (void*)element.Get();
  175. eventData[P_ACCEPT] = accept;
  176. SendEvent(E_DRAGDROPTEST, eventData);
  177. accept = eventData[P_ACCEPT].GetBool();
  178. }
  179. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  180. }
  181. else if (dragSource)
  182. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  183. }
  184. // Touch hover
  185. Input* input = GetSubsystem<Input>();
  186. if (input)
  187. {
  188. unsigned numTouches = input->GetNumTouches();
  189. for (unsigned i = 0; i < numTouches; ++i)
  190. {
  191. TouchState* touch = input->GetTouch(i);
  192. WeakPtr<UIElement> element(GetElementAt(touch->position_));
  193. if (element)
  194. element->OnHover(element->ScreenToElement(touch->position_), touch->position_, MOUSEB_LEFT, 0, 0);
  195. }
  196. }
  197. Update(timeStep, rootElement_);
  198. }
  199. void UI::RenderUpdate()
  200. {
  201. if (!rootElement_ || !graphics_)
  202. return;
  203. PROFILE(GetUIBatches);
  204. // If the OS cursor is visible, do not render the UI's own cursor
  205. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  206. bool uiCursorVisible = false;
  207. if (osCursorVisible && cursor_)
  208. {
  209. uiCursorVisible = cursor_->IsVisible();
  210. cursor_->SetTempVisible(false);
  211. }
  212. // Get batches & quads from the UI elements
  213. batches_.Clear();
  214. quads_.Clear();
  215. const IntVector2& rootSize = rootElement_->GetSize();
  216. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  217. // If no drag, reset cursor shape for next frame
  218. if (cursor_ && !dragElement_)
  219. cursor_->SetShape(CS_NORMAL);
  220. // Restore UI cursor visibility state
  221. if (osCursorVisible && cursor_)
  222. cursor_->SetTempVisible(uiCursorVisible);
  223. }
  224. void UI::Render()
  225. {
  226. PROFILE(RenderUI);
  227. if (!graphics_ || graphics_->IsDeviceLost() || !quads_.Size())
  228. return;
  229. // Update quad geometry into the vertex buffer
  230. unsigned numVertices = quads_.Size() * 6;
  231. // Resize the vertex buffer if too small or much too large
  232. if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
  233. vertexBuffer_->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  234. unsigned vertexSize = vertexBuffer_->GetVertexSize();
  235. void* dest = vertexBuffer_->Lock(0, numVertices, true);
  236. if (!dest)
  237. return;
  238. for (unsigned i = 0; i < batches_.Size(); ++i)
  239. batches_[i].UpdateGeometry(graphics_, ((unsigned char*)dest) + batches_[i].quadStart_ * vertexSize * 6);
  240. vertexBuffer_->Unlock();
  241. Vector2 scale(2.0f, -2.0f);
  242. Vector2 offset(-1.0f, 1.0f);
  243. Matrix4 projection(Matrix4::IDENTITY);
  244. projection.m00_ = scale.x_;
  245. projection.m03_ = offset.x_;
  246. projection.m11_ = scale.y_;
  247. projection.m13_ = offset.y_;
  248. projection.m22_ = 1.0f;
  249. projection.m23_ = 0.0f;
  250. projection.m33_ = 1.0f;
  251. graphics_->ClearParameterSources();
  252. graphics_->SetCullMode(CULL_CCW);
  253. graphics_->SetDepthTest(CMP_ALWAYS);
  254. graphics_->SetDepthWrite(false);
  255. graphics_->SetStencilTest(false);
  256. graphics_->ResetRenderTargets();
  257. ShaderVariation* ps = 0;
  258. ShaderVariation* vs = 0;
  259. unsigned alphaFormat = Graphics::GetAlphaFormat();
  260. for (unsigned i = 0; i < batches_.Size(); ++i)
  261. {
  262. const UIBatch& batch = batches_[i];
  263. if (!batch.quadCount_)
  264. continue;
  265. if (!batch.texture_)
  266. {
  267. ps = noTexturePS_;
  268. vs = noTextureVS_;
  269. }
  270. else
  271. {
  272. // If texture contains only an alpha channel, use alpha shader (for fonts)
  273. vs = diffTextureVS_;
  274. if (batch.texture_->GetFormat() == alphaFormat)
  275. ps = alphaTexturePS_;
  276. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  277. ps = diffMaskTexturePS_;
  278. else
  279. ps = diffTexturePS_;
  280. }
  281. graphics_->SetShaders(vs, ps);
  282. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  283. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  284. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  285. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  286. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  287. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  288. graphics_->SetBlendMode(batch.blendMode_);
  289. graphics_->SetScissorTest(true, batch.scissor_);
  290. graphics_->SetTexture(0, batch.texture_);
  291. graphics_->SetVertexBuffer(vertexBuffer_);
  292. graphics_->Draw(TRIANGLE_LIST, batch.quadStart_ * 6, batch.quadCount_ * 6);
  293. }
  294. }
  295. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  296. {
  297. SharedPtr<XMLFile> xml(new XMLFile(context_));
  298. if (!xml->Load(source))
  299. return SharedPtr<UIElement>();
  300. else
  301. return LoadLayout(xml, styleFile);
  302. }
  303. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  304. {
  305. PROFILE(LoadUILayout);
  306. SharedPtr<UIElement> root;
  307. if (!file)
  308. {
  309. LOGERROR("Null UI layout XML file");
  310. return root;
  311. }
  312. LOGDEBUG("Loading UI layout " + file->GetName());
  313. XMLElement rootElem = file->GetRoot("element");
  314. if (!rootElem)
  315. {
  316. LOGERROR("No root UI element in " + file->GetName());
  317. return root;
  318. }
  319. String typeName = rootElem.GetAttribute("type");
  320. if (typeName.Empty())
  321. typeName = "UIElement";
  322. root = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(typeName)));
  323. if (!root)
  324. {
  325. LOGERROR("Could not create unknown UI element " + typeName);
  326. return root;
  327. }
  328. root->LoadXML(rootElem, styleFile);
  329. return root;
  330. }
  331. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  332. {
  333. PROFILE(SaveUILayout);
  334. if (element)
  335. return element->SaveXML(dest);
  336. else
  337. return false;
  338. }
  339. void UI::SetClipBoardText(const String& text)
  340. {
  341. clipBoard_ = text;
  342. }
  343. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  344. {
  345. if (!rootElement_)
  346. return 0;
  347. UIElement* result = 0;
  348. GetElementAt(result, rootElement_, position, activeOnly);
  349. return result;
  350. }
  351. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  352. {
  353. return GetElementAt(IntVector2(x, y), activeOnly);
  354. }
  355. UIElement* UI::GetFocusElement() const
  356. {
  357. return focusElement_;
  358. }
  359. UIElement* UI::GetFrontElement() const
  360. {
  361. if (!rootElement_)
  362. return 0;
  363. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  364. int maxPriority = M_MIN_INT;
  365. UIElement* front = 0;
  366. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  367. {
  368. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  369. if (!rootChildren[i]->IsActive() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  370. continue;
  371. int priority = rootChildren[i]->GetPriority();
  372. if (priority > maxPriority)
  373. {
  374. maxPriority = priority;
  375. front = rootChildren[i];
  376. }
  377. }
  378. return front;
  379. }
  380. IntVector2 UI::GetCursorPosition()
  381. {
  382. if (!cursor_)
  383. return IntVector2::ZERO;
  384. else
  385. return cursor_->GetPosition();
  386. }
  387. void UI::Initialize()
  388. {
  389. Graphics* graphics = GetSubsystem<Graphics>();
  390. Renderer* renderer = GetSubsystem<Renderer>();
  391. if (!graphics || !graphics->IsInitialized() || !renderer)
  392. return;
  393. PROFILE(InitUI);
  394. graphics_ = graphics;
  395. rootElement_ = new UIElement(context_);
  396. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  397. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  398. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  399. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  400. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  401. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  402. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  403. vertexBuffer_ = new VertexBuffer(context_);
  404. LOGINFO("Initialized user interface");
  405. initialized_ = true;
  406. }
  407. void UI::Update(float timeStep, UIElement* element)
  408. {
  409. element->Update(timeStep);
  410. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  411. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  412. Update(timeStep, *i);
  413. }
  414. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  415. {
  416. // Set clipping scissor for child elements. No need to draw if zero size
  417. element->AdjustScissor(currentScissor);
  418. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  419. return;
  420. element->SortChildren();
  421. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  422. if (children.Empty())
  423. return;
  424. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  425. // same renderstate
  426. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  427. if (element != rootElement_)
  428. {
  429. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  430. int currentPriority = children.Front()->GetPriority();
  431. while (i != children.End())
  432. {
  433. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  434. {
  435. if (IsVisible(*j, currentScissor))
  436. (*j)->GetBatches(batches_, quads_, currentScissor);
  437. ++j;
  438. }
  439. // Now recurse into the children
  440. while (i != j)
  441. {
  442. if (IsVisible(*i, currentScissor))
  443. GetBatches(*i, currentScissor);
  444. ++i;
  445. }
  446. if (i != children.End())
  447. currentPriority = (*i)->GetPriority();
  448. }
  449. }
  450. // On the root level draw each element and its children immediately after to avoid artifacts
  451. else
  452. {
  453. while (i != children.End())
  454. {
  455. if ((*i)->IsVisible())
  456. {
  457. if (IsVisible(*i, currentScissor))
  458. (*i)->GetBatches(batches_, quads_, currentScissor);
  459. GetBatches(*i, currentScissor);
  460. }
  461. ++i;
  462. }
  463. }
  464. }
  465. bool UI::IsVisible(UIElement* element, const IntRect& currentScissor)
  466. {
  467. // First check element's visibility
  468. if (!element->IsVisible())
  469. return false;
  470. // Then check element dimensions against the scissor rectangle
  471. const IntVector2& screenPos = element->GetScreenPosition();
  472. if (screenPos.x_ >= currentScissor.right_ || screenPos.x_ + element->GetWidth() <= currentScissor.left_ ||
  473. screenPos.y_ >= currentScissor.bottom_ || screenPos.y_ + element->GetHeight() <= currentScissor.top_)
  474. return false;
  475. else
  476. return true;
  477. }
  478. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  479. {
  480. if (!current)
  481. return;
  482. current->SortChildren();
  483. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  484. LayoutMode parentLayoutMode = current->GetLayoutMode();
  485. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  486. {
  487. UIElement* element = *i;
  488. bool hasChildren = element->GetNumChildren() > 0;
  489. if (element != cursor_.Get() && element->IsVisible())
  490. {
  491. if (element->IsInside(position, true))
  492. {
  493. // Store the current result, then recurse into its children. Because children
  494. // are sorted from lowest to highest priority, the topmost match should remain
  495. if (element->IsActive() || !activeOnly)
  496. result = element;
  497. if (hasChildren)
  498. GetElementAt(result, element, position, activeOnly);
  499. // Layout optimization: if the element has no children, can break out after the first match
  500. else if (parentLayoutMode != LM_FREE)
  501. break;
  502. }
  503. else
  504. {
  505. if (hasChildren)
  506. {
  507. if (element->IsInsideCombined(position, true))
  508. GetElementAt(result, element, position, activeOnly);
  509. }
  510. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  511. // or if we already passed all visible elements
  512. else if (parentLayoutMode != LM_FREE)
  513. {
  514. if (i == children.Begin())
  515. {
  516. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  517. element->GetScreenPosition().y_;
  518. int layoutMinSize = current->GetLayoutMinSize();
  519. if (screenPos < 0 && layoutMinSize > 0)
  520. {
  521. unsigned toSkip = -screenPos / layoutMinSize;
  522. if (toSkip > 0)
  523. {
  524. i += (toSkip - 1);
  525. if (i >= children.End())
  526. break;
  527. }
  528. }
  529. }
  530. else if (parentLayoutMode == LM_HORIZONTAL)
  531. {
  532. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  533. break;
  534. }
  535. else if (parentLayoutMode == LM_VERTICAL)
  536. {
  537. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  538. break;
  539. }
  540. }
  541. }
  542. }
  543. }
  544. }
  545. UIElement* UI::GetFocusableElement(UIElement* element)
  546. {
  547. while (element)
  548. {
  549. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  550. break;
  551. element = element->GetParent();
  552. }
  553. return element;
  554. }
  555. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  556. {
  557. using namespace ScreenMode;
  558. if (!initialized_)
  559. Initialize();
  560. else
  561. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  562. }
  563. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  564. {
  565. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  566. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  567. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  568. if (cursor_ && cursor_->IsVisible())
  569. {
  570. IntVector2 pos = cursor_->GetPosition();
  571. WeakPtr<UIElement> element(GetElementAt(pos));
  572. if (element)
  573. {
  574. // Handle focusing & bringing to front
  575. if (button == MOUSEB_LEFT)
  576. {
  577. SetFocusElement(element);
  578. element->BringToFront();
  579. }
  580. // Handle click
  581. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  582. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  583. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  584. {
  585. dragElement_ = element;
  586. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  587. }
  588. }
  589. else
  590. {
  591. // If clicked over no element, or a disabled element, lose focus
  592. SetFocusElement(0);
  593. }
  594. using namespace UIMouseClick;
  595. VariantMap eventData;
  596. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  597. eventData[UIMouseClick::P_X] = pos.x_;
  598. eventData[UIMouseClick::P_Y] = pos.y_;
  599. eventData[UIMouseClick::P_BUTTON] = button;
  600. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  601. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  602. SendEvent(E_UIMOUSECLICK, eventData);
  603. }
  604. }
  605. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  606. {
  607. using namespace MouseButtonUp;
  608. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  609. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  610. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  611. {
  612. IntVector2 pos = cursor_->GetPosition();
  613. if (dragElement_ && !mouseButtons_)
  614. {
  615. if (dragElement_->IsActive() && dragElement_->IsVisible())
  616. {
  617. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  618. // Drag and drop finish
  619. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  620. if (dragSource)
  621. {
  622. WeakPtr<UIElement> target(GetElementAt(pos));
  623. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  624. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  625. if (dragDropFinish)
  626. {
  627. bool accept = target->OnDragDropFinish(dragElement_);
  628. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  629. if (accept && dragElement_ && target)
  630. {
  631. using namespace DragDropFinish;
  632. VariantMap eventData;
  633. eventData[P_SOURCE] = (void*)dragElement_.Get();
  634. eventData[P_TARGET] = (void*)target.Get();
  635. eventData[P_ACCEPT] = accept;
  636. SendEvent(E_DRAGDROPFINISH, eventData);
  637. }
  638. }
  639. }
  640. }
  641. dragElement_.Reset();
  642. }
  643. }
  644. }
  645. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  646. {
  647. using namespace MouseMove;
  648. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  649. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  650. if (cursor_)
  651. {
  652. Input* input = GetSubsystem<Input>();
  653. const IntVector2& rootSize = rootElement_->GetSize();
  654. if (!input->IsMouseVisible())
  655. {
  656. // Relative mouse motion: move cursor only when visible
  657. if (cursor_->IsVisible())
  658. {
  659. IntVector2 pos = cursor_->GetPosition();
  660. pos.x_ += eventData[P_DX].GetInt();
  661. pos.y_ += eventData[P_DY].GetInt();
  662. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  663. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  664. cursor_->SetPosition(pos);
  665. }
  666. }
  667. else
  668. {
  669. // Absolute mouse motion: move always
  670. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  671. }
  672. if (dragElement_ && mouseButtons_)
  673. {
  674. IntVector2 pos = cursor_->GetPosition();
  675. if (dragElement_->IsActive() && dragElement_->IsVisible())
  676. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  677. else
  678. {
  679. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  680. dragElement_.Reset();
  681. }
  682. }
  683. }
  684. }
  685. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  686. {
  687. using namespace MouseWheel;
  688. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  689. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  690. int delta = eventData[P_WHEEL].GetInt();
  691. UIElement* element = GetFocusElement();
  692. if (element)
  693. element->OnWheel(delta, mouseButtons_, qualifiers_);
  694. else
  695. {
  696. // If no element has actual focus, get the element at cursor
  697. if (cursor_)
  698. {
  699. IntVector2 pos = cursor_->GetPosition();
  700. UIElement* element = GetElementAt(pos);
  701. // If the element itself is not focusable, search for a focusable parent
  702. element = GetFocusableElement(element);
  703. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  704. element->OnWheel(delta, mouseButtons_, qualifiers_);
  705. }
  706. }
  707. }
  708. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  709. {
  710. using namespace TouchBegin;
  711. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  712. WeakPtr<UIElement> element(GetElementAt(pos));
  713. if (element)
  714. {
  715. // Handle focusing & bringing to front
  716. SetFocusElement(element);
  717. element->BringToFront();
  718. // Handle click
  719. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  720. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  721. if (element && !dragElement_ )
  722. {
  723. dragElement_ = element;
  724. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  725. }
  726. }
  727. else
  728. {
  729. // If clicked over no element, or a disabled element, lose focus
  730. SetFocusElement(0);
  731. }
  732. using namespace UIMouseClick;
  733. VariantMap clickEventData;
  734. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  735. clickEventData[UIMouseClick::P_X] = pos.x_;
  736. clickEventData[UIMouseClick::P_Y] = pos.y_;
  737. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  738. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  739. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  740. SendEvent(E_UIMOUSECLICK, clickEventData);
  741. }
  742. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  743. {
  744. using namespace TouchEnd;
  745. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  746. // Transmit hover end to the position where the finger was lifted
  747. WeakPtr<UIElement> element(GetElementAt(pos));
  748. if (element)
  749. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  750. if (dragElement_)
  751. {
  752. if (dragElement_->IsActive() && dragElement_->IsVisible())
  753. {
  754. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  755. // Drag and drop finish
  756. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  757. if (dragSource)
  758. {
  759. WeakPtr<UIElement> target(GetElementAt(pos));
  760. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  761. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  762. if (dragDropFinish)
  763. {
  764. bool accept = target->OnDragDropFinish(dragElement_);
  765. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  766. if (accept && dragElement_ && target)
  767. {
  768. using namespace DragDropFinish;
  769. VariantMap eventData;
  770. eventData[P_SOURCE] = (void*)dragElement_.Get();
  771. eventData[P_TARGET] = (void*)target.Get();
  772. eventData[P_ACCEPT] = accept;
  773. SendEvent(E_DRAGDROPFINISH, eventData);
  774. }
  775. }
  776. }
  777. }
  778. dragElement_.Reset();
  779. }
  780. }
  781. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  782. {
  783. using namespace TouchMove;
  784. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  785. if (dragElement_)
  786. {
  787. if (dragElement_->IsActive() && dragElement_->IsVisible())
  788. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  789. else
  790. {
  791. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  792. dragElement_.Reset();
  793. }
  794. }
  795. }
  796. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  797. {
  798. using namespace KeyDown;
  799. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  800. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  801. int key = eventData[P_KEY].GetInt();
  802. UIElement* element = GetFocusElement();
  803. if (element)
  804. {
  805. // Switch focus between focusable elements in the same top level window
  806. if (key == KEY_TAB)
  807. {
  808. UIElement* topLevel = element->GetParent();
  809. while (topLevel && topLevel->GetParent() != rootElement_)
  810. topLevel = topLevel->GetParent();
  811. if (topLevel)
  812. {
  813. topLevel->GetChildren(tempElements_, true);
  814. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  815. {
  816. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  817. i = tempElements_.Erase(i);
  818. else
  819. ++i;
  820. }
  821. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  822. {
  823. if (tempElements_[i] == element)
  824. {
  825. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  826. SetFocusElement(next);
  827. return;
  828. }
  829. }
  830. }
  831. }
  832. // Defocus the element
  833. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  834. element->SetFocus(false);
  835. // If none of the special keys, pass the key to the focused element
  836. else
  837. element->OnKey(key, mouseButtons_, qualifiers_);
  838. }
  839. }
  840. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  841. {
  842. using namespace Char;
  843. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  844. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  845. UIElement* element = GetFocusElement();
  846. if (element)
  847. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  848. }
  849. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  850. {
  851. if (initialized_)
  852. {
  853. using namespace PostUpdate;
  854. Update(eventData[P_TIMESTEP].GetFloat());
  855. }
  856. }
  857. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  858. {
  859. if (initialized_)
  860. RenderUpdate();
  861. }
  862. void RegisterUILibrary(Context* context)
  863. {
  864. Font::RegisterObject(context);
  865. UIElement::RegisterObject(context);
  866. BorderImage::RegisterObject(context);
  867. Button::RegisterObject(context);
  868. CheckBox::RegisterObject(context);
  869. Cursor::RegisterObject(context);
  870. Text::RegisterObject(context);
  871. Window::RegisterObject(context);
  872. LineEdit::RegisterObject(context);
  873. Slider::RegisterObject(context);
  874. ScrollBar::RegisterObject(context);
  875. ScrollView::RegisterObject(context);
  876. ListView::RegisterObject(context);
  877. Menu::RegisterObject(context);
  878. DropDownList::RegisterObject(context);
  879. FileSelector::RegisterObject(context);
  880. }
  881. }