UI.cpp 50 KB

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