Console.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Engine/Console.h"
  26. #include "../Engine/EngineEvents.h"
  27. #include "../Graphics/Graphics.h"
  28. #include "../Input/Input.h"
  29. #include "../IO/IOEvents.h"
  30. #include "../IO/Log.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../UI/DropDownList.h"
  33. #include "../UI/Font.h"
  34. #include "../UI/LineEdit.h"
  35. #include "../UI/ListView.h"
  36. #include "../UI/ScrollBar.h"
  37. #include "../UI/Text.h"
  38. #include "../UI/UI.h"
  39. #include "../UI/UIEvents.h"
  40. #include "../DebugNew.h"
  41. #include <algorithm>
  42. #include <vector>
  43. namespace Urho3D
  44. {
  45. static const int DEFAULT_CONSOLE_ROWS = 16;
  46. static const int DEFAULT_HISTORY_SIZE = 16;
  47. Console::Console(Context* context) :
  48. Object(context),
  49. autoVisibleOnError_(false),
  50. historyRows_(DEFAULT_HISTORY_SIZE),
  51. historyPosition_(0),
  52. historyOrAutoCompleteChange(false),
  53. printing_(false)
  54. {
  55. UI* ui = GetSubsystem<UI>();
  56. UIElement* uiRoot = ui->GetRoot();
  57. // By default prevent the automatic showing of the screen keyboard
  58. focusOnShow_ = !ui->GetUseScreenKeyboard();
  59. background_ = uiRoot->CreateChild<BorderImage>();
  60. background_->SetBringToBack(false);
  61. background_->SetClipChildren(true);
  62. background_->SetEnabled(true);
  63. background_->SetVisible(false); // Hide by default
  64. background_->SetPriority(200); // Show on top of the debug HUD
  65. background_->SetBringToBack(false);
  66. background_->SetLayout(LM_VERTICAL);
  67. rowContainer_ = background_->CreateChild<ListView>();
  68. rowContainer_->SetHighlightMode(HM_ALWAYS);
  69. rowContainer_->SetMultiselect(true);
  70. commandLine_ = background_->CreateChild<UIElement>();
  71. commandLine_->SetLayoutMode(LM_HORIZONTAL);
  72. commandLine_->SetLayoutSpacing(1);
  73. interpreters_ = commandLine_->CreateChild<DropDownList>();
  74. lineEdit_ = commandLine_->CreateChild<LineEdit>();
  75. lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
  76. closeButton_ = uiRoot->CreateChild<Button>();
  77. closeButton_->SetVisible(false);
  78. closeButton_->SetPriority(background_->GetPriority() + 1); // Show on top of console's background
  79. closeButton_->SetBringToBack(false);
  80. SetNumRows(DEFAULT_CONSOLE_ROWS);
  81. SubscribeToEvent(interpreters_, E_ITEMSELECTED, URHO3D_HANDLER(Console, HandleInterpreterSelected));
  82. SubscribeToEvent(lineEdit_, E_TEXTCHANGED, URHO3D_HANDLER(Console, HandleTextChanged));
  83. SubscribeToEvent(lineEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Console, HandleTextFinished));
  84. SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, URHO3D_HANDLER(Console, HandleLineEditKey));
  85. SubscribeToEvent(closeButton_, E_RELEASED, URHO3D_HANDLER(Console, HandleCloseButtonPressed));
  86. SubscribeToEvent(uiRoot, E_RESIZED, URHO3D_HANDLER(Console, HandleRootElementResized));
  87. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Console, HandleLogMessage));
  88. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Console, HandlePostUpdate));
  89. }
  90. Console::~Console()
  91. {
  92. background_->Remove();
  93. closeButton_->Remove();
  94. }
  95. void Console::SetDefaultStyle(XMLFile* style)
  96. {
  97. if (!style)
  98. return;
  99. background_->SetDefaultStyle(style);
  100. background_->SetStyle("ConsoleBackground");
  101. rowContainer_->SetStyleAuto();
  102. for (unsigned i = 0; i < rowContainer_->GetNumItems(); ++i)
  103. rowContainer_->GetItem(i)->SetStyle("ConsoleText");
  104. interpreters_->SetStyleAuto();
  105. for (unsigned i = 0; i < interpreters_->GetNumItems(); ++i)
  106. interpreters_->GetItem(i)->SetStyle("ConsoleText");
  107. lineEdit_->SetStyle("ConsoleLineEdit");
  108. closeButton_->SetDefaultStyle(style);
  109. closeButton_->SetStyle("CloseButton");
  110. UpdateElements();
  111. }
  112. void Console::SetVisible(bool enable)
  113. {
  114. Input* input = GetSubsystem<Input>();
  115. UI* ui = GetSubsystem<UI>();
  116. Cursor* cursor = ui->GetCursor();
  117. background_->SetVisible(enable);
  118. closeButton_->SetVisible(enable);
  119. if (enable)
  120. {
  121. // Check if we have receivers for E_CONSOLECOMMAND every time here in case the handler is being added later dynamically
  122. bool hasInterpreter = PopulateInterpreter();
  123. commandLine_->SetVisible(hasInterpreter);
  124. if (hasInterpreter && focusOnShow_)
  125. ui->SetFocusElement(lineEdit_);
  126. // Ensure the background has no empty space when shown without the lineedit
  127. background_->SetHeight(background_->GetMinHeight());
  128. if (!cursor)
  129. {
  130. // Show OS mouse
  131. input->SetMouseMode(MM_FREE, true);
  132. input->SetMouseVisible(true, true);
  133. }
  134. input->SetMouseGrabbed(false, true);
  135. }
  136. else
  137. {
  138. rowContainer_->SetFocus(false);
  139. interpreters_->SetFocus(false);
  140. lineEdit_->SetFocus(false);
  141. if (!cursor)
  142. {
  143. // Restore OS mouse visibility
  144. input->ResetMouseMode();
  145. input->ResetMouseVisible();
  146. }
  147. input->ResetMouseGrabbed();
  148. }
  149. }
  150. void Console::Toggle()
  151. {
  152. SetVisible(!IsVisible());
  153. }
  154. void Console::SetNumBufferedRows(unsigned rows)
  155. {
  156. if (rows < displayedRows_)
  157. return;
  158. rowContainer_->DisableLayoutUpdate();
  159. int delta = rowContainer_->GetNumItems() - rows;
  160. if (delta > 0)
  161. {
  162. // We have more, remove oldest rows first
  163. for (int i = 0; i < delta; ++i)
  164. rowContainer_->RemoveItem((unsigned)0);
  165. }
  166. else
  167. {
  168. // We have less, add more rows at the top
  169. for (int i = 0; i > delta; --i)
  170. {
  171. Text* text = new Text(context_);
  172. // If style is already set, apply here to ensure proper height of the console when
  173. // amount of rows is changed
  174. if (background_->GetDefaultStyle())
  175. text->SetStyle("ConsoleText");
  176. rowContainer_->InsertItem(0, text);
  177. }
  178. }
  179. rowContainer_->EnsureItemVisibility(rowContainer_->GetItem(rowContainer_->GetNumItems() - 1));
  180. rowContainer_->EnableLayoutUpdate();
  181. rowContainer_->UpdateLayout();
  182. UpdateElements();
  183. }
  184. void Console::SetNumRows(unsigned rows)
  185. {
  186. if (!rows)
  187. return;
  188. displayedRows_ = rows;
  189. if (GetNumBufferedRows() < rows)
  190. SetNumBufferedRows(rows);
  191. UpdateElements();
  192. }
  193. void Console::SetNumHistoryRows(unsigned rows)
  194. {
  195. historyRows_ = rows;
  196. if (history_.Size() > rows)
  197. history_.Resize(rows);
  198. if (historyPosition_ > rows)
  199. historyPosition_ = rows;
  200. }
  201. void Console::SetFocusOnShow(bool enable)
  202. {
  203. focusOnShow_ = enable;
  204. }
  205. void Console::UpdateElements()
  206. {
  207. int width = GetSubsystem<UI>()->GetRoot()->GetWidth();
  208. const IntRect& border = background_->GetLayoutBorder();
  209. const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
  210. rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
  211. rowContainer_->SetFixedHeight(
  212. displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
  213. (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
  214. background_->SetFixedWidth(width);
  215. background_->SetHeight(background_->GetMinHeight());
  216. }
  217. XMLFile* Console::GetDefaultStyle() const
  218. {
  219. return background_->GetDefaultStyle(false);
  220. }
  221. bool Console::IsVisible() const
  222. {
  223. return background_ && background_->IsVisible();
  224. }
  225. unsigned Console::GetNumBufferedRows() const
  226. {
  227. return rowContainer_->GetNumItems();
  228. }
  229. void Console::CopySelectedRows() const
  230. {
  231. rowContainer_->CopySelectedItemsToClipboard();
  232. }
  233. const String& Console::GetHistoryRow(unsigned index) const
  234. {
  235. return index < history_.Size() ? history_[index] : String::EMPTY;
  236. }
  237. void Console::AddAutoComplete(const String & option)
  238. {
  239. // sorted insertion
  240. Vector<String>::Iterator iter = UpperBound(autoComplete_.Begin(), autoComplete_.End(), option);
  241. if(!iter.ptr_)
  242. autoComplete_.Push(option);
  243. // make sure it isn't a duplicate
  244. else if(iter == autoComplete_.Begin() || *(iter-1) != option)
  245. autoComplete_.Insert(iter, option);
  246. }
  247. void Console::RemoveAutoComplete(const String & option)
  248. {
  249. // erase and keep ordered
  250. autoComplete_.Erase(LowerBound(autoComplete_.Begin(), autoComplete_.End(), option));
  251. }
  252. bool Console::PopulateInterpreter()
  253. {
  254. interpreters_->RemoveAllItems();
  255. EventReceiverGroup* group = context_->GetEventReceivers(E_CONSOLECOMMAND);
  256. if (!group || group->receivers_.Empty())
  257. return false;
  258. Vector<String> names;
  259. for (unsigned i = 0; i < group->receivers_.Size(); ++i)
  260. {
  261. Object* receiver = group->receivers_[i];
  262. if (receiver)
  263. names.Push(receiver->GetTypeName());
  264. }
  265. Sort(names.Begin(), names.End());
  266. unsigned selection = M_MAX_UNSIGNED;
  267. for (unsigned i = 0; i < names.Size(); ++i)
  268. {
  269. const String& name = names[i];
  270. if (name == commandInterpreter_)
  271. selection = i;
  272. Text* text = new Text(context_);
  273. text->SetStyle("ConsoleText");
  274. text->SetText(name);
  275. interpreters_->AddItem(text);
  276. }
  277. const IntRect& border = interpreters_->GetPopup()->GetLayoutBorder();
  278. interpreters_->SetMaxWidth(interpreters_->GetListView()->GetContentElement()->GetWidth() + border.left_ + border.right_);
  279. bool enabled = interpreters_->GetNumItems() > 1;
  280. interpreters_->SetEnabled(enabled);
  281. interpreters_->SetFocusMode(enabled ? FM_FOCUSABLE_DEFOCUSABLE : FM_NOTFOCUSABLE);
  282. if (selection == M_MAX_UNSIGNED)
  283. {
  284. selection = 0;
  285. commandInterpreter_ = names[selection];
  286. }
  287. interpreters_->SetSelection(selection);
  288. return true;
  289. }
  290. void Console::HandleInterpreterSelected(StringHash eventType, VariantMap& eventData)
  291. {
  292. commandInterpreter_ = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  293. lineEdit_->SetFocus(true);
  294. }
  295. void Console::HandleTextChanged(StringHash eventType, VariantMap & eventData)
  296. {
  297. // Save the original line
  298. // Make sure the change isn't caused by auto complete or history
  299. if (!historyOrAutoCompleteChange)
  300. autoCompleteLine_ = eventData[TextEntry::P_TEXT].GetString();
  301. historyOrAutoCompleteChange = false;
  302. }
  303. void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
  304. {
  305. using namespace TextFinished;
  306. String line = lineEdit_->GetText();
  307. if (!line.Empty())
  308. {
  309. // Send the command as an event for script subsystem
  310. using namespace ConsoleCommand;
  311. #if URHO3D_CXX11
  312. SendEvent(E_CONSOLECOMMAND, P_COMMAND, line, P_ID, static_cast<Text*>(interpreters_->GetSelectedItem())->GetText());
  313. #else
  314. VariantMap& newEventData = GetEventDataMap();
  315. newEventData[P_COMMAND] = line;
  316. newEventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  317. SendEvent(E_CONSOLECOMMAND, newEventData);
  318. #endif
  319. // Make sure the line isn't the same as the last one
  320. if (history_.Empty() || line != history_.Back())
  321. {
  322. // Store to history, then clear the lineedit
  323. history_.Push(line);
  324. if (history_.Size() > historyRows_)
  325. history_.Erase(history_.Begin());
  326. }
  327. historyPosition_ = history_.Size(); // reset
  328. autoCompleteIter_ = autoComplete_.End(); // reset
  329. currentRow_.Clear();
  330. lineEdit_->SetText(currentRow_);
  331. }
  332. }
  333. void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
  334. {
  335. if (!historyRows_)
  336. return;
  337. using namespace UnhandledKey;
  338. bool changed = false;
  339. switch (eventData[P_KEY].GetInt())
  340. {
  341. case KEY_UP:
  342. if (autoCompleteIter_ == autoComplete_.Begin())
  343. autoCompleteIter_ = autoComplete_.End();
  344. if (autoCompleteIter_ != autoComplete_.End())
  345. {
  346. Vector<String>::Iterator before_begin = --autoComplete_.Begin();
  347. // Search for auto completion that contains the contents of the line
  348. for (--autoCompleteIter_; autoCompleteIter_ != before_begin; --autoCompleteIter_)
  349. {
  350. if (autoCompleteIter_->StartsWith(autoCompleteLine_))
  351. {
  352. historyOrAutoCompleteChange = true;
  353. lineEdit_->SetText(*autoCompleteIter_);
  354. break;
  355. }
  356. }
  357. // If not found
  358. if (autoCompleteIter_ == before_begin)
  359. {
  360. // Reset the iterator
  361. autoCompleteIter_ = autoComplete_.End();
  362. // Reset history position
  363. historyPosition_ = history_.Size();
  364. }
  365. }
  366. // If no more auto complete options and history options left
  367. if (autoCompleteIter_ == autoComplete_.End() &&
  368. historyPosition_ > 0)
  369. {
  370. // If line text is not a history, save the current text value to be restored later
  371. if (historyPosition_ == history_.Size())
  372. currentRow_ = lineEdit_->GetText();
  373. // Use the previous option
  374. --historyPosition_;
  375. changed = true;
  376. }
  377. break;
  378. case KEY_DOWN:
  379. // If history options left
  380. if (historyPosition_ < history_.Size())
  381. {
  382. // Use the next option
  383. ++historyPosition_;
  384. changed = true;
  385. }
  386. else
  387. {
  388. // Loop over
  389. if (autoCompleteIter_ == autoComplete_.End() || !autoCompleteIter_.ptr_)
  390. autoCompleteIter_ = autoComplete_.Begin();
  391. else
  392. ++autoCompleteIter_; // If not starting over, skip checking the currently found completion
  393. Vector<String>::Iterator start_iter = autoCompleteIter_;
  394. // Search for auto completion that contains the contents of the line
  395. for (; autoCompleteIter_ != autoComplete_.End(); ++autoCompleteIter_)
  396. {
  397. if (autoCompleteIter_->StartsWith(autoCompleteLine_))
  398. {
  399. historyOrAutoCompleteChange = true;
  400. lineEdit_->SetText(*autoCompleteIter_);
  401. break;
  402. }
  403. }
  404. // Continue to search the complete range
  405. if (autoCompleteIter_ == autoComplete_.End())
  406. {
  407. for (autoCompleteIter_ = autoComplete_.Begin(); autoCompleteIter_ != start_iter; ++autoCompleteIter_)
  408. {
  409. if (autoCompleteIter_->StartsWith(autoCompleteLine_))
  410. {
  411. historyOrAutoCompleteChange = true;
  412. lineEdit_->SetText(*autoCompleteIter_);
  413. break;
  414. }
  415. }
  416. }
  417. }
  418. break;
  419. default: break;
  420. }
  421. if (changed)
  422. {
  423. historyOrAutoCompleteChange = true;
  424. // Set text to history option
  425. if (historyPosition_ < history_.Size())
  426. lineEdit_->SetText(history_[historyPosition_]);
  427. else // restore the original line value before it was set to history values
  428. {
  429. lineEdit_->SetText(currentRow_);
  430. // Set the auto complete iterator according to the currentRow
  431. for (autoCompleteIter_ = autoComplete_.Begin(); autoCompleteIter_ != autoComplete_.End(); ++autoCompleteIter_)
  432. if (autoCompleteIter_->StartsWith(currentRow_))
  433. break;
  434. }
  435. }
  436. }
  437. void Console::HandleCloseButtonPressed(StringHash eventType, VariantMap& eventData)
  438. {
  439. SetVisible(false);
  440. }
  441. void Console::HandleRootElementResized(StringHash eventType, VariantMap& eventData)
  442. {
  443. UpdateElements();
  444. }
  445. void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  446. {
  447. // If printing a log message causes more messages to be logged (error accessing font), disregard them
  448. if (printing_)
  449. return;
  450. using namespace LogMessage;
  451. int level = eventData[P_LEVEL].GetInt();
  452. // The message may be multi-line, so split to rows in that case
  453. Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
  454. for (unsigned i = 0; i < rows.Size(); ++i)
  455. pendingRows_.Push(MakePair(level, rows[i]));
  456. if (autoVisibleOnError_ && level == LOG_ERROR && !IsVisible())
  457. SetVisible(true);
  458. }
  459. void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  460. {
  461. // Ensure UI-elements are not detached
  462. if (!background_->GetParent())
  463. {
  464. UI* ui = GetSubsystem<UI>();
  465. UIElement* uiRoot = ui->GetRoot();
  466. uiRoot->AddChild(background_);
  467. uiRoot->AddChild(closeButton_);
  468. }
  469. if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
  470. return;
  471. printing_ = true;
  472. rowContainer_->DisableLayoutUpdate();
  473. Text* text = 0;
  474. for (unsigned i = 0; i < pendingRows_.Size(); ++i)
  475. {
  476. rowContainer_->RemoveItem((unsigned)0);
  477. text = new Text(context_);
  478. text->SetText(pendingRows_[i].second_);
  479. // Make error message highlight
  480. text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
  481. rowContainer_->AddItem(text);
  482. }
  483. pendingRows_.Clear();
  484. rowContainer_->EnsureItemVisibility(text);
  485. rowContainer_->EnableLayoutUpdate();
  486. rowContainer_->UpdateLayout();
  487. UpdateElements(); // May need to readjust the height due to scrollbar visibility changes
  488. printing_ = false;
  489. }
  490. }