UI.cpp 26 KB

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