UI.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. mouseButtons_(0),
  58. qualifiers_(0),
  59. initialized_(false),
  60. #ifdef WIN32
  61. nonFocusedMouseWheel_(false) // Default MS Windows behaviour
  62. #else
  63. nonFocusedMouseWheel_(true) // Default Mac OS X and Linux behaviour
  64. #endif
  65. {
  66. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  67. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  68. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  69. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  70. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  71. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  72. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  73. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  74. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  75. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  76. // Delay SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate)) and
  77. // SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate)) until UI is initialized
  78. // Try to initialize right now, but skip if screen mode is not yet set
  79. Initialize();
  80. }
  81. UI::~UI()
  82. {
  83. }
  84. void UI::SetCursor(Cursor* cursor)
  85. {
  86. if (!rootElement_)
  87. return;
  88. // Remove old cursor (if any) and set new
  89. if (cursor_)
  90. {
  91. rootElement_->RemoveChild(cursor_);
  92. cursor_.Reset();
  93. }
  94. if (cursor)
  95. {
  96. rootElement_->AddChild(cursor);
  97. cursor_ = cursor;
  98. IntVector2 pos = cursor_->GetPosition();
  99. const IntVector2& rootSize = rootElement_->GetSize();
  100. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  101. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  102. cursor_->SetPosition(pos);
  103. }
  104. }
  105. void UI::SetFocusElement(UIElement* element)
  106. {
  107. if (!rootElement_)
  108. return;
  109. using namespace FocusChanged;
  110. VariantMap eventData;
  111. eventData[P_CLICKEDELEMENT] = (void*)element;
  112. if (element)
  113. {
  114. // Return if already has focus
  115. if (focusElement_ == element)
  116. return;
  117. // Search for an element in the hierarchy that can alter focus. If none found, exit
  118. element = GetFocusableElement(element);
  119. if (!element)
  120. return;
  121. }
  122. // Remove focus from the old element
  123. if (focusElement_)
  124. {
  125. UIElement* oldFocusElement = focusElement_;
  126. focusElement_.Reset();
  127. VariantMap focusEventData;
  128. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  129. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  130. }
  131. // Then set focus to the new
  132. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  133. {
  134. focusElement_ = element;
  135. VariantMap focusEventData;
  136. focusEventData[Focused::P_ELEMENT] = element;
  137. element->SendEvent(E_FOCUSED, focusEventData);
  138. }
  139. eventData[P_ELEMENT] = (void*)element;
  140. SendEvent(E_FOCUSCHANGED, eventData);
  141. }
  142. void UI::Clear()
  143. {
  144. if (!rootElement_)
  145. return;
  146. rootElement_->RemoveAllChildren();
  147. if (cursor_)
  148. rootElement_->AddChild(cursor_);
  149. }
  150. void UI::Update(float timeStep)
  151. {
  152. assert(rootElement_);
  153. PROFILE(UpdateUI);
  154. if (cursor_ && cursor_->IsVisible())
  155. {
  156. IntVector2 pos = cursor_->GetPosition();
  157. WeakPtr<UIElement> element(GetElementAt(pos));
  158. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  159. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  160. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  161. // Hover effect
  162. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  163. if (element)
  164. {
  165. if (!dragElement_ || dragElement_ == element || dragDropTest)
  166. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  167. }
  168. // Drag and drop test
  169. if (dragDropTest)
  170. {
  171. bool accept = element->OnDragDropTest(dragElement_);
  172. if (accept)
  173. {
  174. using namespace DragDropTest;
  175. VariantMap eventData;
  176. eventData[P_SOURCE] = (void*)dragElement_.Get();
  177. eventData[P_TARGET] = (void*)element.Get();
  178. eventData[P_ACCEPT] = accept;
  179. SendEvent(E_DRAGDROPTEST, eventData);
  180. accept = eventData[P_ACCEPT].GetBool();
  181. }
  182. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  183. }
  184. else if (dragSource)
  185. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  186. }
  187. // Touch hover
  188. Input* input = GetSubsystem<Input>();
  189. if (input)
  190. {
  191. unsigned numTouches = input->GetNumTouches();
  192. for (unsigned i = 0; i < numTouches; ++i)
  193. {
  194. TouchState* touch = input->GetTouch(i);
  195. UIElement* element = GetElementAt(touch->position_);
  196. if (element)
  197. element->OnHover(element->ScreenToElement(touch->position_), touch->position_, MOUSEB_LEFT, 0, 0);
  198. }
  199. }
  200. Update(timeStep, rootElement_);
  201. }
  202. void UI::RenderUpdate()
  203. {
  204. assert(rootElement_ && graphics_);
  205. PROFILE(GetUIBatches);
  206. // If the OS cursor is visible, do not render the UI's own cursor
  207. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  208. bool uiCursorVisible = false;
  209. if (osCursorVisible && cursor_)
  210. {
  211. uiCursorVisible = cursor_->IsVisible();
  212. cursor_->SetTempVisible(false);
  213. }
  214. // Get batches & quads from the UI elements
  215. batches_.Clear();
  216. quads_.Clear();
  217. const IntVector2& rootSize = rootElement_->GetSize();
  218. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  219. // If no drag, reset cursor shape for next frame
  220. if (cursor_ && !dragElement_)
  221. cursor_->SetShape(CS_NORMAL);
  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_ = new UIElement(context_);
  404. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  405. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  406. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  407. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  408. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  409. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  410. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  411. vertexBuffer_ = new VertexBuffer(context_);
  412. initialized_ = true;
  413. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  414. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  415. LOGINFO("Initialized user interface");
  416. }
  417. void UI::Update(float timeStep, UIElement* element)
  418. {
  419. element->Update(timeStep);
  420. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  421. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  422. Update(timeStep, *i);
  423. }
  424. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  425. {
  426. // Set clipping scissor for child elements. No need to draw if zero size
  427. element->AdjustScissor(currentScissor);
  428. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  429. return;
  430. element->SortChildren();
  431. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  432. if (children.Empty())
  433. return;
  434. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  435. // same renderstate
  436. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  437. if (element != rootElement_)
  438. {
  439. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  440. while (i != children.End())
  441. {
  442. int currentPriority = (*i)->GetPriority();
  443. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  444. {
  445. if (IsVisible(*j, currentScissor))
  446. (*j)->GetBatches(batches_, quads_, currentScissor);
  447. ++j;
  448. }
  449. // Now recurse into the children
  450. while (i != j)
  451. {
  452. if (IsVisible(*i, currentScissor))
  453. GetBatches(*i, currentScissor);
  454. ++i;
  455. }
  456. }
  457. }
  458. // On the root level draw each element and its children immediately after to avoid artifacts
  459. else
  460. {
  461. while (i != children.End())
  462. {
  463. if ((*i)->IsVisible())
  464. {
  465. if (IsVisible(*i, currentScissor))
  466. (*i)->GetBatches(batches_, quads_, currentScissor);
  467. GetBatches(*i, currentScissor);
  468. }
  469. ++i;
  470. }
  471. }
  472. }
  473. bool UI::IsVisible(UIElement* element, const IntRect& currentScissor)
  474. {
  475. // First check element's visibility
  476. if (!element->IsVisible())
  477. return false;
  478. // Then check element dimensions against the scissor rectangle
  479. const IntVector2& screenPos = element->GetScreenPosition();
  480. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + element->GetWidth() > currentScissor.left_ &&
  481. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + element->GetHeight() > currentScissor.top_;
  482. }
  483. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  484. {
  485. if (!current)
  486. return;
  487. current->SortChildren();
  488. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  489. LayoutMode parentLayoutMode = current->GetLayoutMode();
  490. for (unsigned i = 0; i < children.Size(); ++i)
  491. {
  492. UIElement* element = children[i];
  493. bool hasChildren = element->GetNumChildren() > 0;
  494. if (element != cursor_.Get() && element->IsVisible())
  495. {
  496. if (element->IsInside(position, true))
  497. {
  498. // Store the current result, then recurse into its children. Because children
  499. // are sorted from lowest to highest priority, the topmost match should remain
  500. if (element->IsActive() || !activeOnly)
  501. result = element;
  502. if (hasChildren)
  503. GetElementAt(result, element, position, activeOnly);
  504. // Layout optimization: if the element has no children, can break out after the first match
  505. else if (parentLayoutMode != LM_FREE)
  506. break;
  507. }
  508. else
  509. {
  510. if (hasChildren)
  511. {
  512. if (element->IsInsideCombined(position, true))
  513. GetElementAt(result, element, position, activeOnly);
  514. }
  515. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  516. // or if we already passed all visible elements
  517. else if (parentLayoutMode != LM_FREE)
  518. {
  519. if (!i)
  520. {
  521. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  522. element->GetScreenPosition().y_;
  523. int layoutMinSize = current->GetLayoutMinSize();
  524. if (screenPos < 0 && layoutMinSize > 0)
  525. {
  526. unsigned toSkip = -screenPos / layoutMinSize;
  527. if (toSkip > 0)
  528. i += (toSkip - 1);
  529. }
  530. }
  531. else if (parentLayoutMode == LM_HORIZONTAL)
  532. {
  533. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  534. break;
  535. }
  536. else if (parentLayoutMode == LM_VERTICAL)
  537. {
  538. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  539. break;
  540. }
  541. }
  542. }
  543. }
  544. }
  545. }
  546. UIElement* UI::GetFocusableElement(UIElement* element)
  547. {
  548. while (element)
  549. {
  550. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  551. break;
  552. element = element->GetParent();
  553. }
  554. return element;
  555. }
  556. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  557. {
  558. using namespace ScreenMode;
  559. if (!initialized_)
  560. Initialize();
  561. else
  562. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  563. }
  564. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  565. {
  566. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  567. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  568. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  569. if (cursor_ && cursor_->IsVisible())
  570. {
  571. IntVector2 pos = cursor_->GetPosition();
  572. WeakPtr<UIElement> element(GetElementAt(pos));
  573. if (element)
  574. {
  575. // Handle focusing & bringing to front
  576. if (button == MOUSEB_LEFT)
  577. {
  578. SetFocusElement(element);
  579. element->BringToFront();
  580. }
  581. // Handle click
  582. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  583. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  584. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  585. {
  586. dragElement_ = element;
  587. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  588. }
  589. }
  590. else
  591. {
  592. // If clicked over no element, or a disabled element, lose focus
  593. SetFocusElement(0);
  594. }
  595. using namespace UIMouseClick;
  596. VariantMap eventData;
  597. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  598. eventData[UIMouseClick::P_X] = pos.x_;
  599. eventData[UIMouseClick::P_Y] = pos.y_;
  600. eventData[UIMouseClick::P_BUTTON] = button;
  601. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  602. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  603. SendEvent(E_UIMOUSECLICK, eventData);
  604. }
  605. }
  606. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  607. {
  608. using namespace MouseButtonUp;
  609. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  610. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  611. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  612. {
  613. IntVector2 pos = cursor_->GetPosition();
  614. if (dragElement_ && !mouseButtons_)
  615. {
  616. if (dragElement_->IsActive() && dragElement_->IsVisible())
  617. {
  618. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  619. // Drag and drop finish
  620. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  621. if (dragSource)
  622. {
  623. WeakPtr<UIElement> target(GetElementAt(pos));
  624. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  625. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  626. if (dragDropFinish)
  627. {
  628. bool accept = target->OnDragDropFinish(dragElement_);
  629. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  630. if (accept && dragElement_ && target)
  631. {
  632. using namespace DragDropFinish;
  633. VariantMap eventData;
  634. eventData[P_SOURCE] = (void*)dragElement_.Get();
  635. eventData[P_TARGET] = (void*)target.Get();
  636. eventData[P_ACCEPT] = accept;
  637. SendEvent(E_DRAGDROPFINISH, eventData);
  638. }
  639. }
  640. }
  641. }
  642. dragElement_.Reset();
  643. }
  644. }
  645. }
  646. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  647. {
  648. using namespace MouseMove;
  649. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  650. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  651. if (cursor_)
  652. {
  653. Input* input = GetSubsystem<Input>();
  654. const IntVector2& rootSize = rootElement_->GetSize();
  655. if (!input->IsMouseVisible())
  656. {
  657. // Relative mouse motion: move cursor only when visible
  658. if (cursor_->IsVisible())
  659. {
  660. IntVector2 pos = cursor_->GetPosition();
  661. pos.x_ += eventData[P_DX].GetInt();
  662. pos.y_ += eventData[P_DY].GetInt();
  663. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  664. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  665. cursor_->SetPosition(pos);
  666. }
  667. }
  668. else
  669. {
  670. // Absolute mouse motion: move always
  671. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  672. }
  673. if (dragElement_ && mouseButtons_)
  674. {
  675. IntVector2 pos = cursor_->GetPosition();
  676. if (dragElement_->IsActive() && dragElement_->IsVisible())
  677. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  678. else
  679. {
  680. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  681. dragElement_.Reset();
  682. }
  683. }
  684. }
  685. }
  686. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  687. {
  688. using namespace MouseWheel;
  689. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  690. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  691. int delta = eventData[P_WHEEL].GetInt();
  692. UIElement* element;
  693. if (!nonFocusedMouseWheel_&& (element = GetFocusElement()))
  694. element->OnWheel(delta, mouseButtons_, qualifiers_);
  695. else
  696. {
  697. // If no element has actual focus or in non-focused mode, get the element at cursor
  698. if (cursor_)
  699. {
  700. IntVector2 pos = cursor_->GetPosition();
  701. element = GetElementAt(pos);
  702. if (nonFocusedMouseWheel_)
  703. {
  704. // Going up the hierarchy chain to find element that could handle mouse wheel
  705. while (element)
  706. {
  707. if (element->GetType() == ListView::GetTypeStatic() ||
  708. element->GetType() == ScrollView::GetTypeStatic())
  709. break;
  710. element = element->GetParent();
  711. }
  712. }
  713. else
  714. // If the element itself is not focusable, search for a focusable parent,
  715. // although the focusable element may not actually handle mouse wheel
  716. element = GetFocusableElement(element);
  717. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  718. element->OnWheel(delta, mouseButtons_, qualifiers_);
  719. }
  720. }
  721. }
  722. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  723. {
  724. using namespace TouchBegin;
  725. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  726. WeakPtr<UIElement> element(GetElementAt(pos));
  727. if (element)
  728. {
  729. // Handle focusing & bringing to front
  730. SetFocusElement(element);
  731. element->BringToFront();
  732. // Handle click
  733. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  734. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  735. if (element && !dragElement_ )
  736. {
  737. dragElement_ = element;
  738. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  739. }
  740. }
  741. else
  742. {
  743. // If clicked over no element, or a disabled element, lose focus
  744. SetFocusElement(0);
  745. }
  746. using namespace UIMouseClick;
  747. VariantMap clickEventData;
  748. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  749. clickEventData[UIMouseClick::P_X] = pos.x_;
  750. clickEventData[UIMouseClick::P_Y] = pos.y_;
  751. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  752. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  753. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  754. SendEvent(E_UIMOUSECLICK, clickEventData);
  755. }
  756. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  757. {
  758. using namespace TouchEnd;
  759. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  760. // Transmit hover end to the position where the finger was lifted
  761. UIElement* element = GetElementAt(pos);
  762. if (element)
  763. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  764. if (dragElement_)
  765. {
  766. if (dragElement_->IsActive() && dragElement_->IsVisible())
  767. {
  768. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  769. // Drag and drop finish
  770. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  771. if (dragSource)
  772. {
  773. WeakPtr<UIElement> target(GetElementAt(pos));
  774. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  775. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  776. if (dragDropFinish)
  777. {
  778. bool accept = target->OnDragDropFinish(dragElement_);
  779. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  780. if (accept && dragElement_ && target)
  781. {
  782. using namespace DragDropFinish;
  783. VariantMap eventData;
  784. eventData[P_SOURCE] = (void*)dragElement_.Get();
  785. eventData[P_TARGET] = (void*)target.Get();
  786. eventData[P_ACCEPT] = accept;
  787. SendEvent(E_DRAGDROPFINISH, eventData);
  788. }
  789. }
  790. }
  791. }
  792. dragElement_.Reset();
  793. }
  794. }
  795. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  796. {
  797. using namespace TouchMove;
  798. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  799. if (dragElement_)
  800. {
  801. if (dragElement_->IsActive() && dragElement_->IsVisible())
  802. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  803. else
  804. {
  805. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  806. dragElement_.Reset();
  807. }
  808. }
  809. }
  810. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  811. {
  812. using namespace KeyDown;
  813. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  814. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  815. int key = eventData[P_KEY].GetInt();
  816. UIElement* element = GetFocusElement();
  817. if (element)
  818. {
  819. // Switch focus between focusable elements in the same top level window
  820. if (key == KEY_TAB)
  821. {
  822. UIElement* topLevel = element->GetParent();
  823. while (topLevel && topLevel->GetParent() != rootElement_)
  824. topLevel = topLevel->GetParent();
  825. if (topLevel)
  826. {
  827. topLevel->GetChildren(tempElements_, true);
  828. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  829. {
  830. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  831. i = tempElements_.Erase(i);
  832. else
  833. ++i;
  834. }
  835. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  836. {
  837. if (tempElements_[i] == element)
  838. {
  839. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  840. SetFocusElement(next);
  841. return;
  842. }
  843. }
  844. }
  845. }
  846. // Defocus the element
  847. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  848. element->SetFocus(false);
  849. // If none of the special keys, pass the key to the focused element
  850. else
  851. element->OnKey(key, mouseButtons_, qualifiers_);
  852. }
  853. }
  854. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  855. {
  856. using namespace Char;
  857. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  858. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  859. UIElement* element = GetFocusElement();
  860. if (element)
  861. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  862. }
  863. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  864. {
  865. using namespace PostUpdate;
  866. Update(eventData[P_TIMESTEP].GetFloat());
  867. }
  868. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  869. {
  870. RenderUpdate();
  871. }
  872. void RegisterUILibrary(Context* context)
  873. {
  874. Font::RegisterObject(context);
  875. UIElement::RegisterObject(context);
  876. BorderImage::RegisterObject(context);
  877. Button::RegisterObject(context);
  878. CheckBox::RegisterObject(context);
  879. Cursor::RegisterObject(context);
  880. Text::RegisterObject(context);
  881. Window::RegisterObject(context);
  882. LineEdit::RegisterObject(context);
  883. Slider::RegisterObject(context);
  884. ScrollBar::RegisterObject(context);
  885. ScrollView::RegisterObject(context);
  886. ListView::RegisterObject(context);
  887. Menu::RegisterObject(context);
  888. DropDownList::RegisterObject(context);
  889. FileSelector::RegisterObject(context);
  890. }
  891. }