UI.cpp 43 KB

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