UIElement.cpp 54 KB

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