2
0

UIElement.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  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 "UI.h"
  30. #include "UIElement.h"
  31. #include "UIEvents.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. const char* horizontalAlignments[] =
  36. {
  37. "Left",
  38. "Center",
  39. "Right",
  40. 0
  41. };
  42. const char* verticalAlignments[] =
  43. {
  44. "Top",
  45. "Center",
  46. "Bottom",
  47. 0
  48. };
  49. static const char* focusModes[] =
  50. {
  51. "NotFocusable",
  52. "ResetFocus",
  53. "Focusable",
  54. "FocusableDefocusable",
  55. 0
  56. };
  57. static const char* dragDropModes[] =
  58. {
  59. "Disabled",
  60. "Source",
  61. "Target",
  62. "SourceAndTarget",
  63. 0
  64. };
  65. static const char* layoutModes[] =
  66. {
  67. "Free",
  68. "Horizontal",
  69. "Vertical",
  70. 0
  71. };
  72. extern const char* UI_CATEGORY;
  73. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  74. {
  75. return lhs->GetPriority() < rhs->GetPriority();
  76. }
  77. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  78. {
  79. return (HorizontalAlignment)GetInt();
  80. }
  81. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  82. {
  83. return (VerticalAlignment)GetInt();
  84. }
  85. template<> FocusMode Variant::Get<FocusMode>() const
  86. {
  87. return (FocusMode)GetInt();
  88. }
  89. template<> LayoutMode Variant::Get<LayoutMode>() const
  90. {
  91. return (LayoutMode)GetInt();
  92. }
  93. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  94. UIElement::UIElement(Context* context) :
  95. Serializable(context),
  96. parent_(0),
  97. clipBorder_(IntRect::ZERO),
  98. priority_(0),
  99. bringToFront_(false),
  100. bringToBack_(true),
  101. clipChildren_(false),
  102. sortChildren_(true),
  103. useDerivedOpacity_(true),
  104. enabled_(false),
  105. editable_(true),
  106. selected_(false),
  107. visible_(true),
  108. hovering_(false),
  109. internal_(false),
  110. focusMode_(FM_NOTFOCUSABLE),
  111. dragDropMode_(DD_DISABLED),
  112. layoutMode_(LM_FREE),
  113. layoutSpacing_(0),
  114. layoutBorder_(IntRect::ZERO),
  115. resizeNestingLevel_(0),
  116. layoutNestingLevel_(0),
  117. layoutMinSize_(0),
  118. indent_(0),
  119. indentSpacing_(16),
  120. position_(IntVector2::ZERO),
  121. positionDirty_(true),
  122. size_(IntVector2::ZERO),
  123. minSize_(IntVector2::ZERO),
  124. maxSize_(M_MAX_INT, M_MAX_INT),
  125. childOffset_(IntVector2::ZERO),
  126. horizontalAlignment_(HA_LEFT),
  127. verticalAlignment_(VA_TOP),
  128. opacity_(1.0f),
  129. opacityDirty_(true),
  130. derivedColorDirty_(true),
  131. sortOrderDirty_(false),
  132. colorGradient_(false),
  133. traversalMode_(TM_BREADTH_FIRST),
  134. elementEventSender_(false)
  135. {
  136. }
  137. UIElement::~UIElement()
  138. {
  139. // If child elements have outside references, detach them
  140. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  141. {
  142. if (i->Refs() > 1)
  143. (*i)->Detach();
  144. }
  145. }
  146. void UIElement::RegisterObject(Context* context)
  147. {
  148. context->RegisterFactory<UIElement>(UI_CATEGORY);
  149. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  150. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  151. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  152. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  153. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2(M_MAX_INT, M_MAX_INT), AM_FILE);
  154. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  155. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  156. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  157. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  158. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  159. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_COLOR, "Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  160. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  161. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  162. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  163. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Editable", IsEditable, SetEditable, bool, true, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  167. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  168. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  169. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  170. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  171. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, true, AM_FILE);
  172. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  173. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  174. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  175. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  176. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  177. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  178. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  179. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE);
  180. }
  181. void UIElement::ApplyAttributes()
  182. {
  183. colorGradient_ = false;
  184. derivedColorDirty_ = true;
  185. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  186. {
  187. if (color_[i] != color_[0])
  188. colorGradient_ = true;
  189. }
  190. }
  191. bool UIElement::LoadXML(const XMLElement& source, bool setInstanceDefault)
  192. {
  193. return LoadXML(source, 0, setInstanceDefault);
  194. }
  195. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile, bool setInstanceDefault)
  196. {
  197. // Get style override if defined
  198. String styleName = source.GetAttribute("style");
  199. // Apply the style first, if the style file is available
  200. if (styleFile)
  201. {
  202. // If not defined, use type name
  203. if (styleName.Empty())
  204. styleName = GetTypeName();
  205. SetStyle(styleName, styleFile);
  206. }
  207. // The 'style' attribute value in the style file cannot be equals to original's applied style to prevent infinite loop
  208. else if (!styleName.Empty() && styleName != appliedStyle_)
  209. {
  210. // Attempt to use the default style file
  211. styleFile = GetDefaultStyle();
  212. if (styleFile)
  213. {
  214. // Remember the original applied style
  215. String appliedStyle(appliedStyle_);
  216. SetStyle(styleName, styleFile);
  217. appliedStyle_ = appliedStyle;
  218. }
  219. }
  220. // Then load rest of the attributes from the source
  221. if (!Serializable::LoadXML(source, setInstanceDefault))
  222. return false;
  223. unsigned nextInternalChild = 0;
  224. // Load child elements. Internal elements are not to be created as they already exist
  225. XMLElement childElem = source.GetChild("element");
  226. while (childElem)
  227. {
  228. bool internalElem = childElem.GetBool("internal");
  229. String typeName = childElem.GetAttribute("type");
  230. if (typeName.Empty())
  231. typeName = "UIElement";
  232. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  233. UIElement* child = 0;
  234. if (!internalElem)
  235. child = CreateChild(typeName, String::EMPTY, index);
  236. else
  237. {
  238. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  239. {
  240. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  241. {
  242. child = children_[i];
  243. nextInternalChild = i + 1;
  244. break;
  245. }
  246. }
  247. if (!child)
  248. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  249. }
  250. if (child)
  251. {
  252. if (!styleFile)
  253. styleFile = GetDefaultStyle();
  254. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  255. return false;
  256. }
  257. childElem = childElem.GetNext("element");
  258. }
  259. ApplyAttributes();
  260. return true;
  261. }
  262. bool UIElement::LoadChildXML(const XMLElement& childElem, XMLFile* styleFile, bool setInstanceDefault)
  263. {
  264. bool internalElem = childElem.GetBool("internal");
  265. if (internalElem)
  266. {
  267. LOGERROR("Loading internal child element is not supported");
  268. return false;
  269. }
  270. String typeName = childElem.GetAttribute("type");
  271. if (typeName.Empty())
  272. typeName = "UIElement";
  273. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  274. UIElement* child = CreateChild(typeName, String::EMPTY, index);
  275. if (child)
  276. {
  277. if (!styleFile)
  278. styleFile = GetDefaultStyle();
  279. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  280. return false;
  281. }
  282. return true;
  283. }
  284. bool UIElement::SaveXML(XMLElement& dest) const
  285. {
  286. // Write type
  287. if (GetTypeName() != "UIElement")
  288. {
  289. if (!dest.SetString("type", GetTypeName()))
  290. return false;
  291. }
  292. // Write internal flag
  293. if (internal_)
  294. {
  295. if (!dest.SetBool("internal", internal_))
  296. return false;
  297. }
  298. // Write style
  299. if (!appliedStyle_.Empty() && appliedStyle_ != "UIElement")
  300. {
  301. if (!dest.SetAttribute("style", appliedStyle_))
  302. return false;
  303. }
  304. else if (internal_)
  305. {
  306. if (!dest.SetAttribute("style", "none"))
  307. return false;
  308. }
  309. // Write attributes
  310. if (!Serializable::SaveXML(dest))
  311. return false;
  312. // Write child elements
  313. for (unsigned i = 0; i < children_.Size(); ++i)
  314. {
  315. UIElement* element = children_[i];
  316. if (element->IsTemporary())
  317. continue;
  318. XMLElement childElem = dest.CreateChild("element");
  319. if (!element->SaveXML(childElem))
  320. return false;
  321. }
  322. // Filter UI-style and implicit attributes
  323. if (!FilterAttributes(dest))
  324. return false;
  325. return true;
  326. }
  327. void UIElement::Update(float timeStep)
  328. {
  329. }
  330. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  331. {
  332. // Reset hovering for next frame
  333. hovering_ = false;
  334. }
  335. void UIElement::GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  336. {
  337. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  338. int horizontalThickness = 1;
  339. int verticalThickness = 1;
  340. if (parent_)
  341. {
  342. switch (parent_->layoutMode_)
  343. {
  344. case LM_HORIZONTAL:
  345. verticalThickness +=2;
  346. break;
  347. case LM_VERTICAL:
  348. horizontalThickness += 2;
  349. break;
  350. default:
  351. break;
  352. }
  353. }
  354. // Left
  355. batch.AddQuad(0, 0, horizontalThickness, size_.y_, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  356. // Top
  357. batch.AddQuad(0, 0, size_.x_, verticalThickness, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  358. // Right
  359. batch.AddQuad(size_.x_ - horizontalThickness, 0, horizontalThickness, size_.y_, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  360. // Bottom
  361. batch.AddQuad(0, size_.y_ - verticalThickness, size_.x_, verticalThickness, 0, 0, 0, 0, DEBUG_DRAW_COLOR);
  362. UIBatch::AddOrMerge(batch, batches);
  363. }
  364. bool UIElement::IsWithinScissor(const IntRect& currentScissor)
  365. {
  366. if (!visible_)
  367. return false;
  368. const IntVector2& screenPos = GetScreenPosition();
  369. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + GetWidth() > currentScissor.left_ &&
  370. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + GetHeight() > currentScissor.top_;
  371. }
  372. const IntVector2& UIElement::GetScreenPosition() const
  373. {
  374. if (positionDirty_)
  375. {
  376. IntVector2 pos = position_;
  377. const UIElement* parent = parent_;
  378. if (parent)
  379. {
  380. const IntVector2& parentScreenPos = parent->GetScreenPosition();
  381. switch (horizontalAlignment_)
  382. {
  383. case HA_LEFT:
  384. pos.x_ += parentScreenPos.x_;
  385. break;
  386. case HA_CENTER:
  387. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ / 2 - size_.x_ / 2;
  388. break;
  389. case HA_RIGHT:
  390. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ - size_.x_;
  391. break;
  392. }
  393. switch (verticalAlignment_)
  394. {
  395. case VA_TOP:
  396. pos.y_ += parentScreenPos.y_;
  397. break;
  398. case VA_CENTER:
  399. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ / 2 - size_.y_ / 2;
  400. break;
  401. case VA_BOTTOM:
  402. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ - size_.y_;
  403. break;
  404. }
  405. pos += parent_->childOffset_;
  406. }
  407. screenPosition_ = pos;
  408. positionDirty_ = false;
  409. }
  410. return screenPosition_;
  411. }
  412. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  413. {
  414. // Reset cursor shape on hover, but do not do that unnecessarily during drag
  415. if (cursor && cursor->IsVisible() && !GetSubsystem<UI>()->GetDragElement())
  416. cursor->SetShape(CS_NORMAL);
  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;
  460. eventData[P_ELEMENT] = (void*)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;
  472. eventData[P_ELEMENT] = (void*)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;
  501. eventData[P_ELEMENT] = (void*)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;
  708. eventData[P_ELEMENT] = (void*)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. }
  784. void UIElement::SetIndentSpacing(int indentSpacing)
  785. {
  786. indentSpacing_ = Max(indentSpacing, 0);
  787. if (parent_)
  788. parent_->UpdateLayout();
  789. UpdateLayout();
  790. }
  791. void UIElement::UpdateLayout()
  792. {
  793. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  794. return;
  795. // Prevent further updates while this update happens
  796. DisableLayoutUpdate();
  797. PODVector<int> positions;
  798. PODVector<int> sizes;
  799. PODVector<int> minSizes;
  800. PODVector<int> maxSizes;
  801. int baseIndentWidth = GetIndentWidth();
  802. if (layoutMode_ == LM_HORIZONTAL)
  803. {
  804. int minChildHeight = 0;
  805. for (unsigned i = 0; i < children_.Size(); ++i)
  806. {
  807. if (!children_[i]->IsVisible())
  808. continue;
  809. positions.Push(baseIndentWidth);
  810. unsigned indent = children_[i]->GetIndentWidth();
  811. sizes.Push(children_[i]->GetWidth() + indent);
  812. minSizes.Push(children_[i]->GetMinWidth() + indent);
  813. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  814. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  815. }
  816. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  817. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  818. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  819. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  820. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  821. // Respect fixed size if already set
  822. if (minSize_.x_ != maxSize_.x_)
  823. minSize_.x_ = minWidth;
  824. if (minSize_.y_ != maxSize_.y_)
  825. minSize_.y_ = minHeight;
  826. SetSize(width, height);
  827. // Validate the size before resizing child elements, in case of min/max limits
  828. width = size_.x_;
  829. height = size_.y_;
  830. unsigned j = 0;
  831. for (unsigned i = 0; i < children_.Size(); ++i)
  832. {
  833. if (!children_[i]->IsVisible())
  834. continue;
  835. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  836. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  837. ++j;
  838. }
  839. }
  840. else if (layoutMode_ == LM_VERTICAL)
  841. {
  842. int minChildWidth = 0;
  843. for (unsigned i = 0; i < children_.Size(); ++i)
  844. {
  845. if (!children_[i]->IsVisible())
  846. continue;
  847. positions.Push(0);
  848. sizes.Push(children_[i]->GetHeight());
  849. minSizes.Push(children_[i]->GetMinHeight());
  850. maxSizes.Push(children_[i]->GetMaxHeight());
  851. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  852. }
  853. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  854. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  855. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  856. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  857. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  858. if (minSize_.x_ != maxSize_.x_)
  859. minSize_.x_ = minWidth;
  860. if (minSize_.y_ != maxSize_.y_)
  861. minSize_.y_ = minHeight;
  862. SetSize(width, height);
  863. width = size_.x_;
  864. height = size_.y_;
  865. unsigned j = 0;
  866. for (unsigned i = 0; i < children_.Size(); ++i)
  867. {
  868. if (!children_[i]->IsVisible())
  869. continue;
  870. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  871. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  872. ++j;
  873. }
  874. }
  875. using namespace LayoutUpdated;
  876. VariantMap eventData;
  877. eventData[P_ELEMENT] = (void*)this;
  878. SendEvent(E_LAYOUTUPDATED, eventData);
  879. EnableLayoutUpdate();
  880. }
  881. void UIElement::DisableLayoutUpdate()
  882. {
  883. ++layoutNestingLevel_;
  884. }
  885. void UIElement::EnableLayoutUpdate()
  886. {
  887. --layoutNestingLevel_;
  888. }
  889. void UIElement::BringToFront()
  890. {
  891. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  892. UIElement* root = GetRoot();
  893. // If element is detached from hierarchy, this must be a no-op
  894. if (!root)
  895. return;
  896. UIElement* ptr = this;
  897. while (ptr && ptr->GetParent() != root)
  898. ptr = ptr->GetParent();
  899. if (!ptr || !ptr->GetBringToFront())
  900. return;
  901. // Get the highest priority used by all other top level elements, assign that to the new front element
  902. // and decrease others' priority where necessary. However, take into account only input-enabled
  903. // elements and those which have the BringToBack flag set
  904. HashSet<int> usedPriorities;
  905. int maxPriority = M_MIN_INT;
  906. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  907. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  908. {
  909. UIElement* other = *i;
  910. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  911. {
  912. int priority = other->GetPriority();
  913. usedPriorities.Insert(priority);
  914. maxPriority = Max(priority, maxPriority);
  915. }
  916. }
  917. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  918. {
  919. ptr->SetPriority(maxPriority);
  920. int minPriority = maxPriority;
  921. while (usedPriorities.Contains(minPriority))
  922. --minPriority;
  923. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  924. {
  925. UIElement* other = *i;
  926. int priority = other->GetPriority();
  927. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  928. other->SetPriority(priority - 1);
  929. }
  930. }
  931. }
  932. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name, unsigned index)
  933. {
  934. // Check that creation succeeds and that the object in fact is a UI element
  935. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  936. if (!newElement)
  937. {
  938. LOGERROR("Could not create unknown UI element type " + type.ToString());
  939. return 0;
  940. }
  941. if (!name.Empty())
  942. newElement->SetName(name);
  943. InsertChild(index, newElement);
  944. return newElement;
  945. }
  946. void UIElement::AddChild(UIElement* element)
  947. {
  948. InsertChild(M_MAX_UNSIGNED, element);
  949. }
  950. void UIElement::InsertChild(unsigned index, UIElement* element)
  951. {
  952. // Check for illegal or redundant parent assignment
  953. if (!element || element == this || element->parent_ == this)
  954. return;
  955. // Check for possible cyclic parent assignment
  956. UIElement* parent = parent_;
  957. while (parent)
  958. {
  959. if (parent == element)
  960. return;
  961. parent = parent->parent_;
  962. }
  963. // Add first, then remove from old parent, to ensure the element does not get deleted
  964. if (index >= children_.Size())
  965. children_.Push(SharedPtr<UIElement>(element));
  966. else
  967. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  968. XMLFile* previousStyleFile = element->GetDefaultStyle();
  969. element->Remove();
  970. if (sortChildren_)
  971. sortOrderDirty_ = true;
  972. element->parent_ = this;
  973. element->MarkDirty();
  974. // If child element did not already have a style file, but has specified a style name, apply it now
  975. if (!previousStyleFile && !element->appliedStyle_.Empty() && GetDefaultStyle())
  976. element->SetStyle(element->appliedStyle_);
  977. VerifyChildAlignment();
  978. UpdateLayout();
  979. // Send change event
  980. UIElement* root = GetRoot();
  981. UIElement* sender = GetElementEventSender();
  982. if (sender)
  983. {
  984. using namespace ElementAdded;
  985. VariantMap eventData;
  986. eventData[P_ROOT] = (void*)root;
  987. eventData[P_PARENT] = (void*)this;
  988. eventData[P_ELEMENT] = (void*)element;
  989. sender->SendEvent(E_ELEMENTADDED, eventData);
  990. }
  991. }
  992. void UIElement::RemoveChild(UIElement* element, unsigned index)
  993. {
  994. for (unsigned i = index; i < children_.Size(); ++i)
  995. {
  996. if (children_[i] == element)
  997. {
  998. // Send change event if not already being destroyed
  999. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1000. if (sender)
  1001. {
  1002. using namespace ElementRemoved;
  1003. VariantMap eventData;
  1004. eventData[P_ROOT] = (void*)GetRoot();
  1005. eventData[P_PARENT] = (void*)this;
  1006. eventData[P_ELEMENT] = (void*)element;
  1007. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1008. }
  1009. element->Detach();
  1010. children_.Erase(i);
  1011. UpdateLayout();
  1012. return;
  1013. }
  1014. }
  1015. }
  1016. void UIElement::RemoveChildAtIndex(unsigned index)
  1017. {
  1018. if (index >= children_.Size())
  1019. return;
  1020. // Send change event if not already being destroyed
  1021. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1022. if (sender)
  1023. {
  1024. using namespace ElementRemoved;
  1025. VariantMap eventData;
  1026. eventData[P_ROOT] = (void*)GetRoot();
  1027. eventData[P_PARENT] = (void*)this;
  1028. eventData[P_ELEMENT] = (void*)children_[index];
  1029. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1030. }
  1031. children_[index]->Detach();
  1032. children_.Erase(index);
  1033. UpdateLayout();
  1034. }
  1035. void UIElement::RemoveAllChildren()
  1036. {
  1037. UIElement* root = GetRoot();
  1038. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1039. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  1040. {
  1041. // Send change event if not already being destroyed
  1042. if (sender)
  1043. {
  1044. using namespace ElementRemoved;
  1045. VariantMap eventData;
  1046. eventData[P_ROOT] = (void*)root;
  1047. eventData[P_PARENT] = (void*)this;
  1048. eventData[P_ELEMENT] = (void*)(*i).Get();
  1049. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1050. }
  1051. (*i++)->Detach();
  1052. }
  1053. children_.Clear();
  1054. UpdateLayout();
  1055. }
  1056. void UIElement::Remove()
  1057. {
  1058. if (parent_)
  1059. parent_->RemoveChild(this);
  1060. }
  1061. unsigned UIElement::FindChild(UIElement* element) const
  1062. {
  1063. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  1064. return i != children_.End() ? i - children_.Begin() : M_MAX_UNSIGNED;
  1065. }
  1066. void UIElement::SetParent(UIElement* parent, unsigned index)
  1067. {
  1068. if (parent)
  1069. parent->InsertChild(index, this);
  1070. }
  1071. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  1072. {
  1073. vars_[key] = value;
  1074. }
  1075. void UIElement::SetInternal(bool enable)
  1076. {
  1077. internal_ = enable;
  1078. }
  1079. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  1080. {
  1081. traversalMode_ = traversalMode;
  1082. }
  1083. void UIElement::SetElementEventSender(bool flag)
  1084. {
  1085. elementEventSender_ = flag;
  1086. }
  1087. float UIElement::GetDerivedOpacity() const
  1088. {
  1089. if (!useDerivedOpacity_)
  1090. return opacity_;
  1091. if (opacityDirty_)
  1092. {
  1093. derivedOpacity_ = opacity_;
  1094. const UIElement* parent = parent_;
  1095. while (parent)
  1096. {
  1097. derivedOpacity_ *= parent->opacity_;
  1098. parent = parent->parent_;
  1099. }
  1100. opacityDirty_ = false;
  1101. }
  1102. return derivedOpacity_;
  1103. }
  1104. bool UIElement::HasFocus() const
  1105. {
  1106. return GetSubsystem<UI>()->GetFocusElement() == this;
  1107. }
  1108. const String& UIElement::GetAppliedStyle() const
  1109. {
  1110. return appliedStyle_ == GetTypeName() ? String::EMPTY : appliedStyle_;
  1111. }
  1112. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  1113. {
  1114. if (recursiveUp)
  1115. {
  1116. const UIElement* element = this;
  1117. while (element)
  1118. {
  1119. if (element->defaultStyle_)
  1120. return element->defaultStyle_;
  1121. element = element->parent_;
  1122. }
  1123. return 0;
  1124. }
  1125. else
  1126. return defaultStyle_;
  1127. }
  1128. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1129. {
  1130. dest.Clear();
  1131. if (!recursive)
  1132. {
  1133. dest.Reserve(children_.Size());
  1134. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1135. dest.Push(*i);
  1136. }
  1137. else
  1138. GetChildrenRecursive(dest);
  1139. }
  1140. unsigned UIElement::GetNumChildren(bool recursive) const
  1141. {
  1142. if (!recursive)
  1143. return children_.Size();
  1144. else
  1145. {
  1146. unsigned allChildren = children_.Size();
  1147. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1148. allChildren += (*i)->GetNumChildren(true);
  1149. return allChildren;
  1150. }
  1151. }
  1152. UIElement* UIElement::GetChild(unsigned index) const
  1153. {
  1154. return index < children_.Size() ? children_[index] : (UIElement*)0;
  1155. }
  1156. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1157. {
  1158. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1159. {
  1160. if ((*i)->name_ == name)
  1161. return *i;
  1162. if (recursive)
  1163. {
  1164. UIElement* element = (*i)->GetChild(name, true);
  1165. if (element)
  1166. return element;
  1167. }
  1168. }
  1169. return 0;
  1170. }
  1171. UIElement* UIElement::GetChild(const ShortStringHash& key, const Variant& value, bool recursive) const
  1172. {
  1173. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1174. {
  1175. const Variant& varValue = (*i)->GetVar(key);
  1176. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1177. return *i;
  1178. if (recursive)
  1179. {
  1180. UIElement* element = (*i)->GetChild(key, value, true);
  1181. if (element)
  1182. return element;
  1183. }
  1184. }
  1185. return 0;
  1186. }
  1187. UIElement* UIElement::GetRoot() const
  1188. {
  1189. UIElement* root = parent_;
  1190. if (!root)
  1191. return 0;
  1192. while (root->GetParent())
  1193. root = root->GetParent();
  1194. return root;
  1195. }
  1196. const Color& UIElement::GetDerivedColor() const
  1197. {
  1198. if (derivedColorDirty_)
  1199. {
  1200. derivedColor_ = color_[C_TOPLEFT];
  1201. derivedColor_.a_ *= GetDerivedOpacity();
  1202. derivedColorDirty_ = false;
  1203. }
  1204. return derivedColor_;
  1205. }
  1206. const Variant& UIElement::GetVar(const ShortStringHash& key) const
  1207. {
  1208. VariantMap::ConstIterator i = vars_.Find(key);
  1209. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1210. }
  1211. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  1212. {
  1213. return screenPosition - GetScreenPosition();
  1214. }
  1215. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  1216. {
  1217. return position + GetScreenPosition();
  1218. }
  1219. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1220. {
  1221. if (isScreen)
  1222. position = ScreenToElement(position);
  1223. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1224. }
  1225. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1226. {
  1227. // If child elements are clipped, no need to expand the rect
  1228. if (clipChildren_)
  1229. return IsInside(position, isScreen);
  1230. if (!isScreen)
  1231. position = ElementToScreen(position);
  1232. IntRect combined = GetCombinedScreenRect();
  1233. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1234. position.y_ < combined.bottom_;
  1235. }
  1236. IntRect UIElement::GetCombinedScreenRect()
  1237. {
  1238. IntVector2 screenPosition(GetScreenPosition());
  1239. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1240. if (!clipChildren_)
  1241. {
  1242. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1243. {
  1244. IntVector2 childPos = (*i)->GetScreenPosition();
  1245. const IntVector2& childSize = (*i)->GetSize();
  1246. if (childPos.x_ < combined.left_)
  1247. combined.left_ = childPos.x_;
  1248. if (childPos.y_ < combined.top_)
  1249. combined.top_ = childPos.y_;
  1250. if (childPos.x_ + childSize.x_ > combined.right_)
  1251. combined.right_ = childPos.x_ + childSize.x_;
  1252. if (childPos.y_ + childSize.y_ > combined.bottom_)
  1253. combined.bottom_ = childPos.y_ + childSize.y_;
  1254. }
  1255. }
  1256. return combined;
  1257. }
  1258. void UIElement::SortChildren()
  1259. {
  1260. if (sortChildren_ && sortOrderDirty_)
  1261. {
  1262. // Only sort when there is no layout
  1263. if (layoutMode_ == LM_FREE)
  1264. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1265. sortOrderDirty_ = false;
  1266. }
  1267. }
  1268. void UIElement::SetChildOffset(const IntVector2& offset)
  1269. {
  1270. if (offset != childOffset_)
  1271. {
  1272. childOffset_ = offset;
  1273. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1274. (*i)->MarkDirty();
  1275. }
  1276. }
  1277. void UIElement::SetHovering(bool enable)
  1278. {
  1279. hovering_ = enable;
  1280. }
  1281. void UIElement::AdjustScissor(IntRect& currentScissor)
  1282. {
  1283. if (clipChildren_)
  1284. {
  1285. IntVector2 screenPos = GetScreenPosition();
  1286. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1287. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1288. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1289. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1290. if (currentScissor.right_ < currentScissor.left_)
  1291. currentScissor.right_ = currentScissor.left_;
  1292. if (currentScissor.bottom_ < currentScissor.top_)
  1293. currentScissor.bottom_ = currentScissor.top_;
  1294. }
  1295. }
  1296. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData, IntRect
  1297. currentScissor)
  1298. {
  1299. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1300. unsigned initialSize = vertexData.Size();
  1301. GetBatches(batches, vertexData, currentScissor);
  1302. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1303. {
  1304. vertexData[i] += floatOffset.x_;
  1305. vertexData[i + 1] += floatOffset.y_;
  1306. }
  1307. AdjustScissor(currentScissor);
  1308. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1309. {
  1310. if ((*i)->IsVisible())
  1311. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1312. }
  1313. }
  1314. UIElement* UIElement::GetElementEventSender() const
  1315. {
  1316. UIElement* element = const_cast<UIElement*>(this);
  1317. if (elementEventSender_)
  1318. return element;
  1319. while (element->parent_)
  1320. {
  1321. element = element->parent_;
  1322. if (element->elementEventSender_)
  1323. return element;
  1324. }
  1325. // If no predefined element event sender in the parental chain, return ultimate root element
  1326. return element;
  1327. }
  1328. void UIElement::MarkDirty()
  1329. {
  1330. positionDirty_ = true;
  1331. opacityDirty_ = true;
  1332. derivedColorDirty_ = true;
  1333. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1334. (*i)->MarkDirty();
  1335. }
  1336. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1337. {
  1338. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1339. if (!matchXPathQuery.SetVariable("attributeName", name))
  1340. return false;
  1341. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1342. return !removeElem || parent.RemoveChild(removeElem);
  1343. }
  1344. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1345. {
  1346. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1347. if (!matchXPathQuery.SetVariable("attributeName", name))
  1348. return false;
  1349. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1350. return false;
  1351. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1352. return !removeElem || parent.RemoveChild(removeElem);
  1353. }
  1354. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1355. {
  1356. // Remove style attribute only when its value is identical to the value stored in style file
  1357. String style = styleElem.GetAttribute("style");
  1358. if (!style.Empty())
  1359. {
  1360. if (style == dest.GetAttribute("style"))
  1361. {
  1362. if (!dest.RemoveAttribute("style"))
  1363. {
  1364. LOGWARNING("Could not remove style attribute");
  1365. return false;
  1366. }
  1367. }
  1368. }
  1369. // Perform the same action recursively for internal child elements stored in style file
  1370. XMLElement childDest = dest.GetChild("element");
  1371. XMLElement childElem = styleElem.GetChild("element");
  1372. while (childDest && childElem)
  1373. {
  1374. if (!childElem.GetBool("internal"))
  1375. {
  1376. LOGERROR("Invalid style file, style element can only contain internal child elements");
  1377. return false;
  1378. }
  1379. if (!FilterUIStyleAttributes(childDest, childElem))
  1380. return false;
  1381. childDest = childDest.GetNext("element");
  1382. childElem = childElem.GetNext("element");
  1383. }
  1384. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1385. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1386. {
  1387. if (internal_)
  1388. {
  1389. if (!dest.SetAttribute("style", "none"))
  1390. return false;
  1391. }
  1392. else
  1393. {
  1394. if (!dest.RemoveAttribute("style"))
  1395. return false;
  1396. }
  1397. }
  1398. return true;
  1399. }
  1400. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1401. {
  1402. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1403. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1404. {
  1405. if (!RemoveChildXML(dest, "Min Size"))
  1406. return false;
  1407. }
  1408. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1409. {
  1410. if (!RemoveChildXML(dest, "Position"))
  1411. return false;
  1412. if (!RemoveChildXML(dest, "Size"))
  1413. return false;
  1414. }
  1415. return true;
  1416. }
  1417. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1418. {
  1419. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1420. {
  1421. UIElement* element = *i;
  1422. dest.Push(element);
  1423. if (!element->children_.Empty())
  1424. element->GetChildrenRecursive(dest);
  1425. }
  1426. }
  1427. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1428. {
  1429. int width = begin + end;
  1430. if (sizes.Empty())
  1431. return width;
  1432. for (unsigned i = 0; i < sizes.Size(); ++i)
  1433. {
  1434. // If calculating maximum size, and the default is specified, do not overflow it
  1435. if (sizes[i] == M_MAX_INT)
  1436. return M_MAX_INT;
  1437. width += sizes[i] + spacing;
  1438. }
  1439. // The last spacing is not needed
  1440. return width - spacing;
  1441. }
  1442. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1443. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1444. {
  1445. int numChildren = sizes.Size();
  1446. if (!numChildren)
  1447. return;
  1448. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1449. if (targetTotalSize < 0)
  1450. targetTotalSize = 0;
  1451. int targetChildSize = targetTotalSize / numChildren;
  1452. int remainder = targetTotalSize % numChildren;
  1453. float add = (float)remainder / numChildren;
  1454. float acc = 0.0f;
  1455. // Initial pass
  1456. for (int i = 0; i < numChildren; ++i)
  1457. {
  1458. int targetSize = targetChildSize;
  1459. if (remainder)
  1460. {
  1461. acc += add;
  1462. if (acc >= 0.5f)
  1463. {
  1464. acc -= 1.0f;
  1465. ++targetSize;
  1466. --remainder;
  1467. }
  1468. }
  1469. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1470. }
  1471. // Error correction passes
  1472. for (;;)
  1473. {
  1474. int actualTotalSize = 0;
  1475. for (int i = 0; i < numChildren; ++i)
  1476. actualTotalSize += sizes[i];
  1477. int error = targetTotalSize - actualTotalSize;
  1478. // Break if no error
  1479. if (!error)
  1480. break;
  1481. // Check which of the children can be resized to correct the error. If none, must break
  1482. PODVector<unsigned> resizable;
  1483. for (int i = 0; i < numChildren; ++i)
  1484. {
  1485. if (error < 0 && sizes[i] > minSizes[i])
  1486. resizable.Push(i);
  1487. else if (error > 0 && sizes[i] < maxSizes[i])
  1488. resizable.Push(i);
  1489. }
  1490. if (resizable.Empty())
  1491. break;
  1492. int numResizable = resizable.Size();
  1493. int errorPerChild = error / numResizable;
  1494. remainder = (abs(error)) % numResizable;
  1495. add = (float)remainder / numResizable;
  1496. acc = 0.0f;
  1497. for (int i = 0; i < numResizable; ++i)
  1498. {
  1499. unsigned index = resizable[i];
  1500. int targetSize = sizes[index] + errorPerChild;
  1501. if (remainder)
  1502. {
  1503. acc += add;
  1504. if (acc >= 0.5f)
  1505. {
  1506. acc -= 1.0f;
  1507. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1508. --remainder;
  1509. }
  1510. }
  1511. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1512. }
  1513. }
  1514. // Calculate final positions and store the minimum child element size
  1515. layoutMinSize_ = M_MAX_INT;
  1516. int position = begin;
  1517. for (int i = 0; i < numChildren; ++i)
  1518. {
  1519. positions[i] = position;
  1520. position += sizes[i] + spacing;
  1521. if (sizes[i] < layoutMinSize_)
  1522. layoutMinSize_ = sizes[i];
  1523. }
  1524. }
  1525. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1526. {
  1527. IntVector2 ret(IntVector2::ZERO);
  1528. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1529. switch (ha)
  1530. {
  1531. case HA_LEFT:
  1532. ret.x_ = layoutBorder_.left_;
  1533. break;
  1534. case HA_RIGHT:
  1535. ret.x_ = -layoutBorder_.right_;
  1536. break;
  1537. default:
  1538. break;
  1539. }
  1540. VerticalAlignment va = child->GetVerticalAlignment();
  1541. switch (va)
  1542. {
  1543. case VA_TOP:
  1544. ret.y_ = layoutBorder_.top_;
  1545. break;
  1546. case VA_BOTTOM:
  1547. ret.y_ = -layoutBorder_.bottom_;
  1548. break;
  1549. default:
  1550. break;
  1551. }
  1552. return ret;
  1553. }
  1554. void UIElement::Detach()
  1555. {
  1556. parent_ = 0;
  1557. MarkDirty();
  1558. }
  1559. void UIElement::VerifyChildAlignment()
  1560. {
  1561. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1562. {
  1563. // Reapply child alignments. If they are illegal compared to layout, they will be set left/top as neded
  1564. (*i)->SetHorizontalAlignment((*i)->GetHorizontalAlignment());
  1565. (*i)->SetVerticalAlignment((*i)->GetVerticalAlignment());
  1566. }
  1567. }
  1568. }