UI.cpp 36 KB

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