ConsoleBase.cs 15 KB

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