UIElement.cpp 53 KB

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