UI.cpp 46 KB

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