Beispiel #1
0
 public PluginInfo(String pluginID, int position, bool isActive, AbstractPlugin plugin)
 {
     this.pluginID = pluginID;
     this.position = position;
     this.isActive = isActive;
     this.plugin   = plugin;
 }
        public FigureParameters(AbstractPlugin figure) : this()
        {
            Type figureType = figure.GetType();

            foreach (PropertyInfo pi in figureType.GetProperties())
            {
                if (pi.Name != "GraphicsPath" && pi.Name != "Pen")
                {
                    this.AddLabel(pi.Name);
                    this.AddNumericUpDown(pi.Name, (int)pi.GetValue(figure));
                }
            }

            this.Draw_button.Click += (sender, args) =>
            {
                foreach (PropertyInfo pi in figureType.GetProperties())
                {
                    if (pi.Name != "GraphicsPath" && pi.Name != "Pen")
                    {
                        pi.SetValue(figure,
                                    (int)(this.ElementsPanel.Controls[pi.Name + NumericUpDownPostfix] as NumericUpDown).Value);
                    }
                }

                this.DialogResult = DialogResult.OK;
            };
        }
Beispiel #3
0
        /// <summary>
        /// Runs the plugin stage with the specififed type
        /// </summary>
        /// <param name="type"></param>
        /// <param name="stage">The stage of the current processing</param>
        /// <param name="script">the script to be processed</param>
        /// <param name="sourceManager"></param>
        /// <param name="defTable">the definitions that are used</param>
        /// <returns>True if the operation completed successfully</returns>
        private bool RunPluginStage(PluginType type, ProcessStage stage, ISourceScript script, ISourceManager sourceManager, IDefinitions defTable)
        {
            List <AbstractPlugin> chain = AbstractPlugin.GetPluginsForStage(_plugins, type, stage);


            bool ret = true;

            if (type == PluginType.FULL_SCRIPT_PLUGIN)
            {
                ret = RunFullScriptStage(chain, stage, script, sourceManager, defTable);
            }
            else if (type == PluginType.LINE_PLUGIN_BEFORE || type == PluginType.LINE_PLUGIN_AFTER)
            {
                string[] src = script.GetSource();
                RunLineStage(chain, stage, src);
                script.SetSource(src);
            }
            if (!ret)
            {
                return(false);
            }


            return(true);
        }
Beispiel #4
0
        public MainForm()
        {
            InitializeComponent();
            foreach (KeyValuePair <string, Type> pair in typeDictionary)
            {
                classBox.Items.Add(pair.Key);
            }
            foreach (KeyValuePair <string, AbstractSerializer> pair in serializers)
            {
                serList.Items.Add(pair.Key);
            }
            string[] files = Directory.GetFiles(".", "*.dll");
            foreach (string path in files)
            {
                Type[] types = null;

                var assembly = Assembly.LoadFrom(path);
                if (assembly != null)
                {
                    types = assembly.GetTypes();
                    foreach (Type type in types)
                    {
                        if (type.IsSubclassOf(typeof(AbstractPlugin)))
                        {
                            AbstractPlugin plugin = Activator.CreateInstance(type) as AbstractPlugin;
                            string         name   = plugin.GetName();
                            plugins.Add(name, plugin);
                            pluginsList.Items.Add(name);
                        }
                    }
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Runs the plugin stage with the specififed type
        /// </summary>
        /// <param name="type"></param>
        /// <param name="stage">The stage of the current processing</param>
        /// <param name="script">the script to be processed</param>
        /// <param name="sourceManager"></param>
        /// <param name="defTable">the definitions that are used</param>
        /// <returns>True if the operation completed successfully</returns>
        private bool RunPluginStage(PluginType type, ProcessStage stage, ISourceScript script,
                                    ISourceManager sourceManager, IDefinitions defTable)
        {
            List <AbstractPlugin> chain = AbstractPlugin.GetPluginsForStage(plugins, type, stage);


            bool ret = true;

            if (type == PluginType.FullScriptPlugin)
            {
                ret = RunFullScriptStage(chain, stage, script, sourceManager, defTable);
            }
            else if (type == PluginType.LinePluginBefore || type == PluginType.LinePluginAfter)
            {
                string[] src = script.GetSource();
                RunLineStage(chain, stage, src);
                script.SetSource(src);
            }
            if (!ret)
            {
                return(false);
            }


            return(true);
        }
Beispiel #6
0
 public override void Save <T>(AbstractPlugin plugin, T obj)
 {
     using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
     {
         var serializer = new BinaryFormatter();
         serializer.Serialize(fs, obj);
     }
 }
Beispiel #7
0
 public override T Load <T>(AbstractPlugin plugin)
 {
     using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
     {
         var serializer = new BinaryFormatter();
         return(serializer.Deserialize(fs) as T);
     }
 }
        /// <summary>
        /// A commandlet represents the abstract idea of the typical IRC command represented with a start-character (!) and a string for identify. All the parsing will be done
        /// by the bot, you only get exactly the events you registered to. For example: you can register an event which is only thrown if used in a private message by certain users,
        /// or in a certain channel.
        /// </summary>
        /// <param name="command">the command string including initial charakter. like "!example" </param>
        /// <param name="helptext">A help for this certain command which should be displayed by the !help command</param>
        /// <param name="handler">The name of the method which should be called, can be private</param>
        /// <param name="plugin">this (the class where this command is provided)</param>
        public PluginCommand(string command, string helptext, EventHandler<CommandEventArgs> handler, AbstractPlugin plugin)
        {
            ExportedCommand = command;
            HelpText = helptext;

            HandlerName = handler.Method.Name;
            Owner = plugin.FullName;
            SourcePlugin = plugin.FullName;
        }
Beispiel #9
0
        public SIMLHub_Old() : base("SIMLHub")
        {
            bot = new SimlBot();

            // Soon it will be substracted
            this.adapterCount = bot.Adapters.Count;

            // Add all adapters
            pluginAdapterPathAndTypes = helper.GetAllSIMLHubPluginIndexAdapterPathAndTypes();
            Console.Write("[SIMLHub] Adapters loading : ");
            foreach (var adapterPair in pluginAdapterPathAndTypes)
            {
                Assembly assembly = Assembly.LoadFrom(adapterPair.Key);

                foreach (var typename in adapterPair.Value)
                {
                    try
                    {
                        IAdapter adapter = (IAdapter)assembly.CreateInstance(typename);

                        AbstractPlugin simlHubPlugin = (AbstractPlugin)adapter;
                        this.Hub.PassThrough(simlHubPlugin.Hub);

                        // Add to bot in not null
                        if (adapter != null)
                        {
                            bot.Adapters.Add(adapter);
                        }
                    }
                    catch { /*Ignore*/ }
                }
            }

            Console.WriteLine("success");

            // Now final value is set
            this.adapterCount = bot.Adapters.Count - this.adapterCount;

            // Add all index.siml files
            Console.Write("[SIMLHub] Index siml merge : ");
            string mergedIndexSimlPackage = helper.GetAllIndexSimlPackage();

            Console.WriteLine("success");


            Console.Write("[SIMLHub] Merged index siml : ");
            bot.PackageManager.LoadFromString(mergedIndexSimlPackage);
            Console.WriteLine("success");

            // Subscribe to IUserResponse for input
            hub.Subscribe <IUserResponse>(this.GetBotReponse);
        }
Beispiel #10
0
 /// <summary>
 /// Add an individual to the master list.
 /// </summary>
 /// <param name="plugin">The plugin instance to add.</param>
 public bool AddPlugin(AbstractPlugin plugin)
 {
     lock (m_pluginsAvailable)
     {
         if (m_pluginsAvailable.ContainsKey(plugin.UUID))
         {
             this.Log().Warn("Plugin with UUID '{0}' is already registered.", plugin.UUID);
             return(false);
         }
         this.Log().Debug("Adding plugin {0} (ID = '{1}')", plugin.GetType().Name, plugin.UUID);
         m_pluginsAvailable[plugin.UUID] = plugin;
     }
     return(true);
 }
Beispiel #11
0
 private void Serialize()
 {
     if (serializers.TryGetValue(serList.SelectedItem.ToString(), out AbstractSerializer ser))
     {
         AbstractPlugin plugin = null;
         object         o      = pluginsList.SelectedItem;
         if (o != null)
         {
             string pluginName = o.ToString();
             plugin = plugins[pluginName];
         }
         ser.Save(plugin, objects);
     }
 }
Beispiel #12
0
 public override void Save <T>(AbstractPlugin plugin, T obj)
 {
     using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
     {
         string text   = JsonConvert.SerializeObject(obj);
         byte[] buffer = Encoding.ASCII.GetBytes(text);
         if (plugin != null)
         {
             buffer = plugin.Encrypt(buffer);
         }
         fs.Write(buffer, 0, buffer.Length);
         fs.Flush();
     }
 }
Beispiel #13
0
        /// <summary>
        /// Converts the Plugin to a basic markdown text that can be used to generate readmes.
        /// </summary>
        /// <param name="plugin">The plugin to list</param>
        /// <returns>The plugin description in markdown</returns>
        public static string[] ToMarkdown(this AbstractPlugin plugin)
        {
            List <string> ret = new List <string>
            {
                "______________________________________________",
                "#### " + plugin.GetType().Name + " Information:",
                "",
                "* Prefix: " + plugin.Prefix.Unpack(", "),
                "* Commands:",
                ""
            };

            ret.AddRange(ToMarkdown(plugin.Info));
            return(ret.ToArray());
        }
Beispiel #14
0
 public override T Load <T>(AbstractPlugin plugin)
 {
     using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
     {
         int    length = (int)fs.Length;
         byte[] buffer = new byte[length];
         fs.Read(buffer, 0, length);
         if (plugin != null)
         {
             buffer = plugin.Decrypt(buffer);
         }
         string text = Encoding.ASCII.GetString(buffer);
         return(JsonConvert.DeserializeObject <T>(text));
     }
 }
Beispiel #15
0
 private void Deserialize()
 {
     if (serializers.TryGetValue(serList.SelectedItem.ToString(), out AbstractSerializer ser))
     {
         AbstractPlugin plugin = null;
         object         o      = pluginsList.SelectedItem;
         if (o != null)
         {
             string pluginName = o.ToString();
             plugin = plugins[pluginName];
         }
         objects = ser.Load <List <Device> >(plugin);
         FillList();
     }
 }
Beispiel #16
0
        /// <summary>
        /// Returns a list of command info.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="listCommands"></param>
        /// <returns></returns>
        public static List <string> ListInfo(this AbstractPlugin plugin, bool listCommands)
        {
            List <string> ret = new List <string>
            {
                "Plugin Name: " + plugin.GetType().Name,
                "Plugin Namespace: " + plugin.GetType().Namespace,
                "Plugin Version: " + plugin.GetType().Assembly.GetName().Version,
                "Plugin Include Global: " + plugin.IncludeGlobal,
                "Plugin Prefixes: " + plugin.Prefix.Unpack(", ")
            };

            if (listCommands)
            {
                ret.Add("Plugin Commands:");
                ret.AddRange(ListAllCommands(plugin.Info, plugin.Prefix));
            }
            ret.Add("");
            return(ret);
        }
        public void InterpretPluginArguments(string[] pluginArgs, AbstractPlugin abstractPlugin)
        {
            var isSuccessful = Parser.Default.ParseArguments(pluginArgs, abstractPlugin, (verb, subOptions) => {
                try
                {
                    var settings = InEngineSettings.Make();
                    if (subOptions == null && (pluginArgs.Contains("-h") || pluginArgs.Contains("--help")))
                    {
                        ExitWithSuccess();
                    }
                    else if (subOptions == null)
                    {
                        ExitWithFailure("");
                    }
                    var command = subOptions as AbstractCommand;
                    if (command is AbstractCommand)
                    {
                        (command as AbstractCommand).Name = verb.Normalize();
                    }
                    if (command is IHasQueueSettings)
                    {
                        (command as IHasQueueSettings).QueueSettings = settings.Queue;
                    }
                    command.MailSettings = settings.Mail;
                    command.Run();
                    ExitWithSuccess();
                }
                catch (Exception exception)
                {
                    ExitWithFailure(exception);
                }
            });

            if (!isSuccessful)
            {
                ExitWithFailure(new CommandFailedException("Could not parse plugin arguments. Use -h, --help for usage."));
            }
        }
Beispiel #18
0
        /// <summary>
        /// Converts the Plugin to a basic markdown text that can be used to generate readmes.
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns></returns>
        public static string[] ToMarkdown(this AbstractPlugin plugin)
        {
            List <string> ret = new List <string>()
            {
                "______________________________________________",
                "#### " + plugin.GetType().Name + " Information:",
                "",
                "* Prefix: " + plugin.Prefix.Unpack(", "),
                "* Commands:",
                ""
            };

            string tab = "\t\t";

            for (int i = 0; i < plugin.Info.Count; i++)
            {
                string[] helpt = plugin.Info[i].HelpText.Split("\n");
                ret.Add(tab + plugin.Info[i].Command + "/" + plugin.Info[i].ShortCut);
                ret.Add(tab + "\t" + helpt.Unpack("\n\t" + tab));
            }

            return(ret.ToArray());
        }
Beispiel #19
0
 public abstract T Load <T>(AbstractPlugin plugin) where T : class;
        /// <summary>
        /// A commandlet represents the abstract idea of the typical IRC command represented with a start-character (!) and a string for identify. All the parsing will be done
        /// by the bot, you only get exactly the events you registered to. For example: you can register an event which is only thrown if used in a private message by certain users,
        /// or in a certain channel.
        /// </summary>
        /// <param name="command">the command string including initial charakter. like "!example" </param>
        /// <param name="helptext">A help for this certain command which should be displayed by the !help command</param>
        /// <param name="handler">The name of the method which should be called, can be private</param>
        /// <param name="plugin">this (the class where this command is provided)</param>
        public PluginCommand(string command, string helptext, EventHandler <CommandEventArgs> handler, AbstractPlugin plugin)
        {
            ExportedCommand = command;
            HelpText        = helptext;

            HandlerName  = handler.Method.Name;
            Owner        = plugin.FullName;
            SourcePlugin = plugin.FullName;
        }
Beispiel #21
0
 public PluginHost(AbstractPlugin plugin)
 {
     m_plugin     = plugin;
     m_messageBus = Locator.Current.GetService <IMessageBus>();
 }
Beispiel #22
0
        public SIMLHub() : base("SIMLHub")
        {
            bot = new SimlBot();

            // Soon it will be substracted
            adapterCount = 0;

            // Add all adapters
            pluginAdapterPathAndTypes = helper.GetAllSIMLHubPluginIndexAdapterPathAndTypes();

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write("[SIMLHub] Adapters loading : ");
            Console.ResetColor();

            simlPlugins = new List <AbstractPlugin>();

            int botAdapterCount = 0;

            foreach (var adapterPair in pluginAdapterPathAndTypes)
            {
                Assembly assembly = Assembly.LoadFrom(adapterPair.Key);

                foreach (var typename in adapterPair.Value)
                {
                    try
                    {
                        IAdapter adapter = (IAdapter)assembly.CreateInstance(typename);

                        AbstractPlugin simlHubPlugin = (AbstractPlugin)adapter;
                        simlPlugins.Add(simlHubPlugin);

                        Hub.PassThrough(simlHubPlugin.Hub);

                        // Add to bot in not null
                        if (adapter != null)
                        {
                            bot.Adapters.Add(adapter);
                            botAdapterCount++;
                        }
                    }
                    catch { /*Ignore*/ }
                }
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("success");
            Console.ResetColor();

            // Now final value is set
            adapterCount = botAdapterCount;
            Console.WriteLine("[SIMLHub] SIMLHub Plugins count: " + adapterCount);

            // Add all index.siml files
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write("[SIMLHub] Index siml merge : ");
            Console.ResetColor();

            string mergedIndexSimlPackage = helper.GetAllIndexSimlPackage();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("success");
            Console.ResetColor();


            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write("[SIMLHub] Merged index siml : ");
            Console.ResetColor();

            bot.PackageManager.LoadFromString(mergedIndexSimlPackage);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("success");
            Console.ResetColor();

            // Subscribe to IUserResponse for input
            hub.Subscribe <IUserResponse>(GenerateAndPublishBotResponse);
            hub.Subscribe <AllPluginsLoaded>(AllPluginsLoadedCallback);

            // Subscribe to IMachineMessage for processing machine generated message
            hub.Subscribe <IMachineMessage>(MakeMachineMessageUserFriendly);
        }
 public PluginLoadEventArgs(string pluginName, PluginLoadEventType pluginLoadEventType, AbstractPlugin plugin)
 {
     PluginName = pluginName;
     EventType = pluginLoadEventType;
     Plugin = plugin;
 }
Beispiel #24
0
 public static void AddPlugin(AbstractPlugin plugin)
 {
     logger.Debug("Registered plugin {0}", plugin.GetType());
     Plugins.Add(plugin);
 }
Beispiel #25
0
        private void ConfigureContainer(IProgress <string> progress)
        {
            // use single logger for whole application
            kernel.Bind <Logger>().ToSelf().InSingletonScope();
            kernel.Get <Logger>();

            Debug.WriteLine("Configuring application container...");

            kernel.Bind <ISettings, Settings>().To <Settings>().InSingletonScope();

            kernel.Bind <ISky, Sky>().To <Sky>().InSingletonScope();
            kernel.Bind <ISkyMap, SkyMap>().To <SkyMap>().InSingletonScope();

            kernel.Bind <SettingsConfig>().ToSelf().InSingletonScope();
            kernel.Bind <ToolbarButtonsConfig>().ToSelf().InSingletonScope();
            kernel.Bind <ContextMenuItemsConfig>().ToSelf().InSingletonScope();

            SettingsConfig               settingsConfig         = kernel.Get <SettingsConfig>();
            ToolbarButtonsConfig         toolbarButtonsConfig   = kernel.Get <ToolbarButtonsConfig>();
            ContextMenuItemsConfig       contextMenuItemsConfig = kernel.Get <ContextMenuItemsConfig>();
            ICollection <AbstractPlugin> plugins = new List <AbstractPlugin>();

            // TODO: consider more proper way to load plugins
            string homeFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            IEnumerable <string> pluginPaths = Directory.EnumerateFiles(homeFolder, "*.dll");

            progress.Report("Loading plugins");

            foreach (string path in pluginPaths)
            {
                try
                {
                    Assembly.LoadFrom(path);
                }
                catch (Exception ex)
                {
                    Trace.TraceError($"Unable to load plugin assembly with path {path}. {ex})");
                }
            }

            // collect all plugins implementations
            // TODO: to support plugin system, we need to load assemblies
            // from the specific directory and search for plugin there
            Type[] pluginTypes = AppDomain.CurrentDomain.GetAssemblies()
                                 .SelectMany(a => a.GetTypes())
                                 .Where(t => typeof(AbstractPlugin).IsAssignableFrom(t) && !t.IsAbstract)
                                 .ToArray();

            // collect all calculators types
            Type[] calcTypes = pluginTypes
                               .SelectMany(p => AbstractPlugin.Calculators(p))
                               .ToArray();

            foreach (Type calcType in calcTypes)
            {
                var types = new[] { calcType }.Concat(calcType.GetInterfaces()).ToArray();
                kernel.Bind(types).To(calcType).InSingletonScope();
            }

            // collect all renderers types
            Type[] rendererTypes = pluginTypes
                                   .SelectMany(p => AbstractPlugin.Renderers(p))
                                   .ToArray();

            foreach (Type rendererType in rendererTypes)
            {
                var types = new[] { rendererType }.Concat(rendererType.GetInterfaces()).ToArray();
                kernel.Bind(rendererType).ToSelf().InSingletonScope();
            }

            // collect all event provider implementations
            Type[] eventProviderTypes = pluginTypes
                                        .SelectMany(p => AbstractPlugin.AstroEventProviders(p))
                                        .ToArray();

            foreach (Type eventProviderType in eventProviderTypes)
            {
                kernel.Bind(eventProviderType).ToSelf().InSingletonScope();
            }

            foreach (Type pluginType in pluginTypes)
            {
                progress.Report($"Creating plugin {pluginType}");

                kernel.Bind(pluginType).ToSelf().InSingletonScope();
                var plugin = kernel.Get(pluginType) as AbstractPlugin;

                // add settings configurations
                settingsConfig.AddRange(plugin.SettingItems);

                // add configured toolbar buttons
                toolbarButtonsConfig.AddRange(plugin.ToolbarItems);

                // add configured context menu items
                contextMenuItemsConfig.AddRange(plugin.ContextMenuItems);

                plugins.Add(plugin);
            }

            // Default rendering order for BaseRenderer descendants.
            settingsConfig.Add(new SettingItem("RenderingOrder", new RenderingOrder(), "Rendering", typeof(RenderersListSettingControl)));

            var settings = kernel.Get <ISettings>();

            // set settings defaults
            foreach (SettingItem item in settingsConfig)
            {
                settings.Set(item.Name, item.DefaultValue);
            }

            settings.Save("Defaults");

            progress.Report($"Loading settings");

            settings.Load();

            SetLanguage(settings.Get <string>("Language"));
            SetColorSchema(settings.Get <ColorSchema>("Schema"));

            SkyContext context = new SkyContext(
                new Date(DateTime.Now).ToJulianEphemerisDay(),
                new CrdsGeographical(settings.Get <CrdsGeographical>("ObserverLocation")));

            progress.Report($"Creating calculators");

            var calculators = calcTypes
                              .Select(c => kernel.Get(c))
                              .Cast <BaseCalc>()
                              .ToArray();

            progress.Report($"Creating event providers");

            var eventProviders = eventProviderTypes
                                 .Select(c => kernel.Get(c))
                                 .Cast <BaseAstroEventsProvider>()
                                 .ToArray();

            progress.Report($"Creating renderers");

            var renderers = rendererTypes.Select(r => kernel.Get(r)).Cast <BaseRenderer>().ToArray();

            kernel.Get <Sky>().Initialize(context, calculators, eventProviders);

            kernel.Get <SkyMap>().Initialize(context, renderers);

            Debug.Write("Application container has been configured.");

            progress.Report($"Initializing shell");

            settings.SettingValueChanged += (settingName, value) =>
            {
                if (settingName == "Schema")
                {
                    SetColorSchema((ColorSchema)value);
                }
                else if (settingName == "Language")
                {
                    SetLanguage((string)value);
                }
            };
        }
Beispiel #26
0
 public abstract void Save <T>(AbstractPlugin plugin, T obj) where T : class;