UI.cpp 44 KB

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