Console.cpp 19 KB

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