UIElement.cpp 54 KB

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