UI.cpp 47 KB

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