2
0

UIElement.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  1. //
  2. // Copyright (c) 2008-2014 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 "CoreEvents.h"
  25. #include "Cursor.h"
  26. #include "HashSet.h"
  27. #include "Log.h"
  28. #include "ObjectAnimation.h"
  29. #include "ResourceCache.h"
  30. #include "Sort.h"
  31. #include "UI.h"
  32. #include "UIElement.h"
  33. #include "UIEvents.h"
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. const char* horizontalAlignments[] =
  38. {
  39. "Left",
  40. "Center",
  41. "Right",
  42. 0
  43. };
  44. const char* verticalAlignments[] =
  45. {
  46. "Top",
  47. "Center",
  48. "Bottom",
  49. 0
  50. };
  51. static const char* focusModes[] =
  52. {
  53. "NotFocusable",
  54. "ResetFocus",
  55. "Focusable",
  56. "FocusableDefocusable",
  57. 0
  58. };
  59. static const char* dragDropModes[] =
  60. {
  61. "Disabled",
  62. "Source",
  63. "Target",
  64. "SourceAndTarget",
  65. 0
  66. };
  67. static const char* layoutModes[] =
  68. {
  69. "Free",
  70. "Horizontal",
  71. "Vertical",
  72. 0
  73. };
  74. extern const char* UI_CATEGORY;
  75. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  76. {
  77. return lhs->GetPriority() < rhs->GetPriority();
  78. }
  79. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  80. {
  81. return (HorizontalAlignment)GetInt();
  82. }
  83. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  84. {
  85. return (VerticalAlignment)GetInt();
  86. }
  87. template<> FocusMode Variant::Get<FocusMode>() const
  88. {
  89. return (FocusMode)GetInt();
  90. }
  91. template<> LayoutMode Variant::Get<LayoutMode>() const
  92. {
  93. return (LayoutMode)GetInt();
  94. }
  95. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  96. UIElement::UIElement(Context* context) :
  97. Animatable(context),
  98. parent_(0),
  99. clipBorder_(IntRect::ZERO),
  100. priority_(0),
  101. bringToFront_(false),
  102. bringToBack_(true),
  103. clipChildren_(false),
  104. sortChildren_(true),
  105. useDerivedOpacity_(true),
  106. enabled_(false),
  107. editable_(true),
  108. selected_(false),
  109. visible_(true),
  110. hovering_(false),
  111. internal_(false),
  112. focusMode_(FM_NOTFOCUSABLE),
  113. dragDropMode_(DD_DISABLED),
  114. layoutMode_(LM_FREE),
  115. layoutSpacing_(0),
  116. layoutBorder_(IntRect::ZERO),
  117. resizeNestingLevel_(0),
  118. layoutNestingLevel_(0),
  119. layoutMinSize_(0),
  120. indent_(0),
  121. indentSpacing_(16),
  122. position_(IntVector2::ZERO),
  123. positionDirty_(true),
  124. size_(IntVector2::ZERO),
  125. minSize_(IntVector2::ZERO),
  126. maxSize_(M_MAX_INT, M_MAX_INT),
  127. childOffset_(IntVector2::ZERO),
  128. horizontalAlignment_(HA_LEFT),
  129. verticalAlignment_(VA_TOP),
  130. opacity_(1.0f),
  131. opacityDirty_(true),
  132. derivedColorDirty_(true),
  133. sortOrderDirty_(false),
  134. colorGradient_(false),
  135. traversalMode_(TM_BREADTH_FIRST),
  136. elementEventSender_(false)
  137. {
  138. }
  139. UIElement::~UIElement()
  140. {
  141. // If child elements have outside references, detach them
  142. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  143. {
  144. if (i->Refs() > 1)
  145. (*i)->Detach();
  146. }
  147. }
  148. void UIElement::RegisterObject(Context* context)
  149. {
  150. context->RegisterFactory<UIElement>(UI_CATEGORY);
  151. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  152. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  153. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  154. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  155. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2(M_MAX_INT, M_MAX_INT), AM_FILE);
  156. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  157. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  158. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  159. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  160. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  161. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_COLOR, "Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  162. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  163. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  164. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  165. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  167. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Editable", IsEditable, SetEditable, bool, true, AM_FILE);
  168. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  169. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  170. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  171. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  172. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  173. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, true, AM_FILE);
  174. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  175. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  176. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  177. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  178. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  179. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  180. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  181. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE);
  182. }
  183. void UIElement::ApplyAttributes()
  184. {
  185. colorGradient_ = false;
  186. derivedColorDirty_ = true;
  187. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  188. {
  189. if (color_[i] != color_[0])
  190. colorGradient_ = true;
  191. }
  192. }
  193. bool UIElement::LoadXML(const XMLElement& source, bool setInstanceDefault)
  194. {
  195. return LoadXML(source, 0, setInstanceDefault);
  196. }
  197. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile, bool setInstanceDefault)
  198. {
  199. // Get style override if defined
  200. String styleName = source.GetAttribute("style");
  201. // Apply the style first, if the style file is available
  202. if (styleFile)
  203. {
  204. // If not defined, use type name
  205. if (styleName.Empty())
  206. styleName = GetTypeName();
  207. SetStyle(styleName, styleFile);
  208. }
  209. // The 'style' attribute value in the style file cannot be equals to original's applied style to prevent infinite loop
  210. else if (!styleName.Empty() && styleName != appliedStyle_)
  211. {
  212. // Attempt to use the default style file
  213. styleFile = GetDefaultStyle();
  214. if (styleFile)
  215. {
  216. // Remember the original applied style
  217. String appliedStyle(appliedStyle_);
  218. SetStyle(styleName, styleFile);
  219. appliedStyle_ = appliedStyle;
  220. }
  221. }
  222. // Then load rest of the attributes from the source
  223. if (!Animatable::LoadXML(source, setInstanceDefault))
  224. return false;
  225. unsigned nextInternalChild = 0;
  226. // Load child elements. Internal elements are not to be created as they already exist
  227. XMLElement childElem = source.GetChild("element");
  228. while (childElem)
  229. {
  230. bool internalElem = childElem.GetBool("internal");
  231. String typeName = childElem.GetAttribute("type");
  232. if (typeName.Empty())
  233. typeName = "UIElement";
  234. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  235. UIElement* child = 0;
  236. if (!internalElem)
  237. child = CreateChild(typeName, String::EMPTY, index);
  238. else
  239. {
  240. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  241. {
  242. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  243. {
  244. child = children_[i];
  245. nextInternalChild = i + 1;
  246. break;
  247. }
  248. }
  249. if (!child)
  250. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  251. }
  252. if (child)
  253. {
  254. if (!styleFile)
  255. styleFile = GetDefaultStyle();
  256. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  257. return false;
  258. }
  259. childElem = childElem.GetNext("element");
  260. }
  261. ApplyAttributes();
  262. return true;
  263. }
  264. bool UIElement::LoadChildXML(const XMLElement& childElem, XMLFile* styleFile, bool setInstanceDefault)
  265. {
  266. bool internalElem = childElem.GetBool("internal");
  267. if (internalElem)
  268. {
  269. LOGERROR("Loading internal child element is not supported");
  270. return false;
  271. }
  272. String typeName = childElem.GetAttribute("type");
  273. if (typeName.Empty())
  274. typeName = "UIElement";
  275. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  276. UIElement* child = CreateChild(typeName, String::EMPTY, index);
  277. if (child)
  278. {
  279. if (!styleFile)
  280. styleFile = GetDefaultStyle();
  281. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  282. return false;
  283. }
  284. return true;
  285. }
  286. bool UIElement::SaveXML(XMLElement& dest) const
  287. {
  288. // Write type
  289. if (GetTypeName() != "UIElement")
  290. {
  291. if (!dest.SetString("type", GetTypeName()))
  292. return false;
  293. }
  294. // Write internal flag
  295. if (internal_)
  296. {
  297. if (!dest.SetBool("internal", internal_))
  298. return false;
  299. }
  300. // Write style
  301. if (!appliedStyle_.Empty() && appliedStyle_ != "UIElement")
  302. {
  303. if (!dest.SetAttribute("style", appliedStyle_))
  304. return false;
  305. }
  306. else if (internal_)
  307. {
  308. if (!dest.SetAttribute("style", "none"))
  309. return false;
  310. }
  311. // Write attributes
  312. if (!Animatable::SaveXML(dest))
  313. return false;
  314. // Write child elements
  315. for (unsigned i = 0; i < children_.Size(); ++i)
  316. {
  317. UIElement* element = children_[i];
  318. if (element->IsTemporary())
  319. continue;
  320. XMLElement childElem = dest.CreateChild("element");
  321. if (!element->SaveXML(childElem))
  322. return false;
  323. }
  324. // Filter UI-style and implicit attributes
  325. if (!FilterAttributes(dest))
  326. return false;
  327. return true;
  328. }
  329. void UIElement::Update(float timeStep)
  330. {
  331. }
  332. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  333. {
  334. // Reset hovering for next frame
  335. hovering_ = false;
  336. }
  337. void UIElement::GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  338. {
  339. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  340. int horizontalThickness = 1;
  341. int verticalThickness = 1;
  342. if (parent_)
  343. {
  344. switch (parent_->layoutMode_)
  345. {
  346. case LM_HORIZONTAL:
  347. verticalThickness +=2;
  348. break;
  349. case LM_VERTICAL:
  350. horizontalThickness += 2;
  351. break;
  352. default:
  353. break;
  354. }
  355. }
  356. batch.SetColor(DEBUG_DRAW_COLOR, true);
  357. // Left
  358. batch.AddQuad(0, 0, horizontalThickness, size_.y_, 0, 0);
  359. // Top
  360. batch.AddQuad(0, 0, size_.x_, verticalThickness, 0, 0);
  361. // Right
  362. batch.AddQuad(size_.x_ - horizontalThickness, 0, horizontalThickness, size_.y_, 0, 0);
  363. // Bottom
  364. batch.AddQuad(0, size_.y_ - verticalThickness, size_.x_, verticalThickness, 0, 0);
  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. hovering_ = true;
  418. }
  419. bool UIElement::LoadXML(Deserializer& source)
  420. {
  421. SharedPtr<XMLFile> xml(new XMLFile(context_));
  422. return xml->Load(source) && LoadXML(xml->GetRoot());
  423. }
  424. bool UIElement::SaveXML(Serializer& dest) const
  425. {
  426. SharedPtr<XMLFile> xml(new XMLFile(context_));
  427. XMLElement rootElem = xml->CreateRoot("element");
  428. return SaveXML(rootElem) && xml->Save(dest);
  429. }
  430. bool UIElement::FilterAttributes(XMLElement& dest) const
  431. {
  432. // Filter UI styling attributes
  433. XMLFile* styleFile = GetDefaultStyle();
  434. if (styleFile)
  435. {
  436. String style = dest.GetAttribute("style");
  437. if (!style.Empty() && style != "none")
  438. {
  439. if (styleXPathQuery_.SetVariable("typeName", style))
  440. {
  441. XMLElement styleElem = GetDefaultStyle()->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  442. if (styleElem && !FilterUIStyleAttributes(dest, styleElem))
  443. return false;
  444. }
  445. }
  446. }
  447. // Filter implicit attributes
  448. if (!FilterImplicitAttributes(dest))
  449. {
  450. LOGERROR("Could not remove implicit attributes");
  451. return false;
  452. }
  453. return true;
  454. }
  455. void UIElement::SetName(const String& name)
  456. {
  457. name_ = name;
  458. using namespace NameChanged;
  459. VariantMap& eventData = GetEventDataMap();
  460. eventData[P_ELEMENT] = this;
  461. SendEvent(E_NAMECHANGED, eventData);
  462. }
  463. void UIElement::SetPosition(const IntVector2& position)
  464. {
  465. if (position != position_)
  466. {
  467. position_ = position;
  468. OnPositionSet();
  469. MarkDirty();
  470. using namespace Positioned;
  471. VariantMap& eventData = GetEventDataMap();
  472. eventData[P_ELEMENT] = this;
  473. eventData[P_X] = position_.x_;
  474. eventData[P_Y] = position_.y_;
  475. SendEvent(E_POSITIONED, eventData);
  476. }
  477. }
  478. void UIElement::SetPosition(int x, int y)
  479. {
  480. SetPosition(IntVector2(x, y));
  481. }
  482. void UIElement::SetSize(const IntVector2& size)
  483. {
  484. ++resizeNestingLevel_;
  485. IntVector2 validatedSize;
  486. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  487. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  488. if (validatedSize != size_)
  489. {
  490. size_ = validatedSize;
  491. if (resizeNestingLevel_ == 1)
  492. {
  493. // Check if parent element's layout needs to be updated first
  494. if (parent_)
  495. parent_->UpdateLayout();
  496. MarkDirty();
  497. OnResize();
  498. UpdateLayout();
  499. using namespace Resized;
  500. VariantMap& eventData = GetEventDataMap();
  501. eventData[P_ELEMENT] = this;
  502. eventData[P_WIDTH] = size_.x_;
  503. eventData[P_HEIGHT] = size_.y_;
  504. SendEvent(E_RESIZED, eventData);
  505. }
  506. }
  507. --resizeNestingLevel_;
  508. }
  509. void UIElement::SetSize(int width, int height)
  510. {
  511. SetSize(IntVector2(width, height));
  512. }
  513. void UIElement::SetWidth(int width)
  514. {
  515. SetSize(IntVector2(width, size_.y_));
  516. }
  517. void UIElement::SetHeight(int height)
  518. {
  519. SetSize(IntVector2(size_.x_, height));
  520. }
  521. void UIElement::SetMinSize(const IntVector2& minSize)
  522. {
  523. minSize_.x_ = Max(minSize.x_, 0);
  524. minSize_.y_ = Max(minSize.y_, 0);
  525. SetSize(size_);
  526. }
  527. void UIElement::SetMinSize(int width, int height)
  528. {
  529. SetMinSize(IntVector2(width, height));
  530. }
  531. void UIElement::SetMinWidth(int width)
  532. {
  533. SetMinSize(IntVector2(width, minSize_.y_));
  534. }
  535. void UIElement::SetMinHeight(int height)
  536. {
  537. SetMinSize(IntVector2(minSize_.x_, height));
  538. }
  539. void UIElement::SetMaxSize(const IntVector2& maxSize)
  540. {
  541. maxSize_.x_ = Max(maxSize.x_, 0);
  542. maxSize_.y_ = Max(maxSize.y_, 0);
  543. SetSize(size_);
  544. }
  545. void UIElement::SetMaxSize(int width, int height)
  546. {
  547. SetMaxSize(IntVector2(width, height));
  548. }
  549. void UIElement::SetMaxWidth(int width)
  550. {
  551. SetMaxSize(IntVector2(width, maxSize_.y_));
  552. }
  553. void UIElement::SetMaxHeight(int height)
  554. {
  555. SetMaxSize(IntVector2(maxSize_.x_, height));
  556. }
  557. void UIElement::SetFixedSize(const IntVector2& size)
  558. {
  559. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  560. SetSize(size);
  561. }
  562. void UIElement::SetFixedSize(int width, int height)
  563. {
  564. SetFixedSize(IntVector2(width, height));
  565. }
  566. void UIElement::SetFixedWidth(int width)
  567. {
  568. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  569. SetWidth(width);
  570. }
  571. void UIElement::SetFixedHeight(int height)
  572. {
  573. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  574. SetHeight(height);
  575. }
  576. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  577. {
  578. SetHorizontalAlignment(hAlign);
  579. SetVerticalAlignment(vAlign);
  580. }
  581. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  582. {
  583. if (align != HA_LEFT && parent_ && parent_->GetLayoutMode() == LM_HORIZONTAL)
  584. {
  585. LOGWARNING("Forcing left alignment because parent element has horizontal layout");
  586. align = HA_LEFT;
  587. }
  588. if (horizontalAlignment_ != align)
  589. {
  590. horizontalAlignment_ = align;
  591. MarkDirty();
  592. }
  593. }
  594. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  595. {
  596. if (align != VA_TOP && parent_ && parent_->GetLayoutMode() == LM_VERTICAL)
  597. {
  598. LOGWARNING("Forcing top alignment because parent element has vertical layout");
  599. align = VA_TOP;
  600. }
  601. if (verticalAlignment_ != align)
  602. {
  603. verticalAlignment_ = align;
  604. MarkDirty();
  605. }
  606. }
  607. void UIElement::SetClipBorder(const IntRect& rect)
  608. {
  609. clipBorder_.left_ = Max(rect.left_, 0);
  610. clipBorder_.top_ = Max(rect.top_, 0);
  611. clipBorder_.right_ = Max(rect.right_, 0);
  612. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  613. }
  614. void UIElement::SetColor(const Color& color)
  615. {
  616. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  617. color_[i] = color;
  618. colorGradient_ = false;
  619. derivedColorDirty_ = true;
  620. }
  621. void UIElement::SetColor(Corner corner, const Color& color)
  622. {
  623. color_[corner] = color;
  624. colorGradient_ = false;
  625. derivedColorDirty_ = true;
  626. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  627. {
  628. if (i != corner && color_[i] != color_[corner])
  629. colorGradient_ = true;
  630. }
  631. }
  632. void UIElement::SetPriority(int priority)
  633. {
  634. priority_ = priority;
  635. if (parent_)
  636. parent_->sortOrderDirty_ = true;
  637. }
  638. void UIElement::SetOpacity(float opacity)
  639. {
  640. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  641. MarkDirty();
  642. }
  643. void UIElement::SetBringToFront(bool enable)
  644. {
  645. bringToFront_ = enable;
  646. }
  647. void UIElement::SetBringToBack(bool enable)
  648. {
  649. bringToBack_ = enable;
  650. }
  651. void UIElement::SetClipChildren(bool enable)
  652. {
  653. clipChildren_ = enable;
  654. }
  655. void UIElement::SetSortChildren(bool enable)
  656. {
  657. if (!sortChildren_ && enable)
  658. sortOrderDirty_ = true;
  659. sortChildren_ = enable;
  660. }
  661. void UIElement::SetUseDerivedOpacity(bool enable)
  662. {
  663. useDerivedOpacity_ = enable;
  664. }
  665. void UIElement::SetEnabled(bool enable)
  666. {
  667. enabled_ = enable;
  668. }
  669. void UIElement::SetEditable(bool enable)
  670. {
  671. editable_ = enable;
  672. OnSetEditable();
  673. }
  674. void UIElement::SetFocusMode(FocusMode mode)
  675. {
  676. focusMode_ = mode;
  677. }
  678. void UIElement::SetFocus(bool enable)
  679. {
  680. if (focusMode_ < FM_FOCUSABLE)
  681. enable = false;
  682. UI* ui = GetSubsystem<UI>();
  683. if (enable)
  684. {
  685. if (ui->GetFocusElement() != this)
  686. ui->SetFocusElement(this);
  687. }
  688. else
  689. {
  690. if (ui->GetFocusElement() == this)
  691. ui->SetFocusElement(0);
  692. }
  693. }
  694. void UIElement::SetSelected(bool enable)
  695. {
  696. selected_ = enable;
  697. }
  698. void UIElement::SetVisible(bool enable)
  699. {
  700. if (enable != visible_)
  701. {
  702. visible_ = enable;
  703. // Parent's layout may change as a result of visibility change
  704. if (parent_)
  705. parent_->UpdateLayout();
  706. using namespace VisibleChanged;
  707. VariantMap& eventData = GetEventDataMap();
  708. eventData[P_ELEMENT] = this;
  709. eventData[P_VISIBLE] = visible_;
  710. SendEvent(E_VISIBLECHANGED, eventData);
  711. }
  712. }
  713. void UIElement::SetDragDropMode(unsigned mode)
  714. {
  715. dragDropMode_ = mode;
  716. }
  717. bool UIElement::SetStyle(const String& styleName, XMLFile* file)
  718. {
  719. // If empty style was requested, replace with type name
  720. String actualStyleName = !styleName.Empty() ? styleName : GetTypeName();
  721. appliedStyle_ = actualStyleName;
  722. if (styleName == "none")
  723. return true;
  724. if (!file)
  725. {
  726. file = GetDefaultStyle();
  727. if (!file)
  728. return false;
  729. }
  730. else
  731. {
  732. // If a custom style file specified, remember it
  733. defaultStyle_ = file;
  734. }
  735. styleXPathQuery_.SetVariable("typeName", actualStyleName);
  736. XMLElement styleElem = file->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  737. return styleElem && SetStyle(styleElem);
  738. }
  739. bool UIElement::SetStyle(const XMLElement& element)
  740. {
  741. appliedStyle_ = element.GetAttribute("type");
  742. // Consider style attribute values as instance-level attribute default values
  743. return LoadXML(element, true);
  744. }
  745. bool UIElement::SetStyleAuto(XMLFile* file)
  746. {
  747. return SetStyle(String::EMPTY, file);
  748. }
  749. void UIElement::SetDefaultStyle(XMLFile* style)
  750. {
  751. defaultStyle_ = style;
  752. }
  753. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  754. {
  755. layoutMode_ = mode;
  756. layoutSpacing_ = Max(spacing, 0);
  757. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  758. VerifyChildAlignment();
  759. UpdateLayout();
  760. }
  761. void UIElement::SetLayoutMode(LayoutMode mode)
  762. {
  763. layoutMode_ = mode;
  764. VerifyChildAlignment();
  765. UpdateLayout();
  766. }
  767. void UIElement::SetLayoutSpacing(int spacing)
  768. {
  769. layoutSpacing_ = Max(spacing, 0);
  770. UpdateLayout();
  771. }
  772. void UIElement::SetLayoutBorder(const IntRect& border)
  773. {
  774. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  775. UpdateLayout();
  776. }
  777. void UIElement::SetIndent(int indent)
  778. {
  779. indent_ = indent;
  780. if (parent_)
  781. parent_->UpdateLayout();
  782. UpdateLayout();
  783. OnIndentSet();
  784. }
  785. void UIElement::SetIndentSpacing(int indentSpacing)
  786. {
  787. indentSpacing_ = Max(indentSpacing, 0);
  788. if (parent_)
  789. parent_->UpdateLayout();
  790. UpdateLayout();
  791. OnIndentSet();
  792. }
  793. void UIElement::UpdateLayout()
  794. {
  795. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  796. return;
  797. // Prevent further updates while this update happens
  798. DisableLayoutUpdate();
  799. PODVector<int> positions;
  800. PODVector<int> sizes;
  801. PODVector<int> minSizes;
  802. PODVector<int> maxSizes;
  803. int baseIndentWidth = GetIndentWidth();
  804. if (layoutMode_ == LM_HORIZONTAL)
  805. {
  806. int minChildHeight = 0;
  807. for (unsigned i = 0; i < children_.Size(); ++i)
  808. {
  809. if (!children_[i]->IsVisible())
  810. continue;
  811. positions.Push(baseIndentWidth);
  812. unsigned indent = children_[i]->GetIndentWidth();
  813. sizes.Push(children_[i]->GetWidth() + indent);
  814. minSizes.Push(children_[i]->GetMinWidth() + indent);
  815. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  816. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  817. }
  818. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  819. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  820. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  821. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  822. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  823. // Respect fixed size if already set
  824. if (minSize_.x_ != maxSize_.x_)
  825. minSize_.x_ = minWidth;
  826. if (minSize_.y_ != maxSize_.y_)
  827. minSize_.y_ = minHeight;
  828. SetSize(width, height);
  829. // Validate the size before resizing child elements, in case of min/max limits
  830. width = size_.x_;
  831. height = size_.y_;
  832. unsigned j = 0;
  833. for (unsigned i = 0; i < children_.Size(); ++i)
  834. {
  835. if (!children_[i]->IsVisible())
  836. continue;
  837. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  838. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  839. ++j;
  840. }
  841. }
  842. else if (layoutMode_ == LM_VERTICAL)
  843. {
  844. int minChildWidth = 0;
  845. for (unsigned i = 0; i < children_.Size(); ++i)
  846. {
  847. if (!children_[i]->IsVisible())
  848. continue;
  849. positions.Push(0);
  850. sizes.Push(children_[i]->GetHeight());
  851. minSizes.Push(children_[i]->GetMinHeight());
  852. maxSizes.Push(children_[i]->GetMaxHeight());
  853. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  854. }
  855. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  856. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  857. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  858. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  859. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  860. if (minSize_.x_ != maxSize_.x_)
  861. minSize_.x_ = minWidth;
  862. if (minSize_.y_ != maxSize_.y_)
  863. minSize_.y_ = minHeight;
  864. SetSize(width, height);
  865. width = size_.x_;
  866. height = size_.y_;
  867. unsigned j = 0;
  868. for (unsigned i = 0; i < children_.Size(); ++i)
  869. {
  870. if (!children_[i]->IsVisible())
  871. continue;
  872. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  873. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  874. ++j;
  875. }
  876. }
  877. using namespace LayoutUpdated;
  878. VariantMap& eventData = GetEventDataMap();
  879. eventData[P_ELEMENT] = this;
  880. SendEvent(E_LAYOUTUPDATED, eventData);
  881. EnableLayoutUpdate();
  882. }
  883. void UIElement::DisableLayoutUpdate()
  884. {
  885. ++layoutNestingLevel_;
  886. }
  887. void UIElement::EnableLayoutUpdate()
  888. {
  889. --layoutNestingLevel_;
  890. }
  891. void UIElement::BringToFront()
  892. {
  893. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  894. UIElement* root = GetRoot();
  895. // If element is detached from hierarchy, this must be a no-op
  896. if (!root)
  897. return;
  898. UIElement* ptr = this;
  899. while (ptr && ptr->GetParent() != root)
  900. ptr = ptr->GetParent();
  901. if (!ptr || !ptr->GetBringToFront())
  902. return;
  903. // Get the highest priority used by all other top level elements, assign that to the new front element
  904. // and decrease others' priority where necessary. However, take into account only input-enabled
  905. // elements and those which have the BringToBack flag set
  906. HashSet<int> usedPriorities;
  907. int maxPriority = M_MIN_INT;
  908. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  909. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  910. {
  911. UIElement* other = *i;
  912. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  913. {
  914. int priority = other->GetPriority();
  915. // M_MAX_INT is used by popups and tooltips. Disregard these to avoid an "arms race" with the priorities
  916. if (priority == M_MAX_INT)
  917. continue;
  918. usedPriorities.Insert(priority);
  919. maxPriority = Max(priority, maxPriority);
  920. }
  921. }
  922. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  923. {
  924. ptr->SetPriority(maxPriority);
  925. int minPriority = maxPriority;
  926. while (usedPriorities.Contains(minPriority))
  927. --minPriority;
  928. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  929. {
  930. UIElement* other = *i;
  931. int priority = other->GetPriority();
  932. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  933. other->SetPriority(priority - 1);
  934. }
  935. }
  936. }
  937. UIElement* UIElement::CreateChild(StringHash type, const String& name, unsigned index)
  938. {
  939. // Check that creation succeeds and that the object in fact is a UI element
  940. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  941. if (!newElement)
  942. {
  943. LOGERROR("Could not create unknown UI element type " + type.ToString());
  944. return 0;
  945. }
  946. if (!name.Empty())
  947. newElement->SetName(name);
  948. InsertChild(index, newElement);
  949. return newElement;
  950. }
  951. void UIElement::AddChild(UIElement* element)
  952. {
  953. InsertChild(M_MAX_UNSIGNED, element);
  954. }
  955. void UIElement::InsertChild(unsigned index, UIElement* element)
  956. {
  957. // Check for illegal or redundant parent assignment
  958. if (!element || element == this || element->parent_ == this)
  959. return;
  960. // Check for possible cyclic parent assignment
  961. UIElement* parent = parent_;
  962. while (parent)
  963. {
  964. if (parent == element)
  965. return;
  966. parent = parent->parent_;
  967. }
  968. // Add first, then remove from old parent, to ensure the element does not get deleted
  969. if (index >= children_.Size())
  970. children_.Push(SharedPtr<UIElement>(element));
  971. else
  972. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  973. XMLFile* previousStyleFile = element->GetDefaultStyle();
  974. element->Remove();
  975. if (sortChildren_)
  976. sortOrderDirty_ = true;
  977. element->parent_ = this;
  978. element->MarkDirty();
  979. // If child element did not already have a style file, but has specified a style name, apply it now
  980. if (!previousStyleFile && !element->appliedStyle_.Empty() && GetDefaultStyle())
  981. element->SetStyle(element->appliedStyle_);
  982. VerifyChildAlignment();
  983. UpdateLayout();
  984. // Send change event
  985. UIElement* root = GetRoot();
  986. UIElement* sender = GetElementEventSender();
  987. if (sender)
  988. {
  989. using namespace ElementAdded;
  990. VariantMap& eventData = GetEventDataMap();
  991. eventData[P_ROOT] = root;
  992. eventData[P_PARENT] = this;
  993. eventData[P_ELEMENT] = element;
  994. sender->SendEvent(E_ELEMENTADDED, eventData);
  995. }
  996. }
  997. void UIElement::RemoveChild(UIElement* element, unsigned index)
  998. {
  999. for (unsigned i = index; i < children_.Size(); ++i)
  1000. {
  1001. if (children_[i] == element)
  1002. {
  1003. // Send change event if not already being destroyed
  1004. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1005. if (sender)
  1006. {
  1007. using namespace ElementRemoved;
  1008. VariantMap& eventData = GetEventDataMap();
  1009. eventData[P_ROOT] = GetRoot();
  1010. eventData[P_PARENT] = this;
  1011. eventData[P_ELEMENT] = element;
  1012. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1013. }
  1014. element->Detach();
  1015. children_.Erase(i);
  1016. UpdateLayout();
  1017. return;
  1018. }
  1019. }
  1020. }
  1021. void UIElement::RemoveChildAtIndex(unsigned index)
  1022. {
  1023. if (index >= children_.Size())
  1024. return;
  1025. // Send change event if not already being destroyed
  1026. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1027. if (sender)
  1028. {
  1029. using namespace ElementRemoved;
  1030. VariantMap& eventData = GetEventDataMap();
  1031. eventData[P_ROOT] = GetRoot();
  1032. eventData[P_PARENT] = this;
  1033. eventData[P_ELEMENT] = children_[index];
  1034. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1035. }
  1036. children_[index]->Detach();
  1037. children_.Erase(index);
  1038. UpdateLayout();
  1039. }
  1040. void UIElement::RemoveAllChildren()
  1041. {
  1042. UIElement* root = GetRoot();
  1043. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1044. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  1045. {
  1046. // Send change event if not already being destroyed
  1047. if (sender)
  1048. {
  1049. using namespace ElementRemoved;
  1050. VariantMap& eventData = GetEventDataMap();
  1051. eventData[P_ROOT] = root;
  1052. eventData[P_PARENT] = this;
  1053. eventData[P_ELEMENT] = (*i).Get();
  1054. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1055. }
  1056. (*i++)->Detach();
  1057. }
  1058. children_.Clear();
  1059. UpdateLayout();
  1060. }
  1061. void UIElement::Remove()
  1062. {
  1063. if (parent_)
  1064. parent_->RemoveChild(this);
  1065. }
  1066. unsigned UIElement::FindChild(UIElement* element) const
  1067. {
  1068. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  1069. return i != children_.End() ? i - children_.Begin() : M_MAX_UNSIGNED;
  1070. }
  1071. void UIElement::SetParent(UIElement* parent, unsigned index)
  1072. {
  1073. if (parent)
  1074. parent->InsertChild(index, this);
  1075. }
  1076. void UIElement::SetVar(StringHash key, const Variant& value)
  1077. {
  1078. vars_[key] = value;
  1079. }
  1080. void UIElement::SetInternal(bool enable)
  1081. {
  1082. internal_ = enable;
  1083. }
  1084. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  1085. {
  1086. traversalMode_ = traversalMode;
  1087. }
  1088. void UIElement::SetElementEventSender(bool flag)
  1089. {
  1090. elementEventSender_ = flag;
  1091. }
  1092. float UIElement::GetDerivedOpacity() const
  1093. {
  1094. if (!useDerivedOpacity_)
  1095. return opacity_;
  1096. if (opacityDirty_)
  1097. {
  1098. derivedOpacity_ = opacity_;
  1099. const UIElement* parent = parent_;
  1100. while (parent)
  1101. {
  1102. derivedOpacity_ *= parent->opacity_;
  1103. parent = parent->parent_;
  1104. }
  1105. opacityDirty_ = false;
  1106. }
  1107. return derivedOpacity_;
  1108. }
  1109. bool UIElement::HasFocus() const
  1110. {
  1111. return GetSubsystem<UI>()->GetFocusElement() == this;
  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 StringHash& 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 StringHash& 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::OnAttributeAnimationAdded()
  1334. {
  1335. if (attributeAnimationInfos_.Size() == 1)
  1336. SubscribeToEvent(E_POSTUPDATE, HANDLER(UIElement, HandlePostUpdate));
  1337. }
  1338. void UIElement::OnAttributeAnimationRemoved()
  1339. {
  1340. if (attributeAnimationInfos_.Empty())
  1341. UnsubscribeFromEvent(E_POSTUPDATE);
  1342. }
  1343. void UIElement::SetObjectAttributeAnimation(const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed)
  1344. {
  1345. Vector<String> names = name.Split('/');
  1346. // Only attribute name
  1347. if (names.Size() == 1)
  1348. SetAttributeAnimation(name, attributeAnimation, wrapMode, speed);
  1349. else
  1350. {
  1351. // Name must in following format: "#0/#1/attribute"
  1352. UIElement* element = this;
  1353. for (unsigned i = 0; i < names.Size() - 1; ++i)
  1354. {
  1355. if (names[i].Front() != '#')
  1356. {
  1357. LOGERROR("Invalid name " + name);
  1358. return;
  1359. }
  1360. unsigned index = ToInt(names[i].Substring(1, names[i].Length() - 1));
  1361. element = element->GetChild(index);
  1362. if (!element)
  1363. {
  1364. LOGERROR("Could not find element by name " + name);
  1365. return;
  1366. }
  1367. }
  1368. element->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1369. }
  1370. }
  1371. void UIElement::MarkDirty()
  1372. {
  1373. positionDirty_ = true;
  1374. opacityDirty_ = true;
  1375. derivedColorDirty_ = true;
  1376. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1377. (*i)->MarkDirty();
  1378. }
  1379. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1380. {
  1381. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1382. if (!matchXPathQuery.SetVariable("attributeName", name))
  1383. return false;
  1384. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1385. return !removeElem || parent.RemoveChild(removeElem);
  1386. }
  1387. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1388. {
  1389. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1390. if (!matchXPathQuery.SetVariable("attributeName", name))
  1391. return false;
  1392. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1393. return false;
  1394. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1395. return !removeElem || parent.RemoveChild(removeElem);
  1396. }
  1397. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1398. {
  1399. // Remove style attribute only when its value is identical to the value stored in style file
  1400. String style = styleElem.GetAttribute("style");
  1401. if (!style.Empty())
  1402. {
  1403. if (style == dest.GetAttribute("style"))
  1404. {
  1405. if (!dest.RemoveAttribute("style"))
  1406. {
  1407. LOGWARNING("Could not remove style attribute");
  1408. return false;
  1409. }
  1410. }
  1411. }
  1412. // Perform the same action recursively for internal child elements stored in style file
  1413. XMLElement childDest = dest.GetChild("element");
  1414. XMLElement childElem = styleElem.GetChild("element");
  1415. while (childDest && childElem)
  1416. {
  1417. if (!childElem.GetBool("internal"))
  1418. {
  1419. LOGERROR("Invalid style file, style element can only contain internal child elements");
  1420. return false;
  1421. }
  1422. if (!FilterUIStyleAttributes(childDest, childElem))
  1423. return false;
  1424. childDest = childDest.GetNext("element");
  1425. childElem = childElem.GetNext("element");
  1426. }
  1427. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1428. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1429. {
  1430. if (internal_)
  1431. {
  1432. if (!dest.SetAttribute("style", "none"))
  1433. return false;
  1434. }
  1435. else
  1436. {
  1437. if (!dest.RemoveAttribute("style"))
  1438. return false;
  1439. }
  1440. }
  1441. return true;
  1442. }
  1443. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1444. {
  1445. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1446. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1447. {
  1448. if (!RemoveChildXML(dest, "Min Size"))
  1449. return false;
  1450. }
  1451. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1452. {
  1453. if (!RemoveChildXML(dest, "Position"))
  1454. return false;
  1455. if (!RemoveChildXML(dest, "Size"))
  1456. return false;
  1457. }
  1458. return true;
  1459. }
  1460. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1461. {
  1462. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1463. {
  1464. UIElement* element = *i;
  1465. dest.Push(element);
  1466. if (!element->children_.Empty())
  1467. element->GetChildrenRecursive(dest);
  1468. }
  1469. }
  1470. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1471. {
  1472. int width = begin + end;
  1473. if (sizes.Empty())
  1474. return width;
  1475. for (unsigned i = 0; i < sizes.Size(); ++i)
  1476. {
  1477. // If calculating maximum size, and the default is specified, do not overflow it
  1478. if (sizes[i] == M_MAX_INT)
  1479. return M_MAX_INT;
  1480. width += sizes[i] + spacing;
  1481. }
  1482. // The last spacing is not needed
  1483. return width - spacing;
  1484. }
  1485. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1486. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1487. {
  1488. int numChildren = sizes.Size();
  1489. if (!numChildren)
  1490. return;
  1491. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1492. if (targetTotalSize < 0)
  1493. targetTotalSize = 0;
  1494. int targetChildSize = targetTotalSize / numChildren;
  1495. int remainder = targetTotalSize % numChildren;
  1496. float add = (float)remainder / numChildren;
  1497. float acc = 0.0f;
  1498. // Initial pass
  1499. for (int i = 0; i < numChildren; ++i)
  1500. {
  1501. int targetSize = targetChildSize;
  1502. if (remainder)
  1503. {
  1504. acc += add;
  1505. if (acc >= 0.5f)
  1506. {
  1507. acc -= 1.0f;
  1508. ++targetSize;
  1509. --remainder;
  1510. }
  1511. }
  1512. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1513. }
  1514. // Error correction passes
  1515. for (;;)
  1516. {
  1517. int actualTotalSize = 0;
  1518. for (int i = 0; i < numChildren; ++i)
  1519. actualTotalSize += sizes[i];
  1520. int error = targetTotalSize - actualTotalSize;
  1521. // Break if no error
  1522. if (!error)
  1523. break;
  1524. // Check which of the children can be resized to correct the error. If none, must break
  1525. PODVector<unsigned> resizable;
  1526. for (int i = 0; i < numChildren; ++i)
  1527. {
  1528. if (error < 0 && sizes[i] > minSizes[i])
  1529. resizable.Push(i);
  1530. else if (error > 0 && sizes[i] < maxSizes[i])
  1531. resizable.Push(i);
  1532. }
  1533. if (resizable.Empty())
  1534. break;
  1535. int numResizable = resizable.Size();
  1536. int errorPerChild = error / numResizable;
  1537. remainder = (abs(error)) % numResizable;
  1538. add = (float)remainder / numResizable;
  1539. acc = 0.0f;
  1540. for (int i = 0; i < numResizable; ++i)
  1541. {
  1542. unsigned index = resizable[i];
  1543. int targetSize = sizes[index] + errorPerChild;
  1544. if (remainder)
  1545. {
  1546. acc += add;
  1547. if (acc >= 0.5f)
  1548. {
  1549. acc -= 1.0f;
  1550. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1551. --remainder;
  1552. }
  1553. }
  1554. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1555. }
  1556. }
  1557. // Calculate final positions and store the minimum child element size
  1558. layoutMinSize_ = M_MAX_INT;
  1559. int position = begin;
  1560. for (int i = 0; i < numChildren; ++i)
  1561. {
  1562. positions[i] = position;
  1563. position += sizes[i] + spacing;
  1564. if (sizes[i] < layoutMinSize_)
  1565. layoutMinSize_ = sizes[i];
  1566. }
  1567. }
  1568. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1569. {
  1570. IntVector2 ret(IntVector2::ZERO);
  1571. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1572. switch (ha)
  1573. {
  1574. case HA_LEFT:
  1575. ret.x_ = layoutBorder_.left_;
  1576. break;
  1577. case HA_RIGHT:
  1578. ret.x_ = -layoutBorder_.right_;
  1579. break;
  1580. default:
  1581. break;
  1582. }
  1583. VerticalAlignment va = child->GetVerticalAlignment();
  1584. switch (va)
  1585. {
  1586. case VA_TOP:
  1587. ret.y_ = layoutBorder_.top_;
  1588. break;
  1589. case VA_BOTTOM:
  1590. ret.y_ = -layoutBorder_.bottom_;
  1591. break;
  1592. default:
  1593. break;
  1594. }
  1595. return ret;
  1596. }
  1597. void UIElement::Detach()
  1598. {
  1599. parent_ = 0;
  1600. MarkDirty();
  1601. }
  1602. void UIElement::VerifyChildAlignment()
  1603. {
  1604. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1605. {
  1606. // Reapply child alignments. If they are illegal compared to layout, they will be set left/top as neded
  1607. (*i)->SetHorizontalAlignment((*i)->GetHorizontalAlignment());
  1608. (*i)->SetVerticalAlignment((*i)->GetVerticalAlignment());
  1609. }
  1610. }
  1611. void UIElement::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1612. {
  1613. using namespace PostUpdate;
  1614. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1615. }
  1616. }