UIElement.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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 Color DEBUG_DRAW_COLOR(Color::BLUE);
  37. const char* horizontalAlignments[] =
  38. {
  39. "Left",
  40. "Center",
  41. "Right",
  42. 0
  43. };
  44. const char* verticalAlignments[] =
  45. {
  46. "Top",
  47. "Center",
  48. "Bottom",
  49. 0
  50. };
  51. static const char* focusModes[] =
  52. {
  53. "NotFocusable",
  54. "ResetFocus",
  55. "Focusable",
  56. "FocusableDefocusable",
  57. 0
  58. };
  59. static const char* dragDropModes[] =
  60. {
  61. "Disabled",
  62. "Source",
  63. "Target",
  64. "SourceAndTarget",
  65. 0
  66. };
  67. static const char* layoutModes[] =
  68. {
  69. "Free",
  70. "Horizontal",
  71. "Vertical",
  72. 0
  73. };
  74. 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. OBJECTTYPESTATIC(UIElement);
  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>();
  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::ZERO, 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, false, 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)
  191. {
  192. return LoadXML(source, 0);
  193. }
  194. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  195. {
  196. // Apply the style first, but only for non-internal elements
  197. if (!internal_ && styleFile)
  198. {
  199. // Use style override if defined, otherwise type name
  200. String styleName = source.GetAttribute("style");
  201. if (styleName.Empty())
  202. styleName = GetTypeName();
  203. SetStyle(styleFile, styleName);
  204. }
  205. // Then load rest of the attributes from the source
  206. if (!Serializable::LoadXML(source))
  207. return false;
  208. unsigned nextInternalChild = 0;
  209. // Load child elements. Internal elements are not to be created as they already exist
  210. XMLElement childElem = source.GetChild("element");
  211. while (childElem)
  212. {
  213. bool internalElem = childElem.GetBool("internal");
  214. String typeName = childElem.GetAttribute("type");
  215. if (typeName.Empty())
  216. typeName = "UIElement";
  217. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  218. UIElement* child = 0;
  219. if (!internalElem)
  220. child = CreateChild(typeName, String::EMPTY, index);
  221. else
  222. {
  223. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  224. {
  225. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  226. {
  227. child = children_[i];
  228. nextInternalChild = i + 1;
  229. break;
  230. }
  231. }
  232. if (!child)
  233. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  234. }
  235. if (child)
  236. {
  237. if (!child->LoadXML(childElem, styleFile))
  238. return false;
  239. }
  240. childElem = childElem.GetNext("element");
  241. }
  242. ApplyAttributes();
  243. return true;
  244. }
  245. bool UIElement::SaveXML(XMLElement& dest)
  246. {
  247. // Write type and internal flag
  248. if (!dest.SetString("type", GetTypeName()))
  249. return false;
  250. if (internal_)
  251. {
  252. if (!dest.SetBool("internal", internal_))
  253. return false;
  254. }
  255. // Write attributes
  256. if (!Serializable::SaveXML(dest))
  257. return false;
  258. // Write child elements
  259. for (unsigned i = 0; i < children_.Size(); ++i)
  260. {
  261. UIElement* element = children_[i];
  262. XMLElement childElem = dest.CreateChild("element");
  263. if (!element->SaveXML(childElem))
  264. return false;
  265. }
  266. return true;
  267. }
  268. void UIElement::Update(float timeStep)
  269. {
  270. }
  271. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  272. {
  273. // Reset hovering for next frame
  274. hovering_ = false;
  275. }
  276. void UIElement::GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  277. {
  278. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  279. // Left
  280. batch.AddQuad(0, 0, 1, size_.y_, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  281. // Top
  282. batch.AddQuad(0, 0, size_.x_, 1, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  283. // Right
  284. batch.AddQuad(size_.x_ - 1, 0, 1, size_.y_, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  285. // Bottom
  286. batch.AddQuad(0, size_.y_ - 1, size_.x_, 1, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  287. UIBatch::AddOrMerge(batch, batches);
  288. }
  289. bool UIElement::IsWithinScissor(const IntRect& currentScissor)
  290. {
  291. if (!visible_)
  292. return false;
  293. const IntVector2& screenPos = GetScreenPosition();
  294. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + GetWidth() > currentScissor.left_ &&
  295. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + GetHeight() > currentScissor.top_;
  296. }
  297. const IntVector2& UIElement::GetScreenPosition() const
  298. {
  299. if (positionDirty_)
  300. {
  301. IntVector2 pos = position_;
  302. const UIElement* parent = parent_;
  303. if (parent)
  304. {
  305. const IntVector2& parentScreenPos = parent->GetScreenPosition();
  306. switch (horizontalAlignment_)
  307. {
  308. case HA_LEFT:
  309. pos.x_ += parentScreenPos.x_;
  310. break;
  311. case HA_CENTER:
  312. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ / 2 - size_.x_ / 2;
  313. break;
  314. case HA_RIGHT:
  315. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ - size_.x_;
  316. break;
  317. }
  318. switch (verticalAlignment_)
  319. {
  320. case VA_TOP:
  321. pos.y_ += parentScreenPos.y_;
  322. break;
  323. case VA_CENTER:
  324. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ / 2 - size_.y_ / 2;
  325. break;
  326. case VA_BOTTOM:
  327. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ - size_.y_;
  328. break;
  329. }
  330. pos += parent_->childOffset_;
  331. }
  332. screenPosition_ = pos;
  333. positionDirty_ = false;
  334. }
  335. return screenPosition_;
  336. }
  337. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  338. {
  339. if (cursor && cursor->IsVisible())
  340. cursor->SetShape(CS_NORMAL);
  341. hovering_ = true;
  342. }
  343. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  344. {
  345. }
  346. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  347. {
  348. }
  349. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  350. {
  351. }
  352. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  353. {
  354. }
  355. bool UIElement::OnDragDropTest(UIElement* source)
  356. {
  357. return true;
  358. }
  359. bool UIElement::OnDragDropFinish(UIElement* source)
  360. {
  361. return true;
  362. }
  363. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  364. {
  365. }
  366. void UIElement::OnKey(int key, int buttons, int qualifiers)
  367. {
  368. }
  369. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  370. {
  371. }
  372. void UIElement::OnResize()
  373. {
  374. }
  375. void UIElement::OnPositionSet()
  376. {
  377. }
  378. bool UIElement::LoadXML(Deserializer& source)
  379. {
  380. SharedPtr<XMLFile> xml(new XMLFile(context_));
  381. if (!xml->Load(source))
  382. return false;
  383. return LoadXML(xml->GetRoot());
  384. }
  385. bool UIElement::SaveXML(Serializer& dest)
  386. {
  387. SharedPtr<XMLFile> xml(new XMLFile(context_));
  388. XMLElement rootElem = xml->CreateRoot("element");
  389. if (!SaveXML(rootElem))
  390. return false;
  391. return xml->Save(dest);
  392. }
  393. void UIElement::SetName(const String& name)
  394. {
  395. name_ = name;
  396. using namespace NameChanged;
  397. VariantMap eventData;
  398. eventData[P_ELEMENT] = (void*)this;
  399. SendEvent(E_NAMECHANGED, eventData);
  400. }
  401. void UIElement::SetPosition(const IntVector2& position)
  402. {
  403. if (position != position_)
  404. {
  405. position_ = position;
  406. OnPositionSet();
  407. MarkDirty();
  408. }
  409. }
  410. void UIElement::SetPosition(int x, int y)
  411. {
  412. SetPosition(IntVector2(x, y));
  413. }
  414. void UIElement::SetSize(const IntVector2& size)
  415. {
  416. ++resizeNestingLevel_;
  417. IntVector2 validatedSize;
  418. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  419. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  420. if (validatedSize != size_)
  421. {
  422. size_ = validatedSize;
  423. if (resizeNestingLevel_ == 1)
  424. {
  425. // Check if parent element's layout needs to be updated first
  426. if (parent_)
  427. parent_->UpdateLayout();
  428. MarkDirty();
  429. OnResize();
  430. UpdateLayout();
  431. using namespace Resized;
  432. VariantMap eventData;
  433. eventData[P_ELEMENT] = (void*)this;
  434. eventData[P_WIDTH] = size_.x_;
  435. eventData[P_HEIGHT] = size_.y_;
  436. SendEvent(E_RESIZED, eventData);
  437. }
  438. }
  439. --resizeNestingLevel_;
  440. }
  441. void UIElement::SetSize(int width, int height)
  442. {
  443. SetSize(IntVector2(width, height));
  444. }
  445. void UIElement::SetWidth(int width)
  446. {
  447. SetSize(IntVector2(width, size_.y_));
  448. }
  449. void UIElement::SetHeight(int height)
  450. {
  451. SetSize(IntVector2(size_.x_, height));
  452. }
  453. void UIElement::SetMinSize(const IntVector2& minSize)
  454. {
  455. minSize_.x_ = Max(minSize.x_, 0);
  456. minSize_.y_ = Max(minSize.y_, 0);
  457. SetSize(size_);
  458. }
  459. void UIElement::SetMinSize(int width, int height)
  460. {
  461. SetMinSize(IntVector2(width, height));
  462. }
  463. void UIElement::SetMinWidth(int width)
  464. {
  465. SetMinSize(IntVector2(width, minSize_.y_));
  466. }
  467. void UIElement::SetMinHeight(int height)
  468. {
  469. SetMinSize(IntVector2(minSize_.x_, height));
  470. }
  471. void UIElement::SetMaxSize(const IntVector2& maxSize)
  472. {
  473. maxSize_.x_ = Max(maxSize.x_, 0);
  474. maxSize_.y_ = Max(maxSize.y_, 0);
  475. SetSize(size_);
  476. }
  477. void UIElement::SetMaxSize(int width, int height)
  478. {
  479. SetMaxSize(IntVector2(width, height));
  480. }
  481. void UIElement::SetMaxWidth(int width)
  482. {
  483. SetMaxSize(IntVector2(width, maxSize_.y_));
  484. }
  485. void UIElement::SetMaxHeight(int height)
  486. {
  487. SetMaxSize(IntVector2(maxSize_.x_, height));
  488. }
  489. void UIElement::SetFixedSize(const IntVector2& size)
  490. {
  491. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  492. SetSize(size);
  493. }
  494. void UIElement::SetFixedSize(int width, int height)
  495. {
  496. SetFixedSize(IntVector2(width, height));
  497. }
  498. void UIElement::SetFixedWidth(int width)
  499. {
  500. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  501. SetWidth(width);
  502. }
  503. void UIElement::SetFixedHeight(int height)
  504. {
  505. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  506. SetHeight(height);
  507. }
  508. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  509. {
  510. horizontalAlignment_ = hAlign;
  511. verticalAlignment_ = vAlign;
  512. MarkDirty();
  513. }
  514. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  515. {
  516. horizontalAlignment_ = align;
  517. MarkDirty();
  518. }
  519. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  520. {
  521. verticalAlignment_ = align;
  522. MarkDirty();
  523. }
  524. void UIElement::SetClipBorder(const IntRect& rect)
  525. {
  526. clipBorder_.left_ = Max(rect.left_, 0);
  527. clipBorder_.top_ = Max(rect.top_, 0);
  528. clipBorder_.right_ = Max(rect.right_, 0);
  529. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  530. }
  531. void UIElement::SetColor(const Color& color)
  532. {
  533. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  534. color_[i] = color;
  535. colorGradient_ = false;
  536. derivedColorDirty_ = true;
  537. }
  538. void UIElement::SetColor(Corner corner, const Color& color)
  539. {
  540. color_[corner] = color;
  541. colorGradient_ = false;
  542. derivedColorDirty_ = true;
  543. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  544. {
  545. if (i != corner && color_[i] != color_[corner])
  546. colorGradient_ = true;
  547. }
  548. }
  549. void UIElement::SetPriority(int priority)
  550. {
  551. priority_ = priority;
  552. if (parent_)
  553. parent_->sortOrderDirty_ = true;
  554. }
  555. void UIElement::SetOpacity(float opacity)
  556. {
  557. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  558. MarkDirty();
  559. }
  560. void UIElement::SetBringToFront(bool enable)
  561. {
  562. bringToFront_ = enable;
  563. }
  564. void UIElement::SetBringToBack(bool enable)
  565. {
  566. bringToBack_ = enable;
  567. }
  568. void UIElement::SetClipChildren(bool enable)
  569. {
  570. clipChildren_ = enable;
  571. }
  572. void UIElement::SetSortChildren(bool enable)
  573. {
  574. if (!sortChildren_ && enable)
  575. sortOrderDirty_ = true;
  576. sortChildren_ = enable;
  577. }
  578. void UIElement::SetUseDerivedOpacity(bool enable)
  579. {
  580. useDerivedOpacity_ = enable;
  581. }
  582. void UIElement::SetEnabled(bool enable)
  583. {
  584. enabled_ = enable;
  585. }
  586. void UIElement::SetFocusMode(FocusMode mode)
  587. {
  588. focusMode_ = mode;
  589. }
  590. void UIElement::SetFocus(bool enable)
  591. {
  592. if (focusMode_ < FM_FOCUSABLE)
  593. enable = false;
  594. UI* ui = GetSubsystem<UI>();
  595. if (!ui)
  596. return;
  597. if (enable)
  598. {
  599. if (ui->GetFocusElement() != this)
  600. ui->SetFocusElement(this);
  601. }
  602. else
  603. {
  604. if (ui->GetFocusElement() == this)
  605. ui->SetFocusElement(0);
  606. }
  607. }
  608. void UIElement::SetSelected(bool enable)
  609. {
  610. selected_ = enable;
  611. }
  612. void UIElement::SetVisible(bool enable)
  613. {
  614. if (enable != visible_)
  615. {
  616. visible_ = enable;
  617. // Parent's layout may change as a result of visibility change
  618. if (parent_)
  619. parent_->UpdateLayout();
  620. using namespace VisibleChanged;
  621. VariantMap eventData;
  622. eventData[P_ELEMENT] = (void*)this;
  623. eventData[P_VISIBLE] = visible_;
  624. SendEvent(E_VISIBLECHANGED, eventData);
  625. }
  626. }
  627. void UIElement::SetDragDropMode(unsigned mode)
  628. {
  629. dragDropMode_ = mode;
  630. }
  631. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  632. {
  633. if (!file)
  634. return;
  635. XMLElement rootElem = file->GetRoot();
  636. XMLElement childElem = rootElem.GetChild("element");
  637. while (childElem)
  638. {
  639. if (typeName == childElem.GetAttribute("type"))
  640. {
  641. SetStyle(childElem);
  642. return;
  643. }
  644. childElem = childElem.GetNext("element");
  645. }
  646. }
  647. void UIElement::SetStyle(const XMLElement& element)
  648. {
  649. LoadXML(element);
  650. }
  651. void UIElement::SetStyleAuto(XMLFile* file)
  652. {
  653. SetStyle(file, GetTypeName());
  654. }
  655. void UIElement::SetDefaultStyle(XMLFile* style)
  656. {
  657. defaultStyle_ = style;
  658. }
  659. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  660. {
  661. layoutMode_ = mode;
  662. layoutSpacing_ = Max(spacing, 0);
  663. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  664. UpdateLayout();
  665. }
  666. void UIElement::SetLayoutMode(LayoutMode mode)
  667. {
  668. layoutMode_ = mode;
  669. UpdateLayout();
  670. }
  671. void UIElement::SetLayoutSpacing(int spacing)
  672. {
  673. layoutSpacing_ = Max(spacing, 0);
  674. UpdateLayout();
  675. }
  676. void UIElement::SetLayoutBorder(const IntRect& border)
  677. {
  678. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  679. UpdateLayout();
  680. }
  681. void UIElement::SetIndent(int indent)
  682. {
  683. indent_ = indent;
  684. if (parent_)
  685. parent_->UpdateLayout();
  686. }
  687. void UIElement::SetIndentSpacing(int indentSpacing)
  688. {
  689. indentSpacing_ = Max(indentSpacing, 0);
  690. if (parent_)
  691. parent_->UpdateLayout();
  692. }
  693. void UIElement::UpdateLayout()
  694. {
  695. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  696. return;
  697. // Prevent further updates while this update happens
  698. DisableLayoutUpdate();
  699. PODVector<int> positions;
  700. PODVector<int> sizes;
  701. PODVector<int> minSizes;
  702. PODVector<int> maxSizes;
  703. int baseIndentWidth = GetIndentWidth();
  704. if (layoutMode_ == LM_HORIZONTAL)
  705. {
  706. int minChildHeight = 0;
  707. for (unsigned i = 0; i < children_.Size(); ++i)
  708. {
  709. if (!children_[i]->IsVisible())
  710. continue;
  711. positions.Push(baseIndentWidth);
  712. unsigned indent = children_[i]->GetIndentWidth();
  713. sizes.Push(children_[i]->GetWidth() + indent);
  714. minSizes.Push(children_[i]->GetMinWidth() + indent);
  715. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  716. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  717. }
  718. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  719. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  720. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  721. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  722. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  723. // Respect fixed size if already set
  724. if (minSize_.x_ != maxSize_.x_)
  725. minSize_.x_ = minWidth;
  726. if (minSize_.y_ != maxSize_.y_)
  727. minSize_.y_ = minHeight;
  728. SetSize(width, height);
  729. // Validate the size before resizing child elements, in case of min/max limits
  730. width = size_.x_;
  731. height = size_.y_;
  732. unsigned j = 0;
  733. for (unsigned i = 0; i < children_.Size(); ++i)
  734. {
  735. if (!children_[i]->IsVisible())
  736. continue;
  737. HorizontalAlignment horizontalAlignment = children_[i]->horizontalAlignment_;
  738. children_[i]->horizontalAlignment_ = HA_LEFT;
  739. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  740. children_[i]->horizontalAlignment_ = horizontalAlignment;
  741. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  742. ++j;
  743. }
  744. }
  745. else if (layoutMode_ == LM_VERTICAL)
  746. {
  747. int minChildWidth = 0;
  748. for (unsigned i = 0; i < children_.Size(); ++i)
  749. {
  750. if (!children_[i]->IsVisible())
  751. continue;
  752. positions.Push(baseIndentWidth);
  753. sizes.Push(children_[i]->GetHeight());
  754. minSizes.Push(children_[i]->GetMinHeight());
  755. maxSizes.Push(children_[i]->GetMaxHeight());
  756. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  757. }
  758. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  759. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  760. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  761. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  762. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  763. if (minSize_.x_ != maxSize_.x_)
  764. minSize_.x_ = minWidth;
  765. if (minSize_.y_ != maxSize_.y_)
  766. minSize_.y_ = minHeight;
  767. SetSize(width, height);
  768. width = size_.x_;
  769. height = size_.y_;
  770. unsigned j = 0;
  771. for (unsigned i = 0; i < children_.Size(); ++i)
  772. {
  773. if (!children_[i]->IsVisible())
  774. continue;
  775. VerticalAlignment verticalAlignment = children_[i]->verticalAlignment_;
  776. children_[i]->verticalAlignment_ = VA_TOP;
  777. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  778. children_[i]->verticalAlignment_ = verticalAlignment;
  779. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  780. ++j;
  781. }
  782. }
  783. using namespace LayoutUpdated;
  784. VariantMap eventData;
  785. eventData[P_ELEMENT] = (void*)this;
  786. SendEvent(E_LAYOUTUPDATED, eventData);
  787. EnableLayoutUpdate();
  788. }
  789. void UIElement::DisableLayoutUpdate()
  790. {
  791. ++layoutNestingLevel_;
  792. }
  793. void UIElement::EnableLayoutUpdate()
  794. {
  795. --layoutNestingLevel_;
  796. }
  797. void UIElement::BringToFront()
  798. {
  799. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  800. UIElement* root = GetRoot();
  801. // If element is detached from hierarchy, this must be a no-op
  802. if (!root)
  803. return;
  804. UIElement* ptr = this;
  805. while (ptr && ptr->GetParent() != root)
  806. ptr = ptr->GetParent();
  807. if (!ptr || !ptr->GetBringToFront())
  808. return;
  809. // Get the highest priority used by all other top level elements, assign that to the new front element
  810. // and decrease others' priority where necessary. However, take into account only input-enabled
  811. // elements and those which have the BringToBack flag set
  812. HashSet<int> usedPriorities;
  813. int maxPriority = M_MIN_INT;
  814. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  815. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  816. {
  817. UIElement* other = *i;
  818. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  819. {
  820. int priority = other->GetPriority();
  821. usedPriorities.Insert(priority);
  822. maxPriority = Max(priority, maxPriority);
  823. }
  824. }
  825. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  826. {
  827. ptr->SetPriority(maxPriority);
  828. int minPriority = maxPriority;
  829. while (usedPriorities.Contains(minPriority))
  830. --minPriority;
  831. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  832. {
  833. UIElement* other = *i;
  834. int priority = other->GetPriority();
  835. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  836. other->SetPriority(priority - 1);
  837. }
  838. }
  839. }
  840. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name, unsigned index)
  841. {
  842. // Check that creation succeeds and that the object in fact is a UI element
  843. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  844. if (!newElement)
  845. {
  846. LOGERROR("Could not create unknown UI element type " + type.ToString());
  847. return 0;
  848. }
  849. if (!name.Empty())
  850. newElement->SetName(name);
  851. InsertChild(index, newElement);
  852. return newElement;
  853. }
  854. void UIElement::AddChild(UIElement* element)
  855. {
  856. InsertChild(M_MAX_UNSIGNED, element);
  857. }
  858. void UIElement::InsertChild(unsigned index, UIElement* element)
  859. {
  860. // Check for illegal or redundant parent assignment
  861. if (!element || element == this || element->parent_ == this)
  862. return;
  863. // Check for possible cyclic parent assignment
  864. UIElement* parent = parent_;
  865. while (parent)
  866. {
  867. if (parent == element)
  868. return;
  869. parent = parent->parent_;
  870. }
  871. // Add first, then remove from old parent, to ensure the element does not get deleted
  872. if (index >= children_.Size())
  873. children_.Push(SharedPtr<UIElement>(element));
  874. else
  875. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  876. element->Remove();
  877. if (sortChildren_)
  878. sortOrderDirty_ = true;
  879. element->parent_ = this;
  880. element->MarkDirty();
  881. UpdateLayout();
  882. // Send change event
  883. UIElement* root = GetRoot();
  884. UIElement* sender = GetElementEventSender();
  885. if (sender)
  886. {
  887. using namespace ElementAdded;
  888. VariantMap eventData;
  889. eventData[P_ROOT] = (void*)root;
  890. eventData[P_PARENT] = (void*)this;
  891. eventData[P_ELEMENT] = (void*)element;
  892. sender->SendEvent(E_ELEMENTADDED, eventData);
  893. }
  894. }
  895. void UIElement::RemoveChild(UIElement* element, unsigned index)
  896. {
  897. UIElement* root = GetRoot();
  898. UIElement* sender = GetElementEventSender();
  899. for (unsigned i = index; i < children_.Size(); ++i)
  900. {
  901. if (children_[i] == element)
  902. {
  903. // Send change event if not already being destroyed
  904. if (Refs() > 0 && sender)
  905. {
  906. using namespace ElementRemoved;
  907. VariantMap eventData;
  908. eventData[P_ROOT] = (void*)root;
  909. eventData[P_PARENT] = (void*)this;
  910. eventData[P_ELEMENT] = (void*)element;
  911. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  912. }
  913. element->Detach();
  914. children_.Erase(i);
  915. UpdateLayout();
  916. return;
  917. }
  918. }
  919. }
  920. void UIElement::RemoveChildAtIndex(unsigned index)
  921. {
  922. if (index >= children_.Size())
  923. return;
  924. children_[index]->Detach();
  925. children_.Erase(index);
  926. UpdateLayout();
  927. }
  928. void UIElement::RemoveAllChildren()
  929. {
  930. UIElement* root = GetRoot();
  931. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  932. {
  933. // Send change event if not already being destroyed
  934. if (Refs() > 0 && root)
  935. {
  936. using namespace ElementRemoved;
  937. VariantMap eventData;
  938. eventData[P_ROOT] = (void*)root;
  939. eventData[P_PARENT] = (void*)this;
  940. eventData[P_ELEMENT] = (void*)(*i).Get();
  941. root->SendEvent(E_ELEMENTREMOVED, eventData);
  942. }
  943. (*i++)->Detach();
  944. }
  945. children_.Clear();
  946. }
  947. void UIElement::Remove()
  948. {
  949. if (parent_)
  950. parent_->RemoveChild(this);
  951. }
  952. unsigned UIElement::FindChild(UIElement* element) const
  953. {
  954. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  955. return i != children_.End() ? i - children_.Begin() : M_MAX_UNSIGNED;
  956. }
  957. void UIElement::SetParent(UIElement* parent, unsigned index)
  958. {
  959. if (parent)
  960. parent->InsertChild(index, this);
  961. }
  962. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  963. {
  964. vars_[key] = value;
  965. }
  966. void UIElement::SetInternal(bool enable)
  967. {
  968. internal_ = enable;
  969. }
  970. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  971. {
  972. traversalMode_ = traversalMode;
  973. }
  974. void UIElement::SetElementEventSender(bool flag)
  975. {
  976. elementEventSender_ = flag;
  977. }
  978. float UIElement::GetDerivedOpacity() const
  979. {
  980. if (!useDerivedOpacity_)
  981. return opacity_;
  982. if (opacityDirty_)
  983. {
  984. derivedOpacity_ = opacity_;
  985. const UIElement* parent = parent_;
  986. while (parent)
  987. {
  988. derivedOpacity_ *= parent->opacity_;
  989. parent = parent->parent_;
  990. }
  991. opacityDirty_ = false;
  992. }
  993. return derivedOpacity_;
  994. }
  995. bool UIElement::HasFocus() const
  996. {
  997. UI* ui = GetSubsystem<UI>();
  998. if (!ui)
  999. return false;
  1000. else
  1001. return ui->GetFocusElement() == this;
  1002. }
  1003. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  1004. {
  1005. if (recursiveUp)
  1006. {
  1007. const UIElement* element = this;
  1008. while (element)
  1009. {
  1010. if (element->defaultStyle_)
  1011. return element->defaultStyle_;
  1012. element = element->parent_;
  1013. }
  1014. return 0;
  1015. }
  1016. else
  1017. return defaultStyle_;
  1018. }
  1019. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1020. {
  1021. dest.Clear();
  1022. if (!recursive)
  1023. {
  1024. dest.Reserve(children_.Size());
  1025. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1026. dest.Push(*i);
  1027. }
  1028. else
  1029. GetChildrenRecursive(dest);
  1030. }
  1031. unsigned UIElement::GetNumChildren(bool recursive) const
  1032. {
  1033. if (!recursive)
  1034. return children_.Size();
  1035. else
  1036. {
  1037. unsigned allChildren = children_.Size();
  1038. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1039. allChildren += (*i)->GetNumChildren(true);
  1040. return allChildren;
  1041. }
  1042. }
  1043. UIElement* UIElement::GetChild(unsigned index) const
  1044. {
  1045. return index < children_.Size() ? children_[index] : (UIElement*)0;
  1046. }
  1047. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1048. {
  1049. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1050. {
  1051. if ((*i)->name_ == name)
  1052. return *i;
  1053. if (recursive)
  1054. {
  1055. UIElement* element = (*i)->GetChild(name, true);
  1056. if (element)
  1057. return element;
  1058. }
  1059. }
  1060. return 0;
  1061. }
  1062. UIElement* UIElement::GetChild(const ShortStringHash& key, const Variant& value, bool recursive) const
  1063. {
  1064. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1065. {
  1066. const Variant& varValue = (*i)->GetVar(key);
  1067. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1068. return *i;
  1069. if (recursive)
  1070. {
  1071. UIElement* element = (*i)->GetChild(key, value, true);
  1072. if (element)
  1073. return element;
  1074. }
  1075. }
  1076. return 0;
  1077. }
  1078. UIElement* UIElement::GetRoot() const
  1079. {
  1080. UIElement* root = parent_;
  1081. if (!root)
  1082. return 0;
  1083. while (root->GetParent())
  1084. root = root->GetParent();
  1085. return root;
  1086. }
  1087. const Color& UIElement::GetDerivedColor() const
  1088. {
  1089. if (derivedColorDirty_)
  1090. {
  1091. derivedColor_ = color_[C_TOPLEFT];
  1092. derivedColor_.a_ *= GetDerivedOpacity();
  1093. derivedColorDirty_ = false;
  1094. }
  1095. return derivedColor_;
  1096. }
  1097. const Variant& UIElement::GetVar(const ShortStringHash& key) const
  1098. {
  1099. VariantMap::ConstIterator i = vars_.Find(key);
  1100. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1101. }
  1102. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  1103. {
  1104. return screenPosition - GetScreenPosition();
  1105. }
  1106. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  1107. {
  1108. return position + GetScreenPosition();
  1109. }
  1110. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1111. {
  1112. if (isScreen)
  1113. position = ScreenToElement(position);
  1114. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1115. }
  1116. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1117. {
  1118. // If child elements are clipped, no need to expand the rect
  1119. if (clipChildren_)
  1120. return IsInside(position, isScreen);
  1121. if (!isScreen)
  1122. position = ElementToScreen(position);
  1123. IntRect combined = GetCombinedScreenRect();
  1124. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1125. position.y_ < combined.bottom_;
  1126. }
  1127. IntRect UIElement::GetCombinedScreenRect()
  1128. {
  1129. IntVector2 screenPosition(GetScreenPosition());
  1130. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1131. if (!clipChildren_)
  1132. {
  1133. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1134. {
  1135. IntVector2 childPos = (*i)->GetScreenPosition();
  1136. const IntVector2& childSize = (*i)->GetSize();
  1137. if (childPos.x_ < combined.left_)
  1138. combined.left_ = childPos.x_;
  1139. if (childPos.y_ < combined.top_)
  1140. combined.top_ = childPos.y_;
  1141. if (childPos.x_ + childSize.x_ > combined.right_)
  1142. combined.right_ = childPos.x_ + childSize.x_;
  1143. if (childPos.y_ + childSize.y_ > combined.bottom_)
  1144. combined.bottom_ = childPos.y_ + childSize.y_;
  1145. }
  1146. }
  1147. return combined;
  1148. }
  1149. void UIElement::SortChildren()
  1150. {
  1151. if (sortChildren_ && sortOrderDirty_)
  1152. {
  1153. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1154. sortOrderDirty_ = false;
  1155. }
  1156. }
  1157. void UIElement::SetChildOffset(const IntVector2& offset)
  1158. {
  1159. if (offset != childOffset_)
  1160. {
  1161. childOffset_ = offset;
  1162. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1163. (*i)->MarkDirty();
  1164. }
  1165. }
  1166. void UIElement::SetHovering(bool enable)
  1167. {
  1168. hovering_ = enable;
  1169. }
  1170. void UIElement::SetTempVisible(bool enable)
  1171. {
  1172. visible_ = enable;
  1173. }
  1174. void UIElement::AdjustScissor(IntRect& currentScissor)
  1175. {
  1176. if (clipChildren_)
  1177. {
  1178. IntVector2 screenPos = GetScreenPosition();
  1179. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1180. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1181. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1182. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1183. if (currentScissor.right_ < currentScissor.left_)
  1184. currentScissor.right_ = currentScissor.left_;
  1185. if (currentScissor.bottom_ < currentScissor.top_)
  1186. currentScissor.bottom_ = currentScissor.top_;
  1187. }
  1188. }
  1189. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData, IntRect
  1190. currentScissor)
  1191. {
  1192. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1193. unsigned initialSize = vertexData.Size();
  1194. GetBatches(batches, vertexData, currentScissor);
  1195. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1196. {
  1197. vertexData[i] += floatOffset.x_;
  1198. vertexData[i + 1] += floatOffset.y_;
  1199. }
  1200. AdjustScissor(currentScissor);
  1201. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1202. {
  1203. if ((*i)->IsVisible())
  1204. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1205. }
  1206. }
  1207. UIElement* UIElement::GetElementEventSender() const
  1208. {
  1209. UIElement* element = const_cast<UIElement*>(this);
  1210. if (elementEventSender_)
  1211. return element;
  1212. while (element->parent_)
  1213. {
  1214. element = element->parent_;
  1215. if (element->elementEventSender_)
  1216. return element;
  1217. }
  1218. // If no predefined element event sender in the parental chain, return ultimate root element
  1219. return element;
  1220. }
  1221. void UIElement::MarkDirty()
  1222. {
  1223. positionDirty_ = true;
  1224. opacityDirty_ = true;
  1225. derivedColorDirty_ = true;
  1226. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1227. (*i)->MarkDirty();
  1228. }
  1229. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1230. {
  1231. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1232. {
  1233. UIElement* element = *i;
  1234. dest.Push(element);
  1235. if (!element->children_.Empty())
  1236. element->GetChildrenRecursive(dest);
  1237. }
  1238. }
  1239. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1240. {
  1241. int width = begin + end;
  1242. if (sizes.Empty())
  1243. return width;
  1244. for (unsigned i = 0; i < sizes.Size(); ++i)
  1245. {
  1246. // If calculating maximum size, and the default is specified, do not overflow it
  1247. if (sizes[i] == M_MAX_INT)
  1248. return M_MAX_INT;
  1249. width += sizes[i] + spacing;
  1250. }
  1251. // The last spacing is not needed
  1252. return width - spacing;
  1253. }
  1254. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1255. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1256. {
  1257. int numChildren = sizes.Size();
  1258. if (!numChildren)
  1259. return;
  1260. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1261. if (targetTotalSize < 0)
  1262. targetTotalSize = 0;
  1263. int targetChildSize = targetTotalSize / numChildren;
  1264. int remainder = targetTotalSize % numChildren;
  1265. float add = (float)remainder / numChildren;
  1266. float acc = 0.0f;
  1267. // Initial pass
  1268. for (int i = 0; i < numChildren; ++i)
  1269. {
  1270. int targetSize = targetChildSize;
  1271. if (remainder)
  1272. {
  1273. acc += add;
  1274. if (acc >= 0.5f)
  1275. {
  1276. acc -= 1.0f;
  1277. ++targetSize;
  1278. --remainder;
  1279. }
  1280. }
  1281. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1282. }
  1283. // Error correction passes
  1284. for (;;)
  1285. {
  1286. int actualTotalSize = 0;
  1287. for (int i = 0; i < numChildren; ++i)
  1288. actualTotalSize += sizes[i];
  1289. int error = targetTotalSize - actualTotalSize;
  1290. // Break if no error
  1291. if (!error)
  1292. break;
  1293. // Check which of the children can be resized to correct the error. If none, must break
  1294. PODVector<unsigned> resizable;
  1295. for (int i = 0; i < numChildren; ++i)
  1296. {
  1297. if (error < 0 && sizes[i] > minSizes[i])
  1298. resizable.Push(i);
  1299. else if (error > 0 && sizes[i] < maxSizes[i])
  1300. resizable.Push(i);
  1301. }
  1302. if (resizable.Empty())
  1303. break;
  1304. int numResizable = resizable.Size();
  1305. int errorPerChild = error / numResizable;
  1306. remainder = (abs(error)) % numResizable;
  1307. add = (float)remainder / numResizable;
  1308. acc = 0.0f;
  1309. for (int i = 0; i < numResizable; ++i)
  1310. {
  1311. unsigned index = resizable[i];
  1312. int targetSize = sizes[index] + errorPerChild;
  1313. if (remainder)
  1314. {
  1315. acc += add;
  1316. if (acc >= 0.5f)
  1317. {
  1318. acc -= 1.0f;
  1319. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1320. --remainder;
  1321. }
  1322. }
  1323. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1324. }
  1325. }
  1326. // Calculate final positions and store the minimum child element size
  1327. layoutMinSize_ = M_MAX_INT;
  1328. int position = begin;
  1329. for (int i = 0; i < numChildren; ++i)
  1330. {
  1331. positions[i] = position;
  1332. position += sizes[i] + spacing;
  1333. if (sizes[i] < layoutMinSize_)
  1334. layoutMinSize_ = sizes[i];
  1335. }
  1336. }
  1337. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1338. {
  1339. IntVector2 ret(IntVector2::ZERO);
  1340. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1341. switch (ha)
  1342. {
  1343. case HA_LEFT:
  1344. ret.x_ = layoutBorder_.left_;
  1345. break;
  1346. case HA_RIGHT:
  1347. ret.x_ = -layoutBorder_.right_;
  1348. break;
  1349. default:
  1350. break;
  1351. }
  1352. VerticalAlignment va = child->GetVerticalAlignment();
  1353. switch (va)
  1354. {
  1355. case VA_TOP:
  1356. ret.y_ = layoutBorder_.top_;
  1357. break;
  1358. case VA_BOTTOM:
  1359. ret.y_ = -layoutBorder_.bottom_;
  1360. break;
  1361. default:
  1362. break;
  1363. }
  1364. return ret;
  1365. }
  1366. void UIElement::Detach()
  1367. {
  1368. parent_ = 0;
  1369. MarkDirty();
  1370. }
  1371. }