UIElement.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Cursor.h"
  25. #include "HashSet.h"
  26. #include "Log.h"
  27. #include "ResourceCache.h"
  28. #include "Sort.h"
  29. #include "StringUtils.h"
  30. #include "UI.h"
  31. #include "UIElement.h"
  32. #include "UIEvents.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. 0
  42. };
  43. const char* verticalAlignments[] =
  44. {
  45. "Top",
  46. "Center",
  47. "Bottom",
  48. 0
  49. };
  50. static const char* focusModes[] =
  51. {
  52. "NotFocusable",
  53. "ResetFocus",
  54. "Focusable",
  55. "FocusableDefocusable",
  56. 0
  57. };
  58. static const char* dragDropModes[] =
  59. {
  60. "Disabled",
  61. "Source",
  62. "Target",
  63. "SourceAndTarget",
  64. 0
  65. };
  66. static const char* layoutModes[] =
  67. {
  68. "Free",
  69. "Horizontal",
  70. "Vertical",
  71. 0
  72. };
  73. 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. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  95. UIElement::UIElement(Context* context) :
  96. Serializable(context),
  97. parent_(0),
  98. clipBorder_(IntRect::ZERO),
  99. priority_(0),
  100. bringToFront_(false),
  101. bringToBack_(true),
  102. clipChildren_(false),
  103. sortChildren_(true),
  104. useDerivedOpacity_(true),
  105. enabled_(false),
  106. selected_(false),
  107. visible_(true),
  108. hovering_(false),
  109. internal_(false),
  110. focusMode_(FM_NOTFOCUSABLE),
  111. dragDropMode_(DD_DISABLED),
  112. layoutMode_(LM_FREE),
  113. layoutSpacing_(0),
  114. layoutBorder_(IntRect::ZERO),
  115. resizeNestingLevel_(0),
  116. layoutNestingLevel_(0),
  117. layoutMinSize_(0),
  118. indent_(0),
  119. indentSpacing_(16),
  120. position_(IntVector2::ZERO),
  121. positionDirty_(true),
  122. size_(IntVector2::ZERO),
  123. minSize_(IntVector2::ZERO),
  124. maxSize_(M_MAX_INT, M_MAX_INT),
  125. childOffset_(IntVector2::ZERO),
  126. horizontalAlignment_(HA_LEFT),
  127. verticalAlignment_(VA_TOP),
  128. opacity_(1.0f),
  129. opacityDirty_(true),
  130. derivedColorDirty_(true),
  131. sortOrderDirty_(false),
  132. colorGradient_(false),
  133. traversalMode_(TM_BREADTH_FIRST),
  134. elementEventSender_(false)
  135. {
  136. }
  137. UIElement::~UIElement()
  138. {
  139. // If child elements have outside references, detach them
  140. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  141. {
  142. if (i->Refs() > 1)
  143. (*i)->Detach();
  144. }
  145. }
  146. void UIElement::RegisterObject(Context* context)
  147. {
  148. context->RegisterFactory<UIElement>();
  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. using namespace Positioned;
  409. VariantMap eventData;
  410. eventData[P_ELEMENT] = (void*)this;
  411. eventData[P_X] = position_.x_;
  412. eventData[P_Y] = position_.y_;
  413. SendEvent(E_POSITIONED, eventData);
  414. }
  415. }
  416. void UIElement::SetPosition(int x, int y)
  417. {
  418. SetPosition(IntVector2(x, y));
  419. }
  420. void UIElement::SetSize(const IntVector2& size)
  421. {
  422. ++resizeNestingLevel_;
  423. IntVector2 validatedSize;
  424. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  425. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  426. if (validatedSize != size_)
  427. {
  428. size_ = validatedSize;
  429. if (resizeNestingLevel_ == 1)
  430. {
  431. // Check if parent element's layout needs to be updated first
  432. if (parent_)
  433. parent_->UpdateLayout();
  434. MarkDirty();
  435. OnResize();
  436. UpdateLayout();
  437. using namespace Resized;
  438. VariantMap eventData;
  439. eventData[P_ELEMENT] = (void*)this;
  440. eventData[P_WIDTH] = size_.x_;
  441. eventData[P_HEIGHT] = size_.y_;
  442. SendEvent(E_RESIZED, eventData);
  443. }
  444. }
  445. --resizeNestingLevel_;
  446. }
  447. void UIElement::SetSize(int width, int height)
  448. {
  449. SetSize(IntVector2(width, height));
  450. }
  451. void UIElement::SetWidth(int width)
  452. {
  453. SetSize(IntVector2(width, size_.y_));
  454. }
  455. void UIElement::SetHeight(int height)
  456. {
  457. SetSize(IntVector2(size_.x_, height));
  458. }
  459. void UIElement::SetMinSize(const IntVector2& minSize)
  460. {
  461. minSize_.x_ = Max(minSize.x_, 0);
  462. minSize_.y_ = Max(minSize.y_, 0);
  463. SetSize(size_);
  464. }
  465. void UIElement::SetMinSize(int width, int height)
  466. {
  467. SetMinSize(IntVector2(width, height));
  468. }
  469. void UIElement::SetMinWidth(int width)
  470. {
  471. SetMinSize(IntVector2(width, minSize_.y_));
  472. }
  473. void UIElement::SetMinHeight(int height)
  474. {
  475. SetMinSize(IntVector2(minSize_.x_, height));
  476. }
  477. void UIElement::SetMaxSize(const IntVector2& maxSize)
  478. {
  479. maxSize_.x_ = Max(maxSize.x_, 0);
  480. maxSize_.y_ = Max(maxSize.y_, 0);
  481. SetSize(size_);
  482. }
  483. void UIElement::SetMaxSize(int width, int height)
  484. {
  485. SetMaxSize(IntVector2(width, height));
  486. }
  487. void UIElement::SetMaxWidth(int width)
  488. {
  489. SetMaxSize(IntVector2(width, maxSize_.y_));
  490. }
  491. void UIElement::SetMaxHeight(int height)
  492. {
  493. SetMaxSize(IntVector2(maxSize_.x_, height));
  494. }
  495. void UIElement::SetFixedSize(const IntVector2& size)
  496. {
  497. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  498. SetSize(size);
  499. }
  500. void UIElement::SetFixedSize(int width, int height)
  501. {
  502. SetFixedSize(IntVector2(width, height));
  503. }
  504. void UIElement::SetFixedWidth(int width)
  505. {
  506. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  507. SetWidth(width);
  508. }
  509. void UIElement::SetFixedHeight(int height)
  510. {
  511. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  512. SetHeight(height);
  513. }
  514. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  515. {
  516. horizontalAlignment_ = hAlign;
  517. verticalAlignment_ = vAlign;
  518. MarkDirty();
  519. }
  520. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  521. {
  522. horizontalAlignment_ = align;
  523. MarkDirty();
  524. }
  525. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  526. {
  527. verticalAlignment_ = align;
  528. MarkDirty();
  529. }
  530. void UIElement::SetClipBorder(const IntRect& rect)
  531. {
  532. clipBorder_.left_ = Max(rect.left_, 0);
  533. clipBorder_.top_ = Max(rect.top_, 0);
  534. clipBorder_.right_ = Max(rect.right_, 0);
  535. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  536. }
  537. void UIElement::SetColor(const Color& color)
  538. {
  539. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  540. color_[i] = color;
  541. colorGradient_ = false;
  542. derivedColorDirty_ = true;
  543. }
  544. void UIElement::SetColor(Corner corner, const Color& color)
  545. {
  546. color_[corner] = color;
  547. colorGradient_ = false;
  548. derivedColorDirty_ = true;
  549. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  550. {
  551. if (i != corner && color_[i] != color_[corner])
  552. colorGradient_ = true;
  553. }
  554. }
  555. void UIElement::SetPriority(int priority)
  556. {
  557. priority_ = priority;
  558. if (parent_)
  559. parent_->sortOrderDirty_ = true;
  560. }
  561. void UIElement::SetOpacity(float opacity)
  562. {
  563. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  564. MarkDirty();
  565. }
  566. void UIElement::SetBringToFront(bool enable)
  567. {
  568. bringToFront_ = enable;
  569. }
  570. void UIElement::SetBringToBack(bool enable)
  571. {
  572. bringToBack_ = enable;
  573. }
  574. void UIElement::SetClipChildren(bool enable)
  575. {
  576. clipChildren_ = enable;
  577. }
  578. void UIElement::SetSortChildren(bool enable)
  579. {
  580. if (!sortChildren_ && enable)
  581. sortOrderDirty_ = true;
  582. sortChildren_ = enable;
  583. }
  584. void UIElement::SetUseDerivedOpacity(bool enable)
  585. {
  586. useDerivedOpacity_ = enable;
  587. }
  588. void UIElement::SetEnabled(bool enable)
  589. {
  590. enabled_ = enable;
  591. }
  592. void UIElement::SetFocusMode(FocusMode mode)
  593. {
  594. focusMode_ = mode;
  595. }
  596. void UIElement::SetFocus(bool enable)
  597. {
  598. if (focusMode_ < FM_FOCUSABLE)
  599. enable = false;
  600. UI* ui = GetSubsystem<UI>();
  601. if (!ui)
  602. return;
  603. if (enable)
  604. {
  605. if (ui->GetFocusElement() != this)
  606. ui->SetFocusElement(this);
  607. }
  608. else
  609. {
  610. if (ui->GetFocusElement() == this)
  611. ui->SetFocusElement(0);
  612. }
  613. }
  614. void UIElement::SetSelected(bool enable)
  615. {
  616. selected_ = enable;
  617. }
  618. void UIElement::SetVisible(bool enable)
  619. {
  620. if (enable != visible_)
  621. {
  622. visible_ = enable;
  623. // Parent's layout may change as a result of visibility change
  624. if (parent_)
  625. parent_->UpdateLayout();
  626. using namespace VisibleChanged;
  627. VariantMap eventData;
  628. eventData[P_ELEMENT] = (void*)this;
  629. eventData[P_VISIBLE] = visible_;
  630. SendEvent(E_VISIBLECHANGED, eventData);
  631. }
  632. }
  633. void UIElement::SetDragDropMode(unsigned mode)
  634. {
  635. dragDropMode_ = mode;
  636. }
  637. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  638. {
  639. if (!file)
  640. return;
  641. styleXPathQuery_.SetVariable("typeName", typeName);
  642. XMLElement styleElem = file->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  643. if (styleElem)
  644. SetStyle(styleElem);
  645. }
  646. void UIElement::SetStyle(const XMLElement& element)
  647. {
  648. LoadXML(element);
  649. }
  650. void UIElement::SetStyleAuto(XMLFile* file)
  651. {
  652. SetStyle(file, GetTypeName());
  653. }
  654. void UIElement::SetDefaultStyle(XMLFile* style)
  655. {
  656. defaultStyle_ = style;
  657. }
  658. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  659. {
  660. layoutMode_ = mode;
  661. layoutSpacing_ = Max(spacing, 0);
  662. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  663. UpdateLayout();
  664. }
  665. void UIElement::SetLayoutMode(LayoutMode mode)
  666. {
  667. layoutMode_ = mode;
  668. UpdateLayout();
  669. }
  670. void UIElement::SetLayoutSpacing(int spacing)
  671. {
  672. layoutSpacing_ = Max(spacing, 0);
  673. UpdateLayout();
  674. }
  675. void UIElement::SetLayoutBorder(const IntRect& border)
  676. {
  677. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  678. UpdateLayout();
  679. }
  680. void UIElement::SetIndent(int indent)
  681. {
  682. indent_ = indent;
  683. if (parent_)
  684. parent_->UpdateLayout();
  685. UpdateLayout();
  686. }
  687. void UIElement::SetIndentSpacing(int indentSpacing)
  688. {
  689. indentSpacing_ = Max(indentSpacing, 0);
  690. if (parent_)
  691. parent_->UpdateLayout();
  692. UpdateLayout();
  693. }
  694. void UIElement::UpdateLayout()
  695. {
  696. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  697. return;
  698. // Prevent further updates while this update happens
  699. DisableLayoutUpdate();
  700. PODVector<int> positions;
  701. PODVector<int> sizes;
  702. PODVector<int> minSizes;
  703. PODVector<int> maxSizes;
  704. int baseIndentWidth = GetIndentWidth();
  705. if (layoutMode_ == LM_HORIZONTAL)
  706. {
  707. int minChildHeight = 0;
  708. for (unsigned i = 0; i < children_.Size(); ++i)
  709. {
  710. if (!children_[i]->IsVisible())
  711. continue;
  712. positions.Push(baseIndentWidth);
  713. unsigned indent = children_[i]->GetIndentWidth();
  714. sizes.Push(children_[i]->GetWidth() + indent);
  715. minSizes.Push(children_[i]->GetMinWidth() + indent);
  716. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  717. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  718. }
  719. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  720. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  721. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  722. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  723. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  724. // Respect fixed size if already set
  725. if (minSize_.x_ != maxSize_.x_)
  726. minSize_.x_ = minWidth;
  727. if (minSize_.y_ != maxSize_.y_)
  728. minSize_.y_ = minHeight;
  729. SetSize(width, height);
  730. // Validate the size before resizing child elements, in case of min/max limits
  731. width = size_.x_;
  732. height = size_.y_;
  733. unsigned j = 0;
  734. for (unsigned i = 0; i < children_.Size(); ++i)
  735. {
  736. if (!children_[i]->IsVisible())
  737. continue;
  738. HorizontalAlignment horizontalAlignment = children_[i]->horizontalAlignment_;
  739. children_[i]->horizontalAlignment_ = HA_LEFT;
  740. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  741. children_[i]->horizontalAlignment_ = horizontalAlignment;
  742. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  743. ++j;
  744. }
  745. }
  746. else if (layoutMode_ == LM_VERTICAL)
  747. {
  748. int minChildWidth = 0;
  749. for (unsigned i = 0; i < children_.Size(); ++i)
  750. {
  751. if (!children_[i]->IsVisible())
  752. continue;
  753. positions.Push(0);
  754. sizes.Push(children_[i]->GetHeight());
  755. minSizes.Push(children_[i]->GetMinHeight());
  756. maxSizes.Push(children_[i]->GetMaxHeight());
  757. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  758. }
  759. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  760. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  761. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  762. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  763. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  764. if (minSize_.x_ != maxSize_.x_)
  765. minSize_.x_ = minWidth;
  766. if (minSize_.y_ != maxSize_.y_)
  767. minSize_.y_ = minHeight;
  768. SetSize(width, height);
  769. width = size_.x_;
  770. height = size_.y_;
  771. unsigned j = 0;
  772. for (unsigned i = 0; i < children_.Size(); ++i)
  773. {
  774. if (!children_[i]->IsVisible())
  775. continue;
  776. VerticalAlignment verticalAlignment = children_[i]->verticalAlignment_;
  777. children_[i]->verticalAlignment_ = VA_TOP;
  778. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  779. children_[i]->verticalAlignment_ = verticalAlignment;
  780. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  781. ++j;
  782. }
  783. }
  784. using namespace LayoutUpdated;
  785. VariantMap eventData;
  786. eventData[P_ELEMENT] = (void*)this;
  787. SendEvent(E_LAYOUTUPDATED, eventData);
  788. EnableLayoutUpdate();
  789. }
  790. void UIElement::DisableLayoutUpdate()
  791. {
  792. ++layoutNestingLevel_;
  793. }
  794. void UIElement::EnableLayoutUpdate()
  795. {
  796. --layoutNestingLevel_;
  797. }
  798. void UIElement::BringToFront()
  799. {
  800. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  801. UIElement* root = GetRoot();
  802. // If element is detached from hierarchy, this must be a no-op
  803. if (!root)
  804. return;
  805. UIElement* ptr = this;
  806. while (ptr && ptr->GetParent() != root)
  807. ptr = ptr->GetParent();
  808. if (!ptr || !ptr->GetBringToFront())
  809. return;
  810. // Get the highest priority used by all other top level elements, assign that to the new front element
  811. // and decrease others' priority where necessary. However, take into account only input-enabled
  812. // elements and those which have the BringToBack flag set
  813. HashSet<int> usedPriorities;
  814. int maxPriority = M_MIN_INT;
  815. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  816. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  817. {
  818. UIElement* other = *i;
  819. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  820. {
  821. int priority = other->GetPriority();
  822. usedPriorities.Insert(priority);
  823. maxPriority = Max(priority, maxPriority);
  824. }
  825. }
  826. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  827. {
  828. ptr->SetPriority(maxPriority);
  829. int minPriority = maxPriority;
  830. while (usedPriorities.Contains(minPriority))
  831. --minPriority;
  832. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  833. {
  834. UIElement* other = *i;
  835. int priority = other->GetPriority();
  836. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  837. other->SetPriority(priority - 1);
  838. }
  839. }
  840. }
  841. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name, unsigned index)
  842. {
  843. // Check that creation succeeds and that the object in fact is a UI element
  844. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  845. if (!newElement)
  846. {
  847. LOGERROR("Could not create unknown UI element type " + type.ToString());
  848. return 0;
  849. }
  850. if (!name.Empty())
  851. newElement->SetName(name);
  852. InsertChild(index, newElement);
  853. return newElement;
  854. }
  855. void UIElement::AddChild(UIElement* element)
  856. {
  857. InsertChild(M_MAX_UNSIGNED, element);
  858. }
  859. void UIElement::InsertChild(unsigned index, UIElement* element)
  860. {
  861. // Check for illegal or redundant parent assignment
  862. if (!element || element == this || element->parent_ == this)
  863. return;
  864. // Check for possible cyclic parent assignment
  865. UIElement* parent = parent_;
  866. while (parent)
  867. {
  868. if (parent == element)
  869. return;
  870. parent = parent->parent_;
  871. }
  872. // Add first, then remove from old parent, to ensure the element does not get deleted
  873. if (index >= children_.Size())
  874. children_.Push(SharedPtr<UIElement>(element));
  875. else
  876. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  877. element->Remove();
  878. if (sortChildren_)
  879. sortOrderDirty_ = true;
  880. element->parent_ = this;
  881. element->MarkDirty();
  882. UpdateLayout();
  883. // Send change event
  884. UIElement* root = GetRoot();
  885. UIElement* sender = GetElementEventSender();
  886. if (sender)
  887. {
  888. using namespace ElementAdded;
  889. VariantMap eventData;
  890. eventData[P_ROOT] = (void*)root;
  891. eventData[P_PARENT] = (void*)this;
  892. eventData[P_ELEMENT] = (void*)element;
  893. sender->SendEvent(E_ELEMENTADDED, eventData);
  894. }
  895. }
  896. void UIElement::RemoveChild(UIElement* element, unsigned index)
  897. {
  898. UIElement* root = GetRoot();
  899. UIElement* sender = GetElementEventSender();
  900. for (unsigned i = index; i < children_.Size(); ++i)
  901. {
  902. if (children_[i] == element)
  903. {
  904. // Send change event if not already being destroyed
  905. if (Refs() > 0 && sender)
  906. {
  907. using namespace ElementRemoved;
  908. VariantMap eventData;
  909. eventData[P_ROOT] = (void*)root;
  910. eventData[P_PARENT] = (void*)this;
  911. eventData[P_ELEMENT] = (void*)element;
  912. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  913. }
  914. element->Detach();
  915. children_.Erase(i);
  916. UpdateLayout();
  917. return;
  918. }
  919. }
  920. }
  921. void UIElement::RemoveChildAtIndex(unsigned index)
  922. {
  923. if (index >= children_.Size())
  924. return;
  925. children_[index]->Detach();
  926. children_.Erase(index);
  927. UpdateLayout();
  928. }
  929. void UIElement::RemoveAllChildren()
  930. {
  931. UIElement* root = GetRoot();
  932. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  933. {
  934. // Send change event if not already being destroyed
  935. if (Refs() > 0 && root)
  936. {
  937. using namespace ElementRemoved;
  938. VariantMap eventData;
  939. eventData[P_ROOT] = (void*)root;
  940. eventData[P_PARENT] = (void*)this;
  941. eventData[P_ELEMENT] = (void*)(*i).Get();
  942. root->SendEvent(E_ELEMENTREMOVED, eventData);
  943. }
  944. (*i++)->Detach();
  945. }
  946. children_.Clear();
  947. }
  948. void UIElement::Remove()
  949. {
  950. if (parent_)
  951. parent_->RemoveChild(this);
  952. }
  953. unsigned UIElement::FindChild(UIElement* element) const
  954. {
  955. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  956. return i != children_.End() ? i - children_.Begin() : M_MAX_UNSIGNED;
  957. }
  958. void UIElement::SetParent(UIElement* parent, unsigned index)
  959. {
  960. if (parent)
  961. parent->InsertChild(index, this);
  962. }
  963. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  964. {
  965. vars_[key] = value;
  966. }
  967. void UIElement::SetInternal(bool enable)
  968. {
  969. internal_ = enable;
  970. }
  971. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  972. {
  973. traversalMode_ = traversalMode;
  974. }
  975. void UIElement::SetElementEventSender(bool flag)
  976. {
  977. elementEventSender_ = flag;
  978. }
  979. float UIElement::GetDerivedOpacity() const
  980. {
  981. if (!useDerivedOpacity_)
  982. return opacity_;
  983. if (opacityDirty_)
  984. {
  985. derivedOpacity_ = opacity_;
  986. const UIElement* parent = parent_;
  987. while (parent)
  988. {
  989. derivedOpacity_ *= parent->opacity_;
  990. parent = parent->parent_;
  991. }
  992. opacityDirty_ = false;
  993. }
  994. return derivedOpacity_;
  995. }
  996. bool UIElement::HasFocus() const
  997. {
  998. UI* ui = GetSubsystem<UI>();
  999. if (!ui)
  1000. return false;
  1001. else
  1002. return ui->GetFocusElement() == this;
  1003. }
  1004. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  1005. {
  1006. if (recursiveUp)
  1007. {
  1008. const UIElement* element = this;
  1009. while (element)
  1010. {
  1011. if (element->defaultStyle_)
  1012. return element->defaultStyle_;
  1013. element = element->parent_;
  1014. }
  1015. return 0;
  1016. }
  1017. else
  1018. return defaultStyle_;
  1019. }
  1020. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1021. {
  1022. dest.Clear();
  1023. if (!recursive)
  1024. {
  1025. dest.Reserve(children_.Size());
  1026. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1027. dest.Push(*i);
  1028. }
  1029. else
  1030. GetChildrenRecursive(dest);
  1031. }
  1032. unsigned UIElement::GetNumChildren(bool recursive) const
  1033. {
  1034. if (!recursive)
  1035. return children_.Size();
  1036. else
  1037. {
  1038. unsigned allChildren = children_.Size();
  1039. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1040. allChildren += (*i)->GetNumChildren(true);
  1041. return allChildren;
  1042. }
  1043. }
  1044. UIElement* UIElement::GetChild(unsigned index) const
  1045. {
  1046. return index < children_.Size() ? children_[index] : (UIElement*)0;
  1047. }
  1048. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1049. {
  1050. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1051. {
  1052. if ((*i)->name_ == name)
  1053. return *i;
  1054. if (recursive)
  1055. {
  1056. UIElement* element = (*i)->GetChild(name, true);
  1057. if (element)
  1058. return element;
  1059. }
  1060. }
  1061. return 0;
  1062. }
  1063. UIElement* UIElement::GetChild(const ShortStringHash& key, const Variant& value, bool recursive) const
  1064. {
  1065. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1066. {
  1067. const Variant& varValue = (*i)->GetVar(key);
  1068. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1069. return *i;
  1070. if (recursive)
  1071. {
  1072. UIElement* element = (*i)->GetChild(key, value, true);
  1073. if (element)
  1074. return element;
  1075. }
  1076. }
  1077. return 0;
  1078. }
  1079. UIElement* UIElement::GetRoot() const
  1080. {
  1081. UIElement* root = parent_;
  1082. if (!root)
  1083. return 0;
  1084. while (root->GetParent())
  1085. root = root->GetParent();
  1086. return root;
  1087. }
  1088. const Color& UIElement::GetDerivedColor() const
  1089. {
  1090. if (derivedColorDirty_)
  1091. {
  1092. derivedColor_ = color_[C_TOPLEFT];
  1093. derivedColor_.a_ *= GetDerivedOpacity();
  1094. derivedColorDirty_ = false;
  1095. }
  1096. return derivedColor_;
  1097. }
  1098. const Variant& UIElement::GetVar(const ShortStringHash& key) const
  1099. {
  1100. VariantMap::ConstIterator i = vars_.Find(key);
  1101. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1102. }
  1103. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  1104. {
  1105. return screenPosition - GetScreenPosition();
  1106. }
  1107. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  1108. {
  1109. return position + GetScreenPosition();
  1110. }
  1111. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1112. {
  1113. if (isScreen)
  1114. position = ScreenToElement(position);
  1115. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1116. }
  1117. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1118. {
  1119. // If child elements are clipped, no need to expand the rect
  1120. if (clipChildren_)
  1121. return IsInside(position, isScreen);
  1122. if (!isScreen)
  1123. position = ElementToScreen(position);
  1124. IntRect combined = GetCombinedScreenRect();
  1125. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1126. position.y_ < combined.bottom_;
  1127. }
  1128. IntRect UIElement::GetCombinedScreenRect()
  1129. {
  1130. IntVector2 screenPosition(GetScreenPosition());
  1131. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1132. if (!clipChildren_)
  1133. {
  1134. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1135. {
  1136. IntVector2 childPos = (*i)->GetScreenPosition();
  1137. const IntVector2& childSize = (*i)->GetSize();
  1138. if (childPos.x_ < combined.left_)
  1139. combined.left_ = childPos.x_;
  1140. if (childPos.y_ < combined.top_)
  1141. combined.top_ = childPos.y_;
  1142. if (childPos.x_ + childSize.x_ > combined.right_)
  1143. combined.right_ = childPos.x_ + childSize.x_;
  1144. if (childPos.y_ + childSize.y_ > combined.bottom_)
  1145. combined.bottom_ = childPos.y_ + childSize.y_;
  1146. }
  1147. }
  1148. return combined;
  1149. }
  1150. void UIElement::SortChildren()
  1151. {
  1152. if (sortChildren_ && sortOrderDirty_)
  1153. {
  1154. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1155. sortOrderDirty_ = false;
  1156. }
  1157. }
  1158. void UIElement::SetChildOffset(const IntVector2& offset)
  1159. {
  1160. if (offset != childOffset_)
  1161. {
  1162. childOffset_ = offset;
  1163. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1164. (*i)->MarkDirty();
  1165. }
  1166. }
  1167. void UIElement::SetHovering(bool enable)
  1168. {
  1169. hovering_ = enable;
  1170. }
  1171. void UIElement::SetTempVisible(bool enable)
  1172. {
  1173. visible_ = enable;
  1174. }
  1175. void UIElement::AdjustScissor(IntRect& currentScissor)
  1176. {
  1177. if (clipChildren_)
  1178. {
  1179. IntVector2 screenPos = GetScreenPosition();
  1180. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1181. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1182. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1183. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1184. if (currentScissor.right_ < currentScissor.left_)
  1185. currentScissor.right_ = currentScissor.left_;
  1186. if (currentScissor.bottom_ < currentScissor.top_)
  1187. currentScissor.bottom_ = currentScissor.top_;
  1188. }
  1189. }
  1190. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData, IntRect
  1191. currentScissor)
  1192. {
  1193. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1194. unsigned initialSize = vertexData.Size();
  1195. GetBatches(batches, vertexData, currentScissor);
  1196. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1197. {
  1198. vertexData[i] += floatOffset.x_;
  1199. vertexData[i + 1] += floatOffset.y_;
  1200. }
  1201. AdjustScissor(currentScissor);
  1202. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1203. {
  1204. if ((*i)->IsVisible())
  1205. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1206. }
  1207. }
  1208. UIElement* UIElement::GetElementEventSender() const
  1209. {
  1210. UIElement* element = const_cast<UIElement*>(this);
  1211. if (elementEventSender_)
  1212. return element;
  1213. while (element->parent_)
  1214. {
  1215. element = element->parent_;
  1216. if (element->elementEventSender_)
  1217. return element;
  1218. }
  1219. // If no predefined element event sender in the parental chain, return ultimate root element
  1220. return element;
  1221. }
  1222. void UIElement::MarkDirty()
  1223. {
  1224. positionDirty_ = true;
  1225. opacityDirty_ = true;
  1226. derivedColorDirty_ = true;
  1227. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1228. (*i)->MarkDirty();
  1229. }
  1230. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1231. {
  1232. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1233. {
  1234. UIElement* element = *i;
  1235. dest.Push(element);
  1236. if (!element->children_.Empty())
  1237. element->GetChildrenRecursive(dest);
  1238. }
  1239. }
  1240. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1241. {
  1242. int width = begin + end;
  1243. if (sizes.Empty())
  1244. return width;
  1245. for (unsigned i = 0; i < sizes.Size(); ++i)
  1246. {
  1247. // If calculating maximum size, and the default is specified, do not overflow it
  1248. if (sizes[i] == M_MAX_INT)
  1249. return M_MAX_INT;
  1250. width += sizes[i] + spacing;
  1251. }
  1252. // The last spacing is not needed
  1253. return width - spacing;
  1254. }
  1255. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1256. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1257. {
  1258. int numChildren = sizes.Size();
  1259. if (!numChildren)
  1260. return;
  1261. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1262. if (targetTotalSize < 0)
  1263. targetTotalSize = 0;
  1264. int targetChildSize = targetTotalSize / numChildren;
  1265. int remainder = targetTotalSize % numChildren;
  1266. float add = (float)remainder / numChildren;
  1267. float acc = 0.0f;
  1268. // Initial pass
  1269. for (int i = 0; i < numChildren; ++i)
  1270. {
  1271. int targetSize = targetChildSize;
  1272. if (remainder)
  1273. {
  1274. acc += add;
  1275. if (acc >= 0.5f)
  1276. {
  1277. acc -= 1.0f;
  1278. ++targetSize;
  1279. --remainder;
  1280. }
  1281. }
  1282. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1283. }
  1284. // Error correction passes
  1285. for (;;)
  1286. {
  1287. int actualTotalSize = 0;
  1288. for (int i = 0; i < numChildren; ++i)
  1289. actualTotalSize += sizes[i];
  1290. int error = targetTotalSize - actualTotalSize;
  1291. // Break if no error
  1292. if (!error)
  1293. break;
  1294. // Check which of the children can be resized to correct the error. If none, must break
  1295. PODVector<unsigned> resizable;
  1296. for (int i = 0; i < numChildren; ++i)
  1297. {
  1298. if (error < 0 && sizes[i] > minSizes[i])
  1299. resizable.Push(i);
  1300. else if (error > 0 && sizes[i] < maxSizes[i])
  1301. resizable.Push(i);
  1302. }
  1303. if (resizable.Empty())
  1304. break;
  1305. int numResizable = resizable.Size();
  1306. int errorPerChild = error / numResizable;
  1307. remainder = (abs(error)) % numResizable;
  1308. add = (float)remainder / numResizable;
  1309. acc = 0.0f;
  1310. for (int i = 0; i < numResizable; ++i)
  1311. {
  1312. unsigned index = resizable[i];
  1313. int targetSize = sizes[index] + errorPerChild;
  1314. if (remainder)
  1315. {
  1316. acc += add;
  1317. if (acc >= 0.5f)
  1318. {
  1319. acc -= 1.0f;
  1320. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1321. --remainder;
  1322. }
  1323. }
  1324. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1325. }
  1326. }
  1327. // Calculate final positions and store the minimum child element size
  1328. layoutMinSize_ = M_MAX_INT;
  1329. int position = begin;
  1330. for (int i = 0; i < numChildren; ++i)
  1331. {
  1332. positions[i] = position;
  1333. position += sizes[i] + spacing;
  1334. if (sizes[i] < layoutMinSize_)
  1335. layoutMinSize_ = sizes[i];
  1336. }
  1337. }
  1338. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1339. {
  1340. IntVector2 ret(IntVector2::ZERO);
  1341. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1342. switch (ha)
  1343. {
  1344. case HA_LEFT:
  1345. ret.x_ = layoutBorder_.left_;
  1346. break;
  1347. case HA_RIGHT:
  1348. ret.x_ = -layoutBorder_.right_;
  1349. break;
  1350. default:
  1351. break;
  1352. }
  1353. VerticalAlignment va = child->GetVerticalAlignment();
  1354. switch (va)
  1355. {
  1356. case VA_TOP:
  1357. ret.y_ = layoutBorder_.top_;
  1358. break;
  1359. case VA_BOTTOM:
  1360. ret.y_ = -layoutBorder_.bottom_;
  1361. break;
  1362. default:
  1363. break;
  1364. }
  1365. return ret;
  1366. }
  1367. void UIElement::Detach()
  1368. {
  1369. parent_ = 0;
  1370. MarkDirty();
  1371. }
  1372. }