UI.cpp 49 KB

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