UI.cpp 27 KB

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