UI.cpp 35 KB

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