UI.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. //
  2. // Copyright (c) 2008-2017 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 "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Container/Sort.h"
  27. #include "../Graphics/Graphics.h"
  28. #include "../Graphics/GraphicsEvents.h"
  29. #include "../Graphics/Shader.h"
  30. #include "../Graphics/ShaderVariation.h"
  31. #include "../Graphics/Texture2D.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../Input/Input.h"
  34. #include "../Input/InputEvents.h"
  35. #include "../IO/Log.h"
  36. #include "../Math/Matrix3x4.h"
  37. #include "../Resource/ResourceCache.h"
  38. #include "../UI/CheckBox.h"
  39. #include "../UI/Cursor.h"
  40. #include "../UI/DropDownList.h"
  41. #include "../UI/FileSelector.h"
  42. #include "../UI/Font.h"
  43. #include "../UI/LineEdit.h"
  44. #include "../UI/ListView.h"
  45. #include "../UI/MessageBox.h"
  46. #include "../UI/ProgressBar.h"
  47. #include "../UI/ScrollBar.h"
  48. #include "../UI/Slider.h"
  49. #include "../UI/Sprite.h"
  50. #include "../UI/Text.h"
  51. #include "../UI/Text3D.h"
  52. #include "../UI/ToolTip.h"
  53. #include "../UI/UI.h"
  54. #include "../UI/UIEvents.h"
  55. #include "../UI/Window.h"
  56. #include "../UI/View3D.h"
  57. #include <SDL/SDL.h>
  58. #include "../DebugNew.h"
  59. #define TOUCHID_MASK(id) (1 << id)
  60. namespace Urho3D
  61. {
  62. StringHash VAR_ORIGIN("Origin");
  63. const StringHash VAR_ORIGINAL_PARENT("OriginalParent");
  64. const StringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex");
  65. const StringHash VAR_PARENT_CHANGED("ParentChanged");
  66. const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f;
  67. const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f;
  68. const float DEFAULT_TOOLTIP_DELAY = 0.5f;
  69. const int DEFAULT_DRAGBEGIN_DISTANCE = 5;
  70. const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048;
  71. const char* UI_CATEGORY = "UI";
  72. UI::UI(Context* context) :
  73. Object(context),
  74. rootElement_(new UIElement(context)),
  75. rootModalElement_(new UIElement(context)),
  76. doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL),
  77. dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL),
  78. defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY),
  79. dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE),
  80. mouseButtons_(0),
  81. lastMouseButtons_(0),
  82. qualifiers_(0),
  83. maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE),
  84. initialized_(false),
  85. usingTouchInput_(false),
  86. #ifdef _WIN32
  87. nonFocusedMouseWheel_(false), // Default MS Windows behaviour
  88. #else
  89. nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
  90. #endif
  91. useSystemClipboard_(false),
  92. #if defined(__ANDROID__) || defined(IOS) || defined(TVOS)
  93. useScreenKeyboard_(true),
  94. #else
  95. useScreenKeyboard_(false),
  96. #endif
  97. useMutableGlyphs_(false),
  98. forceAutoHint_(false),
  99. fontHintLevel_(FONT_HINT_LEVEL_NORMAL),
  100. subpixelGlyphPositions_(false),
  101. uiRendered_(false),
  102. nonModalBatchSize_(0),
  103. dragElementsCount_(0),
  104. dragConfirmedCount_(0),
  105. uiScale_(1.0f),
  106. customSize_(IntVector2::ZERO)
  107. {
  108. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  109. rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
  110. // Register UI library object factories
  111. RegisterUILibrary(context_);
  112. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(UI, HandleScreenMode));
  113. SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(UI, HandleMouseButtonDown));
  114. SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(UI, HandleMouseButtonUp));
  115. SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(UI, HandleMouseMove));
  116. SubscribeToEvent(E_MOUSEWHEEL, URHO3D_HANDLER(UI, HandleMouseWheel));
  117. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(UI, HandleTouchBegin));
  118. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(UI, HandleTouchEnd));
  119. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(UI, HandleTouchMove));
  120. SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(UI, HandleKeyDown));
  121. SubscribeToEvent(E_TEXTINPUT, URHO3D_HANDLER(UI, HandleTextInput));
  122. SubscribeToEvent(E_DROPFILE, URHO3D_HANDLER(UI, HandleDropFile));
  123. // Try to initialize right now, but skip if screen mode is not yet set
  124. Initialize();
  125. }
  126. UI::~UI()
  127. {
  128. }
  129. void UI::SetCursor(Cursor* cursor)
  130. {
  131. // Remove old cursor (if any) and set new
  132. if (cursor_)
  133. {
  134. rootElement_->RemoveChild(cursor_);
  135. cursor_.Reset();
  136. }
  137. if (cursor)
  138. {
  139. rootElement_->AddChild(cursor);
  140. cursor_ = cursor;
  141. IntVector2 pos = cursor_->GetPosition();
  142. const IntVector2& rootSize = rootElement_->GetSize();
  143. const IntVector2& rootPos = rootElement_->GetPosition();
  144. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  145. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  146. cursor_->SetPosition(pos);
  147. }
  148. }
  149. void UI::SetFocusElement(UIElement* element, bool byKey)
  150. {
  151. using namespace FocusChanged;
  152. UIElement* originalElement = element;
  153. if (element)
  154. {
  155. // Return if already has focus
  156. if (focusElement_ == element)
  157. return;
  158. // Only allow child elements of the modal element to receive focus
  159. if (HasModalElement())
  160. {
  161. UIElement* topLevel = element->GetParent();
  162. while (topLevel && topLevel->GetParent() != rootElement_)
  163. topLevel = topLevel->GetParent();
  164. if (topLevel) // If parented to non-modal root then ignore
  165. return;
  166. }
  167. // Search for an element in the hierarchy that can alter focus. If none found, exit
  168. element = GetFocusableElement(element);
  169. if (!element)
  170. return;
  171. }
  172. // Remove focus from the old element
  173. if (focusElement_)
  174. {
  175. UIElement* oldFocusElement = focusElement_;
  176. focusElement_.Reset();
  177. VariantMap& focusEventData = GetEventDataMap();
  178. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  179. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  180. }
  181. // Then set focus to the new
  182. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  183. {
  184. focusElement_ = element;
  185. VariantMap& focusEventData = GetEventDataMap();
  186. focusEventData[Focused::P_ELEMENT] = element;
  187. focusEventData[Focused::P_BYKEY] = byKey;
  188. element->SendEvent(E_FOCUSED, focusEventData);
  189. }
  190. VariantMap& eventData = GetEventDataMap();
  191. eventData[P_CLICKEDELEMENT] = originalElement;
  192. eventData[P_ELEMENT] = element;
  193. SendEvent(E_FOCUSCHANGED, eventData);
  194. }
  195. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  196. {
  197. if (!modalElement)
  198. return false;
  199. // Currently only allow modal window
  200. if (modalElement->GetType() != Window::GetTypeStatic())
  201. return false;
  202. assert(rootModalElement_);
  203. UIElement* currParent = modalElement->GetParent();
  204. if (enable)
  205. {
  206. // Make sure it is not already the child of the root modal element
  207. if (currParent == rootModalElement_)
  208. return false;
  209. // Adopt modal root as parent
  210. modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent);
  211. modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED);
  212. modalElement->SetParent(rootModalElement_);
  213. // If it is a popup element, bring along its top-level parent
  214. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  215. if (originElement)
  216. {
  217. UIElement* element = originElement;
  218. while (element && element->GetParent() != rootElement_)
  219. element = element->GetParent();
  220. if (element)
  221. {
  222. originElement->SetVar(VAR_PARENT_CHANGED, element);
  223. UIElement* oriParent = element->GetParent();
  224. element->SetVar(VAR_ORIGINAL_PARENT, oriParent);
  225. element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED);
  226. element->SetParent(rootModalElement_);
  227. }
  228. }
  229. return true;
  230. }
  231. else
  232. {
  233. // Only the modal element can disable itself
  234. if (currParent != rootModalElement_)
  235. return false;
  236. // Revert back to original parent
  237. modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  238. modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  239. VariantMap& vars = const_cast<VariantMap&>(modalElement->GetVars());
  240. vars.Erase(VAR_ORIGINAL_PARENT);
  241. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  242. // If it is a popup element, revert back its top-level parent
  243. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  244. if (originElement)
  245. {
  246. UIElement* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
  247. if (element)
  248. {
  249. const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
  250. element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  251. element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  252. vars = const_cast<VariantMap&>(element->GetVars());
  253. vars.Erase(VAR_ORIGINAL_PARENT);
  254. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  255. }
  256. }
  257. return true;
  258. }
  259. }
  260. void UI::Clear()
  261. {
  262. rootElement_->RemoveAllChildren();
  263. rootModalElement_->RemoveAllChildren();
  264. if (cursor_)
  265. rootElement_->AddChild(cursor_);
  266. }
  267. void UI::Update(float timeStep)
  268. {
  269. assert(rootElement_ && rootModalElement_);
  270. URHO3D_PROFILE(UpdateUI);
  271. // Expire hovers
  272. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End(); ++i)
  273. i->second_ = false;
  274. Input* input = GetSubsystem<Input>();
  275. bool mouseGrabbed = input->IsMouseGrabbed();
  276. IntVector2 cursorPos;
  277. bool cursorVisible;
  278. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  279. // Drag begin based on time
  280. if (dragElementsCount_ > 0 && !mouseGrabbed)
  281. {
  282. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  283. {
  284. WeakPtr<UIElement> dragElement = i->first_;
  285. UI::DragData* dragData = i->second_;
  286. if (!dragElement)
  287. {
  288. i = DragElementErase(i);
  289. continue;
  290. }
  291. if (!dragData->dragBeginPending)
  292. {
  293. ++i;
  294. continue;
  295. }
  296. if (dragData->dragBeginTimer.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000))
  297. {
  298. dragData->dragBeginPending = false;
  299. IntVector2 beginSendPos = dragData->dragBeginSumPos / dragData->numDragButtons;
  300. dragConfirmedCount_++;
  301. if (!usingTouchInput_)
  302. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons,
  303. qualifiers_, cursor_);
  304. else
  305. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, 0, 0);
  306. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  307. }
  308. ++i;
  309. }
  310. }
  311. // Mouse hover
  312. if (!mouseGrabbed && !input->GetTouchEmulation())
  313. {
  314. if (!usingTouchInput_ && cursorVisible)
  315. ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_);
  316. }
  317. // Touch hover
  318. unsigned numTouches = input->GetNumTouches();
  319. for (unsigned i = 0; i < numTouches; ++i)
  320. {
  321. TouchState* touch = input->GetTouch(i);
  322. IntVector2 touchPos = touch->position_;
  323. touchPos.x_ = (int)(touchPos.x_ / uiScale_);
  324. touchPos.y_ = (int)(touchPos.y_ / uiScale_);
  325. ProcessHover(touchPos, TOUCHID_MASK(touch->touchID_), 0, 0);
  326. }
  327. // End hovers that expired without refreshing
  328. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End();)
  329. {
  330. if (i->first_.Expired() || !i->second_)
  331. {
  332. UIElement* element = i->first_;
  333. if (element)
  334. {
  335. using namespace HoverEnd;
  336. VariantMap& eventData = GetEventDataMap();
  337. eventData[P_ELEMENT] = element;
  338. element->SendEvent(E_HOVEREND, eventData);
  339. }
  340. i = hoveredElements_.Erase(i);
  341. }
  342. else
  343. ++i;
  344. }
  345. Update(timeStep, rootElement_);
  346. Update(timeStep, rootModalElement_);
  347. }
  348. void UI::RenderUpdate()
  349. {
  350. assert(rootElement_ && rootModalElement_ && graphics_);
  351. URHO3D_PROFILE(GetUIBatches);
  352. uiRendered_ = false;
  353. // If the OS cursor is visible, do not render the UI's own cursor
  354. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  355. // Get rendering batches from the non-modal UI elements
  356. batches_.Clear();
  357. vertexData_.Clear();
  358. const IntVector2& rootSize = rootElement_->GetSize();
  359. const IntVector2& rootPos = rootElement_->GetPosition();
  360. // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
  361. IntRect currentScissor = IntRect(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
  362. if (rootElement_->IsVisible())
  363. GetBatches(rootElement_, currentScissor);
  364. // Save the batch size of the non-modal batches for later use
  365. nonModalBatchSize_ = batches_.Size();
  366. // Get rendering batches from the modal UI elements
  367. GetBatches(rootModalElement_, currentScissor);
  368. // Get batches from the cursor (and its possible children) last to draw it on top of everything
  369. if (cursor_ && cursor_->IsVisible() && !osCursorVisible)
  370. {
  371. currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  372. cursor_->GetBatches(batches_, vertexData_, currentScissor);
  373. GetBatches(cursor_, currentScissor);
  374. }
  375. }
  376. void UI::Render(bool resetRenderTargets)
  377. {
  378. // Perform the default render only if not rendered yet
  379. if (resetRenderTargets && uiRendered_)
  380. return;
  381. URHO3D_PROFILE(RenderUI);
  382. // If the OS cursor is visible, apply its shape now if changed
  383. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  384. if (cursor_ && osCursorVisible)
  385. cursor_->ApplyOSCursorShape();
  386. SetVertexData(vertexBuffer_, vertexData_);
  387. SetVertexData(debugVertexBuffer_, debugVertexData_);
  388. // Render non-modal batches
  389. Render(resetRenderTargets, vertexBuffer_, batches_, 0, nonModalBatchSize_);
  390. // Render debug draw
  391. Render(resetRenderTargets, debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size());
  392. // Render modal batches
  393. Render(resetRenderTargets, vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size());
  394. // Clear the debug draw batches and data
  395. debugDrawBatches_.Clear();
  396. debugVertexData_.Clear();
  397. uiRendered_ = true;
  398. }
  399. void UI::DebugDraw(UIElement* element)
  400. {
  401. if (element)
  402. {
  403. const IntVector2& rootSize = rootElement_->GetSize();
  404. const IntVector2& rootPos = rootElement_->GetPosition();
  405. element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, IntRect(rootPos.x_, rootPos.y_,
  406. rootPos.x_ + rootSize.x_,
  407. rootPos.y_ + rootSize.y_));
  408. }
  409. }
  410. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  411. {
  412. SharedPtr<XMLFile> xml(new XMLFile(context_));
  413. if (!xml->Load(source))
  414. return SharedPtr<UIElement>();
  415. else
  416. return LoadLayout(xml, styleFile);
  417. }
  418. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  419. {
  420. URHO3D_PROFILE(LoadUILayout);
  421. SharedPtr<UIElement> root;
  422. if (!file)
  423. {
  424. URHO3D_LOGERROR("Null UI layout XML file");
  425. return root;
  426. }
  427. URHO3D_LOGDEBUG("Loading UI layout " + file->GetName());
  428. XMLElement rootElem = file->GetRoot("element");
  429. if (!rootElem)
  430. {
  431. URHO3D_LOGERROR("No root UI element in " + file->GetName());
  432. return root;
  433. }
  434. String typeName = rootElem.GetAttribute("type");
  435. if (typeName.Empty())
  436. typeName = "UIElement";
  437. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  438. if (!root)
  439. {
  440. URHO3D_LOGERROR("Could not create unknown UI element " + typeName);
  441. return root;
  442. }
  443. // Use default style file of the root element if it has one
  444. if (!styleFile)
  445. styleFile = rootElement_->GetDefaultStyle(false);
  446. // Set it as default for later use by children elements
  447. if (styleFile)
  448. root->SetDefaultStyle(styleFile);
  449. root->LoadXML(rootElem, styleFile);
  450. return root;
  451. }
  452. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  453. {
  454. URHO3D_PROFILE(SaveUILayout);
  455. return element && element->SaveXML(dest);
  456. }
  457. void UI::SetClipboardText(const String& text)
  458. {
  459. clipBoard_ = text;
  460. if (useSystemClipboard_)
  461. SDL_SetClipboardText(text.CString());
  462. }
  463. void UI::SetDoubleClickInterval(float interval)
  464. {
  465. doubleClickInterval_ = Max(interval, 0.0f);
  466. }
  467. void UI::SetDragBeginInterval(float interval)
  468. {
  469. dragBeginInterval_ = Max(interval, 0.0f);
  470. }
  471. void UI::SetDragBeginDistance(int pixels)
  472. {
  473. dragBeginDistance_ = Max(pixels, 0);
  474. }
  475. void UI::SetDefaultToolTipDelay(float delay)
  476. {
  477. defaultToolTipDelay_ = Max(delay, 0.0f);
  478. }
  479. void UI::SetMaxFontTextureSize(int size)
  480. {
  481. if (IsPowerOfTwo((unsigned)size) && size >= FONT_TEXTURE_MIN_SIZE)
  482. {
  483. if (size != maxFontTextureSize_)
  484. {
  485. maxFontTextureSize_ = size;
  486. ReleaseFontFaces();
  487. }
  488. }
  489. }
  490. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  491. {
  492. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  493. }
  494. void UI::SetUseSystemClipboard(bool enable)
  495. {
  496. useSystemClipboard_ = enable;
  497. }
  498. void UI::SetUseScreenKeyboard(bool enable)
  499. {
  500. useScreenKeyboard_ = enable;
  501. }
  502. void UI::SetUseMutableGlyphs(bool enable)
  503. {
  504. if (enable != useMutableGlyphs_)
  505. {
  506. useMutableGlyphs_ = enable;
  507. ReleaseFontFaces();
  508. }
  509. }
  510. void UI::SetForceAutoHint(bool enable)
  511. {
  512. if (enable != forceAutoHint_)
  513. {
  514. forceAutoHint_ = enable;
  515. ReleaseFontFaces();
  516. }
  517. }
  518. void UI::SetFontHintLevel(FontHintLevel level)
  519. {
  520. if (level != fontHintLevel_)
  521. {
  522. fontHintLevel_ = level;
  523. ReleaseFontFaces();
  524. }
  525. }
  526. void UI::SetSubpixelGlyphPositions(bool enable)
  527. {
  528. if (enable != subpixelGlyphPositions_)
  529. {
  530. subpixelGlyphPositions_ = enable;
  531. ReleaseFontFaces();
  532. }
  533. }
  534. void UI::SetScale(float scale)
  535. {
  536. uiScale_ = Max(scale, M_EPSILON);
  537. ResizeRootElement();
  538. }
  539. void UI::SetWidth(float width)
  540. {
  541. IntVector2 size = GetEffectiveRootElementSize(false);
  542. SetScale((float)size.x_ / width);
  543. }
  544. void UI::SetHeight(float height)
  545. {
  546. IntVector2 size = GetEffectiveRootElementSize(false);
  547. SetScale((float)size.y_ / height);
  548. }
  549. void UI::SetCustomSize(const IntVector2& size)
  550. {
  551. customSize_ = IntVector2(Max(0, size.x_), Max(0, size.y_));
  552. ResizeRootElement();
  553. }
  554. void UI::SetCustomSize(int width, int height)
  555. {
  556. customSize_ = IntVector2(Max(0, width), Max(0, height));
  557. ResizeRootElement();
  558. }
  559. IntVector2 UI::GetCursorPosition() const
  560. {
  561. return cursor_ ? cursor_->GetPosition() : GetSubsystem<Input>()->GetMousePosition();
  562. }
  563. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  564. {
  565. IntVector2 positionCopy(position);
  566. const IntVector2& rootSize = rootElement_->GetSize();
  567. const IntVector2& rootPos = rootElement_->GetPosition();
  568. // If position is out of bounds of root element return null.
  569. if (position.x_ < rootPos.x_ || position.x_ > rootPos.x_ + rootSize.x_)
  570. return 0;
  571. if (position.y_ < rootPos.y_ || position.y_ > rootPos.y_ + rootSize.y_)
  572. return 0;
  573. // If UI is smaller than the screen, wrap if necessary
  574. if (rootSize.x_ > 0 && rootSize.y_ > 0)
  575. {
  576. if (positionCopy.x_ >= rootPos.x_ + rootSize.x_)
  577. positionCopy.x_ = rootPos.x_ + ((positionCopy.x_ - rootPos.x_) % rootSize.x_);
  578. if (positionCopy.y_ >= rootPos.y_ + rootSize.y_)
  579. positionCopy.y_ = rootPos.y_ + ((positionCopy.y_ - rootPos.y_) % rootSize.y_);
  580. }
  581. UIElement* result = 0;
  582. GetElementAt(result, HasModalElement() ? rootModalElement_ : rootElement_, positionCopy, enabledOnly);
  583. return result;
  584. }
  585. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  586. {
  587. return GetElementAt(IntVector2(x, y), enabledOnly);
  588. }
  589. UIElement* UI::GetFrontElement() const
  590. {
  591. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  592. int maxPriority = M_MIN_INT;
  593. UIElement* front = 0;
  594. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  595. {
  596. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  597. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  598. continue;
  599. int priority = rootChildren[i]->GetPriority();
  600. if (priority > maxPriority)
  601. {
  602. maxPriority = priority;
  603. front = rootChildren[i];
  604. }
  605. }
  606. return front;
  607. }
  608. const Vector<UIElement*> UI::GetDragElements()
  609. {
  610. // Do not return the element until drag begin event has actually been posted
  611. if (!dragElementsConfirmed_.Empty())
  612. return dragElementsConfirmed_;
  613. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  614. {
  615. WeakPtr<UIElement> dragElement = i->first_;
  616. UI::DragData* dragData = i->second_;
  617. if (!dragElement)
  618. {
  619. i = DragElementErase(i);
  620. continue;
  621. }
  622. if (!dragData->dragBeginPending)
  623. dragElementsConfirmed_.Push(dragElement);
  624. ++i;
  625. }
  626. return dragElementsConfirmed_;
  627. }
  628. UIElement* UI::GetDragElement(unsigned index)
  629. {
  630. GetDragElements();
  631. if (index >= dragElementsConfirmed_.Size())
  632. return (UIElement*)0;
  633. return dragElementsConfirmed_[index];
  634. }
  635. const String& UI::GetClipboardText() const
  636. {
  637. if (useSystemClipboard_)
  638. {
  639. char* text = SDL_GetClipboardText();
  640. clipBoard_ = String(text);
  641. if (text)
  642. SDL_free(text);
  643. }
  644. return clipBoard_;
  645. }
  646. bool UI::HasModalElement() const
  647. {
  648. return rootModalElement_->GetNumChildren() > 0;
  649. }
  650. void UI::Initialize()
  651. {
  652. Graphics* graphics = GetSubsystem<Graphics>();
  653. if (!graphics || !graphics->IsInitialized())
  654. return;
  655. URHO3D_PROFILE(InitUI);
  656. graphics_ = graphics;
  657. UIBatch::posAdjust = Vector3(Graphics::GetPixelUVOffset(), 0.0f);
  658. // Set initial root element size
  659. ResizeRootElement();
  660. vertexBuffer_ = new VertexBuffer(context_);
  661. debugVertexBuffer_ = new VertexBuffer(context_);
  662. initialized_ = true;
  663. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(UI, HandleBeginFrame));
  664. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UI, HandlePostUpdate));
  665. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(UI, HandleRenderUpdate));
  666. URHO3D_LOGINFO("Initialized user interface");
  667. }
  668. void UI::Update(float timeStep, UIElement* element)
  669. {
  670. // Keep a weak pointer to the element in case it destroys itself on update
  671. WeakPtr<UIElement> elementWeak(element);
  672. element->Update(timeStep);
  673. if (elementWeak.Expired())
  674. return;
  675. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  676. // Update of an element may modify its child vector. Use just index-based iteration to be safe
  677. for (unsigned i = 0; i < children.Size(); ++i)
  678. Update(timeStep, children[i]);
  679. }
  680. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  681. {
  682. if (vertexData.Empty())
  683. return;
  684. // Update quad geometry into the vertex buffer
  685. // Resize the vertex buffer first if too small or much too large
  686. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  687. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  688. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  689. dest->SetData(&vertexData[0]);
  690. }
  691. void UI::Render(bool resetRenderTargets, VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart,
  692. unsigned batchEnd)
  693. {
  694. // Engine does not render when window is closed or device is lost
  695. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  696. if (batches.Empty())
  697. return;
  698. if (resetRenderTargets)
  699. graphics_->ResetRenderTargets();
  700. IntVector2 viewSize = graphics_->GetViewport().Size();
  701. Vector2 invScreenSize(1.0f / (float)viewSize.x_, 1.0f / (float)viewSize.y_);
  702. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  703. Vector2 offset(-1.0f, 1.0f);
  704. Matrix4 projection(Matrix4::IDENTITY);
  705. projection.m00_ = scale.x_ * uiScale_;
  706. projection.m03_ = offset.x_;
  707. projection.m11_ = scale.y_ * uiScale_;
  708. projection.m13_ = offset.y_;
  709. projection.m22_ = 1.0f;
  710. projection.m23_ = 0.0f;
  711. projection.m33_ = 1.0f;
  712. graphics_->ClearParameterSources();
  713. graphics_->SetColorWrite(true);
  714. graphics_->SetCullMode(CULL_CCW);
  715. graphics_->SetDepthTest(CMP_ALWAYS);
  716. graphics_->SetDepthWrite(false);
  717. graphics_->SetFillMode(FILL_SOLID);
  718. graphics_->SetStencilTest(false);
  719. graphics_->SetVertexBuffer(buffer);
  720. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  721. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  722. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  723. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  724. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  725. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  726. unsigned alphaFormat = Graphics::GetAlphaFormat();
  727. for (unsigned i = batchStart; i < batchEnd; ++i)
  728. {
  729. const UIBatch& batch = batches[i];
  730. if (batch.vertexStart_ == batch.vertexEnd_)
  731. continue;
  732. ShaderVariation* ps;
  733. ShaderVariation* vs;
  734. if (!batch.texture_)
  735. {
  736. ps = noTexturePS;
  737. vs = noTextureVS;
  738. }
  739. else
  740. {
  741. // If texture contains only an alpha channel, use alpha shader (for fonts)
  742. vs = diffTextureVS;
  743. if (batch.texture_->GetFormat() == alphaFormat)
  744. ps = alphaTexturePS;
  745. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  746. ps = diffMaskTexturePS;
  747. else
  748. ps = diffTexturePS;
  749. }
  750. graphics_->SetShaders(vs, ps);
  751. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  752. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  753. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  754. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  755. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  756. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  757. float elapsedTime = GetSubsystem<Time>()->GetElapsedTime();
  758. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  759. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  760. IntRect scissor = batch.scissor_;
  761. scissor.left_ = (int)(scissor.left_ * uiScale_);
  762. scissor.top_ = (int)(scissor.top_ * uiScale_);
  763. scissor.right_ = (int)(scissor.right_ * uiScale_);
  764. scissor.bottom_ = (int)(scissor.bottom_ * uiScale_);
  765. graphics_->SetBlendMode(batch.blendMode_);
  766. graphics_->SetScissorTest(true, scissor);
  767. graphics_->SetTexture(0, batch.texture_);
  768. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE,
  769. (batch.vertexEnd_ - batch.vertexStart_) / UI_VERTEX_SIZE);
  770. }
  771. }
  772. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  773. {
  774. // Set clipping scissor for child elements. No need to draw if zero size
  775. element->AdjustScissor(currentScissor);
  776. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  777. return;
  778. element->SortChildren();
  779. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  780. if (children.Empty())
  781. return;
  782. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  783. // same renderstate
  784. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  785. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  786. {
  787. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  788. while (i != children.End())
  789. {
  790. int currentPriority = (*i)->GetPriority();
  791. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  792. {
  793. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  794. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  795. ++j;
  796. }
  797. // Now recurse into the children
  798. while (i != j)
  799. {
  800. if ((*i)->IsVisible() && (*i) != cursor_)
  801. GetBatches(*i, currentScissor);
  802. ++i;
  803. }
  804. }
  805. }
  806. // On the root level draw each element and its children immediately after to avoid artifacts
  807. else
  808. {
  809. while (i != children.End())
  810. {
  811. if ((*i) != cursor_)
  812. {
  813. if ((*i)->IsWithinScissor(currentScissor))
  814. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  815. if ((*i)->IsVisible())
  816. GetBatches(*i, currentScissor);
  817. }
  818. ++i;
  819. }
  820. }
  821. }
  822. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  823. {
  824. if (!current)
  825. return;
  826. current->SortChildren();
  827. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  828. LayoutMode parentLayoutMode = current->GetLayoutMode();
  829. for (unsigned i = 0; i < children.Size(); ++i)
  830. {
  831. UIElement* element = children[i];
  832. bool hasChildren = element->GetNumChildren() > 0;
  833. if (element != cursor_.Get() && element->IsVisible())
  834. {
  835. if (element->IsInside(position, true))
  836. {
  837. // Store the current result, then recurse into its children. Because children
  838. // are sorted from lowest to highest priority, the topmost match should remain
  839. if (element->IsEnabled() || !enabledOnly)
  840. result = element;
  841. if (hasChildren)
  842. GetElementAt(result, element, position, enabledOnly);
  843. // Layout optimization: if the element has no children, can break out after the first match
  844. else if (parentLayoutMode != LM_FREE)
  845. break;
  846. }
  847. else
  848. {
  849. if (hasChildren)
  850. {
  851. if (element->IsInsideCombined(position, true))
  852. GetElementAt(result, element, position, enabledOnly);
  853. }
  854. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  855. // or if we already passed all visible elements
  856. else if (parentLayoutMode != LM_FREE)
  857. {
  858. if (!i)
  859. {
  860. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  861. element->GetScreenPosition().y_;
  862. int layoutMaxSize = current->GetLayoutElementMaxSize();
  863. if (screenPos < 0 && layoutMaxSize > 0)
  864. {
  865. unsigned toSkip = (unsigned)(-screenPos / layoutMaxSize);
  866. if (toSkip > 0)
  867. i += (toSkip - 1);
  868. }
  869. }
  870. // Note: we cannot check for the up / left limits of positioning, since the element may be off the visible
  871. // screen but some of its layouted children will yet be visible. In down & right directions we can terminate
  872. // the loop, since all further children will be further down or right.
  873. else if (parentLayoutMode == LM_HORIZONTAL)
  874. {
  875. if (element->GetScreenPosition().x_ >= rootElement_->GetPosition().x_ + rootElement_->GetSize().x_)
  876. break;
  877. }
  878. else if (parentLayoutMode == LM_VERTICAL)
  879. {
  880. if (element->GetScreenPosition().y_ >= rootElement_->GetPosition().y_ + rootElement_->GetSize().y_)
  881. break;
  882. }
  883. }
  884. }
  885. }
  886. }
  887. }
  888. UIElement* UI::GetFocusableElement(UIElement* element)
  889. {
  890. while (element)
  891. {
  892. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  893. break;
  894. element = element->GetParent();
  895. }
  896. return element;
  897. }
  898. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  899. {
  900. // Prefer software cursor then OS-specific cursor
  901. if (cursor_ && cursor_->IsVisible())
  902. {
  903. pos = cursor_->GetPosition();
  904. visible = true;
  905. }
  906. else if (GetSubsystem<Input>()->GetMouseMode() == MM_RELATIVE)
  907. visible = true;
  908. else
  909. {
  910. Input* input = GetSubsystem<Input>();
  911. pos = input->GetMousePosition();
  912. visible = input->IsMouseVisible();
  913. if (!visible && cursor_)
  914. pos = cursor_->GetPosition();
  915. }
  916. pos.x_ = (int)(pos.x_ / uiScale_);
  917. pos.y_ = (int)(pos.y_ / uiScale_);
  918. }
  919. void UI::SetCursorShape(CursorShape shape)
  920. {
  921. if (cursor_)
  922. cursor_->SetShape(shape);
  923. }
  924. void UI::ReleaseFontFaces()
  925. {
  926. URHO3D_LOGDEBUG("Reloading font faces");
  927. PODVector<Font*> fonts;
  928. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  929. for (unsigned i = 0; i < fonts.Size(); ++i)
  930. fonts[i]->ReleaseFaces();
  931. }
  932. void UI::ProcessHover(const IntVector2& cursorPos, int buttons, int qualifiers, Cursor* cursor)
  933. {
  934. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  935. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  936. {
  937. WeakPtr<UIElement> dragElement = i->first_;
  938. UI::DragData* dragData = i->second_;
  939. if (!dragElement)
  940. {
  941. i = DragElementErase(i);
  942. continue;
  943. }
  944. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE) != 0;
  945. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  946. bool dragDropTest = dragSource && dragTarget && element != dragElement;
  947. // If drag start event has not been posted yet, do not do drag handling here
  948. if (dragData->dragBeginPending)
  949. dragSource = dragTarget = dragDropTest = false;
  950. // Hover effect
  951. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  952. if (element && element->IsEnabled())
  953. {
  954. if (dragElement == element || dragDropTest)
  955. {
  956. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  957. // Begin hover event
  958. if (!hoveredElements_.Contains(element))
  959. {
  960. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, 0);
  961. // Exit if element is destroyed by the event handling
  962. if (!element)
  963. return;
  964. }
  965. hoveredElements_[element] = true;
  966. }
  967. }
  968. // Drag and drop test
  969. if (dragDropTest)
  970. {
  971. bool accept = element->OnDragDropTest(dragElement);
  972. if (accept)
  973. {
  974. using namespace DragDropTest;
  975. VariantMap& eventData = GetEventDataMap();
  976. eventData[P_SOURCE] = dragElement.Get();
  977. eventData[P_TARGET] = element.Get();
  978. eventData[P_ACCEPT] = accept;
  979. SendEvent(E_DRAGDROPTEST, eventData);
  980. accept = eventData[P_ACCEPT].GetBool();
  981. }
  982. if (cursor)
  983. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  984. }
  985. else if (dragSource && cursor)
  986. cursor->SetShape(dragElement == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  987. ++i;
  988. }
  989. // Hover effect
  990. // If no drag is going on, transmit hover event.
  991. if (element && element->IsEnabled())
  992. {
  993. if (dragElementsCount_ == 0)
  994. {
  995. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  996. // Begin hover event
  997. if (!hoveredElements_.Contains(element))
  998. {
  999. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, 0);
  1000. // Exit if element is destroyed by the event handling
  1001. if (!element)
  1002. return;
  1003. }
  1004. hoveredElements_[element] = true;
  1005. }
  1006. }
  1007. }
  1008. void UI::ProcessClickBegin(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  1009. {
  1010. if (cursorVisible)
  1011. {
  1012. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  1013. bool newButton;
  1014. if (usingTouchInput_)
  1015. newButton = (button & buttons) == 0;
  1016. else
  1017. newButton = true;
  1018. buttons |= button;
  1019. if (element)
  1020. SetFocusElement(element);
  1021. // Focus change events may destroy the element, check again.
  1022. if (element)
  1023. {
  1024. // Handle focusing & bringing to front
  1025. element->BringToFront();
  1026. // Handle click
  1027. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1028. SendClickEvent(E_UIMOUSECLICK, 0, element, cursorPos, button, buttons, qualifiers);
  1029. // Fire double click event if element matches and is in time
  1030. if (doubleClickElement_ && element == doubleClickElement_ &&
  1031. clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
  1032. {
  1033. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1034. doubleClickElement_.Reset();
  1035. SendClickEvent(E_UIMOUSEDOUBLECLICK, 0, element, cursorPos, button, buttons, qualifiers);
  1036. }
  1037. else
  1038. {
  1039. doubleClickElement_ = element;
  1040. clickTimer_.Reset();
  1041. }
  1042. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  1043. bool dragElementsContain = dragElements_.Contains(element);
  1044. if (element && !dragElementsContain)
  1045. {
  1046. DragData* dragData = new DragData();
  1047. dragElements_[element] = dragData;
  1048. dragData->dragBeginPending = true;
  1049. dragData->sumPos = cursorPos;
  1050. dragData->dragBeginSumPos = cursorPos;
  1051. dragData->dragBeginTimer.Reset();
  1052. dragData->dragButtons = button;
  1053. dragData->numDragButtons = CountSetBits((unsigned)dragData->dragButtons);
  1054. dragElementsCount_++;
  1055. dragElementsContain = dragElements_.Contains(element);
  1056. }
  1057. else if (element && dragElementsContain && newButton)
  1058. {
  1059. DragData* dragData = dragElements_[element];
  1060. dragData->sumPos += cursorPos;
  1061. dragData->dragBeginSumPos += cursorPos;
  1062. dragData->dragButtons |= button;
  1063. dragData->numDragButtons = CountSetBits((unsigned)dragData->dragButtons);
  1064. }
  1065. }
  1066. else
  1067. {
  1068. // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
  1069. if (!HasModalElement())
  1070. SetFocusElement(0);
  1071. SendClickEvent(E_UIMOUSECLICK, 0, element, cursorPos, button, buttons, qualifiers);
  1072. if (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
  1073. SendClickEvent(E_UIMOUSEDOUBLECLICK, 0, element, cursorPos, button, buttons, qualifiers);
  1074. }
  1075. lastMouseButtons_ = buttons;
  1076. }
  1077. }
  1078. void UI::ProcessClickEnd(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  1079. {
  1080. WeakPtr<UIElement> element;
  1081. if (cursorVisible)
  1082. element = GetElementAt(cursorPos);
  1083. // Handle end of drag
  1084. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1085. {
  1086. WeakPtr<UIElement> dragElement = i->first_;
  1087. UI::DragData* dragData = i->second_;
  1088. if (!dragElement || !cursorVisible)
  1089. {
  1090. i = DragElementErase(i);
  1091. continue;
  1092. }
  1093. if (dragData->dragButtons & button)
  1094. {
  1095. // Handle end of click
  1096. if (element)
  1097. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor,
  1098. dragElement);
  1099. SendClickEvent(E_UIMOUSECLICKEND, dragElement, element, cursorPos, button, buttons, qualifiers);
  1100. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1101. {
  1102. dragElement->OnDragEnd(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, buttons,
  1103. cursor);
  1104. SendDragOrHoverEvent(E_DRAGEND, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1105. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE) != 0;
  1106. if (dragSource)
  1107. {
  1108. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  1109. bool dragDropFinish = dragSource && dragTarget && element != dragElement;
  1110. if (dragDropFinish)
  1111. {
  1112. bool accept = element->OnDragDropFinish(dragElement);
  1113. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  1114. if (accept && dragElement && element)
  1115. {
  1116. using namespace DragDropFinish;
  1117. VariantMap& eventData = GetEventDataMap();
  1118. eventData[P_SOURCE] = dragElement.Get();
  1119. eventData[P_TARGET] = element.Get();
  1120. eventData[P_ACCEPT] = accept;
  1121. SendEvent(E_DRAGDROPFINISH, eventData);
  1122. }
  1123. }
  1124. }
  1125. }
  1126. i = DragElementErase(i);
  1127. }
  1128. else
  1129. ++i;
  1130. }
  1131. }
  1132. void UI::ProcessMove(const IntVector2& cursorPos, const IntVector2& cursorDeltaPos, int buttons, int qualifiers, Cursor* cursor,
  1133. bool cursorVisible)
  1134. {
  1135. if (cursorVisible && dragElementsCount_ > 0 && buttons)
  1136. {
  1137. Input* input = GetSubsystem<Input>();
  1138. bool mouseGrabbed = input->IsMouseGrabbed();
  1139. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1140. {
  1141. WeakPtr<UIElement> dragElement = i->first_;
  1142. UI::DragData* dragData = i->second_;
  1143. if (!dragElement)
  1144. {
  1145. i = DragElementErase(i);
  1146. continue;
  1147. }
  1148. if (!(dragData->dragButtons & buttons))
  1149. {
  1150. ++i;
  1151. continue;
  1152. }
  1153. // Calculate the position that we should send for this drag event.
  1154. IntVector2 sendPos;
  1155. if (usingTouchInput_)
  1156. {
  1157. dragData->sumPos += cursorDeltaPos;
  1158. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1159. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1160. }
  1161. else
  1162. {
  1163. dragData->sumPos = cursorPos;
  1164. sendPos = cursorPos;
  1165. }
  1166. if (dragElement->IsEnabled() && dragElement->IsVisible())
  1167. {
  1168. // Signal drag begin if distance threshold was exceeded
  1169. if (dragData->dragBeginPending && !mouseGrabbed)
  1170. {
  1171. IntVector2 beginSendPos;
  1172. beginSendPos.x_ = dragData->dragBeginSumPos.x_ / dragData->numDragButtons;
  1173. beginSendPos.y_ = dragData->dragBeginSumPos.y_ / dragData->numDragButtons;
  1174. IntVector2 offset = cursorPos - beginSendPos;
  1175. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  1176. {
  1177. dragData->dragBeginPending = false;
  1178. dragConfirmedCount_++;
  1179. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, buttons, qualifiers,
  1180. cursor);
  1181. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  1182. }
  1183. }
  1184. if (!dragData->dragBeginPending)
  1185. {
  1186. dragElement->OnDragMove(dragElement->ScreenToElement(sendPos), sendPos, cursorDeltaPos, buttons, qualifiers,
  1187. cursor);
  1188. SendDragOrHoverEvent(E_DRAGMOVE, dragElement, sendPos, cursorDeltaPos, dragData);
  1189. }
  1190. }
  1191. else
  1192. {
  1193. dragElement->OnDragEnd(dragElement->ScreenToElement(sendPos), sendPos, dragData->dragButtons, buttons, cursor);
  1194. SendDragOrHoverEvent(E_DRAGEND, dragElement, sendPos, IntVector2::ZERO, dragData);
  1195. dragElement.Reset();
  1196. }
  1197. ++i;
  1198. }
  1199. }
  1200. }
  1201. void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos, const IntVector2& deltaPos,
  1202. UI::DragData* dragData)
  1203. {
  1204. if (!element)
  1205. return;
  1206. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1207. using namespace DragMove;
  1208. VariantMap& eventData = GetEventDataMap();
  1209. eventData[P_ELEMENT] = element;
  1210. eventData[P_X] = screenPos.x_;
  1211. eventData[P_Y] = screenPos.y_;
  1212. eventData[P_ELEMENTX] = relativePos.x_;
  1213. eventData[P_ELEMENTY] = relativePos.y_;
  1214. if (eventType == E_DRAGMOVE)
  1215. {
  1216. eventData[P_DX] = deltaPos.x_;
  1217. eventData[P_DY] = deltaPos.y_;
  1218. }
  1219. if (dragData)
  1220. {
  1221. eventData[P_BUTTONS] = dragData->dragButtons;
  1222. eventData[P_NUMBUTTONS] = dragData->numDragButtons;
  1223. }
  1224. element->SendEvent(eventType, eventData);
  1225. }
  1226. void UI::SendClickEvent(StringHash eventType, UIElement* beginElement, UIElement* endElement, const IntVector2& pos, int button,
  1227. int buttons, int qualifiers)
  1228. {
  1229. VariantMap& eventData = GetEventDataMap();
  1230. eventData[UIMouseClick::P_ELEMENT] = endElement;
  1231. eventData[UIMouseClick::P_X] = pos.x_;
  1232. eventData[UIMouseClick::P_Y] = pos.y_;
  1233. eventData[UIMouseClick::P_BUTTON] = button;
  1234. eventData[UIMouseClick::P_BUTTONS] = buttons;
  1235. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers;
  1236. // For click end events, send also the element the click began on
  1237. if (eventType == E_UIMOUSECLICKEND)
  1238. eventData[UIMouseClickEnd::P_BEGINELEMENT] = beginElement;
  1239. if (endElement)
  1240. {
  1241. // Send also element version of the event
  1242. if (eventType == E_UIMOUSECLICK)
  1243. endElement->SendEvent(E_CLICK, eventData);
  1244. else if (eventType == E_UIMOUSECLICKEND)
  1245. endElement->SendEvent(E_CLICKEND, eventData);
  1246. else if (eventType == E_UIMOUSEDOUBLECLICK)
  1247. endElement->SendEvent(E_DOUBLECLICK, eventData);
  1248. }
  1249. // Send the global event from the UI subsystem last
  1250. SendEvent(eventType, eventData);
  1251. }
  1252. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1253. {
  1254. using namespace ScreenMode;
  1255. if (!initialized_)
  1256. Initialize();
  1257. else
  1258. ResizeRootElement();
  1259. }
  1260. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  1261. {
  1262. using namespace MouseButtonDown;
  1263. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1264. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1265. usingTouchInput_ = false;
  1266. IntVector2 cursorPos;
  1267. bool cursorVisible;
  1268. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1269. // Handle drag cancelling
  1270. ProcessDragCancel();
  1271. Input* input = GetSubsystem<Input>();
  1272. if (!input->IsMouseGrabbed())
  1273. ProcessClickBegin(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1274. }
  1275. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  1276. {
  1277. using namespace MouseButtonUp;
  1278. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1279. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1280. IntVector2 cursorPos;
  1281. bool cursorVisible;
  1282. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1283. ProcessClickEnd(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1284. }
  1285. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  1286. {
  1287. using namespace MouseMove;
  1288. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1289. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1290. usingTouchInput_ = false;
  1291. Input* input = GetSubsystem<Input>();
  1292. const IntVector2& rootSize = rootElement_->GetSize();
  1293. const IntVector2& rootPos = rootElement_->GetPosition();
  1294. IntVector2 DeltaP = IntVector2(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
  1295. if (cursor_)
  1296. {
  1297. if (!input->IsMouseVisible())
  1298. {
  1299. if (!input->IsMouseLocked())
  1300. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  1301. else if (cursor_->IsVisible())
  1302. {
  1303. // Relative mouse motion: move cursor only when visible
  1304. IntVector2 pos = cursor_->GetPosition();
  1305. pos.x_ += eventData[P_DX].GetInt();
  1306. pos.y_ += eventData[P_DY].GetInt();
  1307. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  1308. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  1309. cursor_->SetPosition(pos);
  1310. }
  1311. }
  1312. else
  1313. {
  1314. // Absolute mouse motion: move always
  1315. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  1316. }
  1317. }
  1318. IntVector2 cursorPos;
  1319. bool cursorVisible;
  1320. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1321. ProcessMove(cursorPos, DeltaP, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1322. }
  1323. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1324. {
  1325. Input* input = GetSubsystem<Input>();
  1326. if (input->IsMouseGrabbed())
  1327. return;
  1328. using namespace MouseWheel;
  1329. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1330. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1331. int delta = eventData[P_WHEEL].GetInt();
  1332. usingTouchInput_ = false;
  1333. IntVector2 cursorPos;
  1334. bool cursorVisible;
  1335. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1336. UIElement* element;
  1337. if (!nonFocusedMouseWheel_ && (element = focusElement_))
  1338. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1339. else
  1340. {
  1341. // If no element has actual focus or in non-focused mode, get the element at cursor
  1342. if (cursorVisible)
  1343. {
  1344. element = GetElementAt(cursorPos);
  1345. if (nonFocusedMouseWheel_)
  1346. {
  1347. // Going up the hierarchy chain to find element that could handle mouse wheel
  1348. while (element)
  1349. {
  1350. if (element->GetType() == ListView::GetTypeStatic() ||
  1351. element->GetType() == ScrollView::GetTypeStatic())
  1352. break;
  1353. element = element->GetParent();
  1354. }
  1355. }
  1356. else
  1357. // If the element itself is not focusable, search for a focusable parent,
  1358. // although the focusable element may not actually handle mouse wheel
  1359. element = GetFocusableElement(element);
  1360. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1361. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1362. }
  1363. }
  1364. }
  1365. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1366. {
  1367. Input* input = GetSubsystem<Input>();
  1368. if (input->IsMouseGrabbed())
  1369. return;
  1370. using namespace TouchBegin;
  1371. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1372. pos.x_ = int(pos.x_ / uiScale_);
  1373. pos.y_ = int(pos.y_ / uiScale_);
  1374. usingTouchInput_ = true;
  1375. int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
  1376. WeakPtr<UIElement> element(GetElementAt(pos));
  1377. if (element)
  1378. {
  1379. ProcessClickBegin(pos, touchId, touchDragElements_[element], 0, 0, true);
  1380. touchDragElements_[element] |= touchId;
  1381. }
  1382. else
  1383. ProcessClickBegin(pos, touchId, touchId, 0, 0, true);
  1384. }
  1385. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1386. {
  1387. using namespace TouchEnd;
  1388. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1389. pos.x_ = int(pos.x_ / uiScale_);
  1390. pos.y_ = int(pos.y_ / uiScale_);
  1391. // Get the touch index
  1392. int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
  1393. // Transmit hover end to the position where the finger was lifted
  1394. WeakPtr<UIElement> element(GetElementAt(pos));
  1395. // Clear any drag events that were using the touch id
  1396. for (HashMap<WeakPtr<UIElement>, int>::Iterator i = touchDragElements_.Begin(); i != touchDragElements_.End();)
  1397. {
  1398. int touches = i->second_;
  1399. if (touches & touchId)
  1400. i = touchDragElements_.Erase(i);
  1401. else
  1402. ++i;
  1403. }
  1404. if (element && element->IsEnabled())
  1405. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  1406. ProcessClickEnd(pos, touchId, 0, 0, 0, true);
  1407. }
  1408. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1409. {
  1410. using namespace TouchMove;
  1411. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1412. IntVector2 deltaPos(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
  1413. pos.x_ = int(pos.x_ / uiScale_);
  1414. pos.y_ = int(pos.y_ / uiScale_);
  1415. deltaPos.x_ = int(deltaPos.x_ / uiScale_);
  1416. deltaPos.y_ = int(deltaPos.y_ / uiScale_);
  1417. usingTouchInput_ = true;
  1418. int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
  1419. ProcessMove(pos, deltaPos, touchId, 0, 0, true);
  1420. }
  1421. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1422. {
  1423. using namespace KeyDown;
  1424. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1425. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1426. int key = eventData[P_KEY].GetInt();
  1427. // Cancel UI dragging
  1428. if (key == KEY_ESCAPE && dragElementsCount_ > 0)
  1429. {
  1430. ProcessDragCancel();
  1431. return;
  1432. }
  1433. // Dismiss modal element if any when ESC key is pressed
  1434. if (key == KEY_ESCAPE && HasModalElement())
  1435. {
  1436. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1437. if (element->GetVars().Contains(VAR_ORIGIN))
  1438. // If it is a popup, dismiss by defocusing it
  1439. SetFocusElement(0);
  1440. else
  1441. {
  1442. // If it is a modal window, by resetting its modal flag
  1443. Window* window = dynamic_cast<Window*>(element);
  1444. if (window && window->GetModalAutoDismiss())
  1445. window->SetModal(false);
  1446. }
  1447. return;
  1448. }
  1449. UIElement* element = focusElement_;
  1450. if (element)
  1451. {
  1452. // Switch focus between focusable elements in the same top level window
  1453. if (key == KEY_TAB)
  1454. {
  1455. UIElement* topLevel = element->GetParent();
  1456. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1457. topLevel = topLevel->GetParent();
  1458. if (topLevel)
  1459. {
  1460. topLevel->GetChildren(tempElements_, true);
  1461. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1462. {
  1463. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1464. i = tempElements_.Erase(i);
  1465. else
  1466. ++i;
  1467. }
  1468. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1469. {
  1470. if (tempElements_[i] == element)
  1471. {
  1472. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1473. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1474. UIElement* next = tempElements_[nextIndex];
  1475. SetFocusElement(next, true);
  1476. return;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. // Defocus the element
  1482. else if (key == KEY_ESCAPE && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1483. element->SetFocus(false);
  1484. // If none of the special keys, pass the key to the focused element
  1485. else
  1486. element->OnKey(key, mouseButtons_, qualifiers_);
  1487. }
  1488. }
  1489. void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
  1490. {
  1491. using namespace TextInput;
  1492. UIElement* element = focusElement_;
  1493. if (element)
  1494. element->OnTextInput(eventData[P_TEXT].GetString());
  1495. }
  1496. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1497. {
  1498. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1499. // custom shapes can do it after this, but needs to do it each frame
  1500. if (cursor_ && dragElementsCount_ == 0)
  1501. cursor_->SetShape(CS_NORMAL);
  1502. }
  1503. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1504. {
  1505. using namespace PostUpdate;
  1506. Update(eventData[P_TIMESTEP].GetFloat());
  1507. }
  1508. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1509. {
  1510. RenderUpdate();
  1511. }
  1512. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1513. {
  1514. Input* input = GetSubsystem<Input>();
  1515. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1516. if (input->IsMouseVisible())
  1517. {
  1518. IntVector2 screenPos = input->GetMousePosition();
  1519. screenPos.x_ = int(screenPos.x_ / uiScale_);
  1520. screenPos.y_ = int(screenPos.y_ / uiScale_);
  1521. UIElement* element = GetElementAt(screenPos);
  1522. using namespace UIDropFile;
  1523. VariantMap uiEventData;
  1524. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1525. uiEventData[P_X] = screenPos.x_;
  1526. uiEventData[P_Y] = screenPos.y_;
  1527. uiEventData[P_ELEMENT] = element;
  1528. if (element)
  1529. {
  1530. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1531. uiEventData[P_ELEMENTX] = relativePos.x_;
  1532. uiEventData[P_ELEMENTY] = relativePos.y_;
  1533. }
  1534. SendEvent(E_UIDROPFILE, uiEventData);
  1535. }
  1536. }
  1537. HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator UI::DragElementErase(HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i)
  1538. {
  1539. // If running the engine frame in response to an event (re-entering UI frame logic) the dragElements_ may already be empty
  1540. if (dragElements_.Empty())
  1541. return dragElements_.End();
  1542. dragElementsConfirmed_.Clear();
  1543. DragData* dragData = i->second_;
  1544. if (!dragData->dragBeginPending)
  1545. --dragConfirmedCount_;
  1546. i = dragElements_.Erase(i);
  1547. --dragElementsCount_;
  1548. delete dragData;
  1549. return i;
  1550. }
  1551. void UI::ProcessDragCancel()
  1552. {
  1553. // How to tell difference between drag cancel and new selection on multi-touch?
  1554. if (usingTouchInput_)
  1555. return;
  1556. IntVector2 cursorPos;
  1557. bool cursorVisible;
  1558. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1559. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1560. {
  1561. WeakPtr<UIElement> dragElement = i->first_;
  1562. UI::DragData* dragData = i->second_;
  1563. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1564. {
  1565. dragElement->OnDragCancel(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, mouseButtons_,
  1566. cursor_);
  1567. SendDragOrHoverEvent(E_DRAGCANCEL, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1568. i = DragElementErase(i);
  1569. }
  1570. else
  1571. ++i;
  1572. }
  1573. }
  1574. IntVector2 UI::SumTouchPositions(UI::DragData* dragData, const IntVector2& oldSendPos)
  1575. {
  1576. IntVector2 sendPos = oldSendPos;
  1577. if (usingTouchInput_)
  1578. {
  1579. int buttons = dragData->dragButtons;
  1580. dragData->sumPos = IntVector2::ZERO;
  1581. Input* input = GetSubsystem<Input>();
  1582. for (int i = 0; (1 << i) <= buttons; i++)
  1583. {
  1584. if ((1 << i) & buttons)
  1585. {
  1586. TouchState* ts = input->GetTouch((unsigned)i);
  1587. if (!ts)
  1588. break;
  1589. IntVector2 pos = ts->position_;
  1590. dragData->sumPos.x_ += (int)(pos.x_ / uiScale_);
  1591. dragData->sumPos.y_ += (int)(pos.y_ / uiScale_);
  1592. }
  1593. }
  1594. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1595. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1596. }
  1597. return sendPos;
  1598. }
  1599. void UI::ResizeRootElement()
  1600. {
  1601. IntVector2 effectiveSize = GetEffectiveRootElementSize();
  1602. rootElement_->SetSize(effectiveSize);
  1603. rootModalElement_->SetSize(effectiveSize);
  1604. }
  1605. IntVector2 UI::GetEffectiveRootElementSize(bool applyScale) const
  1606. {
  1607. // Use a fake size in headless mode
  1608. IntVector2 size = graphics_ ? IntVector2(graphics_->GetWidth(), graphics_->GetHeight()) : IntVector2(1024, 768);
  1609. if (customSize_.x_ > 0 && customSize_.y_ > 0)
  1610. size = customSize_;
  1611. if (applyScale)
  1612. {
  1613. size.x_ = (int)((float)size.x_ / uiScale_ + 0.5f);
  1614. size.y_ = (int)((float)size.y_ / uiScale_ + 0.5f);
  1615. }
  1616. return size;
  1617. }
  1618. void RegisterUILibrary(Context* context)
  1619. {
  1620. Font::RegisterObject(context);
  1621. UIElement::RegisterObject(context);
  1622. BorderImage::RegisterObject(context);
  1623. Sprite::RegisterObject(context);
  1624. Button::RegisterObject(context);
  1625. CheckBox::RegisterObject(context);
  1626. Cursor::RegisterObject(context);
  1627. Text::RegisterObject(context);
  1628. Text3D::RegisterObject(context);
  1629. Window::RegisterObject(context);
  1630. View3D::RegisterObject(context);
  1631. LineEdit::RegisterObject(context);
  1632. Slider::RegisterObject(context);
  1633. ScrollBar::RegisterObject(context);
  1634. ScrollView::RegisterObject(context);
  1635. ListView::RegisterObject(context);
  1636. Menu::RegisterObject(context);
  1637. DropDownList::RegisterObject(context);
  1638. FileSelector::RegisterObject(context);
  1639. MessageBox::RegisterObject(context);
  1640. ProgressBar::RegisterObject(context);
  1641. ToolTip::RegisterObject(context);
  1642. }
  1643. }