UI.cpp 48 KB

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