LocalConsole.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 = new Regex(
  52. @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)", RegexOptions.Singleline | RegexOptions.Compiled);
  53. private int m_cursorYPosition = -1;
  54. private int m_cursorXPosition = 0;
  55. private StringBuilder m_commandLine = new StringBuilder();
  56. private bool m_echo = true;
  57. private List<string> m_history = new List<string>();
  58. private static readonly ConsoleColor[] Colors = {
  59. // the dark colors don't seem to be visible on some black background terminals like putty :(
  60. //ConsoleColor.DarkBlue,
  61. //ConsoleColor.DarkGreen,
  62. //ConsoleColor.DarkCyan,
  63. //ConsoleColor.DarkMagenta,
  64. //ConsoleColor.DarkYellow,
  65. ConsoleColor.Gray,
  66. //ConsoleColor.DarkGray,
  67. ConsoleColor.Blue,
  68. ConsoleColor.Green,
  69. ConsoleColor.Cyan,
  70. ConsoleColor.Magenta,
  71. ConsoleColor.Yellow
  72. };
  73. private static ConsoleColor DeriveColor(string input)
  74. {
  75. // it is important to do Abs, hash values can be negative
  76. return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
  77. }
  78. public LocalConsole(string defaultPrompt, IConfig startupConfig = null) : base(defaultPrompt)
  79. {
  80. if (startupConfig == null) return;
  81. m_historyEnable = startupConfig.GetBoolean("ConsoleHistoryFileEnabled", false);
  82. if (!m_historyEnable)
  83. {
  84. m_log.Info("[LOCAL CONSOLE]: Persistent command line history from file is Disabled");
  85. return;
  86. }
  87. string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt");
  88. int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100);
  89. m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile));
  90. m_historytimestamps = startupConfig.GetBoolean("ConsoleHistoryTimeStamp", false);
  91. m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1} {2} timestamps",
  92. m_historySize, m_historyPath, m_historytimestamps?"with":"without");
  93. if (File.Exists(m_historyPath))
  94. {
  95. List<string> originallines = new List<string>();
  96. using (StreamReader history_file = new StreamReader(m_historyPath))
  97. {
  98. string line;
  99. while ((line = history_file.ReadLine()) != null)
  100. {
  101. originallines.Add(line);
  102. if(line.StartsWith("["))
  103. {
  104. int indx = line.IndexOf("]:> ");
  105. if(indx > 0)
  106. {
  107. if(indx + 4 >= line.Length)
  108. line = String.Empty;
  109. else
  110. line = line.Substring(indx + 4);
  111. }
  112. }
  113. m_history.Add(line);
  114. }
  115. }
  116. if (m_history.Count > m_historySize)
  117. {
  118. while (m_history.Count > m_historySize)
  119. {
  120. m_history.RemoveAt(0);
  121. originallines.RemoveAt(0);
  122. }
  123. using (StreamWriter history_file = new StreamWriter(m_historyPath))
  124. {
  125. foreach (string line in originallines)
  126. {
  127. history_file.WriteLine(line);
  128. }
  129. }
  130. }
  131. m_log.InfoFormat("[LOCAL CONSOLE]: Read {0} lines of command line history from file {1}", m_history.Count, m_historyPath);
  132. }
  133. else
  134. {
  135. m_log.InfoFormat("[LOCAL CONSOLE]: Creating new empty command line history file {0}", m_historyPath);
  136. File.Create(m_historyPath).Dispose();
  137. }
  138. System.Console.TreatControlCAsInput = true;
  139. }
  140. private void AddToHistory(string text)
  141. {
  142. while (m_history.Count >= 100)
  143. m_history.RemoveAt(0);
  144. m_history.Add(text);
  145. if (m_historyEnable)
  146. {
  147. if (m_historytimestamps)
  148. text = String.Format("[{0} {1}]:> {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), text);
  149. File.AppendAllText(m_historyPath, text + Environment.NewLine);
  150. }
  151. }
  152. /// <summary>
  153. /// Set the cursor row.
  154. /// </summary>
  155. ///
  156. /// <param name="top">
  157. /// 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
  158. /// then it is set to one less than the height.
  159. /// </param>
  160. /// <returns>
  161. /// The new cursor row.
  162. /// </returns>
  163. private int SetCursorTop(int top)
  164. {
  165. // mono seems to fail unless we do check both left and top ranges, even current
  166. int left = System.Console.CursorLeft;
  167. if (left <= 0)
  168. left = 0;
  169. else
  170. {
  171. int bufferWidth = System.Console.BufferWidth;
  172. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  173. if (bufferWidth > 0 && left >= bufferWidth)
  174. left = bufferWidth - 1;
  175. }
  176. if (top <= 0)
  177. top = 0;
  178. else
  179. {
  180. int bufferHeight = System.Console.BufferHeight;
  181. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  182. if (bufferHeight > 0 && top >= bufferHeight)
  183. top = bufferHeight - 1;
  184. }
  185. System.Console.SetCursorPosition(left, top);
  186. return top;
  187. }
  188. /// <summary>
  189. /// Set the cursor column.
  190. /// </summary>
  191. ///
  192. /// <param name="left">
  193. /// 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
  194. /// then it is set to one less than the width.
  195. /// </param>
  196. /// <returns>
  197. /// The new cursor column.
  198. /// </returns>
  199. private int SetCursorLeft(int left)
  200. {
  201. int top = System.Console.CursorTop;
  202. if (top <= 0)
  203. top = 0;
  204. else
  205. {
  206. int bufferHeight = System.Console.BufferHeight;
  207. if (bufferHeight > 0 && top >= bufferHeight)
  208. top = bufferHeight - 1;
  209. }
  210. if (left <= 0)
  211. left = 0;
  212. else
  213. {
  214. int bufferWidth = System.Console.BufferWidth;
  215. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  216. if (bufferWidth > 0 && left >= bufferWidth)
  217. left = bufferWidth - 1;
  218. }
  219. System.Console.SetCursorPosition(left, top);
  220. return left;
  221. }
  222. private void SetCursorTopLeft(int top, int left)
  223. {
  224. if (top <= 0)
  225. top = 0;
  226. else
  227. {
  228. int bufferHeight = System.Console.BufferHeight;
  229. if (bufferHeight > 0 && top >= bufferHeight)
  230. top = bufferHeight - 1;
  231. }
  232. if (left <= 0)
  233. left = 0;
  234. else
  235. {
  236. int bufferWidth = System.Console.BufferWidth;
  237. if (bufferWidth > 0 && left >= bufferWidth)
  238. left = bufferWidth - 1;
  239. }
  240. System.Console.SetCursorPosition(left, top);
  241. }
  242. private int SetCursorZeroLeft(int top)
  243. {
  244. if (top <= 0)
  245. {
  246. System.Console.SetCursorPosition(0, 0);
  247. return 0;
  248. }
  249. int bufferHeight = System.Console.BufferHeight;
  250. if (bufferHeight > 0 && top >= bufferHeight)
  251. {
  252. top = bufferHeight - 1;
  253. }
  254. System.Console.SetCursorPosition(0, top);
  255. return top;
  256. }
  257. private void Show()
  258. {
  259. lock (m_commandLine)
  260. {
  261. if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
  262. return;
  263. int xc = prompt.Length + m_cursorXPosition;
  264. int new_x = xc % System.Console.BufferWidth;
  265. int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
  266. int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
  267. if (end_y >= System.Console.BufferHeight) // wrap
  268. {
  269. m_cursorYPosition--;
  270. new_y--;
  271. SetCursorZeroLeft(System.Console.BufferHeight - 1);
  272. System.Console.WriteLine(" ");
  273. }
  274. m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
  275. if (m_echo)
  276. System.Console.Write("{0}{1}", prompt, m_commandLine);
  277. else
  278. System.Console.Write("{0}", prompt);
  279. SetCursorTopLeft(new_y, new_x);
  280. }
  281. }
  282. public override void LockOutput()
  283. {
  284. Monitor.Enter(m_commandLine);
  285. try
  286. {
  287. if (m_cursorYPosition != -1)
  288. {
  289. m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
  290. int count = m_commandLine.Length + prompt.Length;
  291. char[] spaces = new char[count];
  292. for(int i = 0; i < spaces.Length; i++)
  293. spaces[i] = ' ';
  294. System.Console.Write(spaces);
  295. m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
  296. }
  297. }
  298. catch (Exception)
  299. {
  300. }
  301. }
  302. public override void UnlockOutput()
  303. {
  304. if (m_cursorYPosition != -1)
  305. {
  306. m_cursorYPosition = System.Console.CursorTop;
  307. Show();
  308. }
  309. Monitor.Exit(m_commandLine);
  310. }
  311. private void WriteColorText(ConsoleColor color, string sender)
  312. {
  313. try
  314. {
  315. lock (this)
  316. {
  317. try
  318. {
  319. System.Console.ForegroundColor = color;
  320. System.Console.Write(sender);
  321. System.Console.ResetColor();
  322. }
  323. catch (ArgumentNullException)
  324. {
  325. // Some older systems dont support coloured text.
  326. System.Console.WriteLine(sender);
  327. }
  328. }
  329. }
  330. catch (ObjectDisposedException)
  331. {
  332. }
  333. }
  334. private void WriteLocalText(string text, string level)
  335. {
  336. string outText = text;
  337. if (level != null)
  338. {
  339. MatchCollection matches = m_categoryRegex.Matches(text);
  340. if (matches.Count == 1)
  341. {
  342. outText = matches[0].Groups["End"].Value;
  343. System.Console.Write(matches[0].Groups["Front"].Value);
  344. System.Console.Write("[");
  345. WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
  346. matches[0].Groups["Category"].Value);
  347. System.Console.Write("]:");
  348. }
  349. else
  350. {
  351. outText = outText.Trim();
  352. }
  353. }
  354. if (level == "error")
  355. WriteColorText(ConsoleColor.Red, outText);
  356. else if (level == "warn")
  357. WriteColorText(ConsoleColor.Yellow, outText);
  358. else
  359. System.Console.Write(outText);
  360. }
  361. public override void Output(string format)
  362. {
  363. Output(format, null);
  364. }
  365. public override void Output(string format, params object[] components)
  366. {
  367. string level = null;
  368. if(components != null && components.Length > 0)
  369. {
  370. ConsoleLevel cl = components[0] as ConsoleLevel;
  371. if (cl != null)
  372. {
  373. level = cl.ToString();
  374. if (components.Length > 1)
  375. {
  376. object[] tmp = new object[components.Length - 1];
  377. Array.Copy(components, 1, tmp, 0, components.Length - 1);
  378. components = tmp;
  379. }
  380. else
  381. components = null;
  382. }
  383. }
  384. string text = (components == null || components.Length == 0) ? format : String.Format(format, components);
  385. FireOnOutput(text);
  386. lock (m_commandLine)
  387. {
  388. if (m_cursorYPosition == -1)
  389. {
  390. WriteLocalText(text, level);
  391. System.Console.WriteLine();
  392. return;
  393. }
  394. m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
  395. int count = m_commandLine.Length + prompt.Length - text.Length;
  396. WriteLocalText(text, level);
  397. for (int i = 0; i < count; ++i)
  398. System.Console.Write(" ");
  399. System.Console.WriteLine();
  400. m_cursorYPosition = System.Console.CursorTop;
  401. Show();
  402. }
  403. }
  404. private bool ContextHelp()
  405. {
  406. string[] words = Parser.Parse(m_commandLine.ToString());
  407. bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
  408. // Allow ? through while typing a URI
  409. //
  410. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  411. return false;
  412. string[] opts = Commands.FindNextOption(words, trailingSpace);
  413. if (opts[0].StartsWith("Command help:"))
  414. Output(opts[0]);
  415. else
  416. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  417. return true;
  418. }
  419. public override string ReadLine(string p, bool isCommand, bool e)
  420. {
  421. m_cursorXPosition = 0;
  422. prompt = p;
  423. m_echo = e;
  424. int historyLine = m_history.Count;
  425. lock (m_commandLine)
  426. {
  427. SetCursorLeft(0); // Needed for mono
  428. m_cursorYPosition = System.Console.CursorTop;
  429. // mono is silly
  430. if (m_cursorYPosition >= System.Console.BufferHeight)
  431. m_cursorYPosition = System.Console.BufferHeight - 1;
  432. m_commandLine.Clear();
  433. }
  434. while (true)
  435. {
  436. Show();
  437. //Reduce collisions with internal read terminal information like cursor position on linux
  438. //while(System.Console.KeyAvailable == false)
  439. // Thread.Sleep(100);
  440. ConsoleKeyInfo key = System.Console.ReadKey(true);
  441. if((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKey.C)
  442. {
  443. System.Console.Write(Environment.NewLine);
  444. LocalCancelKeyPressed();
  445. return string.Empty;
  446. }
  447. char enteredChar = key.KeyChar;
  448. if (!Char.IsControl(enteredChar))
  449. {
  450. if (m_cursorXPosition >= 318)
  451. continue;
  452. if (enteredChar == '?' && isCommand)
  453. {
  454. if (ContextHelp())
  455. continue;
  456. }
  457. m_commandLine.Insert(m_cursorXPosition, enteredChar);
  458. m_cursorXPosition++;
  459. }
  460. else
  461. {
  462. switch (key.Key)
  463. {
  464. case ConsoleKey.Backspace:
  465. if (m_cursorXPosition == 0)
  466. break;
  467. m_commandLine.Remove(m_cursorXPosition-1, 1);
  468. m_cursorXPosition--;
  469. m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
  470. if (m_echo)
  471. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  472. else
  473. System.Console.Write("{0}", prompt);
  474. break;
  475. case ConsoleKey.Delete:
  476. if (m_cursorXPosition == m_commandLine.Length)
  477. break;
  478. m_commandLine.Remove(m_cursorXPosition, 1);
  479. m_cursorYPosition = SetCursorZeroLeft(m_cursorYPosition);
  480. if (m_echo)
  481. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  482. else
  483. System.Console.Write("{0}", prompt);
  484. break;
  485. case ConsoleKey.End:
  486. m_cursorXPosition = m_commandLine.Length;
  487. break;
  488. case ConsoleKey.Home:
  489. m_cursorXPosition = 0;
  490. break;
  491. case ConsoleKey.UpArrow:
  492. if (historyLine < 1)
  493. break;
  494. historyLine--;
  495. LockOutput();
  496. m_commandLine.Remove(0, m_commandLine.Length);
  497. m_commandLine.Append(m_history[historyLine]);
  498. m_cursorXPosition = m_commandLine.Length;
  499. UnlockOutput();
  500. break;
  501. case ConsoleKey.DownArrow:
  502. if (historyLine >= m_history.Count)
  503. break;
  504. historyLine++;
  505. LockOutput();
  506. m_commandLine.Remove(0, m_commandLine.Length);
  507. if (historyLine != m_history.Count)
  508. m_commandLine.Append(m_history[historyLine]);
  509. m_cursorXPosition = m_commandLine.Length;
  510. UnlockOutput();
  511. break;
  512. case ConsoleKey.LeftArrow:
  513. if (m_cursorXPosition > 0)
  514. m_cursorXPosition--;
  515. break;
  516. case ConsoleKey.RightArrow:
  517. if (m_cursorXPosition < m_commandLine.Length)
  518. m_cursorXPosition++;
  519. break;
  520. case ConsoleKey.Enter:
  521. SetCursorLeft(0);
  522. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  523. System.Console.WriteLine();
  524. //Show();
  525. lock (m_commandLine)
  526. {
  527. m_cursorYPosition = -1;
  528. }
  529. string commandLine = m_commandLine.ToString();
  530. if (isCommand)
  531. {
  532. string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
  533. if (cmd.Length != 0)
  534. {
  535. int index;
  536. for (index=0 ; index < cmd.Length ; index++)
  537. {
  538. if (cmd[index].Contains(" "))
  539. cmd[index] = "\"" + cmd[index] + "\"";
  540. }
  541. AddToHistory(String.Join(" ", cmd));
  542. return String.Empty;
  543. }
  544. }
  545. // If we're not echoing to screen (e.g. a password) then we probably don't want it in history
  546. if (m_echo && commandLine != "")
  547. AddToHistory(commandLine);
  548. return commandLine;
  549. default:
  550. break;
  551. }
  552. }
  553. }
  554. }
  555. }
  556. }