UIElement.cpp 55 KB

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