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