UIElement.cpp 54 KB

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