UI.cpp 35 KB

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