UIElement.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Cursor.h"
  25. #include "HashSet.h"
  26. #include "Log.h"
  27. #include "ResourceCache.h"
  28. #include "Sort.h"
  29. #include "StringUtils.h"
  30. #include "UI.h"
  31. #include "UIElement.h"
  32. #include "UIEvents.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. 0
  42. };
  43. const char* verticalAlignments[] =
  44. {
  45. "Top",
  46. "Center",
  47. "Bottom",
  48. 0
  49. };
  50. static const char* focusModes[] =
  51. {
  52. "NotFocusable",
  53. "ResetFocus",
  54. "Focusable",
  55. "FocusableDefocusable",
  56. 0
  57. };
  58. static const char* dragDropModes[] =
  59. {
  60. "Disabled",
  61. "Source",
  62. "Target",
  63. "SourceAndTarget",
  64. 0
  65. };
  66. static const char* layoutModes[] =
  67. {
  68. "Free",
  69. "Horizontal",
  70. "Vertical",
  71. 0
  72. };
  73. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  74. {
  75. return lhs->GetPriority() < rhs->GetPriority();
  76. }
  77. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  78. {
  79. return (HorizontalAlignment)GetInt();
  80. }
  81. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  82. {
  83. return (VerticalAlignment)GetInt();
  84. }
  85. template<> FocusMode Variant::Get<FocusMode>() const
  86. {
  87. return (FocusMode)GetInt();
  88. }
  89. template<> LayoutMode Variant::Get<LayoutMode>() const
  90. {
  91. return (LayoutMode)GetInt();
  92. }
  93. OBJECTTYPESTATIC(UIElement);
  94. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  95. UIElement::UIElement(Context* context) :
  96. Serializable(context),
  97. parent_(0),
  98. clipBorder_(IntRect::ZERO),
  99. priority_(0),
  100. bringToFront_(false),
  101. bringToBack_(true),
  102. clipChildren_(false),
  103. sortChildren_(true),
  104. useDerivedOpacity_(true),
  105. enabled_(false),
  106. selected_(false),
  107. visible_(true),
  108. hovering_(false),
  109. internal_(false),
  110. focusMode_(FM_NOTFOCUSABLE),
  111. dragDropMode_(DD_DISABLED),
  112. layoutMode_(LM_FREE),
  113. layoutSpacing_(0),
  114. layoutBorder_(IntRect::ZERO),
  115. resizeNestingLevel_(0),
  116. layoutNestingLevel_(0),
  117. layoutMinSize_(0),
  118. indent_(0),
  119. indentSpacing_(16),
  120. position_(IntVector2::ZERO),
  121. positionDirty_(true),
  122. size_(IntVector2::ZERO),
  123. minSize_(IntVector2::ZERO),
  124. maxSize_(M_MAX_INT, M_MAX_INT),
  125. childOffset_(IntVector2::ZERO),
  126. horizontalAlignment_(HA_LEFT),
  127. verticalAlignment_(VA_TOP),
  128. opacity_(1.0f),
  129. opacityDirty_(true),
  130. derivedColorDirty_(true),
  131. sortOrderDirty_(false),
  132. colorGradient_(false),
  133. traversalMode_(TM_BREADTH_FIRST),
  134. elementEventSender_(false)
  135. {
  136. }
  137. UIElement::~UIElement()
  138. {
  139. // If child elements have outside references, detach them
  140. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  141. {
  142. if (i->Refs() > 1)
  143. (*i)->Detach();
  144. }
  145. }
  146. void UIElement::RegisterObject(Context* context)
  147. {
  148. context->RegisterFactory<UIElement>();
  149. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  150. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  151. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  152. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  153. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2(M_MAX_INT, M_MAX_INT), AM_FILE);
  154. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  155. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  156. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  157. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  158. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  159. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_COLOR, "Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  160. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  161. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  162. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  163. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  167. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  168. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  169. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  170. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, true, AM_FILE);
  171. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  172. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  173. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  174. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  175. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  176. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  177. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  178. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE);
  179. }
  180. void UIElement::ApplyAttributes()
  181. {
  182. colorGradient_ = false;
  183. derivedColorDirty_ = true;
  184. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  185. {
  186. if (color_[i] != color_[0])
  187. colorGradient_ = true;
  188. }
  189. }
  190. bool UIElement::LoadXML(const XMLElement& source, bool setInstanceDefault)
  191. {
  192. return LoadXML(source, 0, setInstanceDefault);
  193. }
  194. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile, bool setInstanceDefault)
  195. {
  196. // Get style override if defined
  197. String styleName = source.GetAttribute("style");
  198. // Apply the style first, if the style file is available
  199. if (styleFile)
  200. {
  201. // If not defined, use type name
  202. if (styleName.Empty())
  203. styleName = GetTypeName();
  204. SetStyle(styleFile, styleName);
  205. }
  206. // The 'style' attribute value in the style file cannot be equals to original's applied style to prevent infinite loop
  207. else if (!styleName.Empty() && styleName != appliedStyle_)
  208. {
  209. // Attempt to use the default style file
  210. styleFile = GetDefaultStyle();
  211. if (styleFile)
  212. {
  213. // Remember the original applied style
  214. String appliedStyle(appliedStyle_);
  215. SetStyle(styleFile, styleName);
  216. appliedStyle_ = appliedStyle;
  217. }
  218. }
  219. // Then load rest of the attributes from the source
  220. if (!Serializable::LoadXML(source, setInstanceDefault))
  221. return false;
  222. unsigned nextInternalChild = 0;
  223. // Load child elements. Internal elements are not to be created as they already exist
  224. XMLElement childElem = source.GetChild("element");
  225. while (childElem)
  226. {
  227. bool internalElem = childElem.GetBool("internal");
  228. String typeName = childElem.GetAttribute("type");
  229. if (typeName.Empty())
  230. typeName = "UIElement";
  231. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  232. UIElement* child = 0;
  233. if (!internalElem)
  234. child = CreateChild(typeName, String::EMPTY, index);
  235. else
  236. {
  237. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  238. {
  239. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  240. {
  241. child = children_[i];
  242. nextInternalChild = i + 1;
  243. break;
  244. }
  245. }
  246. if (!child)
  247. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  248. }
  249. if (child)
  250. {
  251. if (!styleFile)
  252. styleFile = GetDefaultStyle();
  253. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  254. return false;
  255. }
  256. childElem = childElem.GetNext("element");
  257. }
  258. ApplyAttributes();
  259. return true;
  260. }
  261. bool UIElement::LoadChildXML(const XMLElement& childElem, XMLFile* styleFile, bool setInstanceDefault)
  262. {
  263. bool internalElem = childElem.GetBool("internal");
  264. if (internalElem)
  265. {
  266. LOGERROR("Loading internal child element is not supported");
  267. return false;
  268. }
  269. String typeName = childElem.GetAttribute("type");
  270. if (typeName.Empty())
  271. typeName = "UIElement";
  272. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  273. UIElement* child = CreateChild(typeName, String::EMPTY, index);
  274. if (child)
  275. {
  276. if (!styleFile)
  277. styleFile = GetDefaultStyle();
  278. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  279. return false;
  280. }
  281. return true;
  282. }
  283. bool UIElement::SaveXML(XMLElement& dest) const
  284. {
  285. // Write type
  286. if (GetTypeName() != "UIElement")
  287. {
  288. if (!dest.SetString("type", GetTypeName()))
  289. return false;
  290. }
  291. // Write internal flag
  292. if (internal_)
  293. {
  294. if (!dest.SetBool("internal", internal_))
  295. return false;
  296. }
  297. // Write style
  298. if (!appliedStyle_.Empty())
  299. {
  300. if (!dest.SetAttribute("style", appliedStyle_))
  301. return false;
  302. }
  303. else if (internal_)
  304. {
  305. if (!dest.SetAttribute("style", "none"))
  306. return false;
  307. }
  308. // Write attributes
  309. if (!Serializable::SaveXML(dest))
  310. return false;
  311. // Write child elements
  312. for (unsigned i = 0; i < children_.Size(); ++i)
  313. {
  314. UIElement* element = children_[i];
  315. XMLElement childElem = dest.CreateChild("element");
  316. if (!element->SaveXML(childElem))
  317. return false;
  318. }
  319. // Filter UI-style and implicit attributes
  320. //\todo Fail the serialization when encountered error in filtering, for now let it passes until the filtering process is stable and fully tested in the field
  321. // if (!FilterAttributes(dest))
  322. // return false;
  323. FilterAttributes(dest);
  324. return true;
  325. }
  326. void UIElement::Update(float timeStep)
  327. {
  328. }
  329. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  330. {
  331. // Reset hovering for next frame
  332. hovering_ = false;
  333. }
  334. void UIElement::GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  335. {
  336. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  337. int horizontalThickness = 1;
  338. int verticalThickness = 1;
  339. if (parent_)
  340. {
  341. switch (parent_->layoutMode_)
  342. {
  343. case LM_HORIZONTAL:
  344. verticalThickness +=2;
  345. break;
  346. case LM_VERTICAL:
  347. horizontalThickness += 2;
  348. break;
  349. default:
  350. break;
  351. }
  352. }
  353. // Left
  354. batch.AddQuad(0, 0, horizontalThickness, size_.y_, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  355. // Top
  356. batch.AddQuad(0, 0, size_.x_, verticalThickness, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  357. // Right
  358. batch.AddQuad(size_.x_ - horizontalThickness, 0, horizontalThickness, size_.y_, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  359. // Bottom
  360. batch.AddQuad(0, size_.y_ - verticalThickness, size_.x_, verticalThickness, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  361. UIBatch::AddOrMerge(batch, batches);
  362. }
  363. bool UIElement::IsWithinScissor(const IntRect& currentScissor)
  364. {
  365. if (!visible_)
  366. return false;
  367. const IntVector2& screenPos = GetScreenPosition();
  368. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + GetWidth() > currentScissor.left_ &&
  369. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + GetHeight() > currentScissor.top_;
  370. }
  371. const IntVector2& UIElement::GetScreenPosition() const
  372. {
  373. if (positionDirty_)
  374. {
  375. IntVector2 pos = position_;
  376. const UIElement* parent = parent_;
  377. if (parent)
  378. {
  379. const IntVector2& parentScreenPos = parent->GetScreenPosition();
  380. switch (horizontalAlignment_)
  381. {
  382. case HA_LEFT:
  383. pos.x_ += parentScreenPos.x_;
  384. break;
  385. case HA_CENTER:
  386. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ / 2 - size_.x_ / 2;
  387. break;
  388. case HA_RIGHT:
  389. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ - size_.x_;
  390. break;
  391. }
  392. switch (verticalAlignment_)
  393. {
  394. case VA_TOP:
  395. pos.y_ += parentScreenPos.y_;
  396. break;
  397. case VA_CENTER:
  398. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ / 2 - size_.y_ / 2;
  399. break;
  400. case VA_BOTTOM:
  401. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ - size_.y_;
  402. break;
  403. }
  404. pos += parent_->childOffset_;
  405. }
  406. screenPosition_ = pos;
  407. positionDirty_ = false;
  408. }
  409. return screenPosition_;
  410. }
  411. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  412. {
  413. if (cursor && cursor->IsVisible())
  414. cursor->SetShape(CS_NORMAL);
  415. hovering_ = true;
  416. }
  417. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  418. {
  419. }
  420. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  421. {
  422. }
  423. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  424. {
  425. }
  426. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  427. {
  428. }
  429. bool UIElement::OnDragDropTest(UIElement* source)
  430. {
  431. return true;
  432. }
  433. bool UIElement::OnDragDropFinish(UIElement* source)
  434. {
  435. return true;
  436. }
  437. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  438. {
  439. }
  440. void UIElement::OnKey(int key, int buttons, int qualifiers)
  441. {
  442. }
  443. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  444. {
  445. }
  446. void UIElement::OnResize()
  447. {
  448. }
  449. void UIElement::OnPositionSet()
  450. {
  451. }
  452. bool UIElement::LoadXML(Deserializer& source)
  453. {
  454. SharedPtr<XMLFile> xml(new XMLFile(context_));
  455. return xml->Load(source) && LoadXML(xml->GetRoot());
  456. }
  457. bool UIElement::SaveXML(Serializer& dest) const
  458. {
  459. SharedPtr<XMLFile> xml(new XMLFile(context_));
  460. XMLElement rootElem = xml->CreateRoot("element");
  461. return SaveXML(rootElem) && xml->Save(dest);
  462. }
  463. bool UIElement::FilterAttributes(XMLElement& dest) const
  464. {
  465. // Filter UI styling attributes
  466. XMLFile* styleFile = GetDefaultStyle();
  467. if (styleFile)
  468. {
  469. String style = dest.GetAttribute("style");
  470. if (!style.Empty() && style != "none")
  471. {
  472. if (styleXPathQuery_.SetVariable("typeName", style))
  473. {
  474. XMLElement styleElem = GetDefaultStyle()->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  475. if (!styleElem || !FilterUIStyleAttributes(dest, styleElem))
  476. return false;
  477. }
  478. }
  479. }
  480. // Filter implicit attributes
  481. if (!FilterImplicitAttributes(dest))
  482. {
  483. LOGERROR("Could not remove implicit attributes");
  484. return false;
  485. }
  486. return true;
  487. }
  488. void UIElement::SetName(const String& name)
  489. {
  490. name_ = name;
  491. using namespace NameChanged;
  492. VariantMap eventData;
  493. eventData[P_ELEMENT] = (void*)this;
  494. SendEvent(E_NAMECHANGED, eventData);
  495. }
  496. void UIElement::SetPosition(const IntVector2& position)
  497. {
  498. if (position != position_)
  499. {
  500. position_ = position;
  501. OnPositionSet();
  502. MarkDirty();
  503. using namespace Positioned;
  504. VariantMap eventData;
  505. eventData[P_ELEMENT] = (void*)this;
  506. eventData[P_X] = position_.x_;
  507. eventData[P_Y] = position_.y_;
  508. SendEvent(E_POSITIONED, eventData);
  509. }
  510. }
  511. void UIElement::SetPosition(int x, int y)
  512. {
  513. SetPosition(IntVector2(x, y));
  514. }
  515. void UIElement::SetSize(const IntVector2& size)
  516. {
  517. ++resizeNestingLevel_;
  518. IntVector2 validatedSize;
  519. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  520. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  521. if (validatedSize != size_)
  522. {
  523. size_ = validatedSize;
  524. if (resizeNestingLevel_ == 1)
  525. {
  526. // Check if parent element's layout needs to be updated first
  527. if (parent_)
  528. parent_->UpdateLayout();
  529. MarkDirty();
  530. OnResize();
  531. UpdateLayout();
  532. using namespace Resized;
  533. VariantMap eventData;
  534. eventData[P_ELEMENT] = (void*)this;
  535. eventData[P_WIDTH] = size_.x_;
  536. eventData[P_HEIGHT] = size_.y_;
  537. SendEvent(E_RESIZED, eventData);
  538. }
  539. }
  540. --resizeNestingLevel_;
  541. }
  542. void UIElement::SetSize(int width, int height)
  543. {
  544. SetSize(IntVector2(width, height));
  545. }
  546. void UIElement::SetWidth(int width)
  547. {
  548. SetSize(IntVector2(width, size_.y_));
  549. }
  550. void UIElement::SetHeight(int height)
  551. {
  552. SetSize(IntVector2(size_.x_, height));
  553. }
  554. void UIElement::SetMinSize(const IntVector2& minSize)
  555. {
  556. minSize_.x_ = Max(minSize.x_, 0);
  557. minSize_.y_ = Max(minSize.y_, 0);
  558. SetSize(size_);
  559. }
  560. void UIElement::SetMinSize(int width, int height)
  561. {
  562. SetMinSize(IntVector2(width, height));
  563. }
  564. void UIElement::SetMinWidth(int width)
  565. {
  566. SetMinSize(IntVector2(width, minSize_.y_));
  567. }
  568. void UIElement::SetMinHeight(int height)
  569. {
  570. SetMinSize(IntVector2(minSize_.x_, height));
  571. }
  572. void UIElement::SetMaxSize(const IntVector2& maxSize)
  573. {
  574. maxSize_.x_ = Max(maxSize.x_, 0);
  575. maxSize_.y_ = Max(maxSize.y_, 0);
  576. SetSize(size_);
  577. }
  578. void UIElement::SetMaxSize(int width, int height)
  579. {
  580. SetMaxSize(IntVector2(width, height));
  581. }
  582. void UIElement::SetMaxWidth(int width)
  583. {
  584. SetMaxSize(IntVector2(width, maxSize_.y_));
  585. }
  586. void UIElement::SetMaxHeight(int height)
  587. {
  588. SetMaxSize(IntVector2(maxSize_.x_, height));
  589. }
  590. void UIElement::SetFixedSize(const IntVector2& size)
  591. {
  592. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  593. SetSize(size);
  594. }
  595. void UIElement::SetFixedSize(int width, int height)
  596. {
  597. SetFixedSize(IntVector2(width, height));
  598. }
  599. void UIElement::SetFixedWidth(int width)
  600. {
  601. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  602. SetWidth(width);
  603. }
  604. void UIElement::SetFixedHeight(int height)
  605. {
  606. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  607. SetHeight(height);
  608. }
  609. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  610. {
  611. horizontalAlignment_ = hAlign;
  612. verticalAlignment_ = vAlign;
  613. MarkDirty();
  614. }
  615. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  616. {
  617. horizontalAlignment_ = align;
  618. MarkDirty();
  619. }
  620. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  621. {
  622. verticalAlignment_ = align;
  623. MarkDirty();
  624. }
  625. void UIElement::SetClipBorder(const IntRect& rect)
  626. {
  627. clipBorder_.left_ = Max(rect.left_, 0);
  628. clipBorder_.top_ = Max(rect.top_, 0);
  629. clipBorder_.right_ = Max(rect.right_, 0);
  630. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  631. }
  632. void UIElement::SetColor(const Color& color)
  633. {
  634. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  635. color_[i] = color;
  636. colorGradient_ = false;
  637. derivedColorDirty_ = true;
  638. }
  639. void UIElement::SetColor(Corner corner, const Color& color)
  640. {
  641. color_[corner] = color;
  642. colorGradient_ = false;
  643. derivedColorDirty_ = true;
  644. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  645. {
  646. if (i != corner && color_[i] != color_[corner])
  647. colorGradient_ = true;
  648. }
  649. }
  650. void UIElement::SetPriority(int priority)
  651. {
  652. priority_ = priority;
  653. if (parent_)
  654. parent_->sortOrderDirty_ = true;
  655. }
  656. void UIElement::SetOpacity(float opacity)
  657. {
  658. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  659. MarkDirty();
  660. }
  661. void UIElement::SetBringToFront(bool enable)
  662. {
  663. bringToFront_ = enable;
  664. }
  665. void UIElement::SetBringToBack(bool enable)
  666. {
  667. bringToBack_ = enable;
  668. }
  669. void UIElement::SetClipChildren(bool enable)
  670. {
  671. clipChildren_ = enable;
  672. }
  673. void UIElement::SetSortChildren(bool enable)
  674. {
  675. if (!sortChildren_ && enable)
  676. sortOrderDirty_ = true;
  677. sortChildren_ = enable;
  678. }
  679. void UIElement::SetUseDerivedOpacity(bool enable)
  680. {
  681. useDerivedOpacity_ = enable;
  682. }
  683. void UIElement::SetEnabled(bool enable)
  684. {
  685. enabled_ = enable;
  686. }
  687. void UIElement::SetFocusMode(FocusMode mode)
  688. {
  689. focusMode_ = mode;
  690. }
  691. void UIElement::SetFocus(bool enable)
  692. {
  693. if (focusMode_ < FM_FOCUSABLE)
  694. enable = false;
  695. UI* ui = GetSubsystem<UI>();
  696. if (!ui)
  697. return;
  698. if (enable)
  699. {
  700. if (ui->GetFocusElement() != this)
  701. ui->SetFocusElement(this);
  702. }
  703. else
  704. {
  705. if (ui->GetFocusElement() == this)
  706. ui->SetFocusElement(0);
  707. }
  708. }
  709. void UIElement::SetSelected(bool enable)
  710. {
  711. selected_ = enable;
  712. }
  713. void UIElement::SetVisible(bool enable)
  714. {
  715. if (enable != visible_)
  716. {
  717. visible_ = enable;
  718. // Parent's layout may change as a result of visibility change
  719. if (parent_)
  720. parent_->UpdateLayout();
  721. using namespace VisibleChanged;
  722. VariantMap eventData;
  723. eventData[P_ELEMENT] = (void*)this;
  724. eventData[P_VISIBLE] = visible_;
  725. SendEvent(E_VISIBLECHANGED, eventData);
  726. }
  727. }
  728. void UIElement::SetDragDropMode(unsigned mode)
  729. {
  730. dragDropMode_ = mode;
  731. }
  732. bool UIElement::SetStyle(XMLFile* file, const String& styleName)
  733. {
  734. appliedStyle_ = styleName;
  735. if (styleName == "none")
  736. return true;
  737. if (!file)
  738. return false;
  739. styleXPathQuery_.SetVariable("typeName", styleName);
  740. XMLElement styleElem = file->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  741. return styleElem && SetStyle(styleElem);
  742. }
  743. bool UIElement::SetStyle(const XMLElement& element)
  744. {
  745. appliedStyle_ = element.GetAttribute("type");
  746. // Consider style attribute values as instance-level attribute default values
  747. return LoadXML(element, true);
  748. }
  749. bool UIElement::SetStyleAuto(XMLFile* file)
  750. {
  751. return SetStyle(file, GetTypeName());
  752. }
  753. void UIElement::SetDefaultStyle(XMLFile* style)
  754. {
  755. defaultStyle_ = style;
  756. }
  757. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  758. {
  759. layoutMode_ = mode;
  760. layoutSpacing_ = Max(spacing, 0);
  761. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  762. UpdateLayout();
  763. }
  764. void UIElement::SetLayoutMode(LayoutMode mode)
  765. {
  766. layoutMode_ = mode;
  767. UpdateLayout();
  768. }
  769. void UIElement::SetLayoutSpacing(int spacing)
  770. {
  771. layoutSpacing_ = Max(spacing, 0);
  772. UpdateLayout();
  773. }
  774. void UIElement::SetLayoutBorder(const IntRect& border)
  775. {
  776. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  777. UpdateLayout();
  778. }
  779. void UIElement::SetIndent(int indent)
  780. {
  781. indent_ = indent;
  782. if (parent_)
  783. parent_->UpdateLayout();
  784. UpdateLayout();
  785. }
  786. void UIElement::SetIndentSpacing(int indentSpacing)
  787. {
  788. indentSpacing_ = Max(indentSpacing, 0);
  789. if (parent_)
  790. parent_->UpdateLayout();
  791. UpdateLayout();
  792. }
  793. void UIElement::UpdateLayout()
  794. {
  795. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  796. return;
  797. // Prevent further updates while this update happens
  798. DisableLayoutUpdate();
  799. PODVector<int> positions;
  800. PODVector<int> sizes;
  801. PODVector<int> minSizes;
  802. PODVector<int> maxSizes;
  803. int baseIndentWidth = GetIndentWidth();
  804. if (layoutMode_ == LM_HORIZONTAL)
  805. {
  806. int minChildHeight = 0;
  807. for (unsigned i = 0; i < children_.Size(); ++i)
  808. {
  809. if (!children_[i]->IsVisible())
  810. continue;
  811. positions.Push(baseIndentWidth);
  812. unsigned indent = children_[i]->GetIndentWidth();
  813. sizes.Push(children_[i]->GetWidth() + indent);
  814. minSizes.Push(children_[i]->GetMinWidth() + indent);
  815. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  816. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  817. }
  818. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  819. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  820. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  821. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  822. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  823. // Respect fixed size if already set
  824. if (minSize_.x_ != maxSize_.x_)
  825. minSize_.x_ = minWidth;
  826. if (minSize_.y_ != maxSize_.y_)
  827. minSize_.y_ = minHeight;
  828. SetSize(width, height);
  829. // Validate the size before resizing child elements, in case of min/max limits
  830. width = size_.x_;
  831. height = size_.y_;
  832. unsigned j = 0;
  833. for (unsigned i = 0; i < children_.Size(); ++i)
  834. {
  835. if (!children_[i]->IsVisible())
  836. continue;
  837. HorizontalAlignment horizontalAlignment = children_[i]->horizontalAlignment_;
  838. children_[i]->horizontalAlignment_ = HA_LEFT;
  839. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  840. children_[i]->horizontalAlignment_ = horizontalAlignment;
  841. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  842. ++j;
  843. }
  844. }
  845. else if (layoutMode_ == LM_VERTICAL)
  846. {
  847. int minChildWidth = 0;
  848. for (unsigned i = 0; i < children_.Size(); ++i)
  849. {
  850. if (!children_[i]->IsVisible())
  851. continue;
  852. positions.Push(0);
  853. sizes.Push(children_[i]->GetHeight());
  854. minSizes.Push(children_[i]->GetMinHeight());
  855. maxSizes.Push(children_[i]->GetMaxHeight());
  856. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  857. }
  858. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  859. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  860. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  861. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  862. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  863. if (minSize_.x_ != maxSize_.x_)
  864. minSize_.x_ = minWidth;
  865. if (minSize_.y_ != maxSize_.y_)
  866. minSize_.y_ = minHeight;
  867. SetSize(width, height);
  868. width = size_.x_;
  869. height = size_.y_;
  870. unsigned j = 0;
  871. for (unsigned i = 0; i < children_.Size(); ++i)
  872. {
  873. if (!children_[i]->IsVisible())
  874. continue;
  875. VerticalAlignment verticalAlignment = children_[i]->verticalAlignment_;
  876. children_[i]->verticalAlignment_ = VA_TOP;
  877. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  878. children_[i]->verticalAlignment_ = verticalAlignment;
  879. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  880. ++j;
  881. }
  882. }
  883. using namespace LayoutUpdated;
  884. VariantMap eventData;
  885. eventData[P_ELEMENT] = (void*)this;
  886. SendEvent(E_LAYOUTUPDATED, eventData);
  887. EnableLayoutUpdate();
  888. }
  889. void UIElement::DisableLayoutUpdate()
  890. {
  891. ++layoutNestingLevel_;
  892. }
  893. void UIElement::EnableLayoutUpdate()
  894. {
  895. --layoutNestingLevel_;
  896. }
  897. void UIElement::BringToFront()
  898. {
  899. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  900. UIElement* root = GetRoot();
  901. // If element is detached from hierarchy, this must be a no-op
  902. if (!root)
  903. return;
  904. UIElement* ptr = this;
  905. while (ptr && ptr->GetParent() != root)
  906. ptr = ptr->GetParent();
  907. if (!ptr || !ptr->GetBringToFront())
  908. return;
  909. // Get the highest priority used by all other top level elements, assign that to the new front element
  910. // and decrease others' priority where necessary. However, take into account only input-enabled
  911. // elements and those which have the BringToBack flag set
  912. HashSet<int> usedPriorities;
  913. int maxPriority = M_MIN_INT;
  914. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  915. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  916. {
  917. UIElement* other = *i;
  918. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  919. {
  920. int priority = other->GetPriority();
  921. usedPriorities.Insert(priority);
  922. maxPriority = Max(priority, maxPriority);
  923. }
  924. }
  925. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  926. {
  927. ptr->SetPriority(maxPriority);
  928. int minPriority = maxPriority;
  929. while (usedPriorities.Contains(minPriority))
  930. --minPriority;
  931. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  932. {
  933. UIElement* other = *i;
  934. int priority = other->GetPriority();
  935. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  936. other->SetPriority(priority - 1);
  937. }
  938. }
  939. }
  940. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name, unsigned index)
  941. {
  942. // Check that creation succeeds and that the object in fact is a UI element
  943. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  944. if (!newElement)
  945. {
  946. LOGERROR("Could not create unknown UI element type " + type.ToString());
  947. return 0;
  948. }
  949. if (!name.Empty())
  950. newElement->SetName(name);
  951. InsertChild(index, newElement);
  952. return newElement;
  953. }
  954. void UIElement::AddChild(UIElement* element)
  955. {
  956. InsertChild(M_MAX_UNSIGNED, element);
  957. }
  958. void UIElement::InsertChild(unsigned index, UIElement* element)
  959. {
  960. // Check for illegal or redundant parent assignment
  961. if (!element || element == this || element->parent_ == this)
  962. return;
  963. // Check for possible cyclic parent assignment
  964. UIElement* parent = parent_;
  965. while (parent)
  966. {
  967. if (parent == element)
  968. return;
  969. parent = parent->parent_;
  970. }
  971. // Add first, then remove from old parent, to ensure the element does not get deleted
  972. if (index >= children_.Size())
  973. children_.Push(SharedPtr<UIElement>(element));
  974. else
  975. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  976. element->Remove();
  977. if (sortChildren_)
  978. sortOrderDirty_ = true;
  979. element->parent_ = this;
  980. element->MarkDirty();
  981. UpdateLayout();
  982. // Send change event
  983. UIElement* root = GetRoot();
  984. UIElement* sender = GetElementEventSender();
  985. if (sender)
  986. {
  987. using namespace ElementAdded;
  988. VariantMap eventData;
  989. eventData[P_ROOT] = (void*)root;
  990. eventData[P_PARENT] = (void*)this;
  991. eventData[P_ELEMENT] = (void*)element;
  992. sender->SendEvent(E_ELEMENTADDED, eventData);
  993. }
  994. }
  995. void UIElement::RemoveChild(UIElement* element, unsigned index)
  996. {
  997. UIElement* root = GetRoot();
  998. UIElement* sender = GetElementEventSender();
  999. for (unsigned i = index; i < children_.Size(); ++i)
  1000. {
  1001. if (children_[i] == element)
  1002. {
  1003. // Send change event if not already being destroyed
  1004. if (Refs() > 0 && sender)
  1005. {
  1006. using namespace ElementRemoved;
  1007. VariantMap eventData;
  1008. eventData[P_ROOT] = (void*)root;
  1009. eventData[P_PARENT] = (void*)this;
  1010. eventData[P_ELEMENT] = (void*)element;
  1011. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1012. }
  1013. element->Detach();
  1014. children_.Erase(i);
  1015. UpdateLayout();
  1016. return;
  1017. }
  1018. }
  1019. }
  1020. void UIElement::RemoveChildAtIndex(unsigned index)
  1021. {
  1022. if (index >= children_.Size())
  1023. return;
  1024. children_[index]->Detach();
  1025. children_.Erase(index);
  1026. UpdateLayout();
  1027. }
  1028. void UIElement::RemoveAllChildren()
  1029. {
  1030. UIElement* root = GetRoot();
  1031. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  1032. {
  1033. // Send change event if not already being destroyed
  1034. if (Refs() > 0 && root)
  1035. {
  1036. using namespace ElementRemoved;
  1037. VariantMap eventData;
  1038. eventData[P_ROOT] = (void*)root;
  1039. eventData[P_PARENT] = (void*)this;
  1040. eventData[P_ELEMENT] = (void*)(*i).Get();
  1041. root->SendEvent(E_ELEMENTREMOVED, eventData);
  1042. }
  1043. (*i++)->Detach();
  1044. }
  1045. children_.Clear();
  1046. }
  1047. void UIElement::Remove()
  1048. {
  1049. if (parent_)
  1050. parent_->RemoveChild(this);
  1051. }
  1052. unsigned UIElement::FindChild(UIElement* element) const
  1053. {
  1054. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  1055. return i != children_.End() ? i - children_.Begin() : M_MAX_UNSIGNED;
  1056. }
  1057. void UIElement::SetParent(UIElement* parent, unsigned index)
  1058. {
  1059. if (parent)
  1060. parent->InsertChild(index, this);
  1061. }
  1062. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  1063. {
  1064. vars_[key] = value;
  1065. }
  1066. void UIElement::SetInternal(bool enable)
  1067. {
  1068. internal_ = enable;
  1069. }
  1070. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  1071. {
  1072. traversalMode_ = traversalMode;
  1073. }
  1074. void UIElement::SetElementEventSender(bool flag)
  1075. {
  1076. elementEventSender_ = flag;
  1077. }
  1078. float UIElement::GetDerivedOpacity() const
  1079. {
  1080. if (!useDerivedOpacity_)
  1081. return opacity_;
  1082. if (opacityDirty_)
  1083. {
  1084. derivedOpacity_ = opacity_;
  1085. const UIElement* parent = parent_;
  1086. while (parent)
  1087. {
  1088. derivedOpacity_ *= parent->opacity_;
  1089. parent = parent->parent_;
  1090. }
  1091. opacityDirty_ = false;
  1092. }
  1093. return derivedOpacity_;
  1094. }
  1095. bool UIElement::HasFocus() const
  1096. {
  1097. UI* ui = GetSubsystem<UI>();
  1098. return ui ? ui->GetFocusElement() == this : false;
  1099. }
  1100. const String& UIElement::GetAppliedStyle() const
  1101. {
  1102. return appliedStyle_ == GetTypeName() ? String::EMPTY : appliedStyle_;
  1103. }
  1104. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  1105. {
  1106. if (recursiveUp)
  1107. {
  1108. const UIElement* element = this;
  1109. while (element)
  1110. {
  1111. if (element->defaultStyle_)
  1112. return element->defaultStyle_;
  1113. element = element->parent_;
  1114. }
  1115. return 0;
  1116. }
  1117. else
  1118. return defaultStyle_;
  1119. }
  1120. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1121. {
  1122. dest.Clear();
  1123. if (!recursive)
  1124. {
  1125. dest.Reserve(children_.Size());
  1126. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1127. dest.Push(*i);
  1128. }
  1129. else
  1130. GetChildrenRecursive(dest);
  1131. }
  1132. unsigned UIElement::GetNumChildren(bool recursive) const
  1133. {
  1134. if (!recursive)
  1135. return children_.Size();
  1136. else
  1137. {
  1138. unsigned allChildren = children_.Size();
  1139. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1140. allChildren += (*i)->GetNumChildren(true);
  1141. return allChildren;
  1142. }
  1143. }
  1144. UIElement* UIElement::GetChild(unsigned index) const
  1145. {
  1146. return index < children_.Size() ? children_[index] : (UIElement*)0;
  1147. }
  1148. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1149. {
  1150. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1151. {
  1152. if ((*i)->name_ == name)
  1153. return *i;
  1154. if (recursive)
  1155. {
  1156. UIElement* element = (*i)->GetChild(name, true);
  1157. if (element)
  1158. return element;
  1159. }
  1160. }
  1161. return 0;
  1162. }
  1163. UIElement* UIElement::GetChild(const ShortStringHash& key, const Variant& value, bool recursive) const
  1164. {
  1165. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1166. {
  1167. const Variant& varValue = (*i)->GetVar(key);
  1168. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1169. return *i;
  1170. if (recursive)
  1171. {
  1172. UIElement* element = (*i)->GetChild(key, value, true);
  1173. if (element)
  1174. return element;
  1175. }
  1176. }
  1177. return 0;
  1178. }
  1179. UIElement* UIElement::GetRoot() const
  1180. {
  1181. UIElement* root = parent_;
  1182. if (!root)
  1183. return 0;
  1184. while (root->GetParent())
  1185. root = root->GetParent();
  1186. return root;
  1187. }
  1188. const Color& UIElement::GetDerivedColor() const
  1189. {
  1190. if (derivedColorDirty_)
  1191. {
  1192. derivedColor_ = color_[C_TOPLEFT];
  1193. derivedColor_.a_ *= GetDerivedOpacity();
  1194. derivedColorDirty_ = false;
  1195. }
  1196. return derivedColor_;
  1197. }
  1198. const Variant& UIElement::GetVar(const ShortStringHash& key) const
  1199. {
  1200. VariantMap::ConstIterator i = vars_.Find(key);
  1201. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1202. }
  1203. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  1204. {
  1205. return screenPosition - GetScreenPosition();
  1206. }
  1207. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  1208. {
  1209. return position + GetScreenPosition();
  1210. }
  1211. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1212. {
  1213. if (isScreen)
  1214. position = ScreenToElement(position);
  1215. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1216. }
  1217. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1218. {
  1219. // If child elements are clipped, no need to expand the rect
  1220. if (clipChildren_)
  1221. return IsInside(position, isScreen);
  1222. if (!isScreen)
  1223. position = ElementToScreen(position);
  1224. IntRect combined = GetCombinedScreenRect();
  1225. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1226. position.y_ < combined.bottom_;
  1227. }
  1228. IntRect UIElement::GetCombinedScreenRect()
  1229. {
  1230. IntVector2 screenPosition(GetScreenPosition());
  1231. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1232. if (!clipChildren_)
  1233. {
  1234. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1235. {
  1236. IntVector2 childPos = (*i)->GetScreenPosition();
  1237. const IntVector2& childSize = (*i)->GetSize();
  1238. if (childPos.x_ < combined.left_)
  1239. combined.left_ = childPos.x_;
  1240. if (childPos.y_ < combined.top_)
  1241. combined.top_ = childPos.y_;
  1242. if (childPos.x_ + childSize.x_ > combined.right_)
  1243. combined.right_ = childPos.x_ + childSize.x_;
  1244. if (childPos.y_ + childSize.y_ > combined.bottom_)
  1245. combined.bottom_ = childPos.y_ + childSize.y_;
  1246. }
  1247. }
  1248. return combined;
  1249. }
  1250. void UIElement::SortChildren()
  1251. {
  1252. if (sortChildren_ && sortOrderDirty_)
  1253. {
  1254. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1255. sortOrderDirty_ = false;
  1256. }
  1257. }
  1258. void UIElement::SetChildOffset(const IntVector2& offset)
  1259. {
  1260. if (offset != childOffset_)
  1261. {
  1262. childOffset_ = offset;
  1263. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1264. (*i)->MarkDirty();
  1265. }
  1266. }
  1267. void UIElement::SetHovering(bool enable)
  1268. {
  1269. hovering_ = enable;
  1270. }
  1271. void UIElement::SetTempVisible(bool enable)
  1272. {
  1273. visible_ = enable;
  1274. }
  1275. void UIElement::AdjustScissor(IntRect& currentScissor)
  1276. {
  1277. if (clipChildren_)
  1278. {
  1279. IntVector2 screenPos = GetScreenPosition();
  1280. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1281. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1282. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1283. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1284. if (currentScissor.right_ < currentScissor.left_)
  1285. currentScissor.right_ = currentScissor.left_;
  1286. if (currentScissor.bottom_ < currentScissor.top_)
  1287. currentScissor.bottom_ = currentScissor.top_;
  1288. }
  1289. }
  1290. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData, IntRect
  1291. currentScissor)
  1292. {
  1293. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1294. unsigned initialSize = vertexData.Size();
  1295. GetBatches(batches, vertexData, currentScissor);
  1296. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1297. {
  1298. vertexData[i] += floatOffset.x_;
  1299. vertexData[i + 1] += floatOffset.y_;
  1300. }
  1301. AdjustScissor(currentScissor);
  1302. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1303. {
  1304. if ((*i)->IsVisible())
  1305. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1306. }
  1307. }
  1308. UIElement* UIElement::GetElementEventSender() const
  1309. {
  1310. UIElement* element = const_cast<UIElement*>(this);
  1311. if (elementEventSender_)
  1312. return element;
  1313. while (element->parent_)
  1314. {
  1315. element = element->parent_;
  1316. if (element->elementEventSender_)
  1317. return element;
  1318. }
  1319. // If no predefined element event sender in the parental chain, return ultimate root element
  1320. return element;
  1321. }
  1322. void UIElement::MarkDirty()
  1323. {
  1324. positionDirty_ = true;
  1325. opacityDirty_ = true;
  1326. derivedColorDirty_ = true;
  1327. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1328. (*i)->MarkDirty();
  1329. }
  1330. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1331. {
  1332. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1333. if (!matchXPathQuery.SetVariable("attributeName", name))
  1334. return false;
  1335. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1336. return !removeElem || parent.RemoveChild(removeElem);
  1337. }
  1338. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1339. {
  1340. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1341. if (!matchXPathQuery.SetVariable("attributeName", name))
  1342. return false;
  1343. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1344. return false;
  1345. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1346. return !removeElem || parent.RemoveChild(removeElem);
  1347. }
  1348. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1349. {
  1350. // Remove style attribute only when its value is identical to the value stored in style file
  1351. String style = styleElem.GetAttribute("style");
  1352. if (!style.Empty())
  1353. {
  1354. if (style == dest.GetAttribute("style"))
  1355. {
  1356. if (!dest.RemoveAttribute("style"))
  1357. {
  1358. LOGWARNING("Could not remove style attribute");
  1359. return false;
  1360. }
  1361. }
  1362. }
  1363. // Perform the same action recursively for internal child elements stored in style file
  1364. XMLElement childDest = dest.GetChild("element");
  1365. XMLElement childElem = styleElem.GetChild("element");
  1366. while (childDest && childElem)
  1367. {
  1368. if (!childElem.GetBool("internal"))
  1369. {
  1370. LOGERROR("Invalid style style, style element can only contain internal child elements");
  1371. return false;
  1372. }
  1373. if (!FilterUIStyleAttributes(childDest, childElem))
  1374. return false;
  1375. childDest = childDest.GetNext("element");
  1376. childElem = childElem.GetNext("element");
  1377. }
  1378. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1379. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1380. {
  1381. if (internal_)
  1382. {
  1383. if (!dest.SetAttribute("style", "none"))
  1384. return false;
  1385. }
  1386. else
  1387. {
  1388. if (!dest.RemoveAttribute("style"))
  1389. return false;
  1390. }
  1391. }
  1392. return true;
  1393. }
  1394. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1395. {
  1396. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1397. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1398. {
  1399. if (!RemoveChildXML(dest, "Min Size"))
  1400. return false;
  1401. }
  1402. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1403. {
  1404. if (!RemoveChildXML(dest, "Position"))
  1405. return false;
  1406. if (!RemoveChildXML(dest, "Size"))
  1407. return false;
  1408. }
  1409. return true;
  1410. }
  1411. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1412. {
  1413. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1414. {
  1415. UIElement* element = *i;
  1416. dest.Push(element);
  1417. if (!element->children_.Empty())
  1418. element->GetChildrenRecursive(dest);
  1419. }
  1420. }
  1421. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1422. {
  1423. int width = begin + end;
  1424. if (sizes.Empty())
  1425. return width;
  1426. for (unsigned i = 0; i < sizes.Size(); ++i)
  1427. {
  1428. // If calculating maximum size, and the default is specified, do not overflow it
  1429. if (sizes[i] == M_MAX_INT)
  1430. return M_MAX_INT;
  1431. width += sizes[i] + spacing;
  1432. }
  1433. // The last spacing is not needed
  1434. return width - spacing;
  1435. }
  1436. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1437. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1438. {
  1439. int numChildren = sizes.Size();
  1440. if (!numChildren)
  1441. return;
  1442. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1443. if (targetTotalSize < 0)
  1444. targetTotalSize = 0;
  1445. int targetChildSize = targetTotalSize / numChildren;
  1446. int remainder = targetTotalSize % numChildren;
  1447. float add = (float)remainder / numChildren;
  1448. float acc = 0.0f;
  1449. // Initial pass
  1450. for (int i = 0; i < numChildren; ++i)
  1451. {
  1452. int targetSize = targetChildSize;
  1453. if (remainder)
  1454. {
  1455. acc += add;
  1456. if (acc >= 0.5f)
  1457. {
  1458. acc -= 1.0f;
  1459. ++targetSize;
  1460. --remainder;
  1461. }
  1462. }
  1463. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1464. }
  1465. // Error correction passes
  1466. for (;;)
  1467. {
  1468. int actualTotalSize = 0;
  1469. for (int i = 0; i < numChildren; ++i)
  1470. actualTotalSize += sizes[i];
  1471. int error = targetTotalSize - actualTotalSize;
  1472. // Break if no error
  1473. if (!error)
  1474. break;
  1475. // Check which of the children can be resized to correct the error. If none, must break
  1476. PODVector<unsigned> resizable;
  1477. for (int i = 0; i < numChildren; ++i)
  1478. {
  1479. if (error < 0 && sizes[i] > minSizes[i])
  1480. resizable.Push(i);
  1481. else if (error > 0 && sizes[i] < maxSizes[i])
  1482. resizable.Push(i);
  1483. }
  1484. if (resizable.Empty())
  1485. break;
  1486. int numResizable = resizable.Size();
  1487. int errorPerChild = error / numResizable;
  1488. remainder = (abs(error)) % numResizable;
  1489. add = (float)remainder / numResizable;
  1490. acc = 0.0f;
  1491. for (int i = 0; i < numResizable; ++i)
  1492. {
  1493. unsigned index = resizable[i];
  1494. int targetSize = sizes[index] + errorPerChild;
  1495. if (remainder)
  1496. {
  1497. acc += add;
  1498. if (acc >= 0.5f)
  1499. {
  1500. acc -= 1.0f;
  1501. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1502. --remainder;
  1503. }
  1504. }
  1505. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1506. }
  1507. }
  1508. // Calculate final positions and store the minimum child element size
  1509. layoutMinSize_ = M_MAX_INT;
  1510. int position = begin;
  1511. for (int i = 0; i < numChildren; ++i)
  1512. {
  1513. positions[i] = position;
  1514. position += sizes[i] + spacing;
  1515. if (sizes[i] < layoutMinSize_)
  1516. layoutMinSize_ = sizes[i];
  1517. }
  1518. }
  1519. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1520. {
  1521. IntVector2 ret(IntVector2::ZERO);
  1522. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1523. switch (ha)
  1524. {
  1525. case HA_LEFT:
  1526. ret.x_ = layoutBorder_.left_;
  1527. break;
  1528. case HA_RIGHT:
  1529. ret.x_ = -layoutBorder_.right_;
  1530. break;
  1531. default:
  1532. break;
  1533. }
  1534. VerticalAlignment va = child->GetVerticalAlignment();
  1535. switch (va)
  1536. {
  1537. case VA_TOP:
  1538. ret.y_ = layoutBorder_.top_;
  1539. break;
  1540. case VA_BOTTOM:
  1541. ret.y_ = -layoutBorder_.bottom_;
  1542. break;
  1543. default:
  1544. break;
  1545. }
  1546. return ret;
  1547. }
  1548. void UIElement::Detach()
  1549. {
  1550. parent_ = 0;
  1551. MarkDirty();
  1552. }
  1553. }