UI.cpp 35 KB

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