Console.cpp 18 KB

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