UIElement.cpp 54 KB

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