UI.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CheckBox.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "Cursor.h"
  28. #include "DropDownList.h"
  29. #include "FileSelector.h"
  30. #include "Font.h"
  31. #include "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "InputEvents.h"
  34. #include "LineEdit.h"
  35. #include "ListView.h"
  36. #include "Log.h"
  37. #include "Matrix3x4.h"
  38. #include "Profiler.h"
  39. #include "ResourceCache.h"
  40. #include "ScrollBar.h"
  41. #include "Shader.h"
  42. #include "ShaderVariation.h"
  43. #include "Slider.h"
  44. #include "Text.h"
  45. #include "Texture2D.h"
  46. #include "UI.h"
  47. #include "UIEvents.h"
  48. #include "VertexBuffer.h"
  49. #include "Window.h"
  50. #include "Sort.h"
  51. #include "DebugNew.h"
  52. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  53. {
  54. return lhs->GetPriority() < rhs->GetPriority();
  55. }
  56. OBJECTTYPESTATIC(UI);
  57. UI::UI(Context* context) :
  58. Object(context),
  59. mouseButtons_(0),
  60. qualifiers_(0),
  61. initialized_(false)
  62. {
  63. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  64. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  65. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  66. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  67. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  68. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  69. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  70. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  71. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  72. // Try to initialize right now, but skip if screen mode is not yet set
  73. Initialize();
  74. }
  75. UI::~UI()
  76. {
  77. }
  78. void UI::SetCursor(Cursor* cursor)
  79. {
  80. if (!rootElement_)
  81. return;
  82. // Remove old cursor (if any) and set new
  83. if (cursor_)
  84. {
  85. rootElement_->RemoveChild(cursor_);
  86. cursor_.Reset();
  87. }
  88. if (cursor)
  89. {
  90. rootElement_->AddChild(cursor);
  91. cursor_ = cursor;
  92. IntVector2 pos = cursor_->GetPosition();
  93. const IntVector2& rootSize = rootElement_->GetSize();
  94. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  95. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  96. cursor_->SetPosition(pos);
  97. }
  98. }
  99. void UI::SetFocusElement(UIElement* element)
  100. {
  101. if (!rootElement_)
  102. return;
  103. using namespace FocusChanged;
  104. VariantMap eventData;
  105. eventData[P_ORIGINALELEMENT] = (void*)element;
  106. if (element)
  107. {
  108. // Return if already has focus
  109. if (focusElement_ == element)
  110. return;
  111. // Search for an element in the hierarchy that can alter focus. If none found, exit
  112. element = GetFocusableElement(element);
  113. if (!element)
  114. return;
  115. }
  116. // Remove focus from the old element
  117. if (focusElement_)
  118. {
  119. UIElement* oldFocusElement = focusElement_;
  120. focusElement_.Reset();
  121. oldFocusElement->OnDefocus();
  122. VariantMap focusEventData;
  123. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  124. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  125. }
  126. // Then set focus to the new
  127. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  128. {
  129. focusElement_ = element;
  130. element->OnFocus();
  131. VariantMap focusEventData;
  132. focusEventData[Focused::P_ELEMENT] = element;
  133. element->SendEvent(E_FOCUSED, focusEventData);
  134. }
  135. eventData[P_ELEMENT] = (void*)element;
  136. SendEvent(E_FOCUSCHANGED, eventData);
  137. }
  138. void UI::Clear()
  139. {
  140. if (!rootElement_)
  141. return;
  142. rootElement_->RemoveAllChildren();
  143. if (cursor_)
  144. rootElement_->AddChild(cursor_);
  145. }
  146. void UI::Update(float timeStep)
  147. {
  148. if (!rootElement_)
  149. return;
  150. PROFILE(UpdateUI);
  151. if (cursor_ && cursor_->IsVisible())
  152. {
  153. IntVector2 pos = cursor_->GetPosition();
  154. WeakPtr<UIElement> element(GetElementAt(pos));
  155. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  156. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  157. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  158. // Hover effect
  159. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  160. if (element)
  161. {
  162. if (!dragElement_ || dragElement_ == element || dragDropTest)
  163. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  164. }
  165. // Drag and drop test
  166. if (dragDropTest)
  167. {
  168. bool accept = element->OnDragDropTest(dragElement_);
  169. if (accept)
  170. {
  171. using namespace DragDropTest;
  172. VariantMap eventData;
  173. eventData[P_SOURCE] = (void*)dragElement_.Get();
  174. eventData[P_TARGET] = (void*)element.Get();
  175. eventData[P_ACCEPT] = accept;
  176. SendEvent(E_DRAGDROPTEST, eventData);
  177. accept = eventData[P_ACCEPT].GetBool();
  178. }
  179. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  180. }
  181. else if (dragSource)
  182. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  183. }
  184. Update(timeStep, rootElement_);
  185. }
  186. void UI::RenderUpdate()
  187. {
  188. if (!rootElement_ || !graphics_ || graphics_->IsDeviceLost())
  189. return;
  190. {
  191. PROFILE(GetUIBatches);
  192. // Get batches & quads from the UI elements
  193. batches_.Clear();
  194. quads_.Clear();
  195. const IntVector2& rootSize = rootElement_->GetSize();
  196. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  197. }
  198. {
  199. PROFILE(UpdateUIGeometry);
  200. // Update quad geometry into the vertex buffer
  201. unsigned numVertices = quads_.Size() * 6;
  202. if (numVertices)
  203. {
  204. if (vertexBuffer_->GetVertexCount() < numVertices)
  205. vertexBuffer_->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  206. unsigned vertexSize = vertexBuffer_->GetVertexSize();
  207. unsigned char* lockedData = (unsigned char*)vertexBuffer_->Lock(0, numVertices, LOCK_DISCARD);
  208. if (lockedData)
  209. {
  210. for (unsigned i = 0; i < batches_.Size(); ++i)
  211. batches_[i].UpdateGeometry(graphics_, lockedData + 6 * batches_[i].quadStart_ * vertexSize);
  212. vertexBuffer_->Unlock();
  213. }
  214. }
  215. }
  216. // If no drag, reset cursor shape for next frame
  217. if (cursor_ && !dragElement_)
  218. cursor_->SetShape(CS_NORMAL);
  219. }
  220. void UI::Render()
  221. {
  222. PROFILE(RenderUI);
  223. if (!graphics_)
  224. return;
  225. Vector2 scale(2.0f, -2.0f);
  226. Vector2 offset(-1.0f, 1.0f);
  227. Matrix4 projection(Matrix4::IDENTITY);
  228. projection.m00_ = scale.x_;
  229. projection.m03_ = offset.x_;
  230. projection.m11_ = scale.y_;
  231. projection.m13_ = offset.y_;
  232. projection.m22_ = 1.0f;
  233. projection.m23_ = 0.0f;
  234. projection.m33_ = 1.0f;
  235. graphics_->ClearParameterSources();
  236. graphics_->ResetRenderTargets();
  237. graphics_->SetAlphaTest(false);
  238. graphics_->SetCullMode(CULL_CCW);
  239. graphics_->SetDepthTest(CMP_ALWAYS);
  240. graphics_->SetDepthWrite(false);
  241. graphics_->SetFillMode(FILL_SOLID);
  242. graphics_->SetStencilTest(false);
  243. ShaderVariation* ps = 0;
  244. ShaderVariation* vs = 0;
  245. unsigned alphaFormat = Graphics::GetAlphaFormat();
  246. for (unsigned i = 0; i < batches_.Size(); ++i)
  247. {
  248. const UIBatch& batch = batches_[i];
  249. if (!batch.quadCount_)
  250. continue;
  251. if (!batch.texture_)
  252. {
  253. ps = noTexturePS_;
  254. vs = noTextureVS_;
  255. }
  256. else
  257. {
  258. // If texture contains only an alpha channel, use alpha shader (for fonts)
  259. vs = diffTextureVS_;
  260. if (batch.texture_->GetFormat() == alphaFormat)
  261. ps = alphaTexturePS_;
  262. else
  263. ps = diffTexturePS_;
  264. }
  265. graphics_->SetShaders(vs, ps);
  266. if (graphics_->NeedParameterUpdate(VSP_MODEL, this))
  267. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  268. if (graphics_->NeedParameterUpdate(VSP_VIEWPROJ, this))
  269. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  270. if (graphics_->NeedParameterUpdate(PSP_MATDIFFCOLOR, this))
  271. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  272. // Use alpha test if not alpha blending
  273. if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  274. graphics_->SetAlphaTest(true, CMP_GREATEREQUAL, 0.5f);
  275. else
  276. graphics_->SetAlphaTest(false);
  277. graphics_->SetBlendMode(batch.blendMode_);
  278. graphics_->SetScissorTest(true, batch.scissor_);
  279. graphics_->SetTexture(0, batch.texture_);
  280. graphics_->SetVertexBuffer(vertexBuffer_);
  281. graphics_->Draw(TRIANGLE_LIST, batch.quadStart_ * 6, batch.quadCount_ * 6);
  282. }
  283. }
  284. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  285. {
  286. PROFILE(LoadUILayout);
  287. SharedPtr<UIElement> root;
  288. if (!file)
  289. {
  290. LOGERROR("Null UI layout XML file");
  291. return root;
  292. }
  293. LOGDEBUG("Loading UI layout " + file->GetName());
  294. XMLElement rootElem = file->GetRoot("element");
  295. if (!rootElem)
  296. {
  297. LOGERROR("No root UI element in " + file->GetName());
  298. return root;
  299. }
  300. String type = rootElem.GetString("type");
  301. if (type.Empty())
  302. type = "UIElement";
  303. root = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  304. if (!root)
  305. {
  306. LOGERROR("Could not create UI element " + type);
  307. return root;
  308. }
  309. root->SetName(rootElem.GetString("name"));
  310. String styleName = rootElem.HasAttribute("style") ? rootElem.GetString("style") : rootElem.GetString("type");
  311. // First set the base style from the style file if exists, then apply UI layout overrides
  312. if (styleFile)
  313. root->SetStyle(styleFile, styleName);
  314. root->SetStyle(rootElem);
  315. // Load rest of the elements recursively
  316. LoadLayout(root, rootElem, styleFile);
  317. return root;
  318. }
  319. void UI::SetClipBoardText(const String& text)
  320. {
  321. clipBoard_ = text;
  322. }
  323. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  324. {
  325. if (!rootElement_)
  326. return 0;
  327. UIElement* result = 0;
  328. GetElementAt(result, rootElement_, position, activeOnly);
  329. return result;
  330. }
  331. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  332. {
  333. return GetElementAt(IntVector2(x, y), activeOnly);
  334. }
  335. UIElement* UI::GetFocusElement() const
  336. {
  337. return focusElement_;
  338. }
  339. UIElement* UI::GetFrontElement() const
  340. {
  341. if (!rootElement_)
  342. return 0;
  343. PODVector<UIElement*> rootChildren = rootElement_->GetChildren(false);
  344. int maxPriority = M_MIN_INT;
  345. UIElement* front = 0;
  346. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  347. {
  348. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  349. if (!rootChildren[i]->IsActive() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  350. continue;
  351. int priority = rootChildren[i]->GetPriority();
  352. if (priority > maxPriority)
  353. {
  354. maxPriority = priority;
  355. front = rootChildren[i];
  356. }
  357. }
  358. return front;
  359. }
  360. IntVector2 UI::GetCursorPosition()
  361. {
  362. if (!cursor_)
  363. return IntVector2::ZERO;
  364. else
  365. return cursor_->GetPosition();
  366. }
  367. void UI::Initialize()
  368. {
  369. Graphics* graphics = GetSubsystem<Graphics>();
  370. ResourceCache* cache = GetSubsystem<ResourceCache>();
  371. if (!graphics || !graphics->IsInitialized() || !cache)
  372. return;
  373. PROFILE(InitUI);
  374. graphics_ = graphics;
  375. cache_ = cache;
  376. rootElement_ = new UIElement(context_);
  377. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  378. #ifdef USE_OPENGL
  379. Shader* basicVS = cache->GetResource<Shader>("Shaders/GLSL/Basic.vert");
  380. Shader* basicPS = cache->GetResource<Shader>("Shaders/GLSL/Basic.frag");
  381. #else
  382. Shader* basicVS = cache->GetResource<Shader>("Shaders/SM2/Basic.vs2");
  383. Shader* basicPS = cache->GetResource<Shader>("Shaders/SM2/Basic.ps2");
  384. #endif
  385. if (basicVS && basicPS)
  386. {
  387. noTextureVS_ = basicVS->GetVariation("VCol");
  388. diffTextureVS_ = basicVS->GetVariation("DiffVCol");
  389. noTexturePS_ = basicPS->GetVariation("VCol");
  390. diffTexturePS_ = basicPS->GetVariation("DiffVCol");
  391. alphaTexturePS_ = basicPS->GetVariation("AlphaVCol");
  392. }
  393. vertexBuffer_ = new VertexBuffer(context_);
  394. LOGINFO("Initialized user interface");
  395. initialized_ = true;
  396. }
  397. void UI::Update(float timeStep, UIElement* element)
  398. {
  399. element->Update(timeStep);
  400. const PODVector<UIElement*> children = element->GetChildren();
  401. for (PODVector<UIElement*>::ConstIterator i = children.Begin(); i != children.End(); ++i)
  402. Update(timeStep, *i);
  403. }
  404. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  405. {
  406. // Set clipping scissor for child elements. No need to draw if zero size
  407. element->AdjustScissor(currentScissor);
  408. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  409. return;
  410. PODVector<UIElement*> children = element->GetChildren();
  411. if (children.Empty())
  412. return;
  413. Sort(children.Begin(), children.End(), CompareUIElements);
  414. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  415. // same renderstate
  416. PODVector<UIElement*>::ConstIterator i = children.Begin();
  417. if (element != rootElement_)
  418. {
  419. PODVector<UIElement*>::ConstIterator j = i;
  420. int currentPriority = children.Front()->GetPriority();
  421. while (i != children.End())
  422. {
  423. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  424. {
  425. if (IsVisible(*j, currentScissor))
  426. (*j)->GetBatches(batches_, quads_, currentScissor);
  427. ++j;
  428. }
  429. // Now recurse into the children
  430. while (i != j)
  431. {
  432. if (IsVisible(*i, currentScissor))
  433. GetBatches(*i, currentScissor);
  434. ++i;
  435. }
  436. if (i != children.End())
  437. currentPriority = (*i)->GetPriority();
  438. }
  439. }
  440. // On the root level draw each element and its children immediately after to avoid artifacts
  441. else
  442. {
  443. while (i != children.End())
  444. {
  445. if ((*i)->IsVisible())
  446. {
  447. if (IsVisible(*i, currentScissor))
  448. (*i)->GetBatches(batches_, quads_, currentScissor);
  449. GetBatches(*i, currentScissor);
  450. }
  451. ++i;
  452. }
  453. }
  454. }
  455. bool UI::IsVisible(UIElement* element, const IntRect& currentScissor)
  456. {
  457. // First check element's visibility
  458. if (!element->IsVisible())
  459. return false;
  460. // Then check element dimensions against the scissor rectangle
  461. const IntVector2& screenPos = element->GetScreenPosition();
  462. if (screenPos.x_ >= currentScissor.right_ || screenPos.x_ + element->GetWidth() <= currentScissor.left_ ||
  463. screenPos.y_ >= currentScissor.bottom_ || screenPos.y_ + element->GetHeight() <= currentScissor.top_)
  464. return false;
  465. else
  466. return true;
  467. }
  468. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  469. {
  470. if (!current)
  471. return;
  472. // Get children from lowest priority to highest
  473. PODVector<UIElement*> children = current->GetChildren(false);
  474. Sort(children.Begin(), children.End(), CompareUIElements);
  475. for (PODVector<UIElement*>::ConstIterator i = children.Begin(); i != children.End(); ++i)
  476. {
  477. UIElement* element = *i;
  478. if (element != cursor_.Get() && element->IsVisible())
  479. {
  480. if (element->IsInside(position, true))
  481. {
  482. // Store the current result, then recurse into its children. Because children
  483. // are sorted from lowest to highest priority, the topmost match should remain
  484. if (element->IsActive() || !activeOnly)
  485. result = element;
  486. }
  487. if (element->IsInsideCombined(position, true))
  488. GetElementAt(result, element, position, activeOnly);
  489. }
  490. }
  491. }
  492. UIElement* UI::GetFocusableElement(UIElement* element)
  493. {
  494. while (element)
  495. {
  496. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  497. break;
  498. element = element->GetParent();
  499. }
  500. return element;
  501. }
  502. void UI::LoadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  503. {
  504. XMLElement childElem = elem.GetChild("element");
  505. while (childElem)
  506. {
  507. // Create element
  508. String type = childElem.GetString("type");
  509. if (type.Empty())
  510. type = "UIElement";
  511. SharedPtr<UIElement> child = DynamicCast<UIElement>(context_->CreateObject(ShortStringHash(type)));
  512. if (!child)
  513. {
  514. LOGERROR("Could not create UI element " + type);
  515. childElem = childElem.GetNext("element");
  516. continue;
  517. }
  518. child->SetName(childElem.GetString("name"));
  519. // Add to the hierarchy
  520. current->AddChild(child);
  521. // First set the base style from the style file if exists, then apply UI layout overrides
  522. String styleName = childElem.HasAttribute("style") ? childElem.GetString("style") : childElem.GetString("type");
  523. if (styleFile)
  524. child->SetStyle(styleFile, styleName);
  525. child->SetStyle(childElem);
  526. // Load the children recursively
  527. LoadLayout(child, childElem, styleFile);
  528. childElem = childElem.GetNext("element");
  529. }
  530. }
  531. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  532. {
  533. using namespace ScreenMode;
  534. if (!initialized_)
  535. Initialize();
  536. else
  537. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  538. }
  539. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  540. {
  541. using namespace MouseMove;
  542. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  543. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  544. if (cursor_)
  545. {
  546. const IntVector2& rootSize = rootElement_->GetSize();
  547. // Move cursor only when visible
  548. if (cursor_->IsVisible())
  549. {
  550. IntVector2 pos = cursor_->GetPosition();
  551. pos.x_ += eventData[P_DX].GetInt();
  552. pos.y_ += eventData[P_DY].GetInt();
  553. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  554. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  555. cursor_->SetPosition(pos);
  556. }
  557. if (dragElement_ && mouseButtons_)
  558. {
  559. IntVector2 pos = cursor_->GetPosition();
  560. if (dragElement_->IsActive() && dragElement_->IsVisible())
  561. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  562. else
  563. {
  564. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  565. dragElement_.Reset();
  566. }
  567. }
  568. }
  569. }
  570. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  571. {
  572. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  573. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  574. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  575. if (cursor_ && cursor_->IsVisible())
  576. {
  577. IntVector2 pos = cursor_->GetPosition();
  578. WeakPtr<UIElement> element(GetElementAt(pos));
  579. if (element)
  580. {
  581. // Handle focusing & bringing to front
  582. if (button == MOUSEB_LEFT)
  583. {
  584. SetFocusElement(element);
  585. element->BringToFront();
  586. }
  587. // Handle click
  588. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  589. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  590. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  591. {
  592. dragElement_ = element;
  593. element->OnDragStart(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  594. }
  595. }
  596. else
  597. {
  598. // If clicked over no element, or a disabled element, lose focus
  599. SetFocusElement(0);
  600. }
  601. using namespace UIMouseClick;
  602. VariantMap eventData;
  603. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  604. eventData[UIMouseClick::P_X] = pos.x_;
  605. eventData[UIMouseClick::P_Y] = pos.y_;
  606. eventData[UIMouseClick::P_BUTTON] = button;
  607. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  608. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  609. SendEvent(E_UIMOUSECLICK, eventData);
  610. }
  611. }
  612. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  613. {
  614. using namespace MouseButtonUp;
  615. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  616. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  617. if (cursor_ && (cursor_->IsVisible())|| (dragElement_))
  618. {
  619. IntVector2 pos = cursor_->GetPosition();
  620. if (dragElement_ && !mouseButtons_)
  621. {
  622. if (dragElement_->IsActive() && dragElement_->IsVisible())
  623. {
  624. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  625. // Drag and drop finish
  626. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  627. if (dragSource)
  628. {
  629. WeakPtr<UIElement> target(GetElementAt(pos));
  630. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  631. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  632. if (dragDropFinish)
  633. {
  634. bool accept = target->OnDragDropFinish(dragElement_);
  635. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  636. if (accept && dragElement_ && target)
  637. {
  638. using namespace DragDropFinish;
  639. VariantMap eventData;
  640. eventData[P_SOURCE] = (void*)dragElement_.Get();
  641. eventData[P_TARGET] = (void*)target.Get();
  642. eventData[P_ACCEPT] = accept;
  643. SendEvent(E_DRAGDROPFINISH, eventData);
  644. }
  645. }
  646. }
  647. }
  648. dragElement_.Reset();
  649. }
  650. }
  651. }
  652. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  653. {
  654. using namespace MouseWheel;
  655. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  656. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  657. int delta = eventData[P_WHEEL].GetInt();
  658. UIElement* element = GetFocusElement();
  659. if (element)
  660. element->OnWheel(delta, mouseButtons_, qualifiers_);
  661. else
  662. {
  663. // If no element has actual focus, get the element at cursor
  664. if (cursor_)
  665. {
  666. IntVector2 pos = cursor_->GetPosition();
  667. UIElement* element = GetElementAt(pos);
  668. // If the element itself is not focusable, search for a focusable parent
  669. element = GetFocusableElement(element);
  670. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  671. element->OnWheel(delta, mouseButtons_, qualifiers_);
  672. }
  673. }
  674. }
  675. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  676. {
  677. using namespace KeyDown;
  678. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  679. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  680. int key = eventData[P_KEY].GetInt();
  681. UIElement* element = GetFocusElement();
  682. if (element)
  683. {
  684. // Switch focus between focusable elements in the same top level window
  685. if (key == KEY_TAB)
  686. {
  687. UIElement* topLevel = element->GetParent();
  688. while (topLevel && topLevel->GetParent() != rootElement_)
  689. topLevel = topLevel->GetParent();
  690. if (topLevel)
  691. {
  692. PODVector<UIElement*> children = topLevel->GetChildren(true);
  693. for (PODVector<UIElement*>::Iterator i = children.Begin(); i != children.End();)
  694. {
  695. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  696. i = children.Erase(i);
  697. else
  698. ++i;
  699. }
  700. for (unsigned i = 0; i < children.Size(); ++i)
  701. {
  702. if (children[i] == element)
  703. {
  704. UIElement* next = children[(i + 1) % children.Size()];
  705. SetFocusElement(next);
  706. return;
  707. }
  708. }
  709. }
  710. }
  711. // Defocus the element
  712. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  713. element->SetFocus(false);
  714. // If none of the special keys, pass the key to the focused element
  715. else
  716. element->OnKey(key, mouseButtons_, qualifiers_);
  717. }
  718. }
  719. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  720. {
  721. using namespace Char;
  722. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  723. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  724. UIElement* element = GetFocusElement();
  725. if (element)
  726. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  727. }
  728. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  729. {
  730. if (initialized_)
  731. {
  732. using namespace PostUpdate;
  733. Update(eventData[P_TIMESTEP].GetFloat());
  734. }
  735. }
  736. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  737. {
  738. if (initialized_)
  739. RenderUpdate();
  740. }
  741. void RegisterUILibrary(Context* context)
  742. {
  743. Font::RegisterObject(context);
  744. UIElement::RegisterObject(context);
  745. BorderImage::RegisterObject(context);
  746. Button::RegisterObject(context);
  747. CheckBox::RegisterObject(context);
  748. Cursor::RegisterObject(context);
  749. Text::RegisterObject(context);
  750. Window::RegisterObject(context);
  751. LineEdit::RegisterObject(context);
  752. Slider::RegisterObject(context);
  753. ScrollBar::RegisterObject(context);
  754. ScrollView::RegisterObject(context);
  755. ListView::RegisterObject(context);
  756. Menu::RegisterObject(context);
  757. DropDownList::RegisterObject(context);
  758. FileSelector::RegisterObject(context);
  759. }