UI.cpp 47 KB

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