LocalConsole.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using System.IO;
  35. using Nini.Config;
  36. using log4net;
  37. namespace OpenSim.Framework.Console
  38. {
  39. /// <summary>
  40. /// A console that uses cursor control and color
  41. /// </summary>
  42. public class LocalConsole : CommandConsole
  43. {
  44. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  45. private string m_historyPath;
  46. private bool m_historyEnable;
  47. private bool m_historytimestamps;
  48. // private readonly object m_syncRoot = new object();
  49. private const string LOGLEVEL_NONE = "(none)";
  50. // Used to extract categories for colourization.
  51. private Regex m_categoryRegex
  52. = new Regex(
  53. @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)", RegexOptions.Singleline | RegexOptions.Compiled);
  54. private int m_cursorYPosition = -1;
  55. private int m_cursorXPosition = 0;
  56. private StringBuilder m_commandLine = new StringBuilder();
  57. private bool m_echo = true;
  58. private List<string> m_history = new List<string>();
  59. private static readonly ConsoleColor[] Colors = {
  60. // the dark colors don't seem to be visible on some black background terminals like putty :(
  61. //ConsoleColor.DarkBlue,
  62. //ConsoleColor.DarkGreen,
  63. //ConsoleColor.DarkCyan,
  64. //ConsoleColor.DarkMagenta,
  65. //ConsoleColor.DarkYellow,
  66. ConsoleColor.Gray,
  67. //ConsoleColor.DarkGray,
  68. ConsoleColor.Blue,
  69. ConsoleColor.Green,
  70. ConsoleColor.Cyan,
  71. ConsoleColor.Magenta,
  72. ConsoleColor.Yellow
  73. };
  74. private static ConsoleColor DeriveColor(string input)
  75. {
  76. // it is important to do Abs, hash values can be negative
  77. return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
  78. }
  79. public LocalConsole(string defaultPrompt, IConfig startupConfig = null) : base(defaultPrompt)
  80. {
  81. if (startupConfig == null) return;
  82. m_historyEnable = startupConfig.GetBoolean("ConsoleHistoryFileEnabled", false);
  83. if (!m_historyEnable)
  84. {
  85. m_log.Info("[LOCAL CONSOLE]: Persistent command line history from file is Disabled");
  86. return;
  87. }
  88. string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt");
  89. int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100);
  90. m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile));
  91. m_historytimestamps = startupConfig.GetBoolean("ConsoleHistoryTimeStamp", false);
  92. m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1} {2} timestamps",
  93. m_historySize, m_historyPath, m_historytimestamps?"with":"without");
  94. if (File.Exists(m_historyPath))
  95. {
  96. List<string> originallines = new List<string>();
  97. using (StreamReader history_file = new StreamReader(m_historyPath))
  98. {
  99. string line;
  100. while ((line = history_file.ReadLine()) != null)
  101. {
  102. originallines.Add(line);
  103. if(line.StartsWith("["))
  104. {
  105. int indx = line.IndexOf("]:> ");
  106. if(indx > 0)
  107. {
  108. if(indx + 4 >= line.Length)
  109. line = String.Empty;
  110. else
  111. line = line.Substring(indx + 4);
  112. }
  113. }
  114. m_history.Add(line);
  115. }
  116. }
  117. if (m_history.Count > m_historySize)
  118. {
  119. while (m_history.Count > m_historySize)
  120. {
  121. m_history.RemoveAt(0);
  122. originallines.RemoveAt(0);
  123. }
  124. using (StreamWriter history_file = new StreamWriter(m_historyPath))
  125. {
  126. foreach (string line in originallines)
  127. {
  128. history_file.WriteLine(line);
  129. }
  130. }
  131. }
  132. m_log.InfoFormat("[LOCAL CONSOLE]: Read {0} lines of command line history from file {1}", m_history.Count, m_historyPath);
  133. }
  134. else
  135. {
  136. m_log.InfoFormat("[LOCAL CONSOLE]: Creating new empty command line history file {0}", m_historyPath);
  137. File.Create(m_historyPath).Dispose();
  138. }
  139. System.Console.TreatControlCAsInput = true;
  140. }
  141. private void AddToHistory(string text)
  142. {
  143. while (m_history.Count >= 100)
  144. m_history.RemoveAt(0);
  145. m_history.Add(text);
  146. if (m_historyEnable)
  147. {
  148. if (m_historytimestamps)
  149. text = String.Format("[{0} {1}]:> {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), text);
  150. File.AppendAllText(m_historyPath, text + Environment.NewLine);
  151. }
  152. }
  153. /// <summary>
  154. /// Set the cursor row.
  155. /// </summary>
  156. ///
  157. /// <param name="top">
  158. /// Row to set. If this is below 0, then the row is set to 0. If it is equal to the buffer height or greater
  159. /// then it is set to one less than the height.
  160. /// </param>
  161. /// <returns>
  162. /// The new cursor row.
  163. /// </returns>
  164. private int SetCursorTop(int top)
  165. {
  166. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  167. // to set a cursor row position with a currently invalid column, mono will throw an exception.
  168. // Therefore, we need to make sure that the column position is valid first.
  169. int left = System.Console.CursorLeft;
  170. if (left < 0)
  171. {
  172. System.Console.CursorLeft = 0;
  173. }
  174. else
  175. {
  176. int bufferWidth = System.Console.BufferWidth;
  177. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  178. if (bufferWidth > 0 && left >= bufferWidth)
  179. System.Console.CursorLeft = bufferWidth - 1;
  180. }
  181. if (top < 0)
  182. {
  183. top = 0;
  184. }
  185. else
  186. {
  187. int bufferHeight = System.Console.BufferHeight;
  188. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  189. if (bufferHeight > 0 && top >= bufferHeight)
  190. top = bufferHeight - 1;
  191. }
  192. System.Console.CursorTop = top;
  193. return top;
  194. }
  195. /// <summary>
  196. /// Set the cursor column.
  197. /// </summary>
  198. ///
  199. /// <param name="left">
  200. /// Column to set. If this is below 0, then the column is set to 0. If it is equal to the buffer width or greater
  201. /// then it is set to one less than the width.
  202. /// </param>
  203. /// <returns>
  204. /// The new cursor column.
  205. /// </returns>
  206. private int SetCursorLeft(int left)
  207. {
  208. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  209. // to set a cursor column position with a currently invalid row, mono will throw an exception.
  210. // Therefore, we need to make sure that the row position is valid first.
  211. int top = System.Console.CursorTop;
  212. if (top < 0)
  213. {
  214. System.Console.CursorTop = 0;
  215. }
  216. else
  217. {
  218. int bufferHeight = System.Console.BufferHeight;
  219. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  220. if (bufferHeight > 0 && top >= bufferHeight)
  221. System.Console.CursorTop = bufferHeight - 1;
  222. }
  223. if (left < 0)
  224. {
  225. left = 0;
  226. }
  227. else
  228. {
  229. int bufferWidth = System.Console.BufferWidth;
  230. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  231. if (bufferWidth > 0 && left >= bufferWidth)
  232. left = bufferWidth - 1;
  233. }
  234. System.Console.CursorLeft = left;
  235. return left;
  236. }
  237. private void Show()
  238. {
  239. lock (m_commandLine)
  240. {
  241. if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
  242. return;
  243. int xc = prompt.Length + m_cursorXPosition;
  244. int new_x = xc % System.Console.BufferWidth;
  245. int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
  246. int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
  247. if (end_y >= System.Console.BufferHeight) // wrap
  248. {
  249. m_cursorYPosition--;
  250. new_y--;
  251. SetCursorLeft(0);
  252. SetCursorTop(System.Console.BufferHeight - 1);
  253. System.Console.WriteLine(" ");
  254. }
  255. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  256. SetCursorLeft(0);
  257. if (m_echo)
  258. System.Console.Write("{0}{1}", prompt, m_commandLine);
  259. else
  260. System.Console.Write("{0}", prompt);
  261. SetCursorTop(new_y);
  262. SetCursorLeft(new_x);
  263. }
  264. }
  265. public override void LockOutput()
  266. {
  267. Monitor.Enter(m_commandLine);
  268. try
  269. {
  270. if (m_cursorYPosition != -1)
  271. {
  272. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  273. System.Console.CursorLeft = 0;
  274. int count = m_commandLine.Length + prompt.Length;
  275. while (count-- > 0)
  276. System.Console.Write(" ");
  277. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  278. SetCursorLeft(0);
  279. }
  280. }
  281. catch (Exception)
  282. {
  283. }
  284. }
  285. public override void UnlockOutput()
  286. {
  287. if (m_cursorYPosition != -1)
  288. {
  289. m_cursorYPosition = System.Console.CursorTop;
  290. Show();
  291. }
  292. Monitor.Exit(m_commandLine);
  293. }
  294. private void WriteColorText(ConsoleColor color, string sender)
  295. {
  296. try
  297. {
  298. lock (this)
  299. {
  300. try
  301. {
  302. System.Console.ForegroundColor = color;
  303. System.Console.Write(sender);
  304. System.Console.ResetColor();
  305. }
  306. catch (ArgumentNullException)
  307. {
  308. // Some older systems dont support coloured text.
  309. System.Console.WriteLine(sender);
  310. }
  311. }
  312. }
  313. catch (ObjectDisposedException)
  314. {
  315. }
  316. }
  317. private void WriteLocalText(string text, string level)
  318. {
  319. string outText = text;
  320. if (level != null)
  321. {
  322. MatchCollection matches = m_categoryRegex.Matches(text);
  323. if (matches.Count == 1)
  324. {
  325. outText = matches[0].Groups["End"].Value;
  326. System.Console.Write(matches[0].Groups["Front"].Value);
  327. System.Console.Write("[");
  328. WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
  329. matches[0].Groups["Category"].Value);
  330. System.Console.Write("]:");
  331. }
  332. else
  333. {
  334. outText = outText.Trim();
  335. }
  336. }
  337. if (level == "error")
  338. WriteColorText(ConsoleColor.Red, outText);
  339. else if (level == "warn")
  340. WriteColorText(ConsoleColor.Yellow, outText);
  341. else
  342. System.Console.Write(outText);
  343. System.Console.WriteLine();
  344. }
  345. public override void Output(string format)
  346. {
  347. Output(format, null);
  348. }
  349. public override void Output(string format, params object[] components)
  350. {
  351. string level = null;
  352. if(components != null && components.Length > 0)
  353. {
  354. if(components[0] == null || components[0] is ConsoleLevel)
  355. {
  356. if(components[0] is ConsoleLevel)
  357. level = ((ConsoleLevel)components[0]).ToString();
  358. if (components.Length > 1)
  359. {
  360. object[] tmp = new object[components.Length - 1];
  361. Array.Copy(components, 1, tmp, 0, components.Length - 1);
  362. components = tmp;
  363. }
  364. else
  365. components = null;
  366. }
  367. }
  368. string text;
  369. if (components == null || components.Length == 0)
  370. text = format;
  371. else
  372. text = String.Format(format, components);
  373. FireOnOutput(text);
  374. lock (m_commandLine)
  375. {
  376. if (m_cursorYPosition == -1)
  377. {
  378. WriteLocalText(text, level);
  379. return;
  380. }
  381. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  382. SetCursorLeft(0);
  383. int count = m_commandLine.Length + prompt.Length;
  384. while (count-- > 0)
  385. System.Console.Write(" ");
  386. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  387. SetCursorLeft(0);
  388. WriteLocalText(text, level);
  389. m_cursorYPosition = System.Console.CursorTop;
  390. Show();
  391. }
  392. }
  393. private bool ContextHelp()
  394. {
  395. string[] words = Parser.Parse(m_commandLine.ToString());
  396. bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
  397. // Allow ? through while typing a URI
  398. //
  399. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  400. return false;
  401. string[] opts = Commands.FindNextOption(words, trailingSpace);
  402. if (opts[0].StartsWith("Command help:"))
  403. Output(opts[0]);
  404. else
  405. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  406. return true;
  407. }
  408. public override string ReadLine(string p, bool isCommand, bool e)
  409. {
  410. m_cursorXPosition = 0;
  411. prompt = p;
  412. m_echo = e;
  413. int historyLine = m_history.Count;
  414. SetCursorLeft(0); // Needed for mono
  415. System.Console.Write(" "); // Needed for mono
  416. lock (m_commandLine)
  417. {
  418. m_cursorYPosition = System.Console.CursorTop;
  419. m_commandLine.Remove(0, m_commandLine.Length);
  420. }
  421. while (true)
  422. {
  423. Show();
  424. ConsoleKeyInfo key = System.Console.ReadKey(true);
  425. if((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKey.C)
  426. {
  427. System.Console.Write(Environment.NewLine);
  428. LocalCancelKeyPressed();
  429. return string.Empty;
  430. }
  431. char enteredChar = key.KeyChar;
  432. if (!Char.IsControl(enteredChar))
  433. {
  434. if (m_cursorXPosition >= 318)
  435. continue;
  436. if (enteredChar == '?' && isCommand)
  437. {
  438. if (ContextHelp())
  439. continue;
  440. }
  441. m_commandLine.Insert(m_cursorXPosition, enteredChar);
  442. m_cursorXPosition++;
  443. }
  444. else
  445. {
  446. switch (key.Key)
  447. {
  448. case ConsoleKey.Backspace:
  449. if (m_cursorXPosition == 0)
  450. break;
  451. m_commandLine.Remove(m_cursorXPosition-1, 1);
  452. m_cursorXPosition--;
  453. SetCursorLeft(0);
  454. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  455. if (m_echo)
  456. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  457. else
  458. System.Console.Write("{0}", prompt);
  459. break;
  460. case ConsoleKey.Delete:
  461. if (m_cursorXPosition == m_commandLine.Length)
  462. break;
  463. m_commandLine.Remove(m_cursorXPosition, 1);
  464. SetCursorLeft(0);
  465. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  466. if (m_echo)
  467. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  468. else
  469. System.Console.Write("{0}", prompt);
  470. break;
  471. case ConsoleKey.End:
  472. m_cursorXPosition = m_commandLine.Length;
  473. break;
  474. case ConsoleKey.Home:
  475. m_cursorXPosition = 0;
  476. break;
  477. case ConsoleKey.UpArrow:
  478. if (historyLine < 1)
  479. break;
  480. historyLine--;
  481. LockOutput();
  482. m_commandLine.Remove(0, m_commandLine.Length);
  483. m_commandLine.Append(m_history[historyLine]);
  484. m_cursorXPosition = m_commandLine.Length;
  485. UnlockOutput();
  486. break;
  487. case ConsoleKey.DownArrow:
  488. if (historyLine >= m_history.Count)
  489. break;
  490. historyLine++;
  491. LockOutput();
  492. if (historyLine == m_history.Count)
  493. {
  494. m_commandLine.Remove(0, m_commandLine.Length);
  495. }
  496. else
  497. {
  498. m_commandLine.Remove(0, m_commandLine.Length);
  499. m_commandLine.Append(m_history[historyLine]);
  500. }
  501. m_cursorXPosition = m_commandLine.Length;
  502. UnlockOutput();
  503. break;
  504. case ConsoleKey.LeftArrow:
  505. if (m_cursorXPosition > 0)
  506. m_cursorXPosition--;
  507. break;
  508. case ConsoleKey.RightArrow:
  509. if (m_cursorXPosition < m_commandLine.Length)
  510. m_cursorXPosition++;
  511. break;
  512. case ConsoleKey.Enter:
  513. SetCursorLeft(0);
  514. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  515. System.Console.WriteLine();
  516. //Show();
  517. lock (m_commandLine)
  518. {
  519. m_cursorYPosition = -1;
  520. }
  521. string commandLine = m_commandLine.ToString();
  522. if (isCommand)
  523. {
  524. string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
  525. if (cmd.Length != 0)
  526. {
  527. int index;
  528. for (index=0 ; index < cmd.Length ; index++)
  529. {
  530. if (cmd[index].Contains(" "))
  531. cmd[index] = "\"" + cmd[index] + "\"";
  532. }
  533. AddToHistory(String.Join(" ", cmd));
  534. return String.Empty;
  535. }
  536. }
  537. // If we're not echoing to screen (e.g. a password) then we probably don't want it in history
  538. if (m_echo && commandLine != "")
  539. AddToHistory(commandLine);
  540. return commandLine;
  541. default:
  542. break;
  543. }
  544. }
  545. }
  546. }
  547. }
  548. }