UI.cpp 50 KB

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