LocalConsole.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 log4net;
  35. namespace OpenSim.Framework.Console
  36. {
  37. /// <summary>
  38. /// A console that uses cursor control and color
  39. /// </summary>
  40. public class LocalConsole : CommandConsole
  41. {
  42. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. // private readonly object m_syncRoot = new object();
  44. private const string LOGLEVEL_NONE = "(none)";
  45. private int m_cursorYPosition = -1;
  46. private int m_cursorXPosition = 0;
  47. private StringBuilder m_commandLine = new StringBuilder();
  48. private bool m_echo = true;
  49. private List<string> m_history = new List<string>();
  50. private static readonly ConsoleColor[] Colors = {
  51. // the dark colors don't seem to be visible on some black background terminals like putty :(
  52. //ConsoleColor.DarkBlue,
  53. //ConsoleColor.DarkGreen,
  54. //ConsoleColor.DarkCyan,
  55. //ConsoleColor.DarkMagenta,
  56. //ConsoleColor.DarkYellow,
  57. ConsoleColor.Gray,
  58. //ConsoleColor.DarkGray,
  59. ConsoleColor.Blue,
  60. ConsoleColor.Green,
  61. ConsoleColor.Cyan,
  62. ConsoleColor.Magenta,
  63. ConsoleColor.Yellow
  64. };
  65. private static ConsoleColor DeriveColor(string input)
  66. {
  67. // it is important to do Abs, hash values can be negative
  68. return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
  69. }
  70. public LocalConsole(string defaultPrompt) : base(defaultPrompt)
  71. {
  72. }
  73. private void AddToHistory(string text)
  74. {
  75. while (m_history.Count >= 100)
  76. m_history.RemoveAt(0);
  77. m_history.Add(text);
  78. }
  79. /// <summary>
  80. /// Set the cursor row.
  81. /// </summary>
  82. ///
  83. /// <param name="top">
  84. /// 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
  85. /// then it is set to one less than the height.
  86. /// </param>
  87. /// <returns>
  88. /// The new cursor row.
  89. /// </returns>
  90. private int SetCursorTop(int top)
  91. {
  92. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  93. // to set a cursor row position with a currently invalid column, mono will throw an exception.
  94. // Therefore, we need to make sure that the column position is valid first.
  95. int left = System.Console.CursorLeft;
  96. if (left < 0)
  97. {
  98. System.Console.CursorLeft = 0;
  99. }
  100. else
  101. {
  102. int bufferWidth = System.Console.BufferWidth;
  103. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  104. if (bufferWidth > 0 && left >= bufferWidth)
  105. System.Console.CursorLeft = bufferWidth - 1;
  106. }
  107. if (top < 0)
  108. {
  109. top = 0;
  110. }
  111. else
  112. {
  113. int bufferHeight = System.Console.BufferHeight;
  114. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  115. if (bufferHeight > 0 && top >= bufferHeight)
  116. top = bufferHeight - 1;
  117. }
  118. System.Console.CursorTop = top;
  119. return top;
  120. }
  121. /// <summary>
  122. /// Set the cursor column.
  123. /// </summary>
  124. ///
  125. /// <param name="left">
  126. /// 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
  127. /// then it is set to one less than the width.
  128. /// </param>
  129. /// <returns>
  130. /// The new cursor column.
  131. /// </returns>
  132. private int SetCursorLeft(int left)
  133. {
  134. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  135. // to set a cursor column position with a currently invalid row, mono will throw an exception.
  136. // Therefore, we need to make sure that the row position is valid first.
  137. int top = System.Console.CursorTop;
  138. if (top < 0)
  139. {
  140. System.Console.CursorTop = 0;
  141. }
  142. else
  143. {
  144. int bufferHeight = System.Console.BufferHeight;
  145. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  146. if (bufferHeight > 0 && top >= bufferHeight)
  147. System.Console.CursorTop = bufferHeight - 1;
  148. }
  149. if (left < 0)
  150. {
  151. left = 0;
  152. }
  153. else
  154. {
  155. int bufferWidth = System.Console.BufferWidth;
  156. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  157. if (bufferWidth > 0 && left >= bufferWidth)
  158. left = bufferWidth - 1;
  159. }
  160. System.Console.CursorLeft = left;
  161. return left;
  162. }
  163. private void Show()
  164. {
  165. lock (m_commandLine)
  166. {
  167. if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
  168. return;
  169. int xc = prompt.Length + m_cursorXPosition;
  170. int new_x = xc % System.Console.BufferWidth;
  171. int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
  172. int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
  173. if (end_y >= System.Console.BufferHeight) // wrap
  174. {
  175. m_cursorYPosition--;
  176. new_y--;
  177. SetCursorLeft(0);
  178. SetCursorTop(System.Console.BufferHeight - 1);
  179. System.Console.WriteLine(" ");
  180. }
  181. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  182. SetCursorLeft(0);
  183. if (m_echo)
  184. System.Console.Write("{0}{1}", prompt, m_commandLine);
  185. else
  186. System.Console.Write("{0}", prompt);
  187. SetCursorTop(new_y);
  188. SetCursorLeft(new_x);
  189. }
  190. }
  191. public override void LockOutput()
  192. {
  193. Monitor.Enter(m_commandLine);
  194. try
  195. {
  196. if (m_cursorYPosition != -1)
  197. {
  198. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  199. System.Console.CursorLeft = 0;
  200. int count = m_commandLine.Length + prompt.Length;
  201. while (count-- > 0)
  202. System.Console.Write(" ");
  203. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  204. SetCursorLeft(0);
  205. }
  206. }
  207. catch (Exception)
  208. {
  209. }
  210. }
  211. public override void UnlockOutput()
  212. {
  213. if (m_cursorYPosition != -1)
  214. {
  215. m_cursorYPosition = System.Console.CursorTop;
  216. Show();
  217. }
  218. Monitor.Exit(m_commandLine);
  219. }
  220. private void WriteColorText(ConsoleColor color, string sender)
  221. {
  222. try
  223. {
  224. lock (this)
  225. {
  226. try
  227. {
  228. System.Console.ForegroundColor = color;
  229. System.Console.Write(sender);
  230. System.Console.ResetColor();
  231. }
  232. catch (ArgumentNullException)
  233. {
  234. // Some older systems dont support coloured text.
  235. System.Console.WriteLine(sender);
  236. }
  237. }
  238. }
  239. catch (ObjectDisposedException)
  240. {
  241. }
  242. }
  243. private void WriteLocalText(string text, string level)
  244. {
  245. string outText = text;
  246. if (level != LOGLEVEL_NONE)
  247. {
  248. string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
  249. Regex RE = new Regex(regex, RegexOptions.Multiline);
  250. MatchCollection matches = RE.Matches(text);
  251. if (matches.Count == 1)
  252. {
  253. outText = matches[0].Groups["End"].Value;
  254. System.Console.Write(matches[0].Groups["Front"].Value);
  255. System.Console.Write("[");
  256. WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
  257. matches[0].Groups["Category"].Value);
  258. System.Console.Write("]:");
  259. }
  260. }
  261. if (level == "error")
  262. WriteColorText(ConsoleColor.Red, outText);
  263. else if (level == "warn")
  264. WriteColorText(ConsoleColor.Yellow, outText);
  265. else
  266. System.Console.Write(outText);
  267. System.Console.WriteLine();
  268. }
  269. public override void Output(string text)
  270. {
  271. Output(text, LOGLEVEL_NONE);
  272. }
  273. public override void Output(string text, string level)
  274. {
  275. lock (m_commandLine)
  276. {
  277. if (m_cursorYPosition == -1)
  278. {
  279. WriteLocalText(text, level);
  280. return;
  281. }
  282. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  283. SetCursorLeft(0);
  284. int count = m_commandLine.Length + prompt.Length;
  285. while (count-- > 0)
  286. System.Console.Write(" ");
  287. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  288. SetCursorLeft(0);
  289. WriteLocalText(text, level);
  290. m_cursorYPosition = System.Console.CursorTop;
  291. Show();
  292. }
  293. }
  294. private bool ContextHelp()
  295. {
  296. string[] words = Parser.Parse(m_commandLine.ToString());
  297. bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
  298. // Allow ? through while typing a URI
  299. //
  300. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  301. return false;
  302. string[] opts = Commands.FindNextOption(words, trailingSpace);
  303. if (opts[0].StartsWith("Command help:"))
  304. Output(opts[0]);
  305. else
  306. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  307. return true;
  308. }
  309. public override string ReadLine(string p, bool isCommand, bool e)
  310. {
  311. m_cursorXPosition = 0;
  312. prompt = p;
  313. m_echo = e;
  314. int historyLine = m_history.Count;
  315. SetCursorLeft(0); // Needed for mono
  316. System.Console.Write(" "); // Needed for mono
  317. lock (m_commandLine)
  318. {
  319. m_cursorYPosition = System.Console.CursorTop;
  320. m_commandLine.Remove(0, m_commandLine.Length);
  321. }
  322. while (true)
  323. {
  324. Show();
  325. ConsoleKeyInfo key = System.Console.ReadKey(true);
  326. char enteredChar = key.KeyChar;
  327. if (!Char.IsControl(enteredChar))
  328. {
  329. if (m_cursorXPosition >= 318)
  330. continue;
  331. if (enteredChar == '?' && isCommand)
  332. {
  333. if (ContextHelp())
  334. continue;
  335. }
  336. m_commandLine.Insert(m_cursorXPosition, enteredChar);
  337. m_cursorXPosition++;
  338. }
  339. else
  340. {
  341. switch (key.Key)
  342. {
  343. case ConsoleKey.Backspace:
  344. if (m_cursorXPosition == 0)
  345. break;
  346. m_commandLine.Remove(m_cursorXPosition-1, 1);
  347. m_cursorXPosition--;
  348. SetCursorLeft(0);
  349. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  350. if (m_echo)
  351. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  352. else
  353. System.Console.Write("{0}", prompt);
  354. break;
  355. case ConsoleKey.End:
  356. m_cursorXPosition = m_commandLine.Length;
  357. break;
  358. case ConsoleKey.Home:
  359. m_cursorXPosition = 0;
  360. break;
  361. case ConsoleKey.UpArrow:
  362. if (historyLine < 1)
  363. break;
  364. historyLine--;
  365. LockOutput();
  366. m_commandLine.Remove(0, m_commandLine.Length);
  367. m_commandLine.Append(m_history[historyLine]);
  368. m_cursorXPosition = m_commandLine.Length;
  369. UnlockOutput();
  370. break;
  371. case ConsoleKey.DownArrow:
  372. if (historyLine >= m_history.Count)
  373. break;
  374. historyLine++;
  375. LockOutput();
  376. if (historyLine == m_history.Count)
  377. {
  378. m_commandLine.Remove(0, m_commandLine.Length);
  379. }
  380. else
  381. {
  382. m_commandLine.Remove(0, m_commandLine.Length);
  383. m_commandLine.Append(m_history[historyLine]);
  384. }
  385. m_cursorXPosition = m_commandLine.Length;
  386. UnlockOutput();
  387. break;
  388. case ConsoleKey.LeftArrow:
  389. if (m_cursorXPosition > 0)
  390. m_cursorXPosition--;
  391. break;
  392. case ConsoleKey.RightArrow:
  393. if (m_cursorXPosition < m_commandLine.Length)
  394. m_cursorXPosition++;
  395. break;
  396. case ConsoleKey.Enter:
  397. SetCursorLeft(0);
  398. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  399. System.Console.WriteLine();
  400. //Show();
  401. lock (m_commandLine)
  402. {
  403. m_cursorYPosition = -1;
  404. }
  405. string commandLine = m_commandLine.ToString();
  406. if (isCommand)
  407. {
  408. string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
  409. if (cmd.Length != 0)
  410. {
  411. int index;
  412. for (index=0 ; index < cmd.Length ; index++)
  413. {
  414. if (cmd[index].Contains(" "))
  415. cmd[index] = "\"" + cmd[index] + "\"";
  416. }
  417. AddToHistory(String.Join(" ", cmd));
  418. return String.Empty;
  419. }
  420. }
  421. // If we're not echoing to screen (e.g. a password) then we probably don't want it in history
  422. if (m_echo && commandLine != "")
  423. AddToHistory(commandLine);
  424. return commandLine;
  425. default:
  426. break;
  427. }
  428. }
  429. }
  430. }
  431. }
  432. }