UI.cpp 47 KB

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