UI.cpp 35 KB

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