UI.cpp 66 KB

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