UI.cpp 59 KB

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