UIElement.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. //
  2. // Copyright (c) 2008-2020 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. /// \file
  23. #pragma once
  24. #include "../Math/Vector2.h"
  25. #include "../Input/InputConstants.h"
  26. #include "../Resource/XMLFile.h"
  27. #include "../Scene/Animatable.h"
  28. #include "../UI/UIBatch.h"
  29. namespace Urho3D
  30. {
  31. /// %UI element horizontal alignment.
  32. enum HorizontalAlignment
  33. {
  34. HA_LEFT = 0,
  35. HA_CENTER,
  36. HA_RIGHT,
  37. HA_CUSTOM
  38. };
  39. /// %UI element vertical alignment.
  40. enum VerticalAlignment
  41. {
  42. VA_TOP = 0,
  43. VA_CENTER,
  44. VA_BOTTOM,
  45. VA_CUSTOM
  46. };
  47. /// %UI element corners.
  48. enum Corner
  49. {
  50. C_TOPLEFT = 0,
  51. C_TOPRIGHT,
  52. C_BOTTOMLEFT,
  53. C_BOTTOMRIGHT,
  54. MAX_UIELEMENT_CORNERS
  55. };
  56. /// %UI element orientation.
  57. enum Orientation
  58. {
  59. O_HORIZONTAL = 0,
  60. O_VERTICAL
  61. };
  62. /// %UI element focus mode.
  63. enum FocusMode
  64. {
  65. /// Is not focusable and does not affect existing focus.
  66. FM_NOTFOCUSABLE = 0,
  67. /// Resets focus when clicked.
  68. FM_RESETFOCUS,
  69. /// Is focusable.
  70. FM_FOCUSABLE,
  71. /// Is focusable and also defocusable by pressing ESC.
  72. FM_FOCUSABLE_DEFOCUSABLE
  73. };
  74. /// Layout operation mode.
  75. enum LayoutMode
  76. {
  77. /// No layout operations will be performed.
  78. LM_FREE = 0,
  79. /// Layout child elements horizontally and resize them to fit. Resize element if necessary.
  80. LM_HORIZONTAL,
  81. /// Layout child elements vertically and resize them to fit. Resize element if necessary.
  82. LM_VERTICAL
  83. };
  84. /// Traversal mode for rendering.
  85. enum TraversalMode
  86. {
  87. /// Traverse through children having same priority first and recurse into their children before traversing children having higher priority.
  88. TM_BREADTH_FIRST = 0,
  89. /// Traverse through each child and its children immediately after in sequence.
  90. TM_DEPTH_FIRST
  91. };
  92. enum DragAndDropMode : unsigned
  93. {
  94. /// Drag and drop disabled.
  95. DD_DISABLED = 0x0,
  96. /// Drag and drop source flag.
  97. DD_SOURCE = 0x1,
  98. /// Drag and drop target flag.
  99. DD_TARGET = 0x2,
  100. /// Drag and drop source and target.
  101. DD_SOURCE_AND_TARGET = 0x3,
  102. };
  103. URHO3D_FLAGSET(DragAndDropMode, DragAndDropModeFlags);
  104. class Cursor;
  105. class ResourceCache;
  106. class Texture2D;
  107. /// Base class for %UI elements.
  108. class URHO3D_API UIElement : public Animatable
  109. {
  110. URHO3D_OBJECT(UIElement, Animatable);
  111. public:
  112. /// Construct.
  113. explicit UIElement(Context* context);
  114. /// Destruct.
  115. ~UIElement() override;
  116. /// Register object factory.
  117. static void RegisterObject(Context* context);
  118. /// Apply attribute changes that can not be applied immediately.
  119. void ApplyAttributes() override;
  120. /// Load from XML data. Return true if successful.
  121. bool LoadXML(const XMLElement& source) override;
  122. /// Load from XML data with style. Return true if successful.
  123. virtual bool LoadXML(const XMLElement& source, XMLFile* styleFile);
  124. /// Create a child by loading from XML data with style. Returns the child element if successful, null if otherwise.
  125. virtual UIElement* LoadChildXML(const XMLElement& childElem, XMLFile* styleFile);
  126. /// Save as XML data. Return true if successful.
  127. bool SaveXML(XMLElement& dest) const override;
  128. /// Perform UI element update.
  129. virtual void Update(float timeStep);
  130. /// Return whether is visible and inside a scissor rectangle and should be rendered.
  131. virtual bool IsWithinScissor(const IntRect& currentScissor);
  132. /// Update and return screen position.
  133. /// @property
  134. virtual const IntVector2& GetScreenPosition() const;
  135. /// Return UI rendering batches.
  136. virtual void GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor);
  137. /// Return UI rendering batches for debug draw.
  138. virtual void GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor);
  139. /// React to mouse hover.
  140. virtual void OnHover(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor);
  141. /// React to mouse click begin.
  142. virtual void OnClickBegin
  143. (const IntVector2& position, const IntVector2& screenPosition, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor) { }
  144. /// React to mouse click end.
  145. virtual void OnClickEnd
  146. (const IntVector2& position, const IntVector2& screenPosition, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor,
  147. UIElement* beginElement) { }
  148. /// React to double mouse click.
  149. virtual void OnDoubleClick
  150. (const IntVector2& position, const IntVector2& screenPosition, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor) { }
  151. /// React to mouse drag begin.
  152. virtual void
  153. OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor);
  154. /// React to mouse drag motion.
  155. virtual void OnDragMove
  156. (const IntVector2& position, const IntVector2& screenPosition, const IntVector2& deltaPos, MouseButtonFlags buttons, QualifierFlags qualifiers,
  157. Cursor* cursor);
  158. /// React to mouse drag end.
  159. virtual void
  160. OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags dragButtons, MouseButtonFlags releaseButtons, Cursor* cursor);
  161. /// React to a mouse drag cancel event (ie, when an extra button is pressed).
  162. virtual void OnDragCancel
  163. (const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags dragButtons, MouseButtonFlags cancelButtons, Cursor* cursor);
  164. /// React to drag and drop test. Return true to signal that the drop is acceptable.
  165. virtual bool OnDragDropTest(UIElement* source);
  166. /// React to drag and drop finish. Return true to signal that the drop was accepted.
  167. virtual bool OnDragDropFinish(UIElement* source);
  168. /// React to mouse wheel.
  169. virtual void OnWheel(int delta, MouseButtonFlags buttons, QualifierFlags qualifiers) { }
  170. /// React to a key press.
  171. virtual void OnKey(Key key, MouseButtonFlags buttons, QualifierFlags qualifiers) { }
  172. /// React to text input event.
  173. virtual void OnTextInput(const String& text) { }
  174. /// React to resize.
  175. virtual void OnResize(const IntVector2& newSize, const IntVector2& delta) { }
  176. /// React to position change.
  177. virtual void OnPositionSet(const IntVector2& newPosition) { }
  178. /// React to editable status change.
  179. virtual void OnSetEditable() { }
  180. /// React to indent change.
  181. virtual void OnIndentSet() { }
  182. /// Convert screen coordinates to element coordinates.
  183. virtual IntVector2 ScreenToElement(const IntVector2& screenPosition);
  184. /// Convert element coordinates to screen coordinates.
  185. virtual IntVector2 ElementToScreen(const IntVector2& position);
  186. /// Return whether the element could handle wheel input.
  187. virtual bool IsWheelHandler() const { return false; }
  188. /// Load from an XML file. Return true if successful.
  189. bool LoadXML(Deserializer& source);
  190. /// Save to an XML file. Return true if successful.
  191. bool SaveXML(Serializer& dest, const String& indentation = "\t") const;
  192. /// Filter attributes in serialization process.
  193. bool FilterAttributes(XMLElement& dest) const;
  194. /// Set name.
  195. /// @property
  196. void SetName(const String& name);
  197. /// Set position.
  198. /// @property
  199. void SetPosition(const IntVector2& position);
  200. /// Set position.
  201. void SetPosition(int x, int y);
  202. /// Set size.
  203. /// @property
  204. void SetSize(const IntVector2& size);
  205. /// Set size.
  206. void SetSize(int width, int height);
  207. /// Set width only.
  208. /// @property
  209. void SetWidth(int width);
  210. /// Set height only.
  211. /// @property
  212. void SetHeight(int height);
  213. /// Set minimum size.
  214. /// @property
  215. void SetMinSize(const IntVector2& minSize);
  216. /// Set minimum size.
  217. void SetMinSize(int width, int height);
  218. /// Set minimum width.
  219. /// @property
  220. void SetMinWidth(int width);
  221. /// Set minimum height.
  222. /// @property
  223. void SetMinHeight(int height);
  224. /// Set maximum size.
  225. /// @property
  226. void SetMaxSize(const IntVector2& maxSize);
  227. /// Set maximum size.
  228. void SetMaxSize(int width, int height);
  229. /// Set maximum width.
  230. /// @property
  231. void SetMaxWidth(int width);
  232. /// Set maximum height.
  233. /// @property
  234. void SetMaxHeight(int height);
  235. /// Set fixed size.
  236. void SetFixedSize(const IntVector2& size);
  237. /// Set fixed size.
  238. void SetFixedSize(int width, int height);
  239. /// Set fixed width.
  240. void SetFixedWidth(int width);
  241. /// Set fixed height.
  242. void SetFixedHeight(int height);
  243. /// Set horizontal and vertical alignment.
  244. void SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign);
  245. /// Set horizontal alignment.
  246. /// @property
  247. void SetHorizontalAlignment(HorizontalAlignment align);
  248. /// Set vertical alignment.
  249. /// @property
  250. void SetVerticalAlignment(VerticalAlignment align);
  251. /// Enable automatic positioning & sizing of the element relative to its parent using min/max anchor and min/max offset. Default false.
  252. /// @property
  253. void SetEnableAnchor(bool enable);
  254. /// Set minimum (top left) anchor in relation to the parent element (from 0 to 1). No effect when anchor is not enabled.
  255. /// @property
  256. void SetMinAnchor(const Vector2& anchor);
  257. /// Set minimum anchor.
  258. void SetMinAnchor(float x, float y);
  259. /// Set maximum (bottom right) anchor in relation to the parent element (from 0 to 1). No effect when anchor is not enabled.
  260. /// @property
  261. void SetMaxAnchor(const Vector2& anchor);
  262. /// Set maximum anchor.
  263. void SetMaxAnchor(float x, float y);
  264. /// Set offset of element's top left from the minimum anchor in pixels. No effect when anchor is not enabled.
  265. /// @property
  266. void SetMinOffset(const IntVector2& offset);
  267. /// Set offset of element's bottom right from the maximum anchor in pixels. No effect when anchor is not enabled.
  268. /// @property
  269. void SetMaxOffset(const IntVector2& offset);
  270. /// Set pivot relative to element's size (from 0 to 1, where 0.5 is center). Overrides horizontal & vertical alignment.
  271. /// @property
  272. void SetPivot(const Vector2& pivot);
  273. /// Set pivot relative to element's size (from 0 to 1, where 0.5 is center). Overrides horizontal & vertical alignment.
  274. void SetPivot(float x, float y);
  275. /// Set child element clipping border.
  276. /// @property
  277. void SetClipBorder(const IntRect& rect);
  278. /// Set color on all corners.
  279. /// @property
  280. void SetColor(const Color& color);
  281. /// Set color on one corner.
  282. /// @property{set_colors}
  283. void SetColor(Corner corner, const Color& color);
  284. /// Set priority.
  285. /// @property
  286. void SetPriority(int priority);
  287. /// Set opacity.
  288. /// @property
  289. void SetOpacity(float opacity);
  290. /// Set whether should be brought to front when focused.
  291. /// @property
  292. void SetBringToFront(bool enable);
  293. /// Set whether should be put to background when another element is focused.
  294. /// @property
  295. void SetBringToBack(bool enable);
  296. /// Set whether should clip child elements. Default false.
  297. /// @property
  298. void SetClipChildren(bool enable);
  299. /// Set whether should sort child elements according to priority. Default true.
  300. /// @property
  301. void SetSortChildren(bool enable);
  302. /// Set whether parent elements' opacity affects opacity. Default true.
  303. /// @property
  304. void SetUseDerivedOpacity(bool enable);
  305. /// Set whether reacts to input. Default false, but is enabled by subclasses if applicable.
  306. /// @property
  307. void SetEnabled(bool enable);
  308. /// Set enabled state on self and child elements. Elements' own enabled state is remembered (IsEnabledSelf) and can be restored.
  309. void SetDeepEnabled(bool enable);
  310. /// Reset enabled state to the element's remembered state prior to calling SetDeepEnabled.
  311. void ResetDeepEnabled();
  312. /// Set enabled state on self and child elements. Unlike SetDeepEnabled this does not remember the elements' own enabled state, but overwrites it.
  313. void SetEnabledRecursive(bool enable);
  314. /// Set whether value is editable through input. Not applicable to all elements. Default true.
  315. /// @property
  316. void SetEditable(bool enable);
  317. /// Set whether is focused. Only one element can be focused at a time.
  318. /// @property
  319. void SetFocus(bool enable);
  320. /// Set selected mode. Actual meaning is element dependent, for example constant hover or pressed effect.
  321. /// @property
  322. void SetSelected(bool enable);
  323. /// Set whether is visible. Visibility propagates to child elements.
  324. /// @property
  325. void SetVisible(bool enable);
  326. /// Set focus mode.
  327. /// @property
  328. void SetFocusMode(FocusMode mode);
  329. /// Set drag and drop flags.
  330. /// @property
  331. void SetDragDropMode(DragAndDropModeFlags mode);
  332. /// Set style from an XML file. Find the style element by name. If the style file is not explicitly provided, use the default style from parental chain. Return true if the style is applied successfully. See also \ref UI_Programmatic.
  333. bool SetStyle(const String& styleName, XMLFile* file = nullptr);
  334. /// Set style from an XML element. Return true if the style is applied successfully.
  335. bool SetStyle(const XMLElement& element);
  336. /// Set style from an XML file. Find the style element automatically by using the element's typename. If the style file is not explicitly provided, use the default style from parental chain. Return true if the style is applied successfully. See also \ref UI_Programmatic.
  337. bool SetStyleAuto(XMLFile* file = nullptr);
  338. /// Set default style file for later use by children elements.
  339. /// @property
  340. void SetDefaultStyle(XMLFile* style);
  341. /// Set layout parameters.
  342. void SetLayout(LayoutMode mode, int spacing = 0, const IntRect& border = IntRect::ZERO);
  343. /// Set layout mode only.
  344. /// @property
  345. void SetLayoutMode(LayoutMode mode);
  346. /// Set layout spacing.
  347. /// @property
  348. void SetLayoutSpacing(int spacing);
  349. /// Set layout border.
  350. /// @property
  351. void SetLayoutBorder(const IntRect& border);
  352. /// Set layout flex scale.
  353. /// @property
  354. void SetLayoutFlexScale(const Vector2& scale);
  355. /// Set horizontal indentation.
  356. /// @property
  357. void SetIndent(int indent);
  358. /// Set indent spacing (number of pixels per indentation level).
  359. /// @property
  360. void SetIndentSpacing(int indentSpacing);
  361. /// Manually update layout. Should not be necessary in most cases, but is provided for completeness.
  362. void UpdateLayout();
  363. /// Disable automatic layout update. Should only be used if there are performance problems.
  364. void DisableLayoutUpdate();
  365. /// Enable automatic layout update.
  366. void EnableLayoutUpdate();
  367. /// Bring UI element to front.
  368. void BringToFront();
  369. /// Create and add a child element and return it.
  370. UIElement* CreateChild(StringHash type, const String& name = String::EMPTY, unsigned index = M_MAX_UNSIGNED);
  371. /// Add a child element.
  372. void AddChild(UIElement* element);
  373. /// Insert a child element into a specific position in the child list.
  374. void InsertChild(unsigned index, UIElement* element);
  375. /// Remove a child element. Starting search at specified index if provided.
  376. void RemoveChild(UIElement* element, unsigned index = 0);
  377. /// Remove a child element at index.
  378. void RemoveChildAtIndex(unsigned index);
  379. /// Remove all child elements.
  380. void RemoveAllChildren();
  381. /// Remove from the parent element. If no other shared pointer references exist, causes immediate deletion.
  382. void Remove();
  383. /// Find child index. Return M_MAX_UNSIGNED if not found.
  384. unsigned FindChild(UIElement* element) const;
  385. /// Set parent element. Same as parent->InsertChild(index, this).
  386. void SetParent(UIElement* parent, unsigned index = M_MAX_UNSIGNED);
  387. /// Set a user variable.
  388. void SetVar(StringHash key, const Variant& value);
  389. /// Mark as internally (programmatically) created. Used when an element composes itself out of child elements.
  390. /// @property
  391. void SetInternal(bool enable);
  392. /// Set traversal mode for rendering. The default traversal mode is TM_BREADTH_FIRST for non-root element. Root element should be set to TM_DEPTH_FIRST to avoid artifacts during rendering.
  393. /// @property
  394. void SetTraversalMode(TraversalMode traversalMode);
  395. /// Set element event sender flag. When child element is added or deleted, the event would be sent using UIElement found in the parental chain having this flag set. If not set, the event is sent using UI's root as per normal.
  396. /// @property
  397. void SetElementEventSender(bool flag);
  398. /// Set tags. Old tags are overwritten.
  399. void SetTags(const StringVector& tags);
  400. /// Add a tag.
  401. void AddTag(const String& tag);
  402. /// Add tags with the specified separator (; by default).
  403. void AddTags(const String& tags, char separator = ';');
  404. /// Add tags.
  405. void AddTags(const StringVector& tags);
  406. /// Remove specific tag. Return true if existed.
  407. bool RemoveTag(const String& tag);
  408. /// Remove all tags.
  409. void RemoveAllTags();
  410. /// Template version of creating a child element.
  411. template <class T> T* CreateChild(const String& name = String::EMPTY, unsigned index = M_MAX_UNSIGNED);
  412. /// Template version of returning child element by index using static cast.
  413. template <class T> T* GetChildStaticCast(unsigned index) const;
  414. /// Template version of returning child element by name using static cast.
  415. template <class T> T* GetChildStaticCast(const String& name, bool recursive = false) const;
  416. /// Template version of returning child element by variable using static cast. If only key is provided, return the first child having the matching variable key. If value is also provided then the actual variable value would also be checked against.
  417. template <class T> T* GetChildStaticCast(const StringHash& key, const Variant& value = Variant::EMPTY, bool recursive = false) const;
  418. /// Template version of returning child element by index using dynamic cast. May return 0 when casting failed.
  419. template <class T> T* GetChildDynamicCast(unsigned index) const;
  420. /// Template version of returning child element by name using dynamic cast. May return 0 when casting failed.
  421. template <class T> T* GetChildDynamicCast(const String& name, bool recursive = false) const;
  422. /// Template version of returning child element by variable. If only key is provided, return the first child having the matching variable key. If value is also provided then the actual variable value would also be checked against using dynamic cast. May return 0 when casting failed.
  423. template <class T> T* GetChildDynamicCast(const StringHash& key, const Variant& value = Variant::EMPTY, bool recursive = false) const;
  424. /// Return name.
  425. /// @property
  426. const String& GetName() const { return name_; }
  427. /// Return position.
  428. /// @property
  429. const IntVector2& GetPosition() const { return position_; }
  430. /// Return size.
  431. /// @property
  432. const IntVector2& GetSize() const { return size_; }
  433. /// Return width.
  434. /// @property
  435. int GetWidth() const { return size_.x_; }
  436. /// Return height.
  437. /// @property
  438. int GetHeight() const { return size_.y_; }
  439. /// Return minimum size.
  440. /// @property
  441. const IntVector2& GetMinSize() const { return minSize_; }
  442. /// Return minimum width.
  443. /// @property
  444. int GetMinWidth() const { return minSize_.x_; }
  445. /// Return minimum height.
  446. /// @property
  447. int GetMinHeight() const { return minSize_.y_; }
  448. /// Return maximum size.
  449. /// @property
  450. const IntVector2& GetMaxSize() const { return maxSize_; }
  451. /// Return minimum width.
  452. /// @property
  453. int GetMaxWidth() const { return maxSize_.x_; }
  454. /// Return minimum height.
  455. /// @property
  456. int GetMaxHeight() const { return maxSize_.y_; }
  457. /// Return true if size is fixed.
  458. /// @property
  459. bool IsFixedSize() const { return minSize_ == maxSize_; }
  460. /// Return true if width is fixed.
  461. /// @property
  462. bool IsFixedWidth() const { return minSize_.x_ == maxSize_.x_; }
  463. /// Return true if height is fixed.
  464. /// @property
  465. bool IsFixedHeight() const { return minSize_.y_ == maxSize_.y_; }
  466. /// Return child element offset.
  467. /// @property
  468. const IntVector2& GetChildOffset() const { return childOffset_; }
  469. /// Return horizontal alignment. If pivot has been adjusted to a custom horizontal setting, returns HA_CUSTOM.
  470. /// @property
  471. HorizontalAlignment GetHorizontalAlignment() const;
  472. /// Return vertical alignment. If pivot has been adjusted to a custom vertical setting, returns VA_CUSTOM.
  473. /// @property
  474. VerticalAlignment GetVerticalAlignment() const;
  475. /// Return whether anchor positioning & sizing is enabled.
  476. /// @property
  477. bool GetEnableAnchor() const { return enableAnchor_; }
  478. /// Return minimum anchor.
  479. /// @property
  480. const Vector2& GetMinAnchor() const { return anchorMin_; }
  481. /// Return maximum anchor.
  482. /// @property
  483. const Vector2& GetMaxAnchor() const { return anchorMax_; }
  484. // Return minimum offset.
  485. /// @property
  486. const IntVector2& GetMinOffset() const { return minOffset_; }
  487. // Return maximum offset.
  488. /// @property
  489. const IntVector2& GetMaxOffset() const { return maxOffset_; }
  490. /// Return pivot.
  491. /// @property
  492. const Vector2& GetPivot() const { return pivot_; }
  493. /// Return child element clipping border.
  494. /// @property
  495. const IntRect& GetClipBorder() const { return clipBorder_; }
  496. /// Return corner color.
  497. /// @property{get_colors}
  498. const Color& GetColor(Corner corner) const { return colors_[corner]; }
  499. /// Return priority.
  500. /// @property
  501. int GetPriority() const { return priority_; }
  502. /// Return opacity.
  503. /// @property
  504. float GetOpacity() const { return opacity_; }
  505. /// Return derived opacity (affected by parent elements). If UseDerivedOpacity is false, returns same as element's own opacity.
  506. /// @property
  507. float GetDerivedOpacity() const;
  508. /// Return whether should be brought to front when focused.
  509. /// @property
  510. bool GetBringToFront() const { return bringToFront_; }
  511. /// Return whether should be put to background when another element is focused.
  512. /// @property
  513. bool GetBringToBack() const { return bringToBack_; }
  514. /// Return whether should clip child elements.
  515. /// @property
  516. bool GetClipChildren() const { return clipChildren_; }
  517. /// Return whether should sort child elements according to priority.
  518. /// @property
  519. bool GetSortChildren() const { return sortChildren_; }
  520. /// Return whether parent elements' opacity affects opacity.
  521. /// @property
  522. bool GetUseDerivedOpacity() const { return useDerivedOpacity_; }
  523. /// Return whether has focus.
  524. /// @property{get_focus}
  525. bool HasFocus() const;
  526. /// Return whether is a direct or indirect child of specified element.
  527. bool IsChildOf(UIElement* element) const;
  528. /// Return whether reacts to input.
  529. /// @property
  530. bool IsEnabled() const { return enabled_; }
  531. /// Returns the element's last own enabled state. May be different than the value returned by IsEnabled when SetDeepEnabled has been used.
  532. /// @property
  533. bool IsEnabledSelf() const { return enabledPrev_; }
  534. /// Return whether value is editable through input.
  535. /// @property
  536. bool IsEditable() const { return editable_; }
  537. /// Return whether is selected. Actual meaning is element dependent.
  538. /// @property
  539. bool IsSelected() const { return selected_; }
  540. /// Return whether element itself should be visible. Elements can be also hidden due to the parent being not visible, use IsVisibleEffective() to check.
  541. /// @property
  542. bool IsVisible() const { return visible_; }
  543. /// Return whether element is effectively visible (parent element chain is visible).
  544. /// @property
  545. bool IsVisibleEffective() const;
  546. /// Return whether the cursor is hovering on this element.
  547. /// @property
  548. bool IsHovering() const { return hovering_; }
  549. /// Return whether is internally created.
  550. /// @property
  551. bool IsInternal() const { return internal_; }
  552. /// Return whether has different color in at least one corner.
  553. /// @property{get_colorGradient}
  554. bool HasColorGradient() const { return colorGradient_; }
  555. /// Return focus mode.
  556. /// @property
  557. FocusMode GetFocusMode() const { return focusMode_; }
  558. /// Return drag and drop flags.
  559. /// @property
  560. DragAndDropModeFlags GetDragDropMode() const { return dragDropMode_; }
  561. /// Return applied style name. Return an empty string when the applied style is an 'auto' style (i.e. style derived from instance's type).
  562. /// @property{get_style}
  563. const String& GetAppliedStyle() const;
  564. /// Return default style.
  565. XMLFile* GetDefaultStyle(bool recursiveUp = true) const;
  566. /// Return layout mode.
  567. /// @property
  568. LayoutMode GetLayoutMode() const { return layoutMode_; }
  569. /// Return layout spacing.
  570. /// @property
  571. int GetLayoutSpacing() const { return layoutSpacing_; }
  572. /// Return layout border.
  573. /// @property
  574. const IntRect& GetLayoutBorder() const { return layoutBorder_; }
  575. /// Return layout flex scale.
  576. /// @property
  577. const Vector2& GetLayoutFlexScale() const { return layoutFlexScale_; }
  578. /// Return number of child elements.
  579. /// @property
  580. unsigned GetNumChildren(bool recursive = false) const;
  581. /// Return child element by index.
  582. /// @property{get_children}
  583. UIElement* GetChild(unsigned index) const;
  584. /// Return child element by name.
  585. UIElement* GetChild(const String& name, bool recursive = false) const;
  586. /// Return child element by variable. If only key is provided, return the first child having the matching variable key. If value is also provided then the actual variable value would also be checked against.
  587. UIElement* GetChild(const StringHash& key, const Variant& value = Variant::EMPTY, bool recursive = false) const;
  588. /// Return immediate child elements.
  589. const Vector<SharedPtr<UIElement> >& GetChildren() const { return children_; }
  590. /// Return child elements either recursively or non-recursively.
  591. void GetChildren(PODVector<UIElement*>& dest, bool recursive = false) const;
  592. /// Return child elements, optionally recursive.
  593. PODVector<UIElement*> GetChildren(bool recursive) const;
  594. /// Return parent element.
  595. /// @property
  596. UIElement* GetParent() const { return parent_; }
  597. /// Return root element.
  598. /// @property
  599. UIElement* GetRoot() const;
  600. /// Return derived color. Only valid when no gradient.
  601. const Color& GetDerivedColor() const;
  602. /// Return a user variable.
  603. const Variant& GetVar(const StringHash& key) const;
  604. /// Return all user variables.
  605. const VariantMap& GetVars() const { return vars_; }
  606. /// Return whether element is tagged by a specific tag.
  607. bool HasTag(const String& tag) const;
  608. /// Return all tags.
  609. /// @property
  610. const StringVector& GetTags() const { return tags_; }
  611. /// Return child elements with a specific tag either recursively or non-recursively.
  612. void GetChildrenWithTag(PODVector<UIElement*>& dest, const String& tag, bool recursive = false) const;
  613. /// Return child elements with a specific tag either recursively or non-recursively.
  614. PODVector<UIElement*> GetChildrenWithTag(const String& tag, bool recursive = false) const;
  615. /// Return the drag button combo if this element is being dragged.
  616. /// @property
  617. MouseButtonFlags GetDragButtonCombo() const { return dragButtonCombo_; }
  618. /// Return the number of buttons dragging this element.
  619. /// @property
  620. unsigned GetDragButtonCount() const { return dragButtonCount_; }
  621. /// Return whether a point (either in element or screen coordinates) is inside the element.
  622. bool IsInside(IntVector2 position, bool isScreen);
  623. /// Return whether a point (either in element or screen coordinates) is inside the combined rect of the element and its children.
  624. bool IsInsideCombined(IntVector2 position, bool isScreen);
  625. /// Return combined screen coordinate rect of element and its children.
  626. /// @property
  627. IntRect GetCombinedScreenRect();
  628. /// Sort child elements if sorting enabled and order dirty. Called by UI.
  629. void SortChildren();
  630. /// Return maximum layout element size in the layout direction. Only valid after layout has been calculated. Used internally by UI for optimizations.
  631. int GetLayoutElementMaxSize() const { return layoutElementMaxSize_; }
  632. /// Return horizontal indentation.
  633. /// @property
  634. int GetIndent() const { return indent_; }
  635. /// Return indent spacing (number of pixels per indentation level).
  636. /// @property
  637. int GetIndentSpacing() const { return indentSpacing_; }
  638. /// Return indent width in pixels.
  639. /// @property
  640. int GetIndentWidth() const { return indent_ * indentSpacing_; }
  641. /// Set child offset.
  642. void SetChildOffset(const IntVector2& offset);
  643. /// Set hovering state.
  644. void SetHovering(bool enable);
  645. /// Adjust scissor for rendering.
  646. void AdjustScissor(IntRect& currentScissor);
  647. /// Get UI rendering batches with a specified offset. Also recurse to child elements.
  648. void GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData, IntRect currentScissor);
  649. /// Return color attribute. Uses just the top-left color.
  650. const Color& GetColorAttr() const { return colors_[0]; }
  651. /// Return traversal mode for rendering.
  652. /// @property
  653. TraversalMode GetTraversalMode() const { return traversalMode_; }
  654. /// Return whether element should send child added / removed events by itself. If false, defers to parent element.
  655. /// @property
  656. bool IsElementEventSender() const { return elementEventSender_; }
  657. /// Get element which should send child added / removed events.
  658. UIElement* GetElementEventSender() const;
  659. /// Return effective minimum size, also considering layout. Used internally.
  660. IntVector2 GetEffectiveMinSize() const;
  661. /// Set texture to which element will be rendered.
  662. void SetRenderTexture(Texture2D* texture);
  663. protected:
  664. /// Handle attribute animation added.
  665. void OnAttributeAnimationAdded() override;
  666. /// Handle attribute animation removed.
  667. void OnAttributeAnimationRemoved() override;
  668. /// Find target of an attribute animation from object hierarchy by name.
  669. Animatable* FindAttributeAnimationTarget(const String& name, String& outName) override;
  670. /// Mark screen position as needing an update.
  671. void MarkDirty();
  672. /// Remove child XML element by matching attribute name.
  673. bool RemoveChildXML(XMLElement& parent, const String& name) const;
  674. /// Remove child XML element by matching attribute name and value.
  675. bool RemoveChildXML(XMLElement& parent, const String& name, const String& value) const;
  676. /// Filter UI-style attributes in serialization process.
  677. bool FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const;
  678. /// Filter implicit attributes in serialization process.
  679. virtual bool FilterImplicitAttributes(XMLElement& dest) const;
  680. /// Update anchored size & position. Only called when anchoring is enabled.
  681. void UpdateAnchoring();
  682. /// Name.
  683. String name_;
  684. /// Child elements.
  685. Vector<SharedPtr<UIElement> > children_;
  686. /// Parent element.
  687. UIElement* parent_{};
  688. /// Child element clipping border.
  689. IntRect clipBorder_;
  690. /// Colors.
  691. Color colors_[MAX_UIELEMENT_CORNERS];
  692. /// User variables.
  693. VariantMap vars_;
  694. /// Priority.
  695. int priority_{};
  696. /// Bring to front when focused flag.
  697. bool bringToFront_{};
  698. /// Bring to back when defocused flag.
  699. bool bringToBack_{true};
  700. /// Clip children flag.
  701. bool clipChildren_{};
  702. /// Sort children according to priority flag.
  703. bool sortChildren_{true};
  704. /// Use derived opacity flag.
  705. bool useDerivedOpacity_{true};
  706. /// Input enabled flag.
  707. bool enabled_{};
  708. /// Last SetEnabled flag before any SetDeepEnabled.
  709. bool enabledPrev_{};
  710. /// Value editable flag.
  711. bool editable_{true};
  712. /// Selected flag.
  713. bool selected_{};
  714. /// Visible flag.
  715. bool visible_{true};
  716. /// Hovering flag.
  717. bool hovering_{};
  718. /// Internally created flag.
  719. bool internal_{};
  720. /// Focus mode.
  721. FocusMode focusMode_{FM_NOTFOCUSABLE};
  722. /// Drag and drop flags.
  723. DragAndDropModeFlags dragDropMode_{DD_DISABLED};
  724. /// Layout mode.
  725. LayoutMode layoutMode_{LM_FREE};
  726. /// Layout spacing.
  727. int layoutSpacing_{};
  728. /// Layout borders.
  729. IntRect layoutBorder_{};
  730. /// Layout flex scale.
  731. Vector2 layoutFlexScale_{Vector2::ONE};
  732. /// Resize nesting level to prevent multiple events and endless loop.
  733. unsigned resizeNestingLevel_{};
  734. /// Layout update nesting level to prevent endless loop.
  735. unsigned layoutNestingLevel_{};
  736. /// Layout element maximum size in layout direction.
  737. int layoutElementMaxSize_{};
  738. /// Horizontal indentation.
  739. int indent_{};
  740. /// Indent spacing (number of pixels per indentation level).
  741. int indentSpacing_{16};
  742. /// Position.
  743. IntVector2 position_{};
  744. /// Screen position.
  745. mutable IntVector2 screenPosition_;
  746. /// Screen position dirty flag.
  747. mutable bool positionDirty_{true};
  748. /// Applied style.
  749. String appliedStyle_;
  750. /// Drag button combo.
  751. MouseButtonFlags dragButtonCombo_{};
  752. /// Drag button count.
  753. unsigned dragButtonCount_{};
  754. private:
  755. /// Return child elements recursively.
  756. void GetChildrenRecursive(PODVector<UIElement*>& dest) const;
  757. /// Return child elements with a specific tag recursively.
  758. void GetChildrenWithTagRecursive(PODVector<UIElement*>& dest, const String& tag) const;
  759. /// Recursively apply style to a child element hierarchy when adding to an element.
  760. void ApplyStyleRecursive(UIElement* element);
  761. /// Calculate layout width for resizing the parent element.
  762. int CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing);
  763. /// Calculate child widths/positions in the layout.
  764. void CalculateLayout
  765. (PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes, const PODVector<int>& maxSizes,
  766. const PODVector<float>& flexScales, int targetSize, int begin, int end, int spacing);
  767. /// Get child element constant position in a layout.
  768. IntVector2 GetLayoutChildPosition(UIElement* child);
  769. /// Detach from parent.
  770. void Detach();
  771. /// Verify that child elements have proper alignment for layout mode.
  772. void VerifyChildAlignment();
  773. /// Handle logic post-update event.
  774. void HandlePostUpdate(StringHash eventType, VariantMap& eventData);
  775. /// Size.
  776. IntVector2 size_;
  777. /// Minimum size.
  778. IntVector2 minSize_;
  779. /// Maximum size.
  780. IntVector2 maxSize_{M_MAX_INT, M_MAX_INT};
  781. /// Child elements' offset. Used internally.
  782. IntVector2 childOffset_;
  783. /// Parent's minimum size calculated by layout. Used internally.
  784. IntVector2 layoutMinSize_;
  785. /// Minimum offset.
  786. IntVector2 minOffset_;
  787. /// Maximum offset.
  788. IntVector2 maxOffset_;
  789. /// Use min/max anchor & min/max offset for position & size instead of setting explicitly.
  790. bool enableAnchor_{};
  791. /// Has pivot changed manually.
  792. bool pivotSet_{};
  793. /// Anchor minimum position.
  794. Vector2 anchorMin_;
  795. /// Anchor maximum position.
  796. Vector2 anchorMax_;
  797. /// Pivot Position.
  798. Vector2 pivot_;
  799. /// Opacity.
  800. float opacity_{1.0f};
  801. /// Derived opacity.
  802. mutable float derivedOpacity_{};
  803. /// Derived color. Only valid when no gradient.
  804. mutable Color derivedColor_;
  805. /// Derived opacity dirty flag.
  806. mutable bool opacityDirty_{true};
  807. /// Derived color dirty flag (only used when no gradient).
  808. mutable bool derivedColorDirty_{true};
  809. /// Child priority sorting dirty flag.
  810. bool sortOrderDirty_{};
  811. /// Has color gradient flag.
  812. bool colorGradient_{};
  813. /// Default style file.
  814. SharedPtr<XMLFile> defaultStyle_;
  815. /// Last applied style file.
  816. WeakPtr<XMLFile> appliedStyleFile_;
  817. /// Traversal mode for rendering.
  818. TraversalMode traversalMode_{TM_BREADTH_FIRST};
  819. /// Flag whether node should send child added / removed events by itself.
  820. bool elementEventSender_{};
  821. /// XPath query for selecting UI-style.
  822. static XPathQuery styleXPathQuery_;
  823. /// Tag list.
  824. StringVector tags_;
  825. };
  826. template <class T> T* UIElement::CreateChild(const String& name, unsigned index)
  827. {
  828. return static_cast<T*>(CreateChild(T::GetTypeStatic(), name, index));
  829. }
  830. template <class T> T* UIElement::GetChildStaticCast(unsigned index) const
  831. {
  832. return static_cast<T*>(GetChild(index));
  833. }
  834. template <class T> T* UIElement::GetChildStaticCast(const String& name, bool recursive) const
  835. {
  836. return static_cast<T*>(GetChild(name, recursive));
  837. }
  838. template <class T> T* UIElement::GetChildStaticCast(const StringHash& key, const Variant& value, bool recursive) const
  839. {
  840. return static_cast<T*>(GetChild(key, value, recursive));
  841. }
  842. template <class T> T* UIElement::GetChildDynamicCast(unsigned index) const
  843. {
  844. return dynamic_cast<T*>(GetChild(index));
  845. }
  846. template <class T> T* UIElement::GetChildDynamicCast(const String& name, bool recursive) const
  847. {
  848. return dynamic_cast<T*>(GetChild(name, recursive));
  849. }
  850. template <class T> T* UIElement::GetChildDynamicCast(const StringHash& key, const Variant& value, bool recursive) const
  851. {
  852. return dynamic_cast<T*>(GetChild(key, value, recursive));
  853. }
  854. }