UIElement.cpp 53 KB

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