UI.cpp 43 KB

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