LocalConsole.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 int y = -1;
  45. private int cp = 0;
  46. private int h = 1;
  47. private StringBuilder cmdline = new StringBuilder();
  48. private bool echo = true;
  49. private List<string> 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 (history.Count >= 100)
  76. history.RemoveAt(0);
  77. 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 bw = System.Console.BufferWidth;
  103. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  104. if (bw > 0 && left >= bw)
  105. System.Console.CursorLeft = bw - 1;
  106. }
  107. if (top < 0)
  108. {
  109. top = 0;
  110. }
  111. else
  112. {
  113. int bh = System.Console.BufferHeight;
  114. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  115. if (bh > 0 && top >= bh)
  116. top = bh - 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 bh = System.Console.BufferHeight;
  145. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  146. if (bh > 0 && top >= bh)
  147. System.Console.CursorTop = bh - 1;
  148. }
  149. if (left < 0)
  150. {
  151. left = 0;
  152. }
  153. else
  154. {
  155. int bw = System.Console.BufferWidth;
  156. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  157. if (bw > 0 && left >= bw)
  158. left = bw - 1;
  159. }
  160. System.Console.CursorLeft = left;
  161. return left;
  162. }
  163. private void Show()
  164. {
  165. lock (cmdline)
  166. {
  167. if (y == -1 || System.Console.BufferWidth == 0)
  168. return;
  169. int xc = prompt.Length + cp;
  170. int new_x = xc % System.Console.BufferWidth;
  171. int new_y = y + xc / System.Console.BufferWidth;
  172. int end_y = y + (cmdline.Length + prompt.Length) / System.Console.BufferWidth;
  173. if (end_y / System.Console.BufferWidth >= h)
  174. h++;
  175. if (end_y >= System.Console.BufferHeight) // wrap
  176. {
  177. y--;
  178. new_y--;
  179. SetCursorLeft(0);
  180. SetCursorTop(System.Console.BufferHeight - 1);
  181. System.Console.WriteLine(" ");
  182. }
  183. y = SetCursorTop(y);
  184. SetCursorLeft(0);
  185. if (echo)
  186. System.Console.Write("{0}{1}", prompt, cmdline);
  187. else
  188. System.Console.Write("{0}", prompt);
  189. SetCursorTop(new_y);
  190. SetCursorLeft(new_x);
  191. }
  192. }
  193. public override void LockOutput()
  194. {
  195. Monitor.Enter(cmdline);
  196. try
  197. {
  198. if (y != -1)
  199. {
  200. y = SetCursorTop(y);
  201. System.Console.CursorLeft = 0;
  202. int count = cmdline.Length + prompt.Length;
  203. while (count-- > 0)
  204. System.Console.Write(" ");
  205. y = SetCursorTop(y);
  206. SetCursorLeft(0);
  207. }
  208. }
  209. catch (Exception)
  210. {
  211. }
  212. }
  213. public override void UnlockOutput()
  214. {
  215. if (y != -1)
  216. {
  217. y = System.Console.CursorTop;
  218. Show();
  219. }
  220. Monitor.Exit(cmdline);
  221. }
  222. private void WriteColorText(ConsoleColor color, string sender)
  223. {
  224. try
  225. {
  226. lock (this)
  227. {
  228. try
  229. {
  230. System.Console.ForegroundColor = color;
  231. System.Console.Write(sender);
  232. System.Console.ResetColor();
  233. }
  234. catch (ArgumentNullException)
  235. {
  236. // Some older systems dont support coloured text.
  237. System.Console.WriteLine(sender);
  238. }
  239. }
  240. }
  241. catch (ObjectDisposedException)
  242. {
  243. }
  244. }
  245. private void WriteLocalText(string text, string level)
  246. {
  247. string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
  248. Regex RE = new Regex(regex, RegexOptions.Multiline);
  249. MatchCollection matches = RE.Matches(text);
  250. string outText = 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. if (level == "error")
  261. WriteColorText(ConsoleColor.Red, outText);
  262. else if (level == "warn")
  263. WriteColorText(ConsoleColor.Yellow, outText);
  264. else
  265. System.Console.Write(outText);
  266. System.Console.WriteLine();
  267. }
  268. public override void Output(string text)
  269. {
  270. Output(text, "normal");
  271. }
  272. public override void Output(string text, string level)
  273. {
  274. lock (cmdline)
  275. {
  276. if (y == -1)
  277. {
  278. WriteLocalText(text, level);
  279. return;
  280. }
  281. y = SetCursorTop(y);
  282. SetCursorLeft(0);
  283. int count = cmdline.Length + prompt.Length;
  284. while (count-- > 0)
  285. System.Console.Write(" ");
  286. y = SetCursorTop(y);
  287. SetCursorLeft(0);
  288. WriteLocalText(text, level);
  289. y = System.Console.CursorTop;
  290. Show();
  291. }
  292. }
  293. private bool ContextHelp()
  294. {
  295. string[] words = Parser.Parse(cmdline.ToString());
  296. bool trailingSpace = cmdline.ToString().EndsWith(" ");
  297. // Allow ? through while typing a URI
  298. //
  299. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  300. return false;
  301. string[] opts = Commands.FindNextOption(words, trailingSpace);
  302. if (opts[0].StartsWith("Command help:"))
  303. Output(opts[0]);
  304. else
  305. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  306. return true;
  307. }
  308. public override string ReadLine(string p, bool isCommand, bool e)
  309. {
  310. h = 1;
  311. cp = 0;
  312. prompt = p;
  313. echo = e;
  314. int historyLine = history.Count;
  315. SetCursorLeft(0); // Needed for mono
  316. System.Console.Write(" "); // Needed for mono
  317. lock (cmdline)
  318. {
  319. y = System.Console.CursorTop;
  320. cmdline.Remove(0, cmdline.Length);
  321. }
  322. while (true)
  323. {
  324. Show();
  325. ConsoleKeyInfo key = System.Console.ReadKey(true);
  326. char c = key.KeyChar;
  327. if (!Char.IsControl(c))
  328. {
  329. if (cp >= 318)
  330. continue;
  331. if (c == '?' && isCommand)
  332. {
  333. if (ContextHelp())
  334. continue;
  335. }
  336. cmdline.Insert(cp, c);
  337. cp++;
  338. }
  339. else
  340. {
  341. switch (key.Key)
  342. {
  343. case ConsoleKey.Backspace:
  344. if (cp == 0)
  345. break;
  346. cmdline.Remove(cp-1, 1);
  347. cp--;
  348. SetCursorLeft(0);
  349. y = SetCursorTop(y);
  350. System.Console.Write("{0}{1} ", prompt, cmdline);
  351. break;
  352. case ConsoleKey.End:
  353. cp = cmdline.Length;
  354. break;
  355. case ConsoleKey.Home:
  356. cp = 0;
  357. break;
  358. case ConsoleKey.UpArrow:
  359. if (historyLine < 1)
  360. break;
  361. historyLine--;
  362. LockOutput();
  363. cmdline.Remove(0, cmdline.Length);
  364. cmdline.Append(history[historyLine]);
  365. cp = cmdline.Length;
  366. UnlockOutput();
  367. break;
  368. case ConsoleKey.DownArrow:
  369. if (historyLine >= history.Count)
  370. break;
  371. historyLine++;
  372. LockOutput();
  373. if (historyLine == history.Count)
  374. {
  375. cmdline.Remove(0, cmdline.Length);
  376. }
  377. else
  378. {
  379. cmdline.Remove(0, cmdline.Length);
  380. cmdline.Append(history[historyLine]);
  381. }
  382. cp = cmdline.Length;
  383. UnlockOutput();
  384. break;
  385. case ConsoleKey.LeftArrow:
  386. if (cp > 0)
  387. cp--;
  388. break;
  389. case ConsoleKey.RightArrow:
  390. if (cp < cmdline.Length)
  391. cp++;
  392. break;
  393. case ConsoleKey.Enter:
  394. SetCursorLeft(0);
  395. y = SetCursorTop(y);
  396. System.Console.WriteLine("{0}{1}", prompt, cmdline);
  397. lock (cmdline)
  398. {
  399. y = -1;
  400. }
  401. if (isCommand)
  402. {
  403. string[] cmd = Commands.Resolve(Parser.Parse(cmdline.ToString()));
  404. if (cmd.Length != 0)
  405. {
  406. int i;
  407. for (i=0 ; i < cmd.Length ; i++)
  408. {
  409. if (cmd[i].Contains(" "))
  410. cmd[i] = "\"" + cmd[i] + "\"";
  411. }
  412. AddToHistory(String.Join(" ", cmd));
  413. return String.Empty;
  414. }
  415. }
  416. AddToHistory(cmdline.ToString());
  417. return cmdline.ToString();
  418. default:
  419. break;
  420. }
  421. }
  422. }
  423. }
  424. }
  425. }