UI.cpp 49 KB

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