Commander.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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.Reflection;
  30. using System.Text;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Environment.Interfaces;
  34. namespace OpenSim.Region.Environment.Modules.Framework.InterfaceCommander
  35. {
  36. /// <summary>
  37. /// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s.
  38. /// Used for console commands and script API generation
  39. /// </summary>
  40. public class Command : ICommand
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. private List<CommandArgument> m_args = new List<CommandArgument>();
  44. private Action<object[]> m_command;
  45. private string m_help;
  46. private string m_name;
  47. private CommandIntentions m_intentions; //A permission type system could implement this and know what a command intends on doing.
  48. public Command(string name, CommandIntentions intention, Action<Object[]> command, string help)
  49. {
  50. m_name = name;
  51. m_command = command;
  52. m_help = help;
  53. m_intentions = intention;
  54. }
  55. #region ICommand Members
  56. public void AddArgument(string name, string helptext, string type)
  57. {
  58. m_args.Add(new CommandArgument(name, helptext, type));
  59. }
  60. public string Name
  61. {
  62. get { return m_name; }
  63. }
  64. public CommandIntentions Intentions
  65. {
  66. get { return m_intentions; }
  67. }
  68. public string Help
  69. {
  70. get { return m_help; }
  71. }
  72. public Dictionary<string, string> Arguments
  73. {
  74. get
  75. {
  76. Dictionary<string, string> tmp = new Dictionary<string, string>();
  77. foreach (CommandArgument arg in m_args)
  78. {
  79. tmp.Add(arg.Name, arg.ArgumentType);
  80. }
  81. return tmp;
  82. }
  83. }
  84. public void ShowConsoleHelp()
  85. {
  86. m_log.Info("== " + Name + " ==");
  87. m_log.Info(m_help);
  88. m_log.Info("= Parameters =");
  89. foreach (CommandArgument arg in m_args)
  90. {
  91. m_log.Info("* " + arg.Name + " (" + arg.ArgumentType + ")");
  92. m_log.Info("\t" + arg.HelpText);
  93. }
  94. }
  95. public void Run(Object[] args)
  96. {
  97. Object[] cleanArgs = new Object[m_args.Count];
  98. if (args.Length < cleanArgs.Length)
  99. {
  100. m_log.Error("Missing " + (cleanArgs.Length - args.Length) + " argument(s)");
  101. ShowConsoleHelp();
  102. return;
  103. }
  104. if (args.Length > cleanArgs.Length)
  105. {
  106. m_log.Error("Too many arguments for this command. Type '<module> <command> help' for help.");
  107. return;
  108. }
  109. int i = 0;
  110. foreach (Object arg in args)
  111. {
  112. if (string.IsNullOrEmpty(arg.ToString()))
  113. {
  114. m_log.Error("Empty arguments are not allowed");
  115. return;
  116. }
  117. try
  118. {
  119. switch (m_args[i].ArgumentType)
  120. {
  121. case "String":
  122. m_args[i].ArgumentValue = arg.ToString();
  123. break;
  124. case "Integer":
  125. m_args[i].ArgumentValue = Int32.Parse(arg.ToString());
  126. break;
  127. case "Double":
  128. m_args[i].ArgumentValue = Double.Parse(arg.ToString());
  129. break;
  130. case "Boolean":
  131. m_args[i].ArgumentValue = Boolean.Parse(arg.ToString());
  132. break;
  133. default:
  134. m_log.Error("Unknown desired type for argument " + m_args[i].Name + " on command " + m_name);
  135. break;
  136. }
  137. }
  138. catch (FormatException)
  139. {
  140. m_log.Error("Argument number " + (i + 1) +
  141. " (" + m_args[i].Name + ") must be a valid " +
  142. m_args[i].ArgumentType.ToLower() + ".");
  143. }
  144. cleanArgs[i] = m_args[i].ArgumentValue;
  145. i++;
  146. }
  147. m_command.Invoke(cleanArgs);
  148. }
  149. #endregion
  150. }
  151. /// <summary>
  152. /// A single command argument, contains name, type and at runtime, value.
  153. /// </summary>
  154. public class CommandArgument
  155. {
  156. private string m_help;
  157. private string m_name;
  158. private string m_type;
  159. private Object m_val;
  160. public CommandArgument(string name, string help, string type)
  161. {
  162. m_name = name;
  163. m_help = help;
  164. m_type = type;
  165. }
  166. public string Name
  167. {
  168. get { return m_name; }
  169. }
  170. public string HelpText
  171. {
  172. get { return m_help; }
  173. }
  174. public string ArgumentType
  175. {
  176. get { return m_type; }
  177. }
  178. public Object ArgumentValue
  179. {
  180. get { return m_val; }
  181. set { m_val = value; }
  182. }
  183. }
  184. /// <summary>
  185. /// A class to enable modules to register console and script commands, which enforces typing and valid input.
  186. /// </summary>
  187. public class Commander : ICommander
  188. {
  189. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  190. private Dictionary<string, ICommand> m_commands = new Dictionary<string, ICommand>();
  191. private string m_name;
  192. public Commander(string name)
  193. {
  194. m_name = name;
  195. }
  196. public Dictionary<string, ICommand> Commands
  197. {
  198. get { return m_commands; }
  199. }
  200. #region ICommander Members
  201. public void RegisterCommand(string commandName, ICommand command)
  202. {
  203. m_commands[commandName] = command;
  204. }
  205. /// <summary>
  206. /// Generates a runtime C# class which can be compiled and inserted via reflection to enable modules to register new script commands
  207. /// </summary>
  208. /// <returns>Returns C# source code to create a binding</returns>
  209. public string GenerateRuntimeAPI()
  210. {
  211. string classSrc = "\n\tpublic class " + m_name + " {\n";
  212. foreach (ICommand com in m_commands.Values)
  213. {
  214. classSrc += "\tpublic void " + EscapeRuntimeAPICommand(com.Name) + "( ";
  215. foreach (KeyValuePair<string, string> arg in com.Arguments)
  216. {
  217. classSrc += arg.Value + " " + Util.Md5Hash(arg.Key) + ",";
  218. }
  219. classSrc = classSrc.Remove(classSrc.Length - 1); // Delete the last comma
  220. classSrc += " )\n\t{\n";
  221. classSrc += "\t\tObject[] args = new Object[" + com.Arguments.Count.ToString() + "];\n";
  222. int i = 0;
  223. foreach (KeyValuePair<string, string> arg in com.Arguments)
  224. {
  225. classSrc += "\t\targs[" + i.ToString() + "] = " + Util.Md5Hash(arg.Key) + " " + ";\n";
  226. i++;
  227. }
  228. classSrc += "\t\tGetCommander(\"" + m_name + "\").Run(\"" + com.Name + "\", args);\n";
  229. classSrc += "\t}\n";
  230. }
  231. classSrc += "}\n";
  232. return classSrc;
  233. }
  234. /// <summary>
  235. /// Runs a specified function with attached arguments
  236. /// *** <b>DO NOT CALL DIRECTLY.</b> ***
  237. /// Call ProcessConsoleCommand instead if handling human input.
  238. /// </summary>
  239. /// <param name="function">The function name to call</param>
  240. /// <param name="args">The function parameters</param>
  241. public void Run(string function, object[] args)
  242. {
  243. m_commands[function].Run(args);
  244. }
  245. public void ProcessConsoleCommand(string function, string[] args)
  246. {
  247. if (m_commands.ContainsKey(function))
  248. {
  249. if (args.Length > 0 && args[0] == "help")
  250. {
  251. m_commands[function].ShowConsoleHelp();
  252. }
  253. else
  254. {
  255. m_commands[function].Run(args);
  256. }
  257. }
  258. else
  259. {
  260. if (function != "help")
  261. m_log.Error("Invalid command - No such command exists");
  262. if (function == "api")
  263. m_log.Info(GenerateRuntimeAPI());
  264. ShowConsoleHelp();
  265. }
  266. }
  267. #endregion
  268. private void ShowConsoleHelp()
  269. {
  270. m_log.Info("===" + m_name + "===");
  271. foreach (ICommand com in m_commands.Values)
  272. {
  273. m_log.Info("* " + com.Name + " - " + com.Help);
  274. }
  275. }
  276. private string EscapeRuntimeAPICommand(string command)
  277. {
  278. command = command.Replace('-', '_');
  279. StringBuilder tmp = new StringBuilder(command);
  280. tmp[0] = tmp[0].ToString().ToUpper().ToCharArray()[0];
  281. return tmp.ToString();
  282. }
  283. }
  284. }