UIElement.cpp 53 KB

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