UI.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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. #define TOUCHID_MASK(id) (1 << id)
  59. namespace Urho3D
  60. {
  61. StringHash VAR_ORIGIN("Origin");
  62. const StringHash VAR_ORIGINAL_PARENT("OriginalParent");
  63. const StringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex");
  64. const StringHash VAR_PARENT_CHANGED("ParentChanged");
  65. const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f;
  66. const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f;
  67. const float DEFAULT_TOOLTIP_DELAY = 0.5f;
  68. const int DEFAULT_DRAGBEGIN_DISTANCE = 5;
  69. const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048;
  70. const char* UI_CATEGORY = "UI";
  71. UI::UI(Context* context) :
  72. Object(context),
  73. rootElement_(new UIElement(context)),
  74. rootModalElement_(new UIElement(context)),
  75. doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL),
  76. dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL),
  77. defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY),
  78. dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE),
  79. mouseButtons_(0),
  80. lastMouseButtons_(0),
  81. qualifiers_(0),
  82. maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE),
  83. dragElementsCount_(0),
  84. dragConfirmedCount_(0),
  85. initialized_(false),
  86. usingTouchInput_(false),
  87. #ifdef WIN32
  88. nonFocusedMouseWheel_(false), // Default MS Windows behaviour
  89. #else
  90. nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
  91. #endif
  92. useSystemClipboard_(false),
  93. #if defined(ANDROID) || defined(IOS)
  94. useScreenKeyboard_(true),
  95. #else
  96. useScreenKeyboard_(false),
  97. #endif
  98. useMutableGlyphs_(false),
  99. forceAutoHint_(false),
  100. nonModalBatchSize_(0)
  101. {
  102. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  103. rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
  104. // Register UI library object factories
  105. RegisterUILibrary(context_);
  106. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  107. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  108. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  109. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  110. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  111. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  112. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  113. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  114. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  115. SubscribeToEvent(E_TEXTINPUT, HANDLER(UI, HandleTextInput));
  116. SubscribeToEvent(E_DROPFILE, HANDLER(UI, HandleDropFile));
  117. // Try to initialize right now, but skip if screen mode is not yet set
  118. Initialize();
  119. }
  120. UI::~UI()
  121. {
  122. }
  123. void UI::SetCursor(Cursor* cursor)
  124. {
  125. // Remove old cursor (if any) and set new
  126. if (cursor_)
  127. {
  128. rootElement_->RemoveChild(cursor_);
  129. cursor_.Reset();
  130. }
  131. if (cursor)
  132. {
  133. rootElement_->AddChild(cursor);
  134. cursor_ = cursor;
  135. IntVector2 pos = cursor_->GetPosition();
  136. const IntVector2& rootSize = rootElement_->GetSize();
  137. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  138. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  139. cursor_->SetPosition(pos);
  140. }
  141. }
  142. void UI::SetFocusElement(UIElement* element, bool byKey)
  143. {
  144. using namespace FocusChanged;
  145. UIElement* originalElement = element;
  146. if (element)
  147. {
  148. // Return if already has focus
  149. if (focusElement_ == element)
  150. return;
  151. // Only allow child elements of the modal element to receive focus
  152. if (HasModalElement())
  153. {
  154. UIElement* topLevel = element->GetParent();
  155. while (topLevel && topLevel->GetParent() != rootElement_)
  156. topLevel = topLevel->GetParent();
  157. if (topLevel) // If parented to non-modal root then ignore
  158. return;
  159. }
  160. // Search for an element in the hierarchy that can alter focus. If none found, exit
  161. element = GetFocusableElement(element);
  162. if (!element)
  163. return;
  164. }
  165. // Remove focus from the old element
  166. if (focusElement_)
  167. {
  168. UIElement* oldFocusElement = focusElement_;
  169. focusElement_.Reset();
  170. VariantMap& focusEventData = GetEventDataMap();
  171. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  172. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  173. }
  174. // Then set focus to the new
  175. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  176. {
  177. focusElement_ = element;
  178. VariantMap& focusEventData = GetEventDataMap();
  179. focusEventData[Focused::P_ELEMENT] = element;
  180. focusEventData[Focused::P_BYKEY] = byKey;
  181. element->SendEvent(E_FOCUSED, focusEventData);
  182. }
  183. VariantMap& eventData = GetEventDataMap();
  184. eventData[P_CLICKEDELEMENT] = originalElement;
  185. eventData[P_ELEMENT] = element;
  186. SendEvent(E_FOCUSCHANGED, eventData);
  187. }
  188. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  189. {
  190. if (!modalElement)
  191. return false;
  192. // Currently only allow modal window
  193. if (modalElement->GetType() != Window::GetTypeStatic())
  194. return false;
  195. assert(rootModalElement_);
  196. UIElement* currParent = modalElement->GetParent();
  197. if (enable)
  198. {
  199. // Make sure it is not already the child of the root modal element
  200. if (currParent == rootModalElement_)
  201. return false;
  202. // Adopt modal root as parent
  203. modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent);
  204. modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED);
  205. modalElement->SetParent(rootModalElement_);
  206. // If it is a popup element, bring along its top-level parent
  207. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  208. if (originElement)
  209. {
  210. UIElement* element = originElement;
  211. while (element && element->GetParent() != rootElement_)
  212. element = element->GetParent();
  213. if (element)
  214. {
  215. originElement->SetVar(VAR_PARENT_CHANGED, element);
  216. UIElement* oriParent = element->GetParent();
  217. element->SetVar(VAR_ORIGINAL_PARENT, oriParent);
  218. element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED);
  219. element->SetParent(rootModalElement_);
  220. }
  221. }
  222. return true;
  223. }
  224. else
  225. {
  226. // Only the modal element can disable itself
  227. if (currParent != rootModalElement_)
  228. return false;
  229. // Revert back to original parent
  230. modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  231. modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  232. VariantMap& vars = const_cast<VariantMap&>(modalElement->GetVars());
  233. vars.Erase(VAR_ORIGINAL_PARENT);
  234. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  235. // If it is a popup element, revert back its top-level parent
  236. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  237. if (originElement)
  238. {
  239. UIElement* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
  240. if (element)
  241. {
  242. const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
  243. element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  244. element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  245. vars = const_cast<VariantMap&>(element->GetVars());
  246. vars.Erase(VAR_ORIGINAL_PARENT);
  247. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  248. }
  249. }
  250. return true;
  251. }
  252. }
  253. void UI::Clear()
  254. {
  255. rootElement_->RemoveAllChildren();
  256. rootModalElement_->RemoveAllChildren();
  257. if (cursor_)
  258. rootElement_->AddChild(cursor_);
  259. }
  260. void UI::Update(float timeStep)
  261. {
  262. assert(rootElement_ && rootModalElement_);
  263. PROFILE(UpdateUI);
  264. // Expire hovers
  265. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End(); ++i)
  266. i->second_ = false;
  267. Input* input = GetSubsystem<Input>();
  268. bool mouseGrabbed = input->IsMouseGrabbed();
  269. IntVector2 cursorPos;
  270. bool cursorVisible;
  271. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  272. // Drag begin based on time
  273. if (dragElementsCount_ > 0 && !mouseGrabbed)
  274. {
  275. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End(); )
  276. {
  277. WeakPtr<UIElement> dragElement = i->first_;
  278. UI::DragData* dragData = i->second_;
  279. if (!dragElement)
  280. {
  281. i = dragElementErase(i);
  282. continue;
  283. }
  284. if (!dragData->dragBeginPending)
  285. {
  286. ++i;
  287. continue;
  288. }
  289. if (dragData->dragBeginTimer.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000))
  290. {
  291. dragData->dragBeginPending = false;
  292. IntVector2 beginSendPos = dragData->dragBeginSumPos / dragData->numDragButtons;
  293. dragConfirmedCount_ ++;
  294. if (!usingTouchInput_)
  295. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, qualifiers_,cursor_);
  296. else
  297. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, 0, 0);
  298. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  299. }
  300. ++i;
  301. }
  302. }
  303. // Mouse hover
  304. if (!mouseGrabbed && !input->GetTouchEmulation())
  305. {
  306. if (!usingTouchInput_ && cursorVisible)
  307. ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_);
  308. }
  309. // Touch hover
  310. unsigned numTouches = input->GetNumTouches();
  311. for (unsigned i = 0; i < numTouches; ++i)
  312. {
  313. TouchState* touch = input->GetTouch(i);
  314. ProcessHover(touch->position_, TOUCHID_MASK(touch->touchID_), 0, 0);
  315. }
  316. // End hovers that expired without refreshing
  317. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End();)
  318. {
  319. if (i->first_.Expired() || !i->second_)
  320. {
  321. UIElement* element = i->first_;
  322. if (element)
  323. {
  324. using namespace HoverEnd;
  325. VariantMap& eventData = GetEventDataMap();
  326. eventData[P_ELEMENT] = element;
  327. element->SendEvent(E_HOVEREND, eventData);
  328. }
  329. i = hoveredElements_.Erase(i);
  330. }
  331. else
  332. ++i;
  333. }
  334. Update(timeStep, rootElement_);
  335. Update(timeStep, rootModalElement_);
  336. }
  337. void UI::RenderUpdate()
  338. {
  339. assert(rootElement_ && rootModalElement_ && graphics_);
  340. PROFILE(GetUIBatches);
  341. // If the OS cursor is visible, do not render the UI's own cursor
  342. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  343. // Get rendering batches from the non-modal UI elements
  344. batches_.Clear();
  345. vertexData_.Clear();
  346. const IntVector2& rootSize = rootElement_->GetSize();
  347. IntRect currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  348. GetBatches(rootElement_, currentScissor);
  349. // Save the batch size of the non-modal batches for later use
  350. nonModalBatchSize_ = batches_.Size();
  351. // Get rendering batches from the modal UI elements
  352. GetBatches(rootModalElement_, currentScissor);
  353. // Get batches from the cursor (and its possible children) last to draw it on top of everything
  354. if (cursor_ && cursor_->IsVisible() && !osCursorVisible)
  355. {
  356. currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  357. cursor_->GetBatches(batches_, vertexData_, currentScissor);
  358. GetBatches(cursor_, currentScissor);
  359. }
  360. }
  361. void UI::Render()
  362. {
  363. PROFILE(RenderUI);
  364. // If the OS cursor is visible, apply its shape now if changed
  365. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  366. if (cursor_ && osCursorVisible)
  367. cursor_->ApplyOSCursorShape();
  368. SetVertexData(vertexBuffer_, vertexData_);
  369. SetVertexData(debugVertexBuffer_, debugVertexData_);
  370. // Render non-modal batches
  371. Render(vertexBuffer_, batches_, 0, nonModalBatchSize_);
  372. // Render debug draw
  373. Render(debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size());
  374. // Render modal batches
  375. Render(vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size());
  376. // Clear the debug draw batches and data
  377. debugDrawBatches_.Clear();
  378. debugVertexData_.Clear();
  379. }
  380. void UI::DebugDraw(UIElement* element)
  381. {
  382. if (element)
  383. {
  384. const IntVector2& rootSize = rootElement_->GetSize();
  385. element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  386. }
  387. }
  388. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  389. {
  390. SharedPtr<XMLFile> xml(new XMLFile(context_));
  391. if (!xml->Load(source))
  392. return SharedPtr<UIElement>();
  393. else
  394. return LoadLayout(xml, styleFile);
  395. }
  396. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  397. {
  398. PROFILE(LoadUILayout);
  399. SharedPtr<UIElement> root;
  400. if (!file)
  401. {
  402. LOGERROR("Null UI layout XML file");
  403. return root;
  404. }
  405. LOGDEBUG("Loading UI layout " + file->GetName());
  406. XMLElement rootElem = file->GetRoot("element");
  407. if (!rootElem)
  408. {
  409. LOGERROR("No root UI element in " + file->GetName());
  410. return root;
  411. }
  412. String typeName = rootElem.GetAttribute("type");
  413. if (typeName.Empty())
  414. typeName = "UIElement";
  415. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  416. if (!root)
  417. {
  418. LOGERROR("Could not create unknown UI element " + typeName);
  419. return root;
  420. }
  421. // Use default style file of the root element if it has one
  422. if (!styleFile)
  423. styleFile = rootElement_->GetDefaultStyle(false);
  424. // Set it as default for later use by children elements
  425. if (styleFile)
  426. root->SetDefaultStyle(styleFile);
  427. root->LoadXML(rootElem, styleFile);
  428. return root;
  429. }
  430. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  431. {
  432. PROFILE(SaveUILayout);
  433. return element && element->SaveXML(dest);
  434. }
  435. void UI::SetClipboardText(const String& text)
  436. {
  437. clipBoard_ = text;
  438. if (useSystemClipboard_)
  439. SDL_SetClipboardText(text.CString());
  440. }
  441. void UI::SetDoubleClickInterval(float interval)
  442. {
  443. doubleClickInterval_ = Max(interval, 0.0f);
  444. }
  445. void UI::SetDragBeginInterval(float interval)
  446. {
  447. dragBeginInterval_ = Max(interval, 0.0f);
  448. }
  449. void UI::SetDragBeginDistance(int pixels)
  450. {
  451. dragBeginDistance_ = Max(pixels, 0);
  452. }
  453. void UI::SetDefaultToolTipDelay(float delay)
  454. {
  455. defaultToolTipDelay_ = Max(delay, 0.0f);
  456. }
  457. void UI::SetMaxFontTextureSize(int size)
  458. {
  459. if (IsPowerOfTwo(size) && size >= FONT_TEXTURE_MIN_SIZE)
  460. {
  461. if (size != maxFontTextureSize_)
  462. {
  463. maxFontTextureSize_ = size;
  464. ReleaseFontFaces();
  465. }
  466. }
  467. }
  468. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  469. {
  470. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  471. }
  472. void UI::SetUseSystemClipboard(bool enable)
  473. {
  474. useSystemClipboard_ = enable;
  475. }
  476. void UI::SetUseScreenKeyboard(bool enable)
  477. {
  478. useScreenKeyboard_ = enable;
  479. }
  480. void UI::SetUseMutableGlyphs(bool enable)
  481. {
  482. if (enable != useMutableGlyphs_)
  483. {
  484. useMutableGlyphs_ = enable;
  485. ReleaseFontFaces();
  486. }
  487. }
  488. void UI::SetForceAutoHint(bool enable)
  489. {
  490. if (enable != forceAutoHint_)
  491. {
  492. forceAutoHint_ = enable;
  493. ReleaseFontFaces();
  494. }
  495. }
  496. IntVector2 UI::GetCursorPosition() const
  497. {
  498. return cursor_ ? cursor_->GetPosition() : GetSubsystem<Input>()->GetMousePosition();
  499. }
  500. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  501. {
  502. UIElement* result = 0;
  503. GetElementAt(result, HasModalElement() ? rootModalElement_ : rootElement_, position, enabledOnly);
  504. return result;
  505. }
  506. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  507. {
  508. return GetElementAt(IntVector2(x, y), enabledOnly);
  509. }
  510. UIElement* UI::GetFrontElement() const
  511. {
  512. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  513. int maxPriority = M_MIN_INT;
  514. UIElement* front = 0;
  515. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  516. {
  517. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  518. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  519. continue;
  520. int priority = rootChildren[i]->GetPriority();
  521. if (priority > maxPriority)
  522. {
  523. maxPriority = priority;
  524. front = rootChildren[i];
  525. }
  526. }
  527. return front;
  528. }
  529. const Vector<UIElement*> UI::GetDragElements()
  530. {
  531. // Do not return the element until drag begin event has actually been posted
  532. if (!dragElementsConfirmed_.Empty())
  533. return dragElementsConfirmed_;
  534. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End(); )
  535. {
  536. WeakPtr<UIElement> dragElement = i->first_;
  537. UI::DragData* dragData = i->second_;
  538. if (!dragElement)
  539. {
  540. i = dragElementErase(i);
  541. continue;
  542. }
  543. if (!dragData->dragBeginPending)
  544. dragElementsConfirmed_.Push(dragElement);
  545. ++i;
  546. }
  547. return dragElementsConfirmed_;
  548. }
  549. UIElement* UI::GetDragElement(unsigned index)
  550. {
  551. GetDragElements();
  552. if (index >= dragElementsConfirmed_.Size())
  553. return (UIElement*)0;
  554. return dragElementsConfirmed_[index];
  555. }
  556. const String& UI::GetClipboardText() const
  557. {
  558. if (useSystemClipboard_)
  559. {
  560. char* text = SDL_GetClipboardText();
  561. clipBoard_ = String(text);
  562. if (text)
  563. SDL_free(text);
  564. }
  565. return clipBoard_;
  566. }
  567. bool UI::HasModalElement() const
  568. {
  569. return rootModalElement_->GetNumChildren() > 0;
  570. }
  571. void UI::Initialize()
  572. {
  573. Graphics* graphics = GetSubsystem<Graphics>();
  574. if (!graphics || !graphics->IsInitialized())
  575. return;
  576. PROFILE(InitUI);
  577. graphics_ = graphics;
  578. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  579. rootModalElement_->SetSize(rootElement_->GetSize());
  580. vertexBuffer_ = new VertexBuffer(context_);
  581. debugVertexBuffer_ = new VertexBuffer(context_);
  582. initialized_ = true;
  583. SubscribeToEvent(E_BEGINFRAME, HANDLER(UI, HandleBeginFrame));
  584. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  585. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  586. LOGINFO("Initialized user interface");
  587. }
  588. void UI::Update(float timeStep, UIElement* element)
  589. {
  590. // Keep a weak pointer to the element in case it destroys itself on update
  591. WeakPtr<UIElement> elementWeak(element);
  592. element->Update(timeStep);
  593. if (elementWeak.Expired())
  594. return;
  595. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  596. // Update of an element may modify its child vector. Use just index-based iteration to be safe
  597. for (unsigned i = 0; i < children.Size(); ++i)
  598. Update(timeStep, children[i]);
  599. }
  600. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  601. {
  602. if (vertexData.Empty())
  603. return;
  604. // Update quad geometry into the vertex buffer
  605. // Resize the vertex buffer first if too small or much too large
  606. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  607. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  608. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  609. dest->SetData(&vertexData[0]);
  610. }
  611. void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  612. {
  613. // Engine does not render when window is closed or device is lost
  614. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  615. if (batches.Empty())
  616. return;
  617. Vector2 invScreenSize(1.0f / (float)graphics_->GetWidth(), 1.0f / (float)graphics_->GetHeight());
  618. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  619. Vector2 offset(-1.0f, 1.0f);
  620. Matrix4 projection(Matrix4::IDENTITY);
  621. projection.m00_ = scale.x_;
  622. projection.m03_ = offset.x_;
  623. projection.m11_ = scale.y_;
  624. projection.m13_ = offset.y_;
  625. projection.m22_ = 1.0f;
  626. projection.m23_ = 0.0f;
  627. projection.m33_ = 1.0f;
  628. graphics_->ClearParameterSources();
  629. graphics_->SetCullMode(CULL_CCW);
  630. graphics_->SetDepthTest(CMP_ALWAYS);
  631. graphics_->SetDepthWrite(false);
  632. graphics_->SetDrawAntialiased(false);
  633. graphics_->SetStencilTest(false);
  634. graphics_->ResetRenderTargets();
  635. graphics_->SetVertexBuffer(buffer);
  636. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  637. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  638. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  639. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  640. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  641. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  642. unsigned alphaFormat = Graphics::GetAlphaFormat();
  643. for (unsigned i = batchStart; i < batchEnd; ++i)
  644. {
  645. const UIBatch& batch = batches[i];
  646. if (batch.vertexStart_ == batch.vertexEnd_)
  647. continue;
  648. ShaderVariation* ps;
  649. ShaderVariation* vs;
  650. if (!batch.texture_)
  651. {
  652. ps = noTexturePS;
  653. vs = noTextureVS;
  654. }
  655. else
  656. {
  657. // If texture contains only an alpha channel, use alpha shader (for fonts)
  658. vs = diffTextureVS;
  659. if (batch.texture_->GetFormat() == alphaFormat)
  660. ps = alphaTexturePS;
  661. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  662. ps = diffMaskTexturePS;
  663. else
  664. ps = diffTexturePS;
  665. }
  666. graphics_->SetShaders(vs, ps);
  667. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  668. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  669. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  670. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  671. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  672. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  673. graphics_->SetBlendMode(batch.blendMode_);
  674. graphics_->SetScissorTest(true, batch.scissor_);
  675. graphics_->SetTexture(0, batch.texture_);
  676. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  677. UI_VERTEX_SIZE);
  678. }
  679. }
  680. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  681. {
  682. // Set clipping scissor for child elements. No need to draw if zero size
  683. element->AdjustScissor(currentScissor);
  684. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  685. return;
  686. element->SortChildren();
  687. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  688. if (children.Empty())
  689. return;
  690. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  691. // same renderstate
  692. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  693. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  694. {
  695. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  696. while (i != children.End())
  697. {
  698. int currentPriority = (*i)->GetPriority();
  699. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  700. {
  701. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  702. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  703. ++j;
  704. }
  705. // Now recurse into the children
  706. while (i != j)
  707. {
  708. if ((*i)->IsVisible() && (*i) != cursor_)
  709. GetBatches(*i, currentScissor);
  710. ++i;
  711. }
  712. }
  713. }
  714. // On the root level draw each element and its children immediately after to avoid artifacts
  715. else
  716. {
  717. while (i != children.End())
  718. {
  719. if ((*i) != cursor_)
  720. {
  721. if ((*i)->IsWithinScissor(currentScissor))
  722. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  723. if ((*i)->IsVisible())
  724. GetBatches(*i, currentScissor);
  725. }
  726. ++i;
  727. }
  728. }
  729. }
  730. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  731. {
  732. if (!current)
  733. return;
  734. current->SortChildren();
  735. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  736. LayoutMode parentLayoutMode = current->GetLayoutMode();
  737. for (unsigned i = 0; i < children.Size(); ++i)
  738. {
  739. UIElement* element = children[i];
  740. bool hasChildren = element->GetNumChildren() > 0;
  741. if (element != cursor_.Get() && element->IsVisible())
  742. {
  743. if (element->IsInside(position, true))
  744. {
  745. // Store the current result, then recurse into its children. Because children
  746. // are sorted from lowest to highest priority, the topmost match should remain
  747. if (element->IsEnabled() || !enabledOnly)
  748. result = element;
  749. if (hasChildren)
  750. GetElementAt(result, element, position, enabledOnly);
  751. // Layout optimization: if the element has no children, can break out after the first match
  752. else if (parentLayoutMode != LM_FREE)
  753. break;
  754. }
  755. else
  756. {
  757. if (hasChildren)
  758. {
  759. if (element->IsInsideCombined(position, true))
  760. GetElementAt(result, element, position, enabledOnly);
  761. }
  762. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  763. // or if we already passed all visible elements
  764. else if (parentLayoutMode != LM_FREE)
  765. {
  766. if (!i)
  767. {
  768. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  769. element->GetScreenPosition().y_;
  770. int layoutMaxSize = current->GetLayoutMaxSize();
  771. if (screenPos < 0 && layoutMaxSize > 0)
  772. {
  773. unsigned toSkip = -screenPos / layoutMaxSize;
  774. if (toSkip > 0)
  775. i += (toSkip - 1);
  776. }
  777. }
  778. else if (parentLayoutMode == LM_HORIZONTAL)
  779. {
  780. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  781. break;
  782. }
  783. else if (parentLayoutMode == LM_VERTICAL)
  784. {
  785. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  786. break;
  787. }
  788. }
  789. }
  790. }
  791. }
  792. }
  793. UIElement* UI::GetFocusableElement(UIElement* element)
  794. {
  795. while (element)
  796. {
  797. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  798. break;
  799. element = element->GetParent();
  800. }
  801. return element;
  802. }
  803. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  804. {
  805. // Prefer software cursor then OS-specific cursor
  806. if (cursor_ && cursor_->IsVisible())
  807. {
  808. pos = cursor_->GetPosition();
  809. visible = true;
  810. }
  811. else if (GetSubsystem<Input>()->GetMouseMode() == MM_RELATIVE)
  812. visible = true;
  813. else
  814. {
  815. Input* input = GetSubsystem<Input>();
  816. pos = input->GetMousePosition();
  817. visible = input->IsMouseVisible();
  818. if (!visible && cursor_)
  819. pos = cursor_->GetPosition();
  820. }
  821. }
  822. void UI::SetCursorShape(CursorShape shape)
  823. {
  824. if (cursor_)
  825. cursor_->SetShape(shape);
  826. }
  827. void UI::ReleaseFontFaces()
  828. {
  829. LOGDEBUG("Reloading font faces");
  830. PODVector<Font*> fonts;
  831. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  832. for (unsigned i = 0; i < fonts.Size(); ++i)
  833. fonts[i]->ReleaseFaces();
  834. }
  835. void UI::ProcessHover(const IntVector2& cursorPos, int buttons, int qualifiers, Cursor* cursor)
  836. {
  837. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  838. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  839. {
  840. WeakPtr<UIElement> dragElement = i->first_;
  841. UI::DragData* dragData = i->second_;
  842. if (!dragElement)
  843. {
  844. i = dragElementErase(i);
  845. continue;
  846. }
  847. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE) != 0;
  848. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  849. bool dragDropTest = dragSource && dragTarget && element != dragElement;
  850. // If drag start event has not been posted yet, do not do drag handling here
  851. if (dragData->dragBeginPending)
  852. dragSource = dragTarget = dragDropTest = false;
  853. // Hover effect
  854. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  855. if (element && element->IsEnabled())
  856. {
  857. if (dragElement == element || dragDropTest)
  858. {
  859. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  860. // Begin hover event
  861. if (!hoveredElements_.Contains(element))
  862. {
  863. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, 0);
  864. // Exit if element is destroyed by the event handling
  865. if (!element)
  866. return;
  867. }
  868. hoveredElements_[element] = true;
  869. }
  870. }
  871. // Drag and drop test
  872. if (dragDropTest)
  873. {
  874. bool accept = element->OnDragDropTest(dragElement);
  875. if (accept)
  876. {
  877. using namespace DragDropTest;
  878. VariantMap& eventData = GetEventDataMap();
  879. eventData[P_SOURCE] = dragElement.Get();
  880. eventData[P_TARGET] = element.Get();
  881. eventData[P_ACCEPT] = accept;
  882. SendEvent(E_DRAGDROPTEST, eventData);
  883. accept = eventData[P_ACCEPT].GetBool();
  884. }
  885. if (cursor)
  886. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  887. }
  888. else if (dragSource && cursor)
  889. cursor->SetShape(dragElement == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  890. ++i;
  891. }
  892. // Hover effect
  893. // If no drag is going on, transmit hover event.
  894. if (element && element->IsEnabled())
  895. {
  896. if (dragElementsCount_ == 0)
  897. {
  898. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  899. // Begin hover event
  900. if (!hoveredElements_.Contains(element))
  901. {
  902. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, 0);
  903. // Exit if element is destroyed by the event handling
  904. if (!element)
  905. return;
  906. }
  907. hoveredElements_[element] = true;
  908. }
  909. }
  910. }
  911. void UI::ProcessClickBegin(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  912. {
  913. if (cursorVisible)
  914. {
  915. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  916. bool newButton;
  917. if (usingTouchInput_)
  918. newButton = (button & buttons) == 0;
  919. else
  920. newButton = true;
  921. buttons |= button;
  922. if (element)
  923. SetFocusElement (element);
  924. // Focus change events may destroy the element, check again.
  925. if (element)
  926. {
  927. // Handle focusing & bringing to front
  928. element->BringToFront();
  929. // Handle click
  930. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  931. SendClickEvent(E_UIMOUSECLICK, NULL, element, cursorPos, button, buttons, qualifiers);
  932. // Fire double click event if element matches and is in time
  933. if (doubleClickElement_ && element == doubleClickElement_ && clickTimer_.GetMSec(true) <
  934. (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
  935. {
  936. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  937. doubleClickElement_.Reset();
  938. SendClickEvent(E_UIMOUSEDOUBLECLICK, NULL, element, cursorPos, button, buttons, qualifiers);
  939. }
  940. else
  941. {
  942. doubleClickElement_ = element;
  943. clickTimer_.Reset();
  944. }
  945. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  946. bool dragElementsContain = dragElements_.Contains(element);
  947. if (element && !dragElementsContain)
  948. {
  949. DragData* dragData = new DragData();
  950. dragElements_[element] = dragData;
  951. dragData->dragBeginPending = true;
  952. dragData->sumPos = cursorPos;
  953. dragData->dragBeginSumPos = cursorPos;
  954. dragData->dragBeginTimer.Reset();
  955. dragData->dragButtons = button;
  956. dragData->numDragButtons = CountSetBits(dragData->dragButtons);
  957. dragElementsCount_++;
  958. dragElementsContain = dragElements_.Contains(element);
  959. }
  960. else if (element && dragElementsContain && newButton)
  961. {
  962. DragData* dragData = dragElements_[element];
  963. dragData->sumPos += cursorPos;
  964. dragData->dragBeginSumPos += cursorPos;
  965. dragData->dragButtons |= button;
  966. dragData->numDragButtons = CountSetBits(dragData->dragButtons);
  967. }
  968. }
  969. else
  970. {
  971. // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
  972. if (!HasModalElement())
  973. SetFocusElement(0);
  974. SendClickEvent(E_UIMOUSECLICK, NULL, element, cursorPos, button, buttons, qualifiers);
  975. }
  976. lastMouseButtons_ = buttons;
  977. }
  978. }
  979. void UI::ProcessClickEnd(const IntVector2& cursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  980. {
  981. if (cursorVisible)
  982. {
  983. WeakPtr<UIElement> element(GetElementAt(cursorPos));
  984. // Handle end of drag
  985. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  986. {
  987. WeakPtr<UIElement> dragElement = i->first_;
  988. UI::DragData* dragData = i->second_;
  989. if (!dragElement)
  990. {
  991. i = dragElementErase(i);
  992. continue;
  993. }
  994. if (dragData->dragButtons & button)
  995. {
  996. // Handle end of click
  997. if (element)
  998. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor, dragElement);
  999. SendClickEvent(E_UIMOUSECLICKEND, dragElement, element, cursorPos, button, buttons, qualifiers);
  1000. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1001. {
  1002. dragElement->OnDragEnd(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, buttons, cursor);
  1003. SendDragOrHoverEvent(E_DRAGEND, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1004. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE) != 0;
  1005. if (dragSource)
  1006. {
  1007. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  1008. bool dragDropFinish = dragSource && dragTarget && element != dragElement;
  1009. if (dragDropFinish)
  1010. {
  1011. bool accept = element->OnDragDropFinish(dragElement);
  1012. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  1013. if (accept && dragElement && element)
  1014. {
  1015. using namespace DragDropFinish;
  1016. VariantMap& eventData = GetEventDataMap();
  1017. eventData[P_SOURCE] = dragElement.Get();
  1018. eventData[P_TARGET] = element.Get();
  1019. eventData[P_ACCEPT] = accept;
  1020. SendEvent(E_DRAGDROPFINISH, eventData);
  1021. }
  1022. }
  1023. }
  1024. }
  1025. i = dragElementErase(i);
  1026. }
  1027. else
  1028. ++i;
  1029. }
  1030. }
  1031. }
  1032. void UI::ProcessMove(const IntVector2& cursorPos, const IntVector2& cursorDeltaPos, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
  1033. {
  1034. if (cursorVisible && dragElementsCount_ > 0 && buttons)
  1035. {
  1036. Input* input = GetSubsystem<Input>();
  1037. bool mouseGrabbed = input->IsMouseGrabbed();
  1038. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1039. {
  1040. WeakPtr<UIElement> dragElement = i->first_;
  1041. UI::DragData* dragData = i->second_;
  1042. if (!dragElement)
  1043. {
  1044. i = dragElementErase(i);
  1045. continue;
  1046. }
  1047. if (!(dragData->dragButtons & buttons))
  1048. {
  1049. ++i;
  1050. continue;
  1051. }
  1052. // Calculate the position that we should send for this drag event.
  1053. IntVector2 sendPos;
  1054. if (usingTouchInput_)
  1055. {
  1056. dragData->sumPos += cursorDeltaPos;
  1057. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1058. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1059. }
  1060. else
  1061. {
  1062. dragData->sumPos = cursorPos;
  1063. sendPos = cursorPos;
  1064. }
  1065. if (dragElement->IsEnabled() && dragElement->IsVisible())
  1066. {
  1067. // Signal drag begin if distance threshold was exceeded
  1068. if (dragData->dragBeginPending && !mouseGrabbed)
  1069. {
  1070. IntVector2 beginSendPos;
  1071. beginSendPos.x_ = dragData->dragBeginSumPos.x_ / dragData->numDragButtons;
  1072. beginSendPos.y_ = dragData->dragBeginSumPos.y_ / dragData->numDragButtons;
  1073. IntVector2 offset = cursorPos - beginSendPos;
  1074. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  1075. {
  1076. dragData->dragBeginPending = false;
  1077. dragConfirmedCount_ ++;
  1078. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, buttons, qualifiers, cursor);
  1079. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  1080. }
  1081. }
  1082. if (!dragData->dragBeginPending)
  1083. {
  1084. dragElement->OnDragMove(dragElement->ScreenToElement(sendPos), sendPos, cursorDeltaPos, buttons, qualifiers, cursor);
  1085. SendDragOrHoverEvent(E_DRAGMOVE, dragElement, sendPos, cursorDeltaPos, dragData);
  1086. }
  1087. }
  1088. else
  1089. {
  1090. dragElement->OnDragEnd(dragElement->ScreenToElement(sendPos), sendPos, dragData->dragButtons, buttons, cursor);
  1091. SendDragOrHoverEvent(E_DRAGEND, dragElement, sendPos, IntVector2::ZERO, dragData);
  1092. dragElement.Reset();
  1093. }
  1094. ++i;
  1095. }
  1096. }
  1097. }
  1098. void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos, const IntVector2& deltaPos, UI::DragData* dragData)
  1099. {
  1100. if (!element)
  1101. return;
  1102. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1103. using namespace DragMove;
  1104. VariantMap& eventData = GetEventDataMap();
  1105. eventData[P_ELEMENT] = element;
  1106. eventData[P_X] = screenPos.x_;
  1107. eventData[P_Y] = screenPos.y_;
  1108. eventData[P_ELEMENTX] = relativePos.x_;
  1109. eventData[P_ELEMENTY] = relativePos.y_;
  1110. if (eventType == E_DRAGMOVE)
  1111. {
  1112. eventData[P_DX] = deltaPos.x_;
  1113. eventData[P_DY] = deltaPos.y_;
  1114. }
  1115. if (dragData)
  1116. {
  1117. eventData[P_BUTTONS] = dragData->dragButtons;
  1118. eventData[P_NUMBUTTONS] = dragData->numDragButtons;
  1119. }
  1120. element->SendEvent(eventType, eventData);
  1121. }
  1122. void UI::SendClickEvent(StringHash eventType, UIElement* beginElement, UIElement* endElement, const IntVector2& pos, int button, int buttons, int qualifiers)
  1123. {
  1124. VariantMap& eventData = GetEventDataMap();
  1125. eventData[UIMouseClick::P_ELEMENT] = endElement;
  1126. eventData[UIMouseClick::P_X] = pos.x_;
  1127. eventData[UIMouseClick::P_Y] = pos.y_;
  1128. eventData[UIMouseClick::P_BUTTON] = button;
  1129. eventData[UIMouseClick::P_BUTTONS] = buttons;
  1130. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers;
  1131. // For click end events, send also the element the click began on
  1132. if (eventType == E_UIMOUSECLICKEND)
  1133. eventData[UIMouseClickEnd::P_BEGINELEMENT] = beginElement;
  1134. SendEvent(eventType, eventData);
  1135. }
  1136. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1137. {
  1138. using namespace ScreenMode;
  1139. if (!initialized_)
  1140. Initialize();
  1141. else
  1142. {
  1143. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  1144. rootModalElement_->SetSize(rootElement_->GetSize());
  1145. }
  1146. }
  1147. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  1148. {
  1149. using namespace MouseButtonDown;
  1150. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1151. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1152. usingTouchInput_ = false;
  1153. IntVector2 cursorPos;
  1154. bool cursorVisible;
  1155. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1156. // Handle drag cancelling
  1157. ProcessDragCancel();
  1158. Input* input = GetSubsystem<Input>();
  1159. if (!input->IsMouseGrabbed())
  1160. ProcessClickBegin(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1161. }
  1162. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  1163. {
  1164. using namespace MouseButtonUp;
  1165. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1166. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1167. IntVector2 cursorPos;
  1168. bool cursorVisible;
  1169. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1170. ProcessClickEnd(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1171. }
  1172. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  1173. {
  1174. using namespace MouseMove;
  1175. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1176. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1177. usingTouchInput_ = false;
  1178. Input* input = GetSubsystem<Input>();
  1179. const IntVector2& rootSize = rootElement_->GetSize();
  1180. IntVector2 DeltaP = IntVector2(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
  1181. if (cursor_)
  1182. {
  1183. if (!input->IsMouseVisible())
  1184. {
  1185. // Relative mouse motion: move cursor only when visible
  1186. if (cursor_->IsVisible())
  1187. {
  1188. IntVector2 pos = cursor_->GetPosition();
  1189. pos.x_ += eventData[P_DX].GetInt();
  1190. pos.y_ += eventData[P_DY].GetInt();
  1191. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  1192. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  1193. cursor_->SetPosition(pos);
  1194. }
  1195. }
  1196. else
  1197. {
  1198. // Absolute mouse motion: move always
  1199. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  1200. }
  1201. }
  1202. IntVector2 cursorPos;
  1203. bool cursorVisible;
  1204. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1205. ProcessMove(cursorPos, DeltaP, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1206. }
  1207. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1208. {
  1209. Input* input = GetSubsystem<Input>();
  1210. if (input->IsMouseGrabbed())
  1211. return;
  1212. using namespace MouseWheel;
  1213. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1214. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1215. int delta = eventData[P_WHEEL].GetInt();
  1216. usingTouchInput_ = false;
  1217. IntVector2 cursorPos;
  1218. bool cursorVisible;
  1219. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1220. UIElement* element;
  1221. if (!nonFocusedMouseWheel_&& (element = focusElement_))
  1222. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1223. else
  1224. {
  1225. // If no element has actual focus or in non-focused mode, get the element at cursor
  1226. if (cursorVisible)
  1227. {
  1228. element = GetElementAt(cursorPos);
  1229. if (nonFocusedMouseWheel_)
  1230. {
  1231. // Going up the hierarchy chain to find element that could handle mouse wheel
  1232. while (element)
  1233. {
  1234. if (element->GetType() == ListView::GetTypeStatic() ||
  1235. element->GetType() == ScrollView::GetTypeStatic())
  1236. break;
  1237. element = element->GetParent();
  1238. }
  1239. }
  1240. else
  1241. // If the element itself is not focusable, search for a focusable parent,
  1242. // although the focusable element may not actually handle mouse wheel
  1243. element = GetFocusableElement(element);
  1244. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1245. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1246. }
  1247. }
  1248. }
  1249. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1250. {
  1251. Input* input = GetSubsystem<Input>();
  1252. if (input->IsMouseGrabbed())
  1253. return;
  1254. using namespace TouchBegin;
  1255. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1256. usingTouchInput_ = true;
  1257. int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
  1258. WeakPtr<UIElement> element(GetElementAt(pos));
  1259. if (element)
  1260. {
  1261. ProcessClickBegin(pos, touchId, touchDragElements_[element], 0, 0, true);
  1262. touchDragElements_[element] |= touchId;
  1263. }
  1264. else
  1265. ProcessClickBegin(pos, touchId, touchId, 0, 0, true);
  1266. }
  1267. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1268. {
  1269. using namespace TouchEnd;
  1270. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1271. // Get the touch index
  1272. int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
  1273. // Transmit hover end to the position where the finger was lifted
  1274. WeakPtr<UIElement> element(GetElementAt(pos));
  1275. // Clear any drag events that were using the touch id
  1276. for (HashMap<WeakPtr<UIElement>, int>::Iterator i = touchDragElements_.Begin(); i != touchDragElements_.End(); )
  1277. {
  1278. int touches = i->second_;
  1279. if (touches & touchId)
  1280. i = touchDragElements_.Erase(i);
  1281. else
  1282. ++i;
  1283. }
  1284. if (element && element->IsEnabled())
  1285. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  1286. ProcessClickEnd(pos, touchId, 0, 0, 0, true);
  1287. }
  1288. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1289. {
  1290. using namespace TouchMove;
  1291. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1292. IntVector2 deltaPos(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
  1293. usingTouchInput_ = true;
  1294. int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
  1295. ProcessMove(pos, deltaPos, touchId, 0, 0, true);
  1296. }
  1297. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1298. {
  1299. using namespace KeyDown;
  1300. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1301. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1302. int key = eventData[P_KEY].GetInt();
  1303. // Cancel UI dragging
  1304. if (key == KEY_ESC && dragElementsCount_ > 0)
  1305. {
  1306. ProcessDragCancel();
  1307. return;
  1308. }
  1309. // Dismiss modal element if any when ESC key is pressed
  1310. if (key == KEY_ESC && HasModalElement())
  1311. {
  1312. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1313. if (element->GetVars().Contains(VAR_ORIGIN))
  1314. // If it is a popup, dismiss by defocusing it
  1315. SetFocusElement(0);
  1316. else
  1317. {
  1318. // If it is a modal window, by resetting its modal flag
  1319. Window* window = dynamic_cast<Window*>(element);
  1320. if (window && window->GetModalAutoDismiss())
  1321. window->SetModal(false);
  1322. }
  1323. return;
  1324. }
  1325. UIElement* element = focusElement_;
  1326. if (element)
  1327. {
  1328. // Switch focus between focusable elements in the same top level window
  1329. if (key == KEY_TAB)
  1330. {
  1331. UIElement* topLevel = element->GetParent();
  1332. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1333. topLevel = topLevel->GetParent();
  1334. if (topLevel)
  1335. {
  1336. topLevel->GetChildren(tempElements_, true);
  1337. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1338. {
  1339. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1340. i = tempElements_.Erase(i);
  1341. else
  1342. ++i;
  1343. }
  1344. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1345. {
  1346. if (tempElements_[i] == element)
  1347. {
  1348. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1349. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1350. UIElement* next = tempElements_[nextIndex];
  1351. SetFocusElement(next, true);
  1352. return;
  1353. }
  1354. }
  1355. }
  1356. }
  1357. // Defocus the element
  1358. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1359. element->SetFocus(false);
  1360. // If none of the special keys, pass the key to the focused element
  1361. else
  1362. element->OnKey(key, mouseButtons_, qualifiers_);
  1363. }
  1364. }
  1365. void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
  1366. {
  1367. using namespace TextInput;
  1368. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  1369. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  1370. UIElement* element = focusElement_;
  1371. if (element)
  1372. element->OnTextInput(eventData[P_TEXT].GetString(), mouseButtons_, qualifiers_);
  1373. }
  1374. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1375. {
  1376. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1377. // custom shapes can do it after this, but needs to do it each frame
  1378. if (cursor_ && dragElementsCount_ == 0)
  1379. cursor_->SetShape(CS_NORMAL);
  1380. }
  1381. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1382. {
  1383. using namespace PostUpdate;
  1384. Update(eventData[P_TIMESTEP].GetFloat());
  1385. }
  1386. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1387. {
  1388. RenderUpdate();
  1389. }
  1390. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1391. {
  1392. Input* input = GetSubsystem<Input>();
  1393. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1394. if (input->IsMouseVisible())
  1395. {
  1396. IntVector2 screenPos = input->GetMousePosition();
  1397. UIElement* element = GetElementAt(screenPos);
  1398. using namespace UIDropFile;
  1399. VariantMap uiEventData;
  1400. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1401. uiEventData[P_X] = screenPos.x_;
  1402. uiEventData[P_Y] = screenPos.y_;
  1403. uiEventData[P_ELEMENT] = element;
  1404. if (element)
  1405. {
  1406. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1407. uiEventData[P_ELEMENTX] = relativePos.x_;
  1408. uiEventData[P_ELEMENTY] = relativePos.y_;
  1409. }
  1410. SendEvent(E_UIDROPFILE, uiEventData);
  1411. }
  1412. }
  1413. HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator UI::dragElementErase(HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i)
  1414. {
  1415. dragElementsConfirmed_.Clear();
  1416. WeakPtr<UIElement> dragElement = i->first_;
  1417. DragData* dragData = i->second_;
  1418. if (!dragData->dragBeginPending)
  1419. dragConfirmedCount_ --;
  1420. i = dragElements_.Erase(i);
  1421. dragElementsCount_ --;
  1422. delete dragData;
  1423. return i;
  1424. }
  1425. void UI::ProcessDragCancel()
  1426. {
  1427. // How to tell difference between drag cancel and new selection on multi-touch?
  1428. if (usingTouchInput_)
  1429. return;
  1430. IntVector2 cursorPos;
  1431. bool cursorVisible;
  1432. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1433. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1434. {
  1435. WeakPtr<UIElement> dragElement = i->first_;
  1436. UI::DragData* dragData = i->second_;
  1437. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1438. {
  1439. dragElement->OnDragCancel(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, mouseButtons_, cursor_);
  1440. SendDragOrHoverEvent(E_DRAGCANCEL, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1441. i = dragElementErase(i);
  1442. }
  1443. else
  1444. ++i;
  1445. }
  1446. }
  1447. IntVector2 UI::SumTouchPositions(UI::DragData* dragData, const IntVector2& oldSendPos)
  1448. {
  1449. IntVector2 sendPos = oldSendPos;
  1450. if (usingTouchInput_)
  1451. {
  1452. int buttons = dragData->dragButtons;
  1453. dragData->sumPos = IntVector2::ZERO;
  1454. Input* input = GetSubsystem<Input>();
  1455. for (int i = 0; (1 << i) <= buttons; i++)
  1456. {
  1457. if ((1 << i) & buttons)
  1458. {
  1459. TouchState* ts = input->GetTouch(i);
  1460. if (!ts)
  1461. break;
  1462. IntVector2 pos = ts->position_;
  1463. dragData->sumPos.x_ += pos.x_;
  1464. dragData->sumPos.y_ += pos.y_;
  1465. }
  1466. }
  1467. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1468. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1469. }
  1470. return sendPos;
  1471. }
  1472. void RegisterUILibrary(Context* context)
  1473. {
  1474. Font::RegisterObject(context);
  1475. UIElement::RegisterObject(context);
  1476. BorderImage::RegisterObject(context);
  1477. Sprite::RegisterObject(context);
  1478. Button::RegisterObject(context);
  1479. CheckBox::RegisterObject(context);
  1480. Cursor::RegisterObject(context);
  1481. Text::RegisterObject(context);
  1482. Text3D::RegisterObject(context);
  1483. Window::RegisterObject(context);
  1484. View3D::RegisterObject(context);
  1485. LineEdit::RegisterObject(context);
  1486. Slider::RegisterObject(context);
  1487. ScrollBar::RegisterObject(context);
  1488. ScrollView::RegisterObject(context);
  1489. ListView::RegisterObject(context);
  1490. Menu::RegisterObject(context);
  1491. DropDownList::RegisterObject(context);
  1492. FileSelector::RegisterObject(context);
  1493. MessageBox::RegisterObject(context);
  1494. ToolTip::RegisterObject(context);
  1495. }
  1496. }