UI.cpp 44 KB

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