UI.cpp 48 KB

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