UI.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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_->SetDrawAntialiased(false);
  593. graphics_->SetStencilTest(false);
  594. graphics_->ResetRenderTargets();
  595. graphics_->SetVertexBuffer(buffer);
  596. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  597. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  598. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  599. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  600. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  601. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  602. unsigned alphaFormat = Graphics::GetAlphaFormat();
  603. for (unsigned i = batchStart; i < batchEnd; ++i)
  604. {
  605. const UIBatch& batch = batches[i];
  606. if (batch.vertexStart_ == batch.vertexEnd_)
  607. continue;
  608. ShaderVariation* ps;
  609. ShaderVariation* vs;
  610. if (!batch.texture_)
  611. {
  612. ps = noTexturePS;
  613. vs = noTextureVS;
  614. }
  615. else
  616. {
  617. // If texture contains only an alpha channel, use alpha shader (for fonts)
  618. vs = diffTextureVS;
  619. if (batch.texture_->GetFormat() == alphaFormat)
  620. ps = alphaTexturePS;
  621. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  622. ps = diffMaskTexturePS;
  623. else
  624. ps = diffTexturePS;
  625. }
  626. graphics_->SetShaders(vs, ps);
  627. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  628. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  629. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  630. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  631. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  632. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  633. graphics_->SetBlendMode(batch.blendMode_);
  634. graphics_->SetScissorTest(true, batch.scissor_);
  635. graphics_->SetTexture(0, batch.texture_);
  636. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  637. UI_VERTEX_SIZE);
  638. }
  639. }
  640. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  641. {
  642. // Set clipping scissor for child elements. No need to draw if zero size
  643. element->AdjustScissor(currentScissor);
  644. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  645. return;
  646. element->SortChildren();
  647. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  648. if (children.Empty())
  649. return;
  650. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  651. // same renderstate
  652. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  653. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  654. {
  655. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  656. while (i != children.End())
  657. {
  658. int currentPriority = (*i)->GetPriority();
  659. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  660. {
  661. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  662. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  663. ++j;
  664. }
  665. // Now recurse into the children
  666. while (i != j)
  667. {
  668. if ((*i)->IsVisible() && (*i) != cursor_)
  669. GetBatches(*i, currentScissor);
  670. ++i;
  671. }
  672. }
  673. }
  674. // On the root level draw each element and its children immediately after to avoid artifacts
  675. else
  676. {
  677. while (i != children.End())
  678. {
  679. if ((*i) != cursor_)
  680. {
  681. if ((*i)->IsWithinScissor(currentScissor))
  682. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  683. if ((*i)->IsVisible())
  684. GetBatches(*i, currentScissor);
  685. }
  686. ++i;
  687. }
  688. }
  689. }
  690. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  691. {
  692. if (!current)
  693. return;
  694. current->SortChildren();
  695. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  696. LayoutMode parentLayoutMode = current->GetLayoutMode();
  697. for (unsigned i = 0; i < children.Size(); ++i)
  698. {
  699. UIElement* element = children[i];
  700. bool hasChildren = element->GetNumChildren() > 0;
  701. if (element != cursor_.Get() && element->IsVisible())
  702. {
  703. if (element->IsInside(position, true))
  704. {
  705. // Store the current result, then recurse into its children. Because children
  706. // are sorted from lowest to highest priority, the topmost match should remain
  707. if (element->IsEnabled() || !enabledOnly)
  708. result = element;
  709. if (hasChildren)
  710. GetElementAt(result, element, position, enabledOnly);
  711. // Layout optimization: if the element has no children, can break out after the first match
  712. else if (parentLayoutMode != LM_FREE)
  713. break;
  714. }
  715. else
  716. {
  717. if (hasChildren)
  718. {
  719. if (element->IsInsideCombined(position, true))
  720. GetElementAt(result, element, position, enabledOnly);
  721. }
  722. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  723. // or if we already passed all visible elements
  724. else if (parentLayoutMode != LM_FREE)
  725. {
  726. if (!i)
  727. {
  728. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  729. element->GetScreenPosition().y_;
  730. int layoutMinSize = current->GetLayoutMinSize();
  731. if (screenPos < 0 && layoutMinSize > 0)
  732. {
  733. unsigned toSkip = -screenPos / layoutMinSize;
  734. if (toSkip > 0)
  735. i += (toSkip - 1);
  736. }
  737. }
  738. else if (parentLayoutMode == LM_HORIZONTAL)
  739. {
  740. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  741. break;
  742. }
  743. else if (parentLayoutMode == LM_VERTICAL)
  744. {
  745. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  746. break;
  747. }
  748. }
  749. }
  750. }
  751. }
  752. }
  753. UIElement* UI::GetFocusableElement(UIElement* element)
  754. {
  755. while (element)
  756. {
  757. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  758. break;
  759. element = element->GetParent();
  760. }
  761. return element;
  762. }
  763. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  764. {
  765. // Prefer software cursor then OS-specific cursor
  766. if (cursor_ && cursor_->IsVisible())
  767. {
  768. pos = cursor_->GetPosition();
  769. visible = true;
  770. }
  771. else
  772. {
  773. Input* input = GetSubsystem<Input>();
  774. pos = input->GetMousePosition();
  775. visible = input->IsMouseVisible();
  776. if (!visible && cursor_)
  777. pos = cursor_->GetPosition();
  778. }
  779. }
  780. void UI::SetCursorShape(CursorShape shape)
  781. {
  782. if (cursor_)
  783. cursor_->SetShape(shape);
  784. }
  785. void UI::ReleaseFontFaces()
  786. {
  787. LOGDEBUG("Reloading font faces");
  788. PODVector<Font*> fonts;
  789. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  790. for (unsigned i = 0; i < fonts.Size(); ++i)
  791. fonts[i]->ReleaseFaces();
  792. }
  793. void UI::ProcessHover(const IntVector2& cursorPos, int buttons, int qualifiers, Cursor* cursor)
  794. {
  795. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  796. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  797. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  798. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  799. // If drag start event has not been posted yet, do not do drag handling here
  800. if (dragBeginPending_)
  801. dragSource = dragTarget = dragDropTest = false;
  802. // Hover effect
  803. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  804. if (element && element->IsEnabled())
  805. {
  806. if (!dragElement_ || dragElement_ == element || dragDropTest)
  807. {
  808. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  809. // Begin hover event
  810. if (!hoveredElements_.Contains(element))
  811. {
  812. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos);
  813. // Exit if element is destroyed by the event handling
  814. if (!element)
  815. return;
  816. }
  817. hoveredElements_[element] = true;
  818. }
  819. }
  820. // Drag and drop test
  821. if (dragDropTest)
  822. {
  823. bool accept = element->OnDragDropTest(dragElement_);
  824. if (accept)
  825. {
  826. using namespace DragDropTest;
  827. VariantMap& eventData = GetEventDataMap();
  828. eventData[P_SOURCE] = dragElement_.Get();
  829. eventData[P_TARGET] = element.Get();
  830. eventData[P_ACCEPT] = accept;
  831. SendEvent(E_DRAGDROPTEST, eventData);
  832. accept = eventData[P_ACCEPT].GetBool();
  833. }
  834. if (cursor)
  835. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  836. }
  837. else if (dragSource && cursor)
  838. cursor->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  839. }
  840. void UI::ProcessClickBegin(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  841. {
  842. if (cursorVisible)
  843. {
  844. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  845. if (element)
  846. {
  847. // Handle focusing & bringing to front
  848. if (button == MOUSEB_LEFT)
  849. {
  850. SetFocusElement(element);
  851. element->BringToFront();
  852. }
  853. // Handle click
  854. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  855. SendClickEvent(E_UIMOUSECLICK, element, cursorPos, button, buttons, qualifiers);
  856. // Remember element clicked on for the click end
  857. clickElement_ = element;
  858. // Fire double click event if element matches and is in time
  859. if (doubleClickElement_ && element == doubleClickElement_ && clickTimer_.GetMSec(true) <
  860. (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
  861. {
  862. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  863. doubleClickElement_.Reset();
  864. SendClickEvent(E_UIMOUSEDOUBLECLICK, element, cursorPos, button, buttons, qualifiers);
  865. }
  866. else
  867. {
  868. doubleClickElement_ = element;
  869. clickTimer_.Reset();
  870. }
  871. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  872. if (element && !dragElement_ && buttons == MOUSEB_LEFT)
  873. {
  874. dragElement_ = element;
  875. dragBeginPending_ = true;
  876. dragBeginPos_ = cursorPos;
  877. dragBeginTimer_.Reset();
  878. }
  879. }
  880. else
  881. {
  882. // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
  883. if (!HasModalElement())
  884. SetFocusElement(0);
  885. SendClickEvent(E_UIMOUSECLICK, element, cursorPos, button, buttons, qualifiers);
  886. }
  887. lastMouseButtons_ = buttons;
  888. }
  889. }
  890. void UI::ProcessClickEnd(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  891. {
  892. if (cursorVisible)
  893. {
  894. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  895. // Handle end of click
  896. if (element)
  897. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor, clickElement_);
  898. SendClickEvent(E_UIMOUSECLICKEND, element, cursorPos, button, buttons, qualifiers);
  899. // Handle end of drag
  900. if (dragElement_ && !buttons)
  901. {
  902. if (dragElement_->IsEnabled() && dragElement_->IsVisible() && !dragBeginPending_)
  903. {
  904. dragElement_->OnDragEnd(dragElement_->ScreenToElement(cursorPos), cursorPos, cursor);
  905. SendDragOrHoverEvent(E_DRAGEND, dragElement_, cursorPos);
  906. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  907. if (dragSource)
  908. {
  909. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  910. bool dragDropFinish = dragSource && dragTarget && element != dragElement_;
  911. if (dragDropFinish)
  912. {
  913. bool accept = element->OnDragDropFinish(dragElement_);
  914. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  915. if (accept && dragElement_ && element)
  916. {
  917. using namespace DragDropFinish;
  918. VariantMap& eventData = GetEventDataMap();
  919. eventData[P_SOURCE] = dragElement_.Get();
  920. eventData[P_TARGET] = element.Get();
  921. eventData[P_ACCEPT] = accept;
  922. SendEvent(E_DRAGDROPFINISH, eventData);
  923. }
  924. }
  925. }
  926. }
  927. dragElement_.Reset();
  928. dragBeginPending_ = false;
  929. }
  930. clickElement_.Reset();
  931. }
  932. }
  933. void UI::ProcessMove(const IntVector2& cursorPos, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  934. {
  935. if (cursorVisible && dragElement_ && buttons)
  936. {
  937. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  938. {
  939. // Signal drag begin if distance threshold was exceeded
  940. if (dragBeginPending_)
  941. {
  942. IntVector2 offset = cursorPos - dragBeginPos_;
  943. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  944. {
  945. dragBeginPending_ = false;
  946. dragElement_->OnDragBegin(dragElement_->ScreenToElement(dragBeginPos_), dragBeginPos_, buttons, qualifiers, cursor);
  947. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement_, dragBeginPos_);
  948. }
  949. }
  950. if (!dragBeginPending_)
  951. {
  952. dragElement_->OnDragMove(dragElement_->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  953. SendDragOrHoverEvent(E_DRAGMOVE, dragElement_, cursorPos);
  954. }
  955. }
  956. else
  957. {
  958. dragElement_->OnDragEnd(dragElement_->ScreenToElement(cursorPos), cursorPos, cursor);
  959. SendDragOrHoverEvent(E_DRAGEND, dragElement_, cursorPos);
  960. dragElement_.Reset();
  961. }
  962. }
  963. }
  964. void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos)
  965. {
  966. if (!element)
  967. return;
  968. IntVector2 relativePos = element->ScreenToElement(screenPos);
  969. using namespace DragBegin;
  970. VariantMap& eventData = GetEventDataMap();
  971. eventData[P_ELEMENT] = element;
  972. eventData[P_X] = screenPos.x_;
  973. eventData[P_Y] = screenPos.y_;
  974. eventData[P_ELEMENTX] = relativePos.x_;
  975. eventData[P_ELEMENTY] = relativePos.y_;
  976. element->SendEvent(eventType, eventData);
  977. }
  978. void UI::SendClickEvent(StringHash eventType, UIElement* element, const IntVector2& pos, int button, int buttons, int qualifiers)
  979. {
  980. VariantMap& eventData = GetEventDataMap();
  981. eventData[UIMouseClick::P_ELEMENT] = element;
  982. eventData[UIMouseClick::P_X] = pos.x_;
  983. eventData[UIMouseClick::P_Y] = pos.y_;
  984. eventData[UIMouseClick::P_BUTTON] = button;
  985. eventData[UIMouseClick::P_BUTTONS] = buttons;
  986. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers;
  987. // For click end events, send also the element the click began on
  988. if (eventType == E_UIMOUSECLICKEND)
  989. eventData[UIMouseClickEnd::P_BEGINELEMENT] = clickElement_;
  990. SendEvent(eventType, eventData);
  991. }
  992. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  993. {
  994. using namespace ScreenMode;
  995. if (!initialized_)
  996. Initialize();
  997. else
  998. {
  999. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  1000. rootModalElement_->SetSize(rootElement_->GetSize());
  1001. }
  1002. }
  1003. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  1004. {
  1005. Input* input = GetSubsystem<Input>();
  1006. if (input->IsMouseGrabbed())
  1007. return;
  1008. using namespace MouseButtonDown;
  1009. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1010. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1011. usingTouchInput_ = false;
  1012. IntVector2 cursorPos;
  1013. bool cursorVisible;
  1014. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1015. ProcessClickBegin(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1016. }
  1017. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  1018. {
  1019. Input* input = GetSubsystem<Input>();
  1020. if (input->IsMouseGrabbed())
  1021. return;
  1022. using namespace MouseButtonUp;
  1023. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1024. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1025. IntVector2 cursorPos;
  1026. bool cursorVisible;
  1027. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1028. ProcessClickEnd(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1029. }
  1030. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  1031. {
  1032. using namespace MouseMove;
  1033. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1034. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1035. usingTouchInput_ = false;
  1036. Input* input = GetSubsystem<Input>();
  1037. const IntVector2& rootSize = rootElement_->GetSize();
  1038. if (cursor_)
  1039. {
  1040. if (!input->IsMouseVisible())
  1041. {
  1042. // Relative mouse motion: move cursor only when visible
  1043. if (cursor_->IsVisible())
  1044. {
  1045. IntVector2 pos = cursor_->GetPosition();
  1046. pos.x_ += eventData[P_DX].GetInt();
  1047. pos.y_ += eventData[P_DY].GetInt();
  1048. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  1049. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  1050. cursor_->SetPosition(pos);
  1051. }
  1052. }
  1053. else
  1054. {
  1055. // Absolute mouse motion: move always
  1056. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  1057. }
  1058. }
  1059. IntVector2 cursorPos;
  1060. bool cursorVisible;
  1061. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1062. ProcessMove(cursorPos, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1063. }
  1064. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1065. {
  1066. Input* input = GetSubsystem<Input>();
  1067. if (input->IsMouseGrabbed())
  1068. return;
  1069. using namespace MouseWheel;
  1070. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1071. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1072. int delta = eventData[P_WHEEL].GetInt();
  1073. usingTouchInput_ = false;
  1074. IntVector2 cursorPos;
  1075. bool cursorVisible;
  1076. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1077. UIElement* element;
  1078. if (!nonFocusedMouseWheel_&& (element = focusElement_))
  1079. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1080. else
  1081. {
  1082. // If no element has actual focus or in non-focused mode, get the element at cursor
  1083. if (cursorVisible)
  1084. {
  1085. element = GetElementAt(cursorPos);
  1086. if (nonFocusedMouseWheel_)
  1087. {
  1088. // Going up the hierarchy chain to find element that could handle mouse wheel
  1089. while (element)
  1090. {
  1091. if (element->GetType() == ListView::GetTypeStatic() ||
  1092. element->GetType() == ScrollView::GetTypeStatic())
  1093. break;
  1094. element = element->GetParent();
  1095. }
  1096. }
  1097. else
  1098. // If the element itself is not focusable, search for a focusable parent,
  1099. // although the focusable element may not actually handle mouse wheel
  1100. element = GetFocusableElement(element);
  1101. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1102. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1103. }
  1104. }
  1105. }
  1106. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1107. {
  1108. using namespace TouchBegin;
  1109. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1110. usingTouchInput_ = true;
  1111. ProcessClickBegin(pos, MOUSEB_LEFT, MOUSEB_LEFT, 0, 0, true);
  1112. }
  1113. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1114. {
  1115. using namespace TouchEnd;
  1116. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1117. // Transmit hover end to the position where the finger was lifted
  1118. UIElement* element = GetElementAt(pos);
  1119. if (element && element->IsEnabled())
  1120. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  1121. ProcessClickEnd(pos, MOUSEB_LEFT, 0, 0, 0, true);
  1122. }
  1123. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1124. {
  1125. using namespace TouchMove;
  1126. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1127. usingTouchInput_ = true;
  1128. ProcessMove(pos, MOUSEB_LEFT, 0, 0, true);
  1129. }
  1130. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1131. {
  1132. using namespace KeyDown;
  1133. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1134. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1135. int key = eventData[P_KEY].GetInt();
  1136. // Cancel UI dragging
  1137. if (key == KEY_ESC && dragElement_)
  1138. {
  1139. IntVector2 cursorPos;
  1140. bool cursorVisible;
  1141. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1142. SendDragOrHoverEvent(E_DRAGCANCEL, dragElement_, cursorPos);
  1143. dragElement_.Reset();
  1144. dragBeginPending_ = false;
  1145. return;
  1146. }
  1147. // Dismiss modal element if any when ESC key is pressed
  1148. if (key == KEY_ESC && HasModalElement())
  1149. {
  1150. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1151. if (element->GetVars().Contains(VAR_ORIGIN))
  1152. // If it is a popup, dismiss by defocusing it
  1153. SetFocusElement(0);
  1154. else
  1155. {
  1156. // If it is a modal window, by resetting its modal flag
  1157. Window* window = dynamic_cast<Window*>(element);
  1158. if (window && window->GetModalAutoDismiss())
  1159. window->SetModal(false);
  1160. }
  1161. return;
  1162. }
  1163. UIElement* element = focusElement_;
  1164. if (element)
  1165. {
  1166. // Switch focus between focusable elements in the same top level window
  1167. if (key == KEY_TAB)
  1168. {
  1169. UIElement* topLevel = element->GetParent();
  1170. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1171. topLevel = topLevel->GetParent();
  1172. if (topLevel)
  1173. {
  1174. topLevel->GetChildren(tempElements_, true);
  1175. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1176. {
  1177. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1178. i = tempElements_.Erase(i);
  1179. else
  1180. ++i;
  1181. }
  1182. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1183. {
  1184. if (tempElements_[i] == element)
  1185. {
  1186. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1187. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1188. UIElement* next = tempElements_[nextIndex];
  1189. SetFocusElement(next, true);
  1190. return;
  1191. }
  1192. }
  1193. }
  1194. }
  1195. // Defocus the element
  1196. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1197. element->SetFocus(false);
  1198. // If none of the special keys, pass the key to the focused element
  1199. else
  1200. element->OnKey(key, mouseButtons_, qualifiers_);
  1201. }
  1202. }
  1203. void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
  1204. {
  1205. using namespace TextInput;
  1206. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1207. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1208. UIElement* element = focusElement_;
  1209. if (element)
  1210. element->OnTextInput(eventData[P_TEXT].GetString(), mouseButtons_, qualifiers_);
  1211. }
  1212. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1213. {
  1214. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1215. // custom shapes can do it after this, but needs to do it each frame
  1216. if (cursor_ && !dragElement_)
  1217. cursor_->SetShape(CS_NORMAL);
  1218. }
  1219. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1220. {
  1221. using namespace PostUpdate;
  1222. Update(eventData[P_TIMESTEP].GetFloat());
  1223. }
  1224. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1225. {
  1226. RenderUpdate();
  1227. }
  1228. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1229. {
  1230. Input* input = GetSubsystem<Input>();
  1231. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1232. if (input->IsMouseVisible())
  1233. {
  1234. IntVector2 screenPos = input->GetMousePosition();
  1235. UIElement* element = GetElementAt(screenPos);
  1236. using namespace UIDropFile;
  1237. VariantMap uiEventData;
  1238. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1239. uiEventData[P_X] = screenPos.x_;
  1240. uiEventData[P_Y] = screenPos.y_;
  1241. uiEventData[P_ELEMENT] = element;
  1242. if (element)
  1243. {
  1244. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1245. uiEventData[P_ELEMENTX] = relativePos.x_;
  1246. uiEventData[P_ELEMENTY] = relativePos.y_;
  1247. }
  1248. SendEvent(E_UIDROPFILE, uiEventData);
  1249. }
  1250. }
  1251. void RegisterUILibrary(Context* context)
  1252. {
  1253. Font::RegisterObject(context);
  1254. UIElement::RegisterObject(context);
  1255. BorderImage::RegisterObject(context);
  1256. Sprite::RegisterObject(context);
  1257. Button::RegisterObject(context);
  1258. CheckBox::RegisterObject(context);
  1259. Cursor::RegisterObject(context);
  1260. Text::RegisterObject(context);
  1261. Text3D::RegisterObject(context);
  1262. Window::RegisterObject(context);
  1263. View3D::RegisterObject(context);
  1264. LineEdit::RegisterObject(context);
  1265. Slider::RegisterObject(context);
  1266. ScrollBar::RegisterObject(context);
  1267. ScrollView::RegisterObject(context);
  1268. ListView::RegisterObject(context);
  1269. Menu::RegisterObject(context);
  1270. DropDownList::RegisterObject(context);
  1271. FileSelector::RegisterObject(context);
  1272. MessageBox::RegisterObject(context);
  1273. ToolTip::RegisterObject(context);
  1274. }
  1275. }