UI.cpp 66 KB

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