UI.cpp 48 KB

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