UI.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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)
  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)
  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() / 6;
  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_ / 6, (batch.vertexEnd_ - batch.vertexStart_) / 6);
  287. }
  288. }
  289. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  290. {
  291. SharedPtr<XMLFile> xml(new XMLFile(context_));
  292. if (!xml->Load(source))
  293. return SharedPtr<UIElement>();
  294. else
  295. return LoadLayout(xml, styleFile);
  296. }
  297. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  298. {
  299. PROFILE(LoadUILayout);
  300. SharedPtr<UIElement> root;
  301. if (!file)
  302. {
  303. LOGERROR("Null UI layout XML file");
  304. return root;
  305. }
  306. LOGDEBUG("Loading UI layout " + file->GetName());
  307. XMLElement rootElem = file->GetRoot("element");
  308. if (!rootElem)
  309. {
  310. LOGERROR("No root UI element in " + file->GetName());
  311. return root;
  312. }
  313. String typeName = rootElem.GetAttribute("type");
  314. if (typeName.Empty())
  315. typeName = "UIElement";
  316. root = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(typeName)));
  317. if (!root)
  318. {
  319. LOGERROR("Could not create unknown UI element " + typeName);
  320. return root;
  321. }
  322. if (styleFile)
  323. // Set it as default for later use by children elements
  324. root->SetDefaultStyle(styleFile);
  325. else
  326. // Use default style file of the root element if it has one
  327. styleFile = rootElement_->GetDefaultStyle(false);
  328. root->LoadXML(rootElem, styleFile);
  329. return root;
  330. }
  331. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  332. {
  333. PROFILE(SaveUILayout);
  334. if (element)
  335. return element->SaveXML(dest);
  336. else
  337. return false;
  338. }
  339. void UI::SetClipBoardText(const String& text)
  340. {
  341. clipBoard_ = text;
  342. }
  343. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  344. {
  345. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  346. }
  347. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  348. {
  349. UIElement* result = 0;
  350. GetElementAt(result, rootElement_, position, activeOnly);
  351. return result;
  352. }
  353. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  354. {
  355. return GetElementAt(IntVector2(x, y), activeOnly);
  356. }
  357. UIElement* UI::GetFocusElement() const
  358. {
  359. return focusElement_;
  360. }
  361. UIElement* UI::GetFrontElement() const
  362. {
  363. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  364. int maxPriority = M_MIN_INT;
  365. UIElement* front = 0;
  366. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  367. {
  368. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  369. if (!rootChildren[i]->IsActive() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  370. continue;
  371. int priority = rootChildren[i]->GetPriority();
  372. if (priority > maxPriority)
  373. {
  374. maxPriority = priority;
  375. front = rootChildren[i];
  376. }
  377. }
  378. return front;
  379. }
  380. IntVector2 UI::GetCursorPosition()
  381. {
  382. if (!cursor_)
  383. return IntVector2::ZERO;
  384. else
  385. return cursor_->GetPosition();
  386. }
  387. void UI::Initialize()
  388. {
  389. Graphics* graphics = GetSubsystem<Graphics>();
  390. Renderer* renderer = GetSubsystem<Renderer>();
  391. if (!graphics || !graphics->IsInitialized() || !renderer)
  392. return;
  393. PROFILE(InitUI);
  394. graphics_ = graphics;
  395. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  396. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  397. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  398. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  399. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  400. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  401. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  402. vertexBuffer_ = new VertexBuffer(context_);
  403. initialized_ = true;
  404. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  405. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  406. LOGINFO("Initialized user interface");
  407. }
  408. void UI::Update(float timeStep, UIElement* element)
  409. {
  410. element->Update(timeStep);
  411. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  412. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  413. Update(timeStep, *i);
  414. }
  415. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  416. {
  417. // Set clipping scissor for child elements. No need to draw if zero size
  418. element->AdjustScissor(currentScissor);
  419. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  420. return;
  421. element->SortChildren();
  422. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  423. if (children.Empty())
  424. return;
  425. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  426. // same renderstate
  427. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  428. if (element != rootElement_)
  429. {
  430. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  431. while (i != children.End())
  432. {
  433. int currentPriority = (*i)->GetPriority();
  434. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  435. {
  436. if ((*j)->IsWithinScissor(currentScissor))
  437. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  438. ++j;
  439. }
  440. // Now recurse into the children
  441. while (i != j)
  442. {
  443. if ((*i)->IsVisible())
  444. GetBatches(*i, currentScissor);
  445. ++i;
  446. }
  447. }
  448. }
  449. // On the root level draw each element and its children immediately after to avoid artifacts
  450. else
  451. {
  452. while (i != children.End())
  453. {
  454. if ((*i)->IsWithinScissor(currentScissor))
  455. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  456. if ((*i)->IsVisible())
  457. GetBatches(*i, currentScissor);
  458. ++i;
  459. }
  460. }
  461. }
  462. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  463. {
  464. if (!current)
  465. return;
  466. current->SortChildren();
  467. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  468. LayoutMode parentLayoutMode = current->GetLayoutMode();
  469. for (unsigned i = 0; i < children.Size(); ++i)
  470. {
  471. UIElement* element = children[i];
  472. bool hasChildren = element->GetNumChildren() > 0;
  473. if (element != cursor_.Get() && element->IsVisible())
  474. {
  475. if (element->IsInside(position, true))
  476. {
  477. // Store the current result, then recurse into its children. Because children
  478. // are sorted from lowest to highest priority, the topmost match should remain
  479. if (element->IsActive() || !activeOnly)
  480. result = element;
  481. if (hasChildren)
  482. GetElementAt(result, element, position, activeOnly);
  483. // Layout optimization: if the element has no children, can break out after the first match
  484. else if (parentLayoutMode != LM_FREE)
  485. break;
  486. }
  487. else
  488. {
  489. if (hasChildren)
  490. {
  491. if (element->IsInsideCombined(position, true))
  492. GetElementAt(result, element, position, activeOnly);
  493. }
  494. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  495. // or if we already passed all visible elements
  496. else if (parentLayoutMode != LM_FREE)
  497. {
  498. if (!i)
  499. {
  500. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  501. element->GetScreenPosition().y_;
  502. int layoutMinSize = current->GetLayoutMinSize();
  503. if (screenPos < 0 && layoutMinSize > 0)
  504. {
  505. unsigned toSkip = -screenPos / layoutMinSize;
  506. if (toSkip > 0)
  507. i += (toSkip - 1);
  508. }
  509. }
  510. else if (parentLayoutMode == LM_HORIZONTAL)
  511. {
  512. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  513. break;
  514. }
  515. else if (parentLayoutMode == LM_VERTICAL)
  516. {
  517. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  518. break;
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }
  525. UIElement* UI::GetFocusableElement(UIElement* element)
  526. {
  527. while (element)
  528. {
  529. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  530. break;
  531. element = element->GetParent();
  532. }
  533. return element;
  534. }
  535. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  536. {
  537. using namespace ScreenMode;
  538. if (!initialized_)
  539. Initialize();
  540. else
  541. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  542. }
  543. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  544. {
  545. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  546. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  547. if (cursor_ && cursor_->IsVisible())
  548. {
  549. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  550. IntVector2 pos = cursor_->GetPosition();
  551. WeakPtr<UIElement> element(GetElementAt(pos));
  552. if (element)
  553. {
  554. // Handle focusing & bringing to front
  555. if (button == MOUSEB_LEFT)
  556. {
  557. SetFocusElement(element);
  558. element->BringToFront();
  559. }
  560. // Handle click
  561. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  562. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  563. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  564. {
  565. dragElement_ = element;
  566. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  567. }
  568. }
  569. else
  570. {
  571. // If clicked over no element, or a disabled element, lose focus
  572. SetFocusElement(0);
  573. }
  574. using namespace UIMouseClick;
  575. VariantMap eventData;
  576. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  577. eventData[UIMouseClick::P_X] = pos.x_;
  578. eventData[UIMouseClick::P_Y] = pos.y_;
  579. eventData[UIMouseClick::P_BUTTON] = button;
  580. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  581. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  582. SendEvent(E_UIMOUSECLICK, eventData);
  583. }
  584. }
  585. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  586. {
  587. using namespace MouseButtonUp;
  588. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  589. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  590. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  591. {
  592. IntVector2 pos = cursor_->GetPosition();
  593. if (dragElement_ && !mouseButtons_)
  594. {
  595. if (dragElement_->IsActive() && dragElement_->IsVisible())
  596. {
  597. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  598. // Drag and drop finish
  599. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  600. if (dragSource)
  601. {
  602. WeakPtr<UIElement> target(GetElementAt(pos));
  603. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  604. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  605. if (dragDropFinish)
  606. {
  607. bool accept = target->OnDragDropFinish(dragElement_);
  608. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  609. if (accept && dragElement_ && target)
  610. {
  611. using namespace DragDropFinish;
  612. VariantMap eventData;
  613. eventData[P_SOURCE] = (void*)dragElement_.Get();
  614. eventData[P_TARGET] = (void*)target.Get();
  615. eventData[P_ACCEPT] = accept;
  616. SendEvent(E_DRAGDROPFINISH, eventData);
  617. }
  618. }
  619. }
  620. }
  621. dragElement_.Reset();
  622. }
  623. }
  624. }
  625. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  626. {
  627. using namespace MouseMove;
  628. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  629. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  630. if (cursor_)
  631. {
  632. Input* input = GetSubsystem<Input>();
  633. const IntVector2& rootSize = rootElement_->GetSize();
  634. if (!input->IsMouseVisible())
  635. {
  636. // Relative mouse motion: move cursor only when visible
  637. if (cursor_->IsVisible())
  638. {
  639. IntVector2 pos = cursor_->GetPosition();
  640. pos.x_ += eventData[P_DX].GetInt();
  641. pos.y_ += eventData[P_DY].GetInt();
  642. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  643. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  644. cursor_->SetPosition(pos);
  645. }
  646. }
  647. else
  648. {
  649. // Absolute mouse motion: move always
  650. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  651. }
  652. if (dragElement_ && mouseButtons_)
  653. {
  654. IntVector2 pos = cursor_->GetPosition();
  655. if (dragElement_->IsActive() && dragElement_->IsVisible())
  656. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  657. else
  658. {
  659. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  660. dragElement_.Reset();
  661. }
  662. }
  663. }
  664. }
  665. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  666. {
  667. using namespace MouseWheel;
  668. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  669. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  670. int delta = eventData[P_WHEEL].GetInt();
  671. UIElement* element;
  672. if (!nonFocusedMouseWheel_&& (element = GetFocusElement()))
  673. element->OnWheel(delta, mouseButtons_, qualifiers_);
  674. else
  675. {
  676. // If no element has actual focus or in non-focused mode, get the element at cursor
  677. if (cursor_)
  678. {
  679. IntVector2 pos = cursor_->GetPosition();
  680. element = GetElementAt(pos);
  681. if (nonFocusedMouseWheel_)
  682. {
  683. // Going up the hierarchy chain to find element that could handle mouse wheel
  684. while (element)
  685. {
  686. if (element->GetType() == ListView::GetTypeStatic() ||
  687. element->GetType() == ScrollView::GetTypeStatic())
  688. break;
  689. element = element->GetParent();
  690. }
  691. }
  692. else
  693. // If the element itself is not focusable, search for a focusable parent,
  694. // although the focusable element may not actually handle mouse wheel
  695. element = GetFocusableElement(element);
  696. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  697. element->OnWheel(delta, mouseButtons_, qualifiers_);
  698. }
  699. }
  700. }
  701. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  702. {
  703. using namespace TouchBegin;
  704. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  705. WeakPtr<UIElement> element(GetElementAt(pos));
  706. if (element)
  707. {
  708. // Handle focusing & bringing to front
  709. SetFocusElement(element);
  710. element->BringToFront();
  711. // Handle click
  712. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  713. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  714. if (element && !dragElement_ )
  715. {
  716. dragElement_ = element;
  717. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  718. }
  719. }
  720. else
  721. {
  722. // If clicked over no element, or a disabled element, lose focus
  723. SetFocusElement(0);
  724. }
  725. using namespace UIMouseClick;
  726. VariantMap clickEventData;
  727. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  728. clickEventData[UIMouseClick::P_X] = pos.x_;
  729. clickEventData[UIMouseClick::P_Y] = pos.y_;
  730. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  731. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  732. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  733. SendEvent(E_UIMOUSECLICK, clickEventData);
  734. }
  735. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  736. {
  737. using namespace TouchEnd;
  738. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  739. // Transmit hover end to the position where the finger was lifted
  740. UIElement* element = GetElementAt(pos);
  741. if (element)
  742. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  743. if (dragElement_)
  744. {
  745. if (dragElement_->IsActive() && dragElement_->IsVisible())
  746. {
  747. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  748. // Drag and drop finish
  749. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  750. if (dragSource)
  751. {
  752. WeakPtr<UIElement> target(GetElementAt(pos));
  753. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  754. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  755. if (dragDropFinish)
  756. {
  757. bool accept = target->OnDragDropFinish(dragElement_);
  758. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  759. if (accept && dragElement_ && target)
  760. {
  761. using namespace DragDropFinish;
  762. VariantMap eventData;
  763. eventData[P_SOURCE] = (void*)dragElement_.Get();
  764. eventData[P_TARGET] = (void*)target.Get();
  765. eventData[P_ACCEPT] = accept;
  766. SendEvent(E_DRAGDROPFINISH, eventData);
  767. }
  768. }
  769. }
  770. }
  771. dragElement_.Reset();
  772. }
  773. }
  774. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  775. {
  776. using namespace TouchMove;
  777. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  778. if (dragElement_)
  779. {
  780. if (dragElement_->IsActive() && dragElement_->IsVisible())
  781. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  782. else
  783. {
  784. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  785. dragElement_.Reset();
  786. }
  787. }
  788. }
  789. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  790. {
  791. using namespace KeyDown;
  792. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  793. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  794. int key = eventData[P_KEY].GetInt();
  795. UIElement* element = GetFocusElement();
  796. if (element)
  797. {
  798. // Switch focus between focusable elements in the same top level window
  799. if (key == KEY_TAB)
  800. {
  801. UIElement* topLevel = element->GetParent();
  802. while (topLevel && topLevel->GetParent() != rootElement_)
  803. topLevel = topLevel->GetParent();
  804. if (topLevel)
  805. {
  806. topLevel->GetChildren(tempElements_, true);
  807. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  808. {
  809. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  810. i = tempElements_.Erase(i);
  811. else
  812. ++i;
  813. }
  814. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  815. {
  816. if (tempElements_[i] == element)
  817. {
  818. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  819. SetFocusElement(next);
  820. return;
  821. }
  822. }
  823. }
  824. }
  825. // Defocus the element
  826. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  827. element->SetFocus(false);
  828. // If none of the special keys, pass the key to the focused element
  829. else
  830. element->OnKey(key, mouseButtons_, qualifiers_);
  831. }
  832. }
  833. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  834. {
  835. using namespace Char;
  836. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  837. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  838. UIElement* element = GetFocusElement();
  839. if (element)
  840. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  841. }
  842. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  843. {
  844. using namespace PostUpdate;
  845. Update(eventData[P_TIMESTEP].GetFloat());
  846. }
  847. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  848. {
  849. RenderUpdate();
  850. }
  851. void RegisterUILibrary(Context* context)
  852. {
  853. Font::RegisterObject(context);
  854. UIElement::RegisterObject(context);
  855. BorderImage::RegisterObject(context);
  856. Sprite::RegisterObject(context);
  857. Button::RegisterObject(context);
  858. CheckBox::RegisterObject(context);
  859. Cursor::RegisterObject(context);
  860. Text::RegisterObject(context);
  861. Window::RegisterObject(context);
  862. LineEdit::RegisterObject(context);
  863. Slider::RegisterObject(context);
  864. ScrollBar::RegisterObject(context);
  865. ScrollView::RegisterObject(context);
  866. ListView::RegisterObject(context);
  867. Menu::RegisterObject(context);
  868. DropDownList::RegisterObject(context);
  869. FileSelector::RegisterObject(context);
  870. }
  871. }