2
0

UI.cpp 43 KB

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