ConsoleBase.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 OpenSim 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.Net;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using log4net;
  34. namespace OpenSim.Framework.Console
  35. {
  36. public class ConsoleBase
  37. {
  38. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. private readonly object m_syncRoot = new object();
  40. public conscmd_callback m_cmdParser;
  41. /// <summary>
  42. /// The default prompt text.
  43. /// </summary>
  44. public string DefaultPrompt
  45. {
  46. set { m_defaultPrompt = value + "# "; }
  47. get { return m_defaultPrompt; }
  48. }
  49. protected string m_defaultPrompt;
  50. /// <summary>
  51. /// Constructor.
  52. /// </summary>
  53. /// <param name="defaultPrompt"></param>
  54. /// <param name="cmdparser"></param>
  55. public ConsoleBase(string defaultPrompt, conscmd_callback cmdparser)
  56. {
  57. DefaultPrompt = defaultPrompt;
  58. m_cmdParser = cmdparser;
  59. }
  60. /// <summary>
  61. /// derive an ansi color from a string, ignoring the darker colors.
  62. /// This is used to help automatically bin component tags with colors
  63. /// in various print functions.
  64. /// </summary>
  65. /// <param name="input">arbitrary string for input</param>
  66. /// <returns>an ansii color</returns>
  67. private static ConsoleColor DeriveColor(string input)
  68. {
  69. int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
  70. return (ConsoleColor) colIdx;
  71. }
  72. /// <summary>
  73. /// Sends a warning to the current console output
  74. /// </summary>
  75. /// <param name="format">The message to send</param>
  76. /// <param name="args">WriteLine-style message arguments</param>
  77. public void Warn(string format, params object[] args)
  78. {
  79. WriteNewLine(ConsoleColor.Yellow, format, args);
  80. }
  81. /// <summary>
  82. /// Sends a warning to the current console output
  83. /// </summary>
  84. /// <param name="sender">The module that sent this message</param>
  85. /// <param name="format">The message to send</param>
  86. /// <param name="args">WriteLine-style message arguments</param>
  87. public void Warn(string sender, string format, params object[] args)
  88. {
  89. WritePrefixLine(DeriveColor(sender), sender);
  90. WriteNewLine(ConsoleColor.Yellow, format, args);
  91. }
  92. /// <summary>
  93. /// Sends a notice to the current console output
  94. /// </summary>
  95. /// <param name="format">The message to send</param>
  96. /// <param name="args">WriteLine-style message arguments</param>
  97. public void Notice(string format, params object[] args)
  98. {
  99. WriteNewLine(ConsoleColor.White, format, args);
  100. }
  101. /// <summary>
  102. /// Sends a notice to the current console output
  103. /// </summary>
  104. /// <param name="sender">The module that sent this message</param>
  105. /// <param name="format">The message to send</param>
  106. /// <param name="args">WriteLine-style message arguments</param>
  107. public void Notice(string sender, string format, params object[] args)
  108. {
  109. WritePrefixLine(DeriveColor(sender), sender);
  110. WriteNewLine(ConsoleColor.White, format, args);
  111. }
  112. /// <summary>
  113. /// Sends an error to the current console output
  114. /// </summary>
  115. /// <param name="format">The message to send</param>
  116. /// <param name="args">WriteLine-style message arguments</param>
  117. public void Error(string format, params object[] args)
  118. {
  119. WriteNewLine(ConsoleColor.Red, format, args);
  120. }
  121. /// <summary>
  122. /// Sends an error to the current console output
  123. /// </summary>
  124. /// <param name="sender">The module that sent this message</param>
  125. /// <param name="format">The message to send</param>
  126. /// <param name="args">WriteLine-style message arguments</param>
  127. public void Error(string sender, string format, params object[] args)
  128. {
  129. WritePrefixLine(DeriveColor(sender), sender);
  130. Error(format, args);
  131. }
  132. /// <summary>
  133. /// Sends a status message to the current console output
  134. /// </summary>
  135. /// <param name="format">The message to send</param>
  136. /// <param name="args">WriteLine-style message arguments</param>
  137. public void Status(string format, params object[] args)
  138. {
  139. WriteNewLine(ConsoleColor.Blue, format, args);
  140. }
  141. /// <summary>
  142. /// Sends a status message to the current console output
  143. /// </summary>
  144. /// <param name="sender">The module that sent this message</param>
  145. /// <param name="format">The message to send</param>
  146. /// <param name="args">WriteLine-style message arguments</param>
  147. public void Status(string sender, string format, params object[] args)
  148. {
  149. WritePrefixLine(DeriveColor(sender), sender);
  150. WriteNewLine(ConsoleColor.Blue, format, args);
  151. }
  152. [Conditional("DEBUG")]
  153. public void Debug(string format, params object[] args)
  154. {
  155. WriteNewLine(ConsoleColor.Gray, format, args);
  156. }
  157. [Conditional("DEBUG")]
  158. public void Debug(string sender, string format, params object[] args)
  159. {
  160. WritePrefixLine(DeriveColor(sender), sender);
  161. WriteNewLine(ConsoleColor.Gray, format, args);
  162. }
  163. private void WriteNewLine(ConsoleColor color, string format, params object[] args)
  164. {
  165. try
  166. {
  167. lock (m_syncRoot)
  168. {
  169. try
  170. {
  171. if (color != ConsoleColor.White)
  172. System.Console.ForegroundColor = color;
  173. System.Console.WriteLine(format, args);
  174. System.Console.ResetColor();
  175. }
  176. catch (ArgumentNullException)
  177. {
  178. // Some older systems dont support coloured text.
  179. System.Console.WriteLine(format, args);
  180. }
  181. catch (FormatException)
  182. {
  183. System.Console.WriteLine(args);
  184. }
  185. }
  186. }
  187. catch (ObjectDisposedException)
  188. {
  189. }
  190. }
  191. private void WritePrefixLine(ConsoleColor color, string sender)
  192. {
  193. try
  194. {
  195. lock (m_syncRoot)
  196. {
  197. sender = sender.ToUpper();
  198. System.Console.WriteLine("[" + sender + "] ");
  199. System.Console.Write("[");
  200. try
  201. {
  202. System.Console.ForegroundColor = color;
  203. System.Console.Write(sender);
  204. System.Console.ResetColor();
  205. }
  206. catch (ArgumentNullException)
  207. {
  208. // Some older systems dont support coloured text.
  209. System.Console.WriteLine(sender);
  210. }
  211. System.Console.Write("] \t");
  212. }
  213. }
  214. catch (ObjectDisposedException)
  215. {
  216. }
  217. }
  218. public string ReadLine()
  219. {
  220. try
  221. {
  222. string line = System.Console.ReadLine();
  223. while (line == null)
  224. {
  225. line = System.Console.ReadLine();
  226. }
  227. return line;
  228. }
  229. catch (Exception e)
  230. {
  231. m_log.Error("[Console]: System.Console.ReadLine exception " + e.ToString());
  232. return String.Empty;
  233. }
  234. }
  235. public int Read()
  236. {
  237. return System.Console.Read();
  238. }
  239. public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue)
  240. {
  241. IPAddress address;
  242. string addressStr;
  243. while (true)
  244. {
  245. addressStr = CmdPrompt(prompt, defaultvalue);
  246. if (IPAddress.TryParse(addressStr, out address))
  247. {
  248. break;
  249. }
  250. else
  251. {
  252. m_log.Error("Illegal address. Please re-enter.");
  253. }
  254. }
  255. return address;
  256. }
  257. public uint CmdPromptIPPort(string prompt, string defaultvalue)
  258. {
  259. uint port;
  260. string portStr;
  261. while (true)
  262. {
  263. portStr = CmdPrompt(prompt, defaultvalue);
  264. if (uint.TryParse(portStr, out port))
  265. {
  266. if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort)
  267. {
  268. break;
  269. }
  270. }
  271. m_log.Error("Illegal address. Please re-enter.");
  272. }
  273. return port;
  274. }
  275. // Displays a prompt and waits for the user to enter a string, then returns that string
  276. // (Done with no echo and suitable for passwords - currently disabled)
  277. public string PasswdPrompt(string prompt)
  278. {
  279. // FIXME: Needs to be better abstracted
  280. System.Console.WriteLine(String.Format("{0}: ", prompt));
  281. //ConsoleColor oldfg = System.Console.ForegroundColor;
  282. //System.Console.ForegroundColor = System.Console.BackgroundColor;
  283. string temp = System.Console.ReadLine();
  284. //System.Console.ForegroundColor = oldfg;
  285. return temp;
  286. }
  287. // Displays a command prompt and waits for the user to enter a string, then returns that string
  288. public string CmdPrompt(string prompt)
  289. {
  290. System.Console.WriteLine(String.Format("{0}: ", prompt));
  291. return ReadLine();
  292. }
  293. // Displays a command prompt and returns a default value if the user simply presses enter
  294. public string CmdPrompt(string prompt, string defaultresponse)
  295. {
  296. string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse));
  297. if (temp == String.Empty)
  298. {
  299. return defaultresponse;
  300. }
  301. else
  302. {
  303. return temp;
  304. }
  305. }
  306. // Displays a command prompt and returns a default value, user may only enter 1 of 2 options
  307. public string CmdPrompt(string prompt, string defaultresponse, string OptionA, string OptionB)
  308. {
  309. bool itisdone = false;
  310. string temp = CmdPrompt(prompt, defaultresponse);
  311. while (itisdone == false)
  312. {
  313. if ((temp == OptionA) || (temp == OptionB))
  314. {
  315. itisdone = true;
  316. }
  317. else
  318. {
  319. System.Console.WriteLine("Valid options are " + OptionA + " or " + OptionB);
  320. temp = CmdPrompt(prompt, defaultresponse);
  321. }
  322. }
  323. return temp;
  324. }
  325. // Runs a command with a number of parameters
  326. public Object RunCmd(string Cmd, string[] cmdparams)
  327. {
  328. m_cmdParser.RunCmd(Cmd, cmdparams);
  329. return null;
  330. }
  331. // Shows data about something
  332. public void ShowCommands(string ShowWhat)
  333. {
  334. m_cmdParser.Show(new string[] { ShowWhat });
  335. }
  336. public void Prompt()
  337. {
  338. string tempstr = CmdPrompt(m_defaultPrompt);
  339. RunCommand(tempstr);
  340. }
  341. public void RunCommand(string cmdline)
  342. {
  343. Regex Extractor = new Regex(@"(['""][^""]+['""])\s*|([^\s]+)\s*", RegexOptions.Compiled);
  344. char[] delims = {' ', '"'};
  345. MatchCollection matches = Extractor.Matches(cmdline);
  346. // Get matches
  347. if (matches.Count == 0)
  348. return;
  349. string cmd = matches[0].Value.Trim(delims);
  350. string[] cmdparams = new string[matches.Count - 1];
  351. for (int i = 1; i < matches.Count; i++)
  352. {
  353. cmdparams[i-1] = matches[i].Value.Trim(delims);
  354. }
  355. try
  356. {
  357. RunCmd(cmd, cmdparams);
  358. }
  359. catch (Exception e)
  360. {
  361. m_log.ErrorFormat("[Console]: Command [{0}] failed with exception {1}", cmdline, e.ToString());
  362. m_log.Error(e.StackTrace);
  363. }
  364. }
  365. public string LineInfo
  366. {
  367. get
  368. {
  369. string result = String.Empty;
  370. string stacktrace = Environment.StackTrace;
  371. List<string> lines = new List<string>(stacktrace.Split(new string[] {"at "}, StringSplitOptions.None));
  372. if (lines.Count > 4)
  373. {
  374. lines.RemoveRange(0, 4);
  375. string tmpLine = lines[0];
  376. int inIndex = tmpLine.IndexOf(" in ");
  377. if (inIndex > -1)
  378. {
  379. result = tmpLine.Substring(0, inIndex);
  380. int lineIndex = tmpLine.IndexOf(":line ");
  381. if (lineIndex > -1)
  382. {
  383. lineIndex += 6;
  384. result += ", line " + tmpLine.Substring(lineIndex, (tmpLine.Length - lineIndex) - 5);
  385. }
  386. }
  387. }
  388. return result;
  389. }
  390. }
  391. }
  392. }