Console.cpp 14 KB

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