UIElement.cpp 54 KB

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