UIElement.cpp 54 KB

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