CommandConsole.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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.Xml;
  29. using System.Collections.Generic;
  30. using System.Diagnostics;
  31. using System.Linq;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Text.RegularExpressions;
  35. using System.Threading;
  36. using log4net;
  37. using OpenSim.Framework;
  38. using Nini.Config;
  39. namespace OpenSim.Framework.Console
  40. {
  41. public class Commands : ICommands
  42. {
  43. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. /// <summary>
  45. /// Encapsulates a command that can be invoked from the console
  46. /// </summary>
  47. private class CommandInfo
  48. {
  49. /// <value>
  50. /// The module from which this command comes
  51. /// </value>
  52. public string module;
  53. /// <value>
  54. /// Whether the module is shared
  55. /// </value>
  56. public bool shared;
  57. /// <value>
  58. /// Very short BNF description
  59. /// </value>
  60. public string help_text;
  61. /// <value>
  62. /// Longer one line help text
  63. /// </value>
  64. public string long_help;
  65. /// <value>
  66. /// Full descriptive help for this command
  67. /// </value>
  68. public string descriptive_help;
  69. /// <value>
  70. /// The method to invoke for this command
  71. /// </value>
  72. public List<CommandDelegate> fn;
  73. }
  74. public const string GeneralHelpText
  75. = "To enter an argument that contains spaces, surround the argument with double quotes.\nFor example, show object name \"My long object name\"\n";
  76. public const string ItemHelpText
  77. = @"For more information, type 'help all' to get a list of all commands,
  78. or type help <item>' where <item> is one of the following:";
  79. /// <value>
  80. /// Commands organized by keyword in a tree
  81. /// </value>
  82. private Dictionary<string, object> tree =
  83. new Dictionary<string, object>();
  84. /// <summary>
  85. /// Commands organized by module
  86. /// </summary>
  87. private Dictionary<string, List<CommandInfo>> m_modulesCommands = new Dictionary<string, List<CommandInfo>>();
  88. /// <summary>
  89. /// Get help for the given help string
  90. /// </summary>
  91. /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param>
  92. /// <returns></returns>
  93. public List<string> GetHelp(string[] cmd)
  94. {
  95. List<string> help = new List<string>();
  96. List<string> helpParts = new List<string>(cmd);
  97. // Remove initial help keyword
  98. helpParts.RemoveAt(0);
  99. help.Add(""); // Will become a newline.
  100. // General help
  101. if (helpParts.Count == 0)
  102. {
  103. help.Add(GeneralHelpText);
  104. help.Add(ItemHelpText);
  105. help.AddRange(CollectModulesHelp(tree));
  106. }
  107. else if (helpParts.Count == 1 && helpParts[0] == "all")
  108. {
  109. help.AddRange(CollectAllCommandsHelp());
  110. }
  111. else
  112. {
  113. help.AddRange(CollectHelp(helpParts));
  114. }
  115. help.Add(""); // Will become a newline.
  116. return help;
  117. }
  118. /// <summary>
  119. /// Collects the help from all commands and return in alphabetical order.
  120. /// </summary>
  121. /// <returns></returns>
  122. private List<string> CollectAllCommandsHelp()
  123. {
  124. List<string> help = new List<string>();
  125. lock (m_modulesCommands)
  126. {
  127. foreach (List<CommandInfo> commands in m_modulesCommands.Values)
  128. {
  129. var ourHelpText = commands.ConvertAll(c => string.Format("{0} - {1}", c.help_text, c.long_help));
  130. help.AddRange(ourHelpText);
  131. }
  132. }
  133. help.Sort();
  134. return help;
  135. }
  136. /// <summary>
  137. /// See if we can find the requested command in order to display longer help
  138. /// </summary>
  139. /// <param name="helpParts"></param>
  140. /// <returns></returns>
  141. private List<string> CollectHelp(List<string> helpParts)
  142. {
  143. string originalHelpRequest = string.Join(" ", helpParts.ToArray());
  144. List<string> help = new List<string>();
  145. // Check modules first to see if we just need to display a list of those commands
  146. if (TryCollectModuleHelp(originalHelpRequest, help))
  147. {
  148. help.Insert(0, ItemHelpText);
  149. return help;
  150. }
  151. Dictionary<string, object> dict = tree;
  152. while (helpParts.Count > 0)
  153. {
  154. string helpPart = helpParts[0];
  155. if (!dict.ContainsKey(helpPart))
  156. break;
  157. //m_log.Debug("Found {0}", helpParts[0]);
  158. if (dict[helpPart] is Dictionary<string, Object>)
  159. dict = (Dictionary<string, object>)dict[helpPart];
  160. helpParts.RemoveAt(0);
  161. }
  162. // There was a command for the given help string
  163. if (dict.ContainsKey(String.Empty))
  164. {
  165. CommandInfo commandInfo = (CommandInfo)dict[String.Empty];
  166. help.Add(commandInfo.help_text);
  167. help.Add(commandInfo.long_help);
  168. string descriptiveHelp = commandInfo.descriptive_help;
  169. // If we do have some descriptive help then insert a spacing line before for readability.
  170. if (descriptiveHelp != string.Empty)
  171. help.Add(string.Empty);
  172. help.Add(commandInfo.descriptive_help);
  173. }
  174. else
  175. {
  176. help.Add(string.Format("No help is available for {0}", originalHelpRequest));
  177. }
  178. return help;
  179. }
  180. /// <summary>
  181. /// Try to collect help for the given module if that module exists.
  182. /// </summary>
  183. /// <param name="moduleName"></param>
  184. /// <param name="helpText">/param>
  185. /// <returns>true if there was the module existed, false otherwise.</returns>
  186. private bool TryCollectModuleHelp(string moduleName, List<string> helpText)
  187. {
  188. lock (m_modulesCommands)
  189. {
  190. foreach (string key in m_modulesCommands.Keys)
  191. {
  192. // Allow topic help requests to succeed whether they are upper or lowercase.
  193. if (moduleName.ToLower() == key.ToLower())
  194. {
  195. List<CommandInfo> commands = m_modulesCommands[key];
  196. var ourHelpText = commands.ConvertAll(c => string.Format("{0} - {1}", c.help_text, c.long_help));
  197. ourHelpText.Sort();
  198. helpText.AddRange(ourHelpText);
  199. return true;
  200. }
  201. }
  202. return false;
  203. }
  204. }
  205. private List<string> CollectModulesHelp(Dictionary<string, object> dict)
  206. {
  207. lock (m_modulesCommands)
  208. {
  209. List<string> helpText = new List<string>(m_modulesCommands.Keys);
  210. helpText.Sort();
  211. return helpText;
  212. }
  213. }
  214. // private List<string> CollectHelp(Dictionary<string, object> dict)
  215. // {
  216. // List<string> result = new List<string>();
  217. //
  218. // foreach (KeyValuePair<string, object> kvp in dict)
  219. // {
  220. // if (kvp.Value is Dictionary<string, Object>)
  221. // {
  222. // result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value));
  223. // }
  224. // else
  225. // {
  226. // if (((CommandInfo)kvp.Value).long_help != String.Empty)
  227. // result.Add(((CommandInfo)kvp.Value).help_text+" - "+
  228. // ((CommandInfo)kvp.Value).long_help);
  229. // }
  230. // }
  231. // return result;
  232. // }
  233. /// <summary>
  234. /// Add a command to those which can be invoked from the console.
  235. /// </summary>
  236. /// <param name="module"></param>
  237. /// <param name="command"></param>
  238. /// <param name="help"></param>
  239. /// <param name="longhelp"></param>
  240. /// <param name="fn"></param>
  241. public void AddCommand(string module, bool shared, string command,
  242. string help, string longhelp, CommandDelegate fn)
  243. {
  244. AddCommand(module, shared, command, help, longhelp, String.Empty, fn);
  245. }
  246. /// <summary>
  247. /// Add a command to those which can be invoked from the console.
  248. /// </summary>
  249. /// <param name="module"></param>
  250. /// <param name="command"></param>
  251. /// <param name="help"></param>
  252. /// <param name="longhelp"></param>
  253. /// <param name="descriptivehelp"></param>
  254. /// <param name="fn"></param>
  255. public void AddCommand(string module, bool shared, string command,
  256. string help, string longhelp, string descriptivehelp,
  257. CommandDelegate fn)
  258. {
  259. string[] parts = Parser.Parse(command);
  260. Dictionary<string, Object> current = tree;
  261. foreach (string part in parts)
  262. {
  263. if (current.ContainsKey(part))
  264. {
  265. if (current[part] is Dictionary<string, Object>)
  266. current = (Dictionary<string, Object>)current[part];
  267. else
  268. return;
  269. }
  270. else
  271. {
  272. current[part] = new Dictionary<string, Object>();
  273. current = (Dictionary<string, Object>)current[part];
  274. }
  275. }
  276. CommandInfo info;
  277. if (current.ContainsKey(String.Empty))
  278. {
  279. info = (CommandInfo)current[String.Empty];
  280. if (!info.shared && !info.fn.Contains(fn))
  281. info.fn.Add(fn);
  282. return;
  283. }
  284. info = new CommandInfo();
  285. info.module = module;
  286. info.shared = shared;
  287. info.help_text = help;
  288. info.long_help = longhelp;
  289. info.descriptive_help = descriptivehelp;
  290. info.fn = new List<CommandDelegate>();
  291. info.fn.Add(fn);
  292. current[String.Empty] = info;
  293. // Now add command to modules dictionary
  294. lock (m_modulesCommands)
  295. {
  296. List<CommandInfo> commands;
  297. if (m_modulesCommands.ContainsKey(module))
  298. {
  299. commands = m_modulesCommands[module];
  300. }
  301. else
  302. {
  303. commands = new List<CommandInfo>();
  304. m_modulesCommands[module] = commands;
  305. }
  306. // m_log.DebugFormat("[COMMAND CONSOLE]: Adding to category {0} command {1}", module, command);
  307. commands.Add(info);
  308. }
  309. }
  310. public string[] FindNextOption(string[] cmd, bool term)
  311. {
  312. Dictionary<string, object> current = tree;
  313. int remaining = cmd.Length;
  314. foreach (string s in cmd)
  315. {
  316. remaining--;
  317. List<string> found = new List<string>();
  318. foreach (string opt in current.Keys)
  319. {
  320. if (remaining > 0 && opt == s)
  321. {
  322. found.Clear();
  323. found.Add(opt);
  324. break;
  325. }
  326. if (opt.StartsWith(s))
  327. {
  328. found.Add(opt);
  329. }
  330. }
  331. if (found.Count == 1 && (remaining != 0 || term))
  332. {
  333. current = (Dictionary<string, object>)current[found[0]];
  334. }
  335. else if (found.Count > 0)
  336. {
  337. return found.ToArray();
  338. }
  339. else
  340. {
  341. break;
  342. // return new string[] {"<cr>"};
  343. }
  344. }
  345. if (current.Count > 1)
  346. {
  347. List<string> choices = new List<string>();
  348. bool addcr = false;
  349. foreach (string s in current.Keys)
  350. {
  351. if (s.Length == 0)
  352. {
  353. CommandInfo ci = (CommandInfo)current[String.Empty];
  354. if (ci.fn.Count != 0)
  355. addcr = true;
  356. }
  357. else
  358. choices.Add(s);
  359. }
  360. if (addcr)
  361. choices.Add("<cr>");
  362. return choices.ToArray();
  363. }
  364. if (current.ContainsKey(String.Empty))
  365. return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text};
  366. return new string[] { new List<string>(current.Keys)[0] };
  367. }
  368. private CommandInfo ResolveCommand(string[] cmd, out string[] result)
  369. {
  370. result = cmd;
  371. int index = -1;
  372. Dictionary<string, object> current = tree;
  373. foreach (string s in cmd)
  374. {
  375. index++;
  376. List<string> found = new List<string>();
  377. foreach (string opt in current.Keys)
  378. {
  379. if (opt == s)
  380. {
  381. found.Clear();
  382. found.Add(opt);
  383. break;
  384. }
  385. if (opt.StartsWith(s))
  386. {
  387. found.Add(opt);
  388. }
  389. }
  390. if (found.Count == 1)
  391. {
  392. result[index] = found[0];
  393. current = (Dictionary<string, object>)current[found[0]];
  394. }
  395. else if (found.Count > 0)
  396. {
  397. return null;
  398. }
  399. else
  400. {
  401. break;
  402. }
  403. }
  404. if (current.ContainsKey(String.Empty))
  405. return (CommandInfo)current[String.Empty];
  406. return null;
  407. }
  408. public bool HasCommand(string command)
  409. {
  410. string[] result;
  411. return ResolveCommand(Parser.Parse(command), out result) != null;
  412. }
  413. public string[] Resolve(string[] cmd)
  414. {
  415. string[] result;
  416. CommandInfo ci = ResolveCommand(cmd, out result);
  417. if (ci == null)
  418. return new string[0];
  419. if (ci.fn.Count == 0)
  420. return new string[0];
  421. foreach (CommandDelegate fn in ci.fn)
  422. {
  423. if (fn != null)
  424. fn(ci.module, result);
  425. else
  426. return new string[0];
  427. }
  428. return result;
  429. }
  430. public XmlElement GetXml(XmlDocument doc)
  431. {
  432. CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty];
  433. ((Dictionary<string, object>)tree["help"]).Remove(string.Empty);
  434. if (((Dictionary<string, object>)tree["help"]).Count == 0)
  435. tree.Remove("help");
  436. CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty];
  437. ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty);
  438. if (((Dictionary<string, object>)tree["quit"]).Count == 0)
  439. tree.Remove("quit");
  440. XmlElement root = doc.CreateElement("", "HelpTree", "");
  441. ProcessTreeLevel(tree, root, doc);
  442. if (!tree.ContainsKey("help"))
  443. tree["help"] = (object) new Dictionary<string, object>();
  444. ((Dictionary<string, object>)tree["help"])[String.Empty] = help;
  445. if (!tree.ContainsKey("quit"))
  446. tree["quit"] = (object) new Dictionary<string, object>();
  447. ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit;
  448. return root;
  449. }
  450. private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc)
  451. {
  452. foreach (KeyValuePair<string, object> kvp in level)
  453. {
  454. if (kvp.Value is Dictionary<string, Object>)
  455. {
  456. XmlElement next = doc.CreateElement("", "Level", "");
  457. next.SetAttribute("Name", kvp.Key);
  458. xml.AppendChild(next);
  459. ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc);
  460. }
  461. else
  462. {
  463. CommandInfo c = (CommandInfo)kvp.Value;
  464. XmlElement cmd = doc.CreateElement("", "Command", "");
  465. XmlElement e;
  466. e = doc.CreateElement("", "Module", "");
  467. cmd.AppendChild(e);
  468. e.AppendChild(doc.CreateTextNode(c.module));
  469. e = doc.CreateElement("", "Shared", "");
  470. cmd.AppendChild(e);
  471. e.AppendChild(doc.CreateTextNode(c.shared.ToString()));
  472. e = doc.CreateElement("", "HelpText", "");
  473. cmd.AppendChild(e);
  474. e.AppendChild(doc.CreateTextNode(c.help_text));
  475. e = doc.CreateElement("", "LongHelp", "");
  476. cmd.AppendChild(e);
  477. e.AppendChild(doc.CreateTextNode(c.long_help));
  478. e = doc.CreateElement("", "Description", "");
  479. cmd.AppendChild(e);
  480. e.AppendChild(doc.CreateTextNode(c.descriptive_help));
  481. xml.AppendChild(cmd);
  482. }
  483. }
  484. }
  485. public void FromXml(XmlElement root, CommandDelegate fn)
  486. {
  487. CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty];
  488. ((Dictionary<string, object>)tree["help"]).Remove(string.Empty);
  489. if (((Dictionary<string, object>)tree["help"]).Count == 0)
  490. tree.Remove("help");
  491. CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty];
  492. ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty);
  493. if (((Dictionary<string, object>)tree["quit"]).Count == 0)
  494. tree.Remove("quit");
  495. tree.Clear();
  496. ReadTreeLevel(tree, root, fn);
  497. if (!tree.ContainsKey("help"))
  498. tree["help"] = (object) new Dictionary<string, object>();
  499. ((Dictionary<string, object>)tree["help"])[String.Empty] = help;
  500. if (!tree.ContainsKey("quit"))
  501. tree["quit"] = (object) new Dictionary<string, object>();
  502. ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit;
  503. }
  504. private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn)
  505. {
  506. Dictionary<string, object> next;
  507. string name;
  508. XmlNodeList nodeL = node.ChildNodes;
  509. XmlNodeList cmdL;
  510. CommandInfo c;
  511. foreach (XmlNode part in nodeL)
  512. {
  513. switch (part.Name)
  514. {
  515. case "Level":
  516. name = ((XmlElement)part).GetAttribute("Name");
  517. next = new Dictionary<string, object>();
  518. level[name] = next;
  519. ReadTreeLevel(next, part, fn);
  520. break;
  521. case "Command":
  522. cmdL = part.ChildNodes;
  523. c = new CommandInfo();
  524. foreach (XmlNode cmdPart in cmdL)
  525. {
  526. switch (cmdPart.Name)
  527. {
  528. case "Module":
  529. c.module = cmdPart.InnerText;
  530. break;
  531. case "Shared":
  532. c.shared = Convert.ToBoolean(cmdPart.InnerText);
  533. break;
  534. case "HelpText":
  535. c.help_text = cmdPart.InnerText;
  536. break;
  537. case "LongHelp":
  538. c.long_help = cmdPart.InnerText;
  539. break;
  540. case "Description":
  541. c.descriptive_help = cmdPart.InnerText;
  542. break;
  543. }
  544. }
  545. c.fn = new List<CommandDelegate>();
  546. c.fn.Add(fn);
  547. level[String.Empty] = c;
  548. break;
  549. }
  550. }
  551. }
  552. }
  553. public class Parser
  554. {
  555. // If an unquoted portion ends with an element matching this regex
  556. // and the next element contains a space, then we have stripped
  557. // embedded quotes that should not have been stripped
  558. private static Regex optionRegex = new Regex("^--[a-zA-Z0-9-]+=$");
  559. public static string[] Parse(string text)
  560. {
  561. List<string> result = new List<string>();
  562. int index;
  563. string[] unquoted = text.Split(new char[] {'"'});
  564. for (index = 0 ; index < unquoted.Length ; index++)
  565. {
  566. if (index % 2 == 0)
  567. {
  568. string[] words = unquoted[index].Split(new char[] {' '});
  569. bool option = false;
  570. foreach (string w in words)
  571. {
  572. if (w != String.Empty)
  573. {
  574. if (optionRegex.Match(w) == Match.Empty)
  575. option = false;
  576. else
  577. option = true;
  578. result.Add(w);
  579. }
  580. }
  581. // The last item matched the regex, put the quotes back
  582. if (option)
  583. {
  584. // If the line ended with it, don't do anything
  585. if (index < (unquoted.Length - 1))
  586. {
  587. // Get and remove the option name
  588. string optionText = result[result.Count - 1];
  589. result.RemoveAt(result.Count - 1);
  590. // Add the quoted value back
  591. optionText += "\"" + unquoted[index + 1] + "\"";
  592. // Push the result into our return array
  593. result.Add(optionText);
  594. // Skip the already used value
  595. index++;
  596. }
  597. }
  598. }
  599. else
  600. {
  601. result.Add(unquoted[index]);
  602. }
  603. }
  604. return result.ToArray();
  605. }
  606. }
  607. /// <summary>
  608. /// A console that processes commands internally
  609. /// </summary>
  610. public class CommandConsole : ConsoleBase, ICommandConsole
  611. {
  612. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  613. public event OnOutputDelegate OnOutput;
  614. public static event OnCntrCCelegate OnCntrC;
  615. public ICommands Commands { get; private set; }
  616. public CommandConsole(string defaultPrompt) : base(defaultPrompt)
  617. {
  618. Commands = new Commands();
  619. Commands.AddCommand(
  620. "Help", false, "help", "help [<item>]",
  621. "Display help on a particular command or on a list of commands in a category", Help);
  622. }
  623. private void Help(string module, string[] cmd)
  624. {
  625. List<string> help = Commands.GetHelp(cmd);
  626. foreach (string s in help)
  627. Output(s);
  628. }
  629. protected void FireOnOutput(string text)
  630. {
  631. OnOutput?.Invoke(text);
  632. }
  633. /// <summary>
  634. /// Display a command prompt on the console and wait for user input
  635. /// </summary>
  636. public void Prompt()
  637. {
  638. string line = ReadLine(DefaultPrompt + "# ", true, true);
  639. if (line != String.Empty)
  640. Output("Invalid command");
  641. }
  642. public void RunCommand(string cmd)
  643. {
  644. string[] parts = Parser.Parse(cmd);
  645. Commands.Resolve(parts);
  646. }
  647. public override string ReadLine(string p, bool isCommand, bool e)
  648. {
  649. System.Console.Write("{0}", p);
  650. string cmdinput = System.Console.ReadLine();
  651. if (isCommand)
  652. {
  653. string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
  654. if (cmd.Length != 0)
  655. {
  656. int i;
  657. for (i=0 ; i < cmd.Length ; i++)
  658. {
  659. if (cmd[i].Contains(" "))
  660. cmd[i] = "\"" + cmd[i] + "\"";
  661. }
  662. return String.Empty;
  663. }
  664. }
  665. return cmdinput;
  666. }
  667. public virtual void ReadConfig(IConfigSource configSource)
  668. {
  669. }
  670. public virtual void SetCntrCHandler(OnCntrCCelegate handler)
  671. {
  672. if(OnCntrC == null)
  673. {
  674. OnCntrC += handler;
  675. System.Console.CancelKeyPress += CancelKeyPressed;
  676. }
  677. }
  678. protected static void CancelKeyPressed(object sender, ConsoleCancelEventArgs args)
  679. {
  680. if (OnCntrC != null && args.SpecialKey == ConsoleSpecialKey.ControlC)
  681. {
  682. OnCntrC?.Invoke();
  683. args.Cancel = false;
  684. }
  685. }
  686. protected static void LocalCancelKeyPressed()
  687. {
  688. OnCntrC?.Invoke();
  689. }
  690. }
  691. }