Console.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //
  2. // Copyright (c) 2008-2015 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 "../Graphics/GraphicsEvents.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. Console::Console(Context* context) :
  47. Object(context),
  48. autoVisibleOnError_(false),
  49. historyRows_(DEFAULT_HISTORY_SIZE),
  50. historyPosition_(0),
  51. printing_(false)
  52. {
  53. UI* ui = GetSubsystem<UI>();
  54. UIElement* uiRoot = ui->GetRoot();
  55. // By default prevent the automatic showing of the screen keyboard
  56. focusOnShow_ = !ui->GetUseScreenKeyboard();
  57. background_ = uiRoot->CreateChild<BorderImage>();
  58. background_->SetBringToBack(false);
  59. background_->SetClipChildren(true);
  60. background_->SetEnabled(true);
  61. background_->SetVisible(false); // Hide by default
  62. background_->SetPriority(200); // Show on top of the debug HUD
  63. background_->SetBringToBack(false);
  64. background_->SetLayout(LM_VERTICAL);
  65. rowContainer_ = background_->CreateChild<ListView>();
  66. rowContainer_->SetHighlightMode(HM_ALWAYS);
  67. rowContainer_->SetMultiselect(true);
  68. commandLine_ = background_->CreateChild<UIElement>();
  69. commandLine_->SetLayoutMode(LM_HORIZONTAL);
  70. commandLine_->SetLayoutSpacing(1);
  71. interpreters_ = commandLine_->CreateChild<DropDownList>();
  72. lineEdit_ = commandLine_->CreateChild<LineEdit>();
  73. lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
  74. closeButton_ = uiRoot->CreateChild<Button>();
  75. closeButton_->SetVisible(false);
  76. closeButton_->SetPriority(background_->GetPriority() + 1); // Show on top of console's background
  77. closeButton_->SetBringToBack(false);
  78. SetNumRows(DEFAULT_CONSOLE_ROWS);
  79. SubscribeToEvent(interpreters_, E_ITEMSELECTED, URHO3D_HANDLER(Console, HandleInterpreterSelected));
  80. SubscribeToEvent(lineEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Console, HandleTextFinished));
  81. SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, URHO3D_HANDLER(Console, HandleLineEditKey));
  82. SubscribeToEvent(closeButton_, E_RELEASED, URHO3D_HANDLER(Console, HandleCloseButtonPressed));
  83. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(Console, HandleScreenMode));
  84. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Console, HandleLogMessage));
  85. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Console, HandlePostUpdate));
  86. }
  87. Console::~Console()
  88. {
  89. background_->Remove();
  90. closeButton_->Remove();
  91. }
  92. void Console::SetDefaultStyle(XMLFile* style)
  93. {
  94. if (!style)
  95. return;
  96. background_->SetDefaultStyle(style);
  97. background_->SetStyle("ConsoleBackground");
  98. rowContainer_->SetStyleAuto();
  99. for (unsigned i = 0; i < rowContainer_->GetNumItems(); ++i)
  100. rowContainer_->GetItem(i)->SetStyle("ConsoleText");
  101. interpreters_->SetStyleAuto();
  102. for (unsigned i = 0; i < interpreters_->GetNumItems(); ++i)
  103. interpreters_->GetItem(i)->SetStyle("ConsoleText");
  104. lineEdit_->SetStyle("ConsoleLineEdit");
  105. closeButton_->SetDefaultStyle(style);
  106. closeButton_->SetStyle("CloseButton");
  107. UpdateElements();
  108. }
  109. void Console::SetVisible(bool enable)
  110. {
  111. Input* input = GetSubsystem<Input>();
  112. background_->SetVisible(enable);
  113. closeButton_->SetVisible(enable);
  114. if (enable)
  115. {
  116. // Check if we have receivers for E_CONSOLECOMMAND every time here in case the handler is being added later dynamically
  117. bool hasInterpreter = PopulateInterpreter();
  118. commandLine_->SetVisible(hasInterpreter);
  119. if (hasInterpreter && focusOnShow_)
  120. GetSubsystem<UI>()->SetFocusElement(lineEdit_);
  121. // Ensure the background has no empty space when shown without the lineedit
  122. background_->SetHeight(background_->GetMinHeight());
  123. // Show OS mouse
  124. input->SetMouseVisible(true, true);
  125. }
  126. else
  127. {
  128. rowContainer_->SetFocus(false);
  129. interpreters_->SetFocus(false);
  130. lineEdit_->SetFocus(false);
  131. // Restore OS mouse visibility
  132. input->ResetMouseVisible();
  133. }
  134. }
  135. void Console::Toggle()
  136. {
  137. SetVisible(!IsVisible());
  138. }
  139. void Console::SetNumBufferedRows(unsigned rows)
  140. {
  141. if (rows < displayedRows_)
  142. return;
  143. rowContainer_->DisableLayoutUpdate();
  144. int delta = rowContainer_->GetNumItems() - rows;
  145. if (delta > 0)
  146. {
  147. // We have more, remove oldest rows first
  148. for (int i = 0; i < delta; ++i)
  149. rowContainer_->RemoveItem((unsigned)0);
  150. }
  151. else
  152. {
  153. // We have less, add more rows at the top
  154. for (int i = 0; i > delta; --i)
  155. {
  156. Text* text = new Text(context_);
  157. // If style is already set, apply here to ensure proper height of the console when
  158. // amount of rows is changed
  159. if (background_->GetDefaultStyle())
  160. text->SetStyle("ConsoleText");
  161. rowContainer_->InsertItem(0, text);
  162. }
  163. }
  164. rowContainer_->EnsureItemVisibility(rowContainer_->GetItem(rowContainer_->GetNumItems() - 1));
  165. rowContainer_->EnableLayoutUpdate();
  166. rowContainer_->UpdateLayout();
  167. UpdateElements();
  168. }
  169. void Console::SetNumRows(unsigned rows)
  170. {
  171. if (!rows)
  172. return;
  173. displayedRows_ = rows;
  174. if (GetNumBufferedRows() < rows)
  175. SetNumBufferedRows(rows);
  176. UpdateElements();
  177. }
  178. void Console::SetNumHistoryRows(unsigned rows)
  179. {
  180. historyRows_ = rows;
  181. if (history_.Size() > rows)
  182. history_.Resize(rows);
  183. if (historyPosition_ > rows)
  184. historyPosition_ = rows;
  185. }
  186. void Console::SetFocusOnShow(bool enable)
  187. {
  188. focusOnShow_ = enable;
  189. }
  190. void Console::UpdateElements()
  191. {
  192. int width = GetSubsystem<Graphics>()->GetWidth();
  193. const IntRect& border = background_->GetLayoutBorder();
  194. const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
  195. rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
  196. rowContainer_->SetFixedHeight(
  197. displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
  198. (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
  199. background_->SetFixedWidth(width);
  200. background_->SetHeight(background_->GetMinHeight());
  201. }
  202. XMLFile* Console::GetDefaultStyle() const
  203. {
  204. return background_->GetDefaultStyle(false);
  205. }
  206. bool Console::IsVisible() const
  207. {
  208. return background_ && background_->IsVisible();
  209. }
  210. unsigned Console::GetNumBufferedRows() const
  211. {
  212. return rowContainer_->GetNumItems();
  213. }
  214. void Console::CopySelectedRows() const
  215. {
  216. rowContainer_->CopySelectedItemsToClipboard();
  217. }
  218. const String& Console::GetHistoryRow(unsigned index) const
  219. {
  220. return index < history_.Size() ? history_[index] : String::EMPTY;
  221. }
  222. bool Console::PopulateInterpreter()
  223. {
  224. interpreters_->RemoveAllItems();
  225. HashSet<Object*>* receivers = context_->GetEventReceivers(E_CONSOLECOMMAND);
  226. if (!receivers || receivers->Empty())
  227. return false;
  228. Vector<String> names;
  229. for (HashSet<Object*>::ConstIterator iter = receivers->Begin(); iter != receivers->End(); ++iter)
  230. names.Push((*iter)->GetTypeName());
  231. Sort(names.Begin(), names.End());
  232. unsigned selection = M_MAX_UNSIGNED;
  233. for (unsigned i = 0; i < names.Size(); ++i)
  234. {
  235. const String& name = names[i];
  236. if (name == commandInterpreter_)
  237. selection = i;
  238. Text* text = new Text(context_);
  239. text->SetStyle("ConsoleText");
  240. text->SetText(name);
  241. interpreters_->AddItem(text);
  242. }
  243. const IntRect& border = interpreters_->GetPopup()->GetLayoutBorder();
  244. interpreters_->SetMaxWidth(interpreters_->GetListView()->GetContentElement()->GetWidth() + border.left_ + border.right_);
  245. bool enabled = interpreters_->GetNumItems() > 1;
  246. interpreters_->SetEnabled(enabled);
  247. interpreters_->SetFocusMode(enabled ? FM_FOCUSABLE_DEFOCUSABLE : FM_NOTFOCUSABLE);
  248. if (selection == M_MAX_UNSIGNED)
  249. {
  250. selection = 0;
  251. commandInterpreter_ = names[selection];
  252. }
  253. interpreters_->SetSelection(selection);
  254. return true;
  255. }
  256. void Console::HandleInterpreterSelected(StringHash eventType, VariantMap& eventData)
  257. {
  258. commandInterpreter_ = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  259. lineEdit_->SetFocus(true);
  260. }
  261. void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
  262. {
  263. using namespace TextFinished;
  264. String line = lineEdit_->GetText();
  265. if (!line.Empty())
  266. {
  267. // Send the command as an event for script subsystem
  268. using namespace ConsoleCommand;
  269. VariantMap& newEventData = GetEventDataMap();
  270. newEventData[P_COMMAND] = line;
  271. newEventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  272. SendEvent(E_CONSOLECOMMAND, newEventData);
  273. // Store to history, then clear the lineedit
  274. history_.Push(line);
  275. if (history_.Size() > historyRows_)
  276. history_.Erase(history_.Begin());
  277. historyPosition_ = history_.Size();
  278. currentRow_.Clear();
  279. lineEdit_->SetText(currentRow_);
  280. }
  281. }
  282. void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
  283. {
  284. if (!historyRows_)
  285. return;
  286. using namespace UnhandledKey;
  287. bool changed = false;
  288. switch (eventData[P_KEY].GetInt())
  289. {
  290. case KEY_UP:
  291. if (historyPosition_ > 0)
  292. {
  293. if (historyPosition_ == history_.Size())
  294. currentRow_ = lineEdit_->GetText();
  295. --historyPosition_;
  296. changed = true;
  297. }
  298. break;
  299. case KEY_DOWN:
  300. if (historyPosition_ < history_.Size())
  301. {
  302. ++historyPosition_;
  303. changed = true;
  304. }
  305. break;
  306. default: break;
  307. }
  308. if (changed)
  309. {
  310. if (historyPosition_ < history_.Size())
  311. lineEdit_->SetText(history_[historyPosition_]);
  312. else
  313. lineEdit_->SetText(currentRow_);
  314. }
  315. }
  316. void Console::HandleCloseButtonPressed(StringHash eventType, VariantMap& eventData)
  317. {
  318. SetVisible(false);
  319. }
  320. void Console::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  321. {
  322. UpdateElements();
  323. }
  324. void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  325. {
  326. // If printing a log message causes more messages to be logged (error accessing font), disregard them
  327. if (printing_)
  328. return;
  329. using namespace LogMessage;
  330. int level = eventData[P_LEVEL].GetInt();
  331. // The message may be multi-line, so split to rows in that case
  332. Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
  333. for (unsigned i = 0; i < rows.Size(); ++i)
  334. pendingRows_.Push(MakePair(level, rows[i]));
  335. if (autoVisibleOnError_ && level == LOG_ERROR && !IsVisible())
  336. SetVisible(true);
  337. }
  338. void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  339. {
  340. // Ensure UI-elements are not detached
  341. if (!background_->GetParent())
  342. {
  343. UI* ui = GetSubsystem<UI>();
  344. UIElement* uiRoot = ui->GetRoot();
  345. uiRoot->AddChild(background_);
  346. uiRoot->AddChild(closeButton_);
  347. }
  348. if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
  349. return;
  350. printing_ = true;
  351. rowContainer_->DisableLayoutUpdate();
  352. Text* text = 0;
  353. for (unsigned i = 0; i < pendingRows_.Size(); ++i)
  354. {
  355. rowContainer_->RemoveItem((unsigned)0);
  356. text = new Text(context_);
  357. text->SetText(pendingRows_[i].second_);
  358. // Make error message highlight
  359. text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
  360. rowContainer_->AddItem(text);
  361. }
  362. pendingRows_.Clear();
  363. rowContainer_->EnsureItemVisibility(text);
  364. rowContainer_->EnableLayoutUpdate();
  365. rowContainer_->UpdateLayout();
  366. UpdateElements(); // May need to readjust the height due to scrollbar visibility changes
  367. printing_ = false;
  368. }
  369. }