UIElement.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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. static const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. 0
  42. };
  43. static 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. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  74. {
  75. return lhs->GetPriority() < rhs->GetPriority();
  76. }
  77. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  78. {
  79. return (HorizontalAlignment)GetInt();
  80. }
  81. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  82. {
  83. return (VerticalAlignment)GetInt();
  84. }
  85. template<> FocusMode Variant::Get<FocusMode>() const
  86. {
  87. return (FocusMode)GetInt();
  88. }
  89. template<> LayoutMode Variant::Get<LayoutMode>() const
  90. {
  91. return (LayoutMode)GetInt();
  92. }
  93. OBJECTTYPESTATIC(UIElement);
  94. UIElement::UIElement(Context* context) :
  95. Serializable(context),
  96. parent_(0),
  97. clipBorder_(IntRect::ZERO),
  98. priority_(0),
  99. bringToFront_(false),
  100. bringToBack_(true),
  101. clipChildren_(false),
  102. sortChildren_(true),
  103. useDerivedOpacity_(true),
  104. active_(false),
  105. selected_(false),
  106. visible_(true),
  107. hovering_(false),
  108. internal_(false),
  109. focusMode_(FM_NOTFOCUSABLE),
  110. dragDropMode_(DD_DISABLED),
  111. layoutMode_(LM_FREE),
  112. layoutSpacing_(0),
  113. layoutBorder_(IntRect::ZERO),
  114. resizeNestingLevel_(0),
  115. layoutNestingLevel_(0),
  116. layoutMinSize_(0),
  117. position_(IntVector2::ZERO),
  118. size_(IntVector2::ZERO),
  119. minSize_(IntVector2::ZERO),
  120. maxSize_(M_MAX_INT, M_MAX_INT),
  121. childOffset_(IntVector2::ZERO),
  122. horizontalAlignment_(HA_LEFT),
  123. verticalAlignment_(VA_TOP),
  124. opacity_(1.0f),
  125. positionDirty_(true),
  126. opacityDirty_(true),
  127. derivedColorDirty_(true),
  128. sortOrderDirty_(false),
  129. colorGradient_(false)
  130. {
  131. }
  132. UIElement::~UIElement()
  133. {
  134. // If child elements have outside references, detach them
  135. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  136. {
  137. if (i->Refs() > 1)
  138. (*i)->Detach();
  139. }
  140. }
  141. void UIElement::RegisterObject(Context* context)
  142. {
  143. context->RegisterFactory<UIElement>();
  144. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  145. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  146. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  147. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  148. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2::ZERO, AM_FILE);
  149. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  150. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  151. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  152. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  153. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  154. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_COLOR, "Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  155. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  156. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  157. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  158. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  159. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Active", IsActive, SetActive, bool, false, AM_FILE);
  160. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  161. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  162. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  163. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, false, AM_FILE);
  166. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  167. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  168. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  169. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  170. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  171. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE);
  172. }
  173. void UIElement::ApplyAttributes()
  174. {
  175. colorGradient_ = false;
  176. derivedColorDirty_ = true;
  177. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  178. {
  179. if (color_[i] != color_[0])
  180. colorGradient_ = true;
  181. }
  182. }
  183. bool UIElement::LoadXML(const XMLElement& source)
  184. {
  185. return LoadXML(source, 0);
  186. }
  187. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  188. {
  189. // Apply the style first, but only for non-internal elements
  190. if (!internal_ && styleFile)
  191. {
  192. // Use style override if defined, otherwise type name
  193. String styleName = source.GetAttribute("style");
  194. if (styleName.Empty())
  195. styleName = GetTypeName();
  196. SetStyle(styleFile, styleName);
  197. }
  198. // Then load rest of the attributes from the source
  199. if (!Serializable::LoadXML(source))
  200. return false;
  201. unsigned nextInternalChild = 0;
  202. // Load child elements. Internal elements are not to be created as they already exist
  203. XMLElement childElem = source.GetChild("element");
  204. while (childElem)
  205. {
  206. bool internalElem = childElem.GetBool("internal");
  207. String typeName = childElem.GetAttribute("type");
  208. if (typeName.Empty())
  209. typeName = "UIElement";
  210. UIElement* child = 0;
  211. if (!internalElem)
  212. child = CreateChild(ShortStringHash(typeName));
  213. else
  214. {
  215. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  216. {
  217. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  218. {
  219. child = children_[i];
  220. nextInternalChild = i + 1;
  221. break;
  222. }
  223. }
  224. if (!child)
  225. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  226. }
  227. if (child)
  228. {
  229. if (!child->LoadXML(childElem, styleFile))
  230. return false;
  231. }
  232. childElem = childElem.GetNext("element");
  233. }
  234. ApplyAttributes();
  235. return true;
  236. }
  237. bool UIElement::SaveXML(XMLElement& dest)
  238. {
  239. // Write type and internal flag
  240. if (!dest.SetString("type", GetTypeName()))
  241. return false;
  242. if (internal_)
  243. {
  244. if (!dest.SetBool("internal", internal_))
  245. return false;
  246. }
  247. // Write attributes
  248. if (!Serializable::SaveXML(dest))
  249. return false;
  250. // Write child elements
  251. for (unsigned i = 0; i < children_.Size(); ++i)
  252. {
  253. UIElement* element = children_[i];
  254. XMLElement childElem = dest.CreateChild("element");
  255. if (!element->SaveXML(childElem))
  256. return false;
  257. }
  258. return true;
  259. }
  260. void UIElement::Update(float timeStep)
  261. {
  262. }
  263. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  264. {
  265. // Reset hovering for next frame
  266. hovering_ = false;
  267. }
  268. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  269. {
  270. if (cursor && cursor->IsVisible())
  271. cursor->SetShape(CS_NORMAL);
  272. hovering_ = true;
  273. }
  274. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  275. {
  276. }
  277. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  278. {
  279. }
  280. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  281. {
  282. }
  283. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  284. {
  285. }
  286. bool UIElement::OnDragDropTest(UIElement* source)
  287. {
  288. return true;
  289. }
  290. bool UIElement::OnDragDropFinish(UIElement* source)
  291. {
  292. return true;
  293. }
  294. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  295. {
  296. }
  297. void UIElement::OnKey(int key, int buttons, int qualifiers)
  298. {
  299. }
  300. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  301. {
  302. }
  303. void UIElement::OnResize()
  304. {
  305. }
  306. bool UIElement::LoadXML(Deserializer& source)
  307. {
  308. SharedPtr<XMLFile> xml(new XMLFile(context_));
  309. if (!xml->Load(source))
  310. return false;
  311. return LoadXML(xml->GetRoot());
  312. }
  313. bool UIElement::SaveXML(Serializer& dest)
  314. {
  315. SharedPtr<XMLFile> xml(new XMLFile(context_));
  316. XMLElement rootElem = xml->CreateRoot("element");
  317. if (!SaveXML(rootElem))
  318. return false;
  319. return xml->Save(dest);
  320. }
  321. void UIElement::SetName(const String& name)
  322. {
  323. name_ = name;
  324. }
  325. void UIElement::SetPosition(const IntVector2& position)
  326. {
  327. if (position != position_)
  328. {
  329. position_ = position;
  330. MarkDirty();
  331. }
  332. }
  333. void UIElement::SetPosition(int x, int y)
  334. {
  335. SetPosition(IntVector2(x, y));
  336. }
  337. void UIElement::SetSize(const IntVector2& size)
  338. {
  339. ++resizeNestingLevel_;
  340. IntVector2 validatedSize;
  341. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  342. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  343. if (validatedSize != size_)
  344. {
  345. size_ = validatedSize;
  346. if (resizeNestingLevel_ == 1)
  347. {
  348. // Check if parent element's layout needs to be updated first
  349. if (parent_)
  350. parent_->UpdateLayout();
  351. MarkDirty();
  352. OnResize();
  353. UpdateLayout();
  354. using namespace Resized;
  355. VariantMap eventData;
  356. eventData[P_ELEMENT] = (void*)this;
  357. eventData[P_WIDTH] = size_.x_;
  358. eventData[P_HEIGHT] = size_.y_;
  359. SendEvent(E_RESIZED, eventData);
  360. }
  361. }
  362. --resizeNestingLevel_;
  363. }
  364. void UIElement::SetSize(int width, int height)
  365. {
  366. SetSize(IntVector2(width, height));
  367. }
  368. void UIElement::SetWidth(int width)
  369. {
  370. SetSize(IntVector2(width, size_.y_));
  371. }
  372. void UIElement::SetHeight(int height)
  373. {
  374. SetSize(IntVector2(size_.x_, height));
  375. }
  376. void UIElement::SetMinSize(const IntVector2& minSize)
  377. {
  378. minSize_.x_ = Max(minSize.x_, 0);
  379. minSize_.y_ = Max(minSize.y_, 0);
  380. SetSize(size_);
  381. }
  382. void UIElement::SetMinSize(int width, int height)
  383. {
  384. SetMinSize(IntVector2(width, height));
  385. }
  386. void UIElement::SetMinWidth(int width)
  387. {
  388. SetMinSize(IntVector2(width, minSize_.y_));
  389. }
  390. void UIElement::SetMinHeight(int height)
  391. {
  392. SetMinSize(IntVector2(minSize_.x_, height));
  393. }
  394. void UIElement::SetMaxSize(const IntVector2& maxSize)
  395. {
  396. maxSize_.x_ = Max(maxSize.x_, 0);
  397. maxSize_.y_ = Max(maxSize.y_, 0);
  398. SetSize(size_);
  399. }
  400. void UIElement::SetMaxSize(int width, int height)
  401. {
  402. SetMaxSize(IntVector2(width, height));
  403. }
  404. void UIElement::SetMaxWidth(int width)
  405. {
  406. SetMaxSize(IntVector2(width, maxSize_.y_));
  407. }
  408. void UIElement::SetMaxHeight(int height)
  409. {
  410. SetMaxSize(IntVector2(maxSize_.x_, height));
  411. }
  412. void UIElement::SetFixedSize(const IntVector2& size)
  413. {
  414. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  415. SetSize(size);
  416. }
  417. void UIElement::SetFixedSize(int width, int height)
  418. {
  419. SetFixedSize(IntVector2(width, height));
  420. }
  421. void UIElement::SetFixedWidth(int width)
  422. {
  423. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  424. SetWidth(width);
  425. }
  426. void UIElement::SetFixedHeight(int height)
  427. {
  428. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  429. SetHeight(height);
  430. }
  431. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  432. {
  433. horizontalAlignment_ = hAlign;
  434. verticalAlignment_ = vAlign;
  435. MarkDirty();
  436. }
  437. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  438. {
  439. horizontalAlignment_ = align;
  440. MarkDirty();
  441. }
  442. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  443. {
  444. verticalAlignment_ = align;
  445. MarkDirty();
  446. }
  447. void UIElement::SetClipBorder(const IntRect& rect)
  448. {
  449. clipBorder_.left_ = Max(rect.left_, 0);
  450. clipBorder_.top_ = Max(rect.top_, 0);
  451. clipBorder_.right_ = Max(rect.right_, 0);
  452. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  453. }
  454. void UIElement::SetColor(const Color& color)
  455. {
  456. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  457. color_[i] = color;
  458. colorGradient_ = false;
  459. derivedColorDirty_ = true;
  460. }
  461. void UIElement::SetColor(Corner corner, const Color& color)
  462. {
  463. color_[corner] = color;
  464. colorGradient_ = false;
  465. derivedColorDirty_ = true;
  466. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  467. {
  468. if (i != corner && color_[i] != color_[corner])
  469. colorGradient_ = true;
  470. }
  471. }
  472. void UIElement::SetPriority(int priority)
  473. {
  474. priority_ = priority;
  475. if (parent_)
  476. parent_->sortOrderDirty_ = true;
  477. }
  478. void UIElement::SetOpacity(float opacity)
  479. {
  480. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  481. MarkDirty();
  482. }
  483. void UIElement::SetBringToFront(bool enable)
  484. {
  485. bringToFront_ = enable;
  486. }
  487. void UIElement::SetBringToBack(bool enable)
  488. {
  489. bringToBack_ = enable;
  490. }
  491. void UIElement::SetClipChildren(bool enable)
  492. {
  493. clipChildren_ = enable;
  494. }
  495. void UIElement::SetSortChildren(bool enable)
  496. {
  497. if (!sortChildren_ && enable)
  498. sortOrderDirty_ = true;
  499. sortChildren_ = enable;
  500. }
  501. void UIElement::SetUseDerivedOpacity(bool enable)
  502. {
  503. useDerivedOpacity_ = enable;
  504. }
  505. void UIElement::SetActive(bool enable)
  506. {
  507. active_ = enable;
  508. }
  509. void UIElement::SetFocusMode(FocusMode mode)
  510. {
  511. focusMode_ = mode;
  512. }
  513. void UIElement::SetFocus(bool enable)
  514. {
  515. if (focusMode_ < FM_FOCUSABLE)
  516. enable = false;
  517. UI* ui = GetSubsystem<UI>();
  518. if (!ui)
  519. return;
  520. if (enable)
  521. {
  522. if (ui->GetFocusElement() != this)
  523. ui->SetFocusElement(this);
  524. }
  525. else
  526. {
  527. if (ui->GetFocusElement() == this)
  528. ui->SetFocusElement(0);
  529. }
  530. }
  531. void UIElement::SetSelected(bool enable)
  532. {
  533. selected_ = enable;
  534. }
  535. void UIElement::SetVisible(bool enable)
  536. {
  537. if (enable != visible_)
  538. {
  539. visible_ = enable;
  540. // Parent's layout may change as a result of visibility change
  541. if (parent_)
  542. parent_->UpdateLayout();
  543. using namespace VisibleChanged;
  544. VariantMap eventData;
  545. eventData[P_ELEMENT] = (void*)this;
  546. eventData[P_VISIBLE] = visible_;
  547. SendEvent(E_VISIBLECHANGED, eventData);
  548. }
  549. }
  550. void UIElement::SetDragDropMode(unsigned mode)
  551. {
  552. dragDropMode_ = mode;
  553. }
  554. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  555. {
  556. if (!file)
  557. return;
  558. XMLElement rootElem = file->GetRoot();
  559. XMLElement childElem = rootElem.GetChild("element");
  560. while (childElem)
  561. {
  562. if (typeName == childElem.GetAttribute("type"))
  563. {
  564. SetStyle(childElem);
  565. return;
  566. }
  567. childElem = childElem.GetNext("element");
  568. }
  569. }
  570. void UIElement::SetStyle(const XMLElement& element)
  571. {
  572. LoadXML(element);
  573. }
  574. void UIElement::SetStyleAuto(XMLFile* file)
  575. {
  576. SetStyle(file, GetTypeName());
  577. }
  578. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  579. {
  580. layoutMode_ = mode;
  581. layoutSpacing_ = Max(spacing, 0);
  582. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  583. UpdateLayout();
  584. }
  585. void UIElement::SetLayoutMode(LayoutMode mode)
  586. {
  587. layoutMode_ = mode;
  588. UpdateLayout();
  589. }
  590. void UIElement::SetLayoutSpacing(int spacing)
  591. {
  592. layoutSpacing_ = Max(spacing, 0);
  593. UpdateLayout();
  594. }
  595. void UIElement::SetLayoutBorder(const IntRect& border)
  596. {
  597. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  598. UpdateLayout();
  599. }
  600. void UIElement::UpdateLayout()
  601. {
  602. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  603. return;
  604. // Prevent further updates while this update happens
  605. DisableLayoutUpdate();
  606. PODVector<int> positions;
  607. PODVector<int> sizes;
  608. PODVector<int> minSizes;
  609. PODVector<int> maxSizes;
  610. if (layoutMode_ == LM_HORIZONTAL)
  611. {
  612. int minChildHeight = 0;
  613. for (unsigned i = 0; i < children_.Size(); ++i)
  614. {
  615. if (!children_[i]->IsVisible())
  616. continue;
  617. positions.Push(0);
  618. sizes.Push(children_[i]->GetWidth());
  619. minSizes.Push(children_[i]->GetMinWidth());
  620. maxSizes.Push(children_[i]->GetMaxWidth());
  621. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  622. }
  623. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  624. layoutSpacing_);
  625. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  626. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  627. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  628. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  629. // Respect fixed size if already set
  630. if (minSize_.x_ != maxSize_.x_)
  631. minSize_.x_ = minWidth;
  632. if (minSize_.y_ != maxSize_.y_)
  633. minSize_.y_ = minHeight;
  634. SetSize(width, height);
  635. // Validate the size before resizing child elements, in case of min/max limits
  636. width = size_.x_;
  637. height = size_.y_;
  638. unsigned j = 0;
  639. for (unsigned i = 0; i < children_.Size(); ++i)
  640. {
  641. if (!children_[i]->IsVisible())
  642. continue;
  643. children_[i]->SetHorizontalAlignment(HA_LEFT);
  644. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  645. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  646. ++j;
  647. }
  648. }
  649. else if (layoutMode_ == LM_VERTICAL)
  650. {
  651. int minChildWidth = 0;
  652. for (unsigned i = 0; i < children_.Size(); ++i)
  653. {
  654. if (!children_[i]->IsVisible())
  655. continue;
  656. positions.Push(0);
  657. sizes.Push(children_[i]->GetHeight());
  658. minSizes.Push(children_[i]->GetMinHeight());
  659. maxSizes.Push(children_[i]->GetMaxHeight());
  660. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  661. }
  662. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  663. layoutSpacing_);
  664. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  665. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  666. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  667. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  668. if (minSize_.x_ != maxSize_.x_)
  669. minSize_.x_ = minWidth;
  670. if (minSize_.y_ != maxSize_.y_)
  671. minSize_.y_ = minHeight;
  672. SetSize(width, height);
  673. width = size_.x_;
  674. height = size_.y_;
  675. unsigned j = 0;
  676. for (unsigned i = 0; i < children_.Size(); ++i)
  677. {
  678. if (!children_[i]->IsVisible())
  679. continue;
  680. children_[i]->SetVerticalAlignment(VA_TOP);
  681. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  682. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  683. ++j;
  684. }
  685. }
  686. EnableLayoutUpdate();
  687. }
  688. void UIElement::DisableLayoutUpdate()
  689. {
  690. ++layoutNestingLevel_;
  691. }
  692. void UIElement::EnableLayoutUpdate()
  693. {
  694. --layoutNestingLevel_;
  695. }
  696. void UIElement::BringToFront()
  697. {
  698. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  699. UIElement* root = GetRoot();
  700. UIElement* ptr = this;
  701. while (ptr && ptr->GetParent() != root)
  702. ptr = ptr->GetParent();
  703. if (!ptr || !ptr->GetBringToFront())
  704. return;
  705. // Get the highest priority used by all other top level elements, assign that to the new front element
  706. // and decrease others' priority where necessary. However, take into account only active (enabled)
  707. // elements and those which have the BringToBack flag set
  708. HashSet<int> usedPriorities;
  709. int maxPriority = M_MIN_INT;
  710. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  711. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  712. {
  713. UIElement* other = *i;
  714. if (other->IsActive() && other->bringToBack_ && other != ptr)
  715. {
  716. int priority = other->GetPriority();
  717. usedPriorities.Insert(priority);
  718. maxPriority = Max(priority, maxPriority);
  719. }
  720. }
  721. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  722. {
  723. ptr->SetPriority(maxPriority);
  724. int minPriority = maxPriority;
  725. while (usedPriorities.Contains(minPriority))
  726. --minPriority;
  727. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  728. {
  729. UIElement* other = *i;
  730. int priority = other->GetPriority();
  731. if (other->IsActive() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  732. other->SetPriority(priority - 1);
  733. }
  734. }
  735. }
  736. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name)
  737. {
  738. // Check that creation succeeds and that the object in fact is a UI element
  739. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  740. if (!newElement)
  741. {
  742. LOGERROR("Could not create unknown UI element type " + type.ToString());
  743. return 0;
  744. }
  745. newElement->SetName(name);
  746. AddChild(newElement);
  747. return newElement;
  748. }
  749. void UIElement::AddChild(UIElement* element)
  750. {
  751. InsertChild(children_.Size(), element);
  752. }
  753. void UIElement::InsertChild(unsigned index, UIElement* element)
  754. {
  755. // Check for illegal or redundant parent assignment
  756. if (!element || element == this || element->parent_ == this)
  757. return;
  758. // Check for possible cyclic parent assignment
  759. UIElement* parent = parent_;
  760. while (parent)
  761. {
  762. if (parent == element)
  763. return;
  764. parent = parent->parent_;
  765. }
  766. // Add first, then remove from old parent, to ensure the element does not get deleted
  767. if (index >= children_.Size())
  768. children_.Push(SharedPtr<UIElement>(element));
  769. else
  770. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  771. element->Remove();
  772. if (sortChildren_)
  773. sortOrderDirty_ = true;
  774. element->parent_ = this;
  775. element->MarkDirty();
  776. UpdateLayout();
  777. }
  778. void UIElement::RemoveChild(UIElement* element, unsigned index)
  779. {
  780. for (unsigned i = index; i < children_.Size(); ++i)
  781. {
  782. if (children_[i] == element)
  783. {
  784. element->Detach();
  785. children_.Erase(i);
  786. UpdateLayout();
  787. return;
  788. }
  789. }
  790. }
  791. void UIElement::RemoveAllChildren()
  792. {
  793. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  794. (*i++)->Detach();
  795. children_.Clear();
  796. }
  797. void UIElement::Remove()
  798. {
  799. if (parent_)
  800. parent_->RemoveChild(this);
  801. }
  802. void UIElement::SetParent(UIElement* parent)
  803. {
  804. if (parent)
  805. parent->AddChild(this);
  806. }
  807. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  808. {
  809. vars_[key] = value;
  810. }
  811. void UIElement::SetInternal(bool enable)
  812. {
  813. internal_ = enable;
  814. }
  815. IntVector2 UIElement::GetScreenPosition() const
  816. {
  817. if (positionDirty_)
  818. {
  819. IntVector2 pos = position_;
  820. const UIElement* parent = parent_;
  821. const UIElement* current = this;
  822. while (parent)
  823. {
  824. switch (current->horizontalAlignment_)
  825. {
  826. case HA_LEFT:
  827. pos.x_ += parent->position_.x_;
  828. break;
  829. case HA_CENTER:
  830. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  831. break;
  832. case HA_RIGHT:
  833. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  834. break;
  835. }
  836. switch (current->verticalAlignment_)
  837. {
  838. case VA_TOP:
  839. pos.y_ += parent->position_.y_;
  840. break;
  841. case VA_CENTER:
  842. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  843. break;
  844. case VA_BOTTOM:
  845. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  846. break;
  847. }
  848. pos += parent->childOffset_;
  849. current = parent;
  850. parent = parent->parent_;
  851. }
  852. screenPosition_ = pos;
  853. positionDirty_ = false;
  854. }
  855. return screenPosition_;
  856. }
  857. float UIElement::GetDerivedOpacity() const
  858. {
  859. if (!useDerivedOpacity_)
  860. return opacity_;
  861. if (opacityDirty_)
  862. {
  863. derivedOpacity_ = opacity_;
  864. const UIElement* parent = parent_;
  865. while (parent)
  866. {
  867. derivedOpacity_ *= parent->opacity_;
  868. parent = parent->parent_;
  869. }
  870. opacityDirty_ = false;
  871. }
  872. return derivedOpacity_;
  873. }
  874. bool UIElement::HasFocus() const
  875. {
  876. UI* ui = GetSubsystem<UI>();
  877. if (!ui)
  878. return false;
  879. else
  880. return ui->GetFocusElement() == this;
  881. }
  882. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  883. {
  884. dest.Clear();
  885. if (!recursive)
  886. {
  887. dest.Reserve(children_.Size());
  888. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  889. dest.Push(*i);
  890. }
  891. else
  892. GetChildrenRecursive(dest);
  893. }
  894. unsigned UIElement::GetNumChildren(bool recursive) const
  895. {
  896. if (!recursive)
  897. return children_.Size();
  898. else
  899. {
  900. unsigned allChildren = children_.Size();
  901. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  902. allChildren += (*i)->GetNumChildren(true);
  903. return allChildren;
  904. }
  905. }
  906. UIElement* UIElement::GetChild(unsigned index) const
  907. {
  908. return index < children_.Size() ? children_[index] : (UIElement*)0;
  909. }
  910. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  911. {
  912. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  913. {
  914. if ((*i)->name_ == name)
  915. return *i;
  916. if (recursive)
  917. {
  918. UIElement* element = (*i)->GetChild(name, true);
  919. if (element)
  920. return element;
  921. }
  922. }
  923. return 0;
  924. }
  925. UIElement* UIElement::GetRoot() const
  926. {
  927. UIElement* root = parent_;
  928. if (!root)
  929. return 0;
  930. while (root->GetParent())
  931. root = root->GetParent();
  932. return root;
  933. }
  934. const Color& UIElement::GetDerivedColor() const
  935. {
  936. if (derivedColorDirty_)
  937. {
  938. derivedColor_ = color_[C_TOPLEFT];
  939. derivedColor_.a_ *= GetDerivedOpacity();
  940. derivedColorDirty_ = false;
  941. }
  942. return derivedColor_;
  943. }
  944. const Variant& UIElement::GetVar(ShortStringHash key) const
  945. {
  946. VariantMap::ConstIterator i = vars_.Find(key);
  947. if (i != vars_.End())
  948. return i->second_;
  949. else
  950. return Variant::EMPTY;
  951. }
  952. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  953. {
  954. return screenPosition - GetScreenPosition();
  955. }
  956. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  957. {
  958. return position + GetScreenPosition();
  959. }
  960. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  961. {
  962. if (isScreen)
  963. position = ScreenToElement(position);
  964. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  965. }
  966. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  967. {
  968. // If child elements are clipped, no need to expand the rect
  969. if (clipChildren_)
  970. return IsInside(position, isScreen);
  971. if (!isScreen)
  972. position = ElementToScreen(position);
  973. IntRect combined = GetCombinedScreenRect();
  974. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  975. position.y_ < combined.bottom_;
  976. }
  977. IntRect UIElement::GetCombinedScreenRect()
  978. {
  979. IntVector2 screenPosition(GetScreenPosition());
  980. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  981. if (!clipChildren_)
  982. {
  983. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  984. {
  985. IntVector2 childPos = (*i)->GetScreenPosition();
  986. const IntVector2& childSize = (*i)->GetSize();
  987. if (childPos.x_ < combined.left_)
  988. combined.left_ = childPos.x_;
  989. if (childPos.y_ < combined.top_)
  990. combined.top_ = childPos.y_;
  991. if (childPos.x_ + childSize.x_ > combined.right_)
  992. combined.right_ = childPos.x_ + childSize.x_;
  993. if (childPos.y_ + childSize.y_ > combined.bottom_)
  994. combined.bottom_ = childPos.y_ + childSize.y_;
  995. }
  996. }
  997. return combined;
  998. }
  999. void UIElement::SortChildren()
  1000. {
  1001. if (sortChildren_ && sortOrderDirty_)
  1002. {
  1003. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1004. sortOrderDirty_ = false;
  1005. }
  1006. }
  1007. void UIElement::SetChildOffset(const IntVector2& offset)
  1008. {
  1009. if (offset != childOffset_)
  1010. {
  1011. childOffset_ = offset;
  1012. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1013. (*i)->MarkDirty();
  1014. }
  1015. }
  1016. void UIElement::SetHovering(bool enable)
  1017. {
  1018. hovering_ = enable;
  1019. }
  1020. void UIElement::SetTempVisible(bool enable)
  1021. {
  1022. visible_ = enable;
  1023. }
  1024. void UIElement::AdjustScissor(IntRect& currentScissor)
  1025. {
  1026. if (clipChildren_)
  1027. {
  1028. IntVector2 screenPos = GetScreenPosition();
  1029. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1030. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1031. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1032. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1033. if (currentScissor.right_ < currentScissor.left_)
  1034. currentScissor.right_ = currentScissor.left_;
  1035. if (currentScissor.bottom_ < currentScissor.top_)
  1036. currentScissor.bottom_ = currentScissor.top_;
  1037. }
  1038. }
  1039. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  1040. currentScissor)
  1041. {
  1042. unsigned initialSize = quads.Size();
  1043. GetBatches(batches, quads, currentScissor);
  1044. for (unsigned i = initialSize; i < quads.Size(); ++i)
  1045. {
  1046. quads[i].left_ += offset.x_;
  1047. quads[i].top_ += offset.y_;
  1048. quads[i].right_ += offset.x_;
  1049. quads[i].bottom_ += offset.y_;
  1050. }
  1051. AdjustScissor(currentScissor);
  1052. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1053. {
  1054. if ((*i)->IsVisible())
  1055. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  1056. }
  1057. }
  1058. void UIElement::MarkDirty()
  1059. {
  1060. positionDirty_ = true;
  1061. opacityDirty_ = true;
  1062. derivedColorDirty_ = true;
  1063. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1064. (*i)->MarkDirty();
  1065. }
  1066. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1067. {
  1068. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1069. {
  1070. UIElement* element = *i;
  1071. dest.Push(element);
  1072. if (!element->children_.Empty())
  1073. element->GetChildrenRecursive(dest);
  1074. }
  1075. }
  1076. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1077. {
  1078. int width = begin + end;
  1079. if (sizes.Empty())
  1080. return width;
  1081. for (unsigned i = 0; i < sizes.Size(); ++i)
  1082. {
  1083. // If calculating maximum size, and the default is specified, do not overflow it
  1084. if (sizes[i] == M_MAX_INT)
  1085. return M_MAX_INT;
  1086. width += sizes[i] + spacing;
  1087. }
  1088. // The last spacing is not needed
  1089. return width - spacing;
  1090. }
  1091. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1092. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1093. {
  1094. int numChildren = sizes.Size();
  1095. if (!numChildren)
  1096. return;
  1097. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1098. if (targetTotalSize < 0)
  1099. targetTotalSize = 0;
  1100. int targetChildSize = targetTotalSize / numChildren;
  1101. int remainder = targetTotalSize % numChildren;
  1102. float add = (float)remainder / numChildren;
  1103. float acc = 0.0f;
  1104. // Initial pass
  1105. for (int i = 0; i < numChildren; ++i)
  1106. {
  1107. int targetSize = targetChildSize;
  1108. if (remainder)
  1109. {
  1110. acc += add;
  1111. if (acc >= 0.5f)
  1112. {
  1113. acc -= 1.0f;
  1114. ++targetSize;
  1115. --remainder;
  1116. }
  1117. }
  1118. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1119. }
  1120. // Error correction passes
  1121. for (;;)
  1122. {
  1123. int actualTotalSize = 0;
  1124. for (int i = 0; i < numChildren; ++i)
  1125. actualTotalSize += sizes[i];
  1126. int error = targetTotalSize - actualTotalSize;
  1127. // Break if no error
  1128. if (!error)
  1129. break;
  1130. // Check which of the children can be resized to correct the error. If none, must break
  1131. PODVector<unsigned> resizable;
  1132. for (int i = 0; i < numChildren; ++i)
  1133. {
  1134. if (error < 0 && sizes[i] > minSizes[i])
  1135. resizable.Push(i);
  1136. else if (error > 0 && sizes[i] < maxSizes[i])
  1137. resizable.Push(i);
  1138. }
  1139. if (resizable.Empty())
  1140. break;
  1141. int numResizable = resizable.Size();
  1142. int errorPerChild = error / numResizable;
  1143. remainder = (abs(error)) % numResizable;
  1144. add = (float)remainder / numResizable;
  1145. acc = 0.0f;
  1146. for (int i = 0; i < numResizable; ++i)
  1147. {
  1148. unsigned index = resizable[i];
  1149. int targetSize = sizes[index] + errorPerChild;
  1150. if (remainder)
  1151. {
  1152. acc += add;
  1153. if (acc >= 0.5f)
  1154. {
  1155. acc -= 1.0f;
  1156. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1157. --remainder;
  1158. }
  1159. }
  1160. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1161. }
  1162. }
  1163. // Calculate final positions and store the minimum child element size
  1164. layoutMinSize_ = M_MAX_INT;
  1165. int position = begin;
  1166. for (int i = 0; i < numChildren; ++i)
  1167. {
  1168. positions[i] = position;
  1169. position += sizes[i] + spacing;
  1170. if (sizes[i] < layoutMinSize_)
  1171. layoutMinSize_ = sizes[i];
  1172. }
  1173. }
  1174. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1175. {
  1176. IntVector2 ret(IntVector2::ZERO);
  1177. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1178. switch (ha)
  1179. {
  1180. case HA_LEFT:
  1181. ret.x_ = layoutBorder_.left_;
  1182. break;
  1183. case HA_RIGHT:
  1184. ret.x_ = -layoutBorder_.right_;
  1185. break;
  1186. default:
  1187. break;
  1188. }
  1189. VerticalAlignment va = child->GetVerticalAlignment();
  1190. switch (va)
  1191. {
  1192. case VA_TOP:
  1193. ret.y_ = layoutBorder_.top_;
  1194. break;
  1195. case VA_BOTTOM:
  1196. ret.y_ = -layoutBorder_.bottom_;
  1197. break;
  1198. default:
  1199. break;
  1200. }
  1201. return ret;
  1202. }
  1203. void UIElement::Detach()
  1204. {
  1205. parent_ = 0;
  1206. MarkDirty();
  1207. }
  1208. }