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