UIElement.cpp 53 KB

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