UI.cpp 29 KB

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