public PluginManagerDialog(Window parent,
						    PluginManager
						    manager)
                : base(Catalog.GetString("Plugins"),
								   parent,
								   DialogFlags.
								   Modal,
								   Catalog.GetString("Close"),
								   ResponseType.
								   None)
            {
                SetupTree ();
                foreach (PluginInfo info in manager.Plugins)
                {
                    if (info.Plugin == null)
                      {
                          continue;
                      }
                    store.AppendValues (info);
                }

                ScrolledWindow win = new ScrolledWindow ();
                  win.HscrollbarPolicy = PolicyType.Automatic;
                  win.VscrollbarPolicy = PolicyType.Automatic;
                  win.Child = tree;
                  VBox.PackStart (win, true, true, 4);
                  SetSizeRequest (400, 400);
                  VBox.ShowAll ();
            }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            #region Discover succeed due to a compatible version

            Console.WriteLine("Discover all ISamplePlugin plugins with version > 1.0 and version < 1.9.3 ...");

            var pm = new PluginManager(Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + "SamplePlugin")
                .Register<ISamplePlugin.ISamplePlugin>(new Version(1, 0), new Version(1, 9, 3))
                    .Discover();

            var plugin = pm.GetPlugins<ISamplePlugin.ISamplePlugin>(p => p.GetType().Name == "SamplePlugin").FirstOrDefault();
            Console.WriteLine("Succeeded for: " + plugin.SampleMethod(1, ""));

            #endregion

            #region Discovering fail due to an incompatible version

            Console.WriteLine("");
            Console.WriteLine("Discover all ISamplePlugin plugins with version > 1.0 and version < 1.8 ...");

            pm = new PluginManager(Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + "SamplePlugin")
                .Register<ISamplePlugin.ISamplePlugin>(new Version(1, 0), new Version(1, 8));

            pm.OnPluginIncompatibleVersion += (sender, e) =>
            {
                Console.WriteLine("Failed: [{0}] is not between [{1}] and [{2}]", e.PluginVersion, e.MinVersion, e.MaxVersion);
            };
            pm.Discover(false); // do not throw an axception

            #endregion

            Console.ReadKey();
        }
Exemplo n.º 3
0
        public override void Initialize()
        {
            // required so we can access property.Value
            //PropertyValueConvertersResolver.Current = new PropertyValueConvertersResolver();

            base.Initialize();

            // this is so the model factory looks into the test assembly
            _pluginManager = PluginManager.Current;
            PluginManager.Current = new PluginManager(false)
            {
                AssembliesToScan = _pluginManager.AssembliesToScan
                    .Union(new[] { typeof(PublishedContentTests).Assembly })
            };

            ApplicationContext.Current = new ApplicationContext(false) { IsReady = true };

            // need to specify a custom callback for unit tests
            // AutoPublishedContentTypes generates properties automatically
            // when they are requested, but we must declare those that we
            // explicitely want to be here...

            var propertyTypes = new[]
                {
                    // AutoPublishedContentType will auto-generate other properties
                    new PublishedPropertyType("umbracoNaviHide", 0, Guid.Parse(Constants.PropertyEditors.TrueFalse)), 
                    new PublishedPropertyType("selectedNodes", 0, Guid.Empty), 
                    new PublishedPropertyType("umbracoUrlAlias", 0, Guid.Empty), 
                    new PublishedPropertyType("content", 0, Guid.Parse(Constants.PropertyEditors.TinyMCEv3)), 
                    new PublishedPropertyType("testRecursive", 0, Guid.Empty), 
                };
            var type = new AutoPublishedContentType(0, "anything", propertyTypes);
            PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
        }
Exemplo n.º 4
0
        internal static void Initialize()
        {
            if (mGlobalInstance == null)
            {
                mGlobalInstance = new PluginManager(true);
                mGlobalInstance.LoadPlugins(@"GlueView\Plugins");
            }

            if (mProjectInstance != null)
            {
                foreach (IPlugin plugin in ((PluginManager)mProjectInstance).mPluginContainers.Keys)
                {
                    ShutDownPlugin(plugin, PluginShutDownReason.GlueShutDown);
                }
            }

            mProjectInstance = new PluginManager(false);

            mInstances.Clear();
            mInstances.Add(mGlobalInstance);
            mInstances.Add(mProjectInstance);

            GluxManager.BeforeVariableSet += OnBeforeVariableSet;
            GluxManager.AfterVariableSet += OnAfterVariableSet;

            mProjectInstance.LoadPlugins(@"GlueView\Plugins");
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            TabsterEnvironment.CreateDirectories();

            // prepare logging
            var logDirectory = TabsterEnvironment.CreateEnvironmentDirectoryPath(TabsterEnvironmentDirectory.ApplicatonData, "Logs");
            Logging.SetLogDirectory(logDirectory);

            // log all the errors
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                var ex = (Exception) e.ExceptionObject;
                Logging.GetLogger().Error(ex);
            };

            _pluginManager = new PluginManager(TabsterEnvironment.CreateEnvironmentDirectoryPath(TabsterEnvironmentDirectory.ApplicatonData, "Plugins"));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var assemblyGuid = ((GuidAttribute) Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (GuidAttribute), true)[0]).Value;
            var filename = Path.Combine(TabsterEnvironment.GetEnvironmentDirectoryPath(TabsterEnvironmentDirectory.ApplicatonData), string.Format("{0}.tmp", assemblyGuid));

            using (var instanceController = new TabsterSingleInstanceController(filename))
            {
                instanceController.Start(new ReadOnlyCollection<string>(args));
            }
        }
Exemplo n.º 6
0
 public MessagePump(PluginManager plugins, ArrayList connections)
 {
     this._run = false;
     this._plugins = plugins;
     this.set_processors();
     this._connections = connections;
     this._run_lock = new object();
 }
Exemplo n.º 7
0
 public void LoadValidDataReaderPlugin()
 {
     using (var pluginManager = new PluginManager(_pluginsDirectory))
     {
         pluginManager.DeployPluginAsync(_pluginAssemblyPath).Wait();
         Assert.AreEqual(1, pluginManager.Plugins.Count());
     }
 }
        public void Load_WhenThePluginExists_ReturnPluginInstance()
        {
            var pluginManager = new PluginManager(_addInRootPath);

            ICalculatorPlugin calculatorPlugin = pluginManager.Load<ICalculatorPlugin>();

            Assert.NotNull(calculatorPlugin);
        }
Exemplo n.º 9
0
        public static void CallCodeGenerationStart(PluginManager pluginManager, IElement element)
        {
            foreach (ICodeGeneratorPlugin plugin in pluginManager.CodeGeneratorPlugins)
            {
                plugin.CodeGenerationStart(element);

            }
        }
Exemplo n.º 10
0
 public static void GenerateAdditionalMethodsPluginCode(PluginManager pluginManager,
     ICodeBlock codeBlock, IElement element)
 {
     foreach (ComponentPluginPair cpp in GetPluginsIn(pluginManager))
     {
         GenerateWithException(cpp.Generator.GenerateAdditionalMethods, codeBlock, element, cpp.Plugin, pluginManager);
     }
 }
        public void Load_WhenTheTypeIsSpecified_ItIsLoaded()
        {
            var pluginManager = new PluginManager(AppDomain.CurrentDomain.BaseDirectory);

            FakeCalculatorPlugin fakePlugin = pluginManager.Load<FakeCalculatorPlugin>();

            Assert.NotNull(fakePlugin);
        }
        public void IsLoaded_WhenPluginIsLoaded_ReturnsTrue()
        {
            var pluginManager = new PluginManager(_addInRootPath);

            ICalculatorPlugin calculatorPlugin = pluginManager.Load<ICalculatorPlugin>();

            Assert.True(pluginManager.IsLoaded<ICalculatorPlugin>());
        }
Exemplo n.º 13
0
 public void Init()
 {
     LayoutBuilder = new DefaultLayoutBuilder();
     RenderManager = new RenderManager(LayoutBuilder);
     PluginManager = new PluginManager(RenderManager, LayoutBuilder);
     AmbilightManager = new AmbilightManager(RenderManager, LayoutBuilder);
     PowerManager = new PowerManager(RenderManager);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ContextMenuBuilder"/> class.
        /// </summary>
        /// <param name="pluginManager">The plugin manager. This can be found on MainWindow.</param>
        /// <param name="mainWindow">The main window command interface. This can be found on mainwindow.</param>
        public ContextMenuBuilder(PluginManager pluginManager, IMainWindow mainWindow)
        {
            Util.ThrowIfParameterNull(pluginManager, "pluginManager");
            Util.ThrowIfParameterNull(pluginManager, "mainWindow");

            _pluginManager = pluginManager;
            _mainWindow = mainWindow;
        }
Exemplo n.º 15
0
        public static void GenerateActivityPluginCode(CodeLocation codeLocation, PluginManager pluginManager,
            ICodeBlock codeBlock, IElement element)
        {

            foreach (ComponentPluginPair cpp in GetPluginsIn(pluginManager, codeLocation))
            {
                GenerateWithException(cpp.Generator.GenerateActivity, codeBlock, element, cpp.Plugin, pluginManager);
            }
        }
Exemplo n.º 16
0
        public override void InitPlugin(PluginManager manager)
        {
            base.InitPlugin(manager);

            manager.MovieScraper.PreMovieInfoScrape += PreMovieInfoScraperAction;
            manager.MovieScraper.PostMovieInfoScrape += PostMovieInfoScraperAction;
            manager.MovieScraper.PreMovieImageScrape += PreMovieImageScraperAction;
            manager.MovieScraper.PostMovieImageScrape += PostMovieImageScraperAction;
        }
        public void Load_WhenTheSamePluginIsLoadedTwice_TheSameInstanceIsReturned()
        {
            var pluginManager = new PluginManager(AppDomain.CurrentDomain.BaseDirectory);

            FakeCalculatorPlugin firstLoad = pluginManager.Load<FakeCalculatorPlugin>();
            FakeCalculatorPlugin secondLoad = pluginManager.Load<FakeCalculatorPlugin>();

            Assert.Equal(firstLoad, secondLoad);
        }
Exemplo n.º 18
0
        public void Configure_throw_argument_null()
        {
            var loaderMock = new Mock<IPluginLoader>();
            var target = new PluginManager(loaderMock.Object);

            Action init2 = () =>target.Configure(null);

            Assert.Throws<ArgumentNullException>("applicationBuilder", init2);
        }
Exemplo n.º 19
0
        public void Configure_need_ConfigureServicesBefore()
        {
            var loaderMock = new Mock<IPluginLoader>();
            var target = new PluginManager(loaderMock.Object);

            Action init2 = () =>target.Configure(new Mock<IApplicationBuilder>().Object);

            Assert.Throws<InvalidOperationException>(init2);
        }
Exemplo n.º 20
0
 public bool Load(PluginManager manager)
 {
     SysConsole.OutputCustom(OutputType, "Hello world!");
     Manager = manager;
     // Set up
     manager.TheServer.Commands.CommandSystem.RegisterCommand(new GreetingCommand(this));
     manager.TheServer.OnWorldLoadPostEvent.Add(ReactToRegionLoadedTWO, 1);
     manager.TheServer.OnWorldLoadPostEvent.Add(ReactToRegionLoaded, 0);
     return true;
 }
        public void Load_WhenTwoVersionsOfThePluginAreLoaded_OperationIsSuccessfull()
        {
            var pluginManager = new PluginManager(AppDomain.CurrentDomain.BaseDirectory);

            FakeCalculatorPlugin plugin = pluginManager.Load<FakeCalculatorPlugin>();
            FakeAnotherCalculatorPlugin anotherPlugin = pluginManager.Load<FakeAnotherCalculatorPlugin>();

            Assert.NotNull(plugin);
            Assert.NotNull(anotherPlugin);
        }
Exemplo n.º 22
0
        public void LoadedPlugins_ReturnEmpty_IfNotCallLoad()
        {
            var loaderMock = new Mock<IPluginLoader>();
            var target = new PluginManager(loaderMock.Object);

            var result = target.LoadedPlugins;

            Assert.NotNull(result);
            Assert.Empty(result);
        }
Exemplo n.º 23
0
        public void Run()
        {
            string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            PluginManager<IUpdatePlugin> plugins = new PluginManager<IUpdatePlugin>(dir);
            plugins.Load(new object[] { });

            foreach (IUpdatePlugin plugin in plugins.Plugins)
                plugin.Run();

            plugins.Unload();
        }
Exemplo n.º 24
0
        public Render(Ox ox)
            : base(ox)
        {
            Priority = (int)PriorityBase.Render -1;

            new Collision(Ox);
            plugins = new PluginManager<IOxRenderComponentPlugin>(Ox.Paths.Application);
            plugins.Load(new object[] { Ox, this });

            Ox.OnEvent += new OxEventHandler(Ox_OnEvent);
        }
Exemplo n.º 25
0
 public static void LogObject(PluginManager.MessageType messageType, object myObject)
 {
     string myObjectDetails = "";
     foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(myObject))
     {
         string name = descriptor.Name;
         object value = descriptor.GetValue(myObject);
         myObjectDetails += name + ": " + value + "\n";
     }
     Debug.Log(messageType + " | " + prefix + " | " +myObjectDetails);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Initialises the plugin.
        /// </summary>
        /// <param name="manager">The plugin manager.</param>
        public virtual void InitPlugin(PluginManager manager)
        {
            this.manager = manager;

            #if DEBUG
            if (log.IsDebugEnabled)
                log.Debug(string.Format(
                    "InitPlugin :: Assembly = {0}; Name = {1}; Version = {2}",
                    AssemblyName, Name, Version));
            #endif
        }
        public void Load_WhenThePluginIsSpecified_IsIsLoadedIntoDifferentApplicationDomain()
        {
            var pluginManager = new PluginManager(AppDomain.CurrentDomain.BaseDirectory);

            FakeCalculatorPlugin fakePlugin = pluginManager.Load<FakeCalculatorPlugin>();

            string currentDomainName = AppDomain.CurrentDomain.FriendlyName;
            _testOutputHelper.WriteLine("Current Domain: {0}", currentDomainName);
            _testOutputHelper.WriteLine("Plugin Domain: {0}", fakePlugin.AppDomainName);
            Assert.NotEqual(currentDomainName, fakePlugin.AppDomainName);
        }
Exemplo n.º 28
0
        public void Should_Get_Plugin_By_PluginIndentifier()
        {
            IPluginManager        pluginManager    = new PluginManager();
            IAllocationDefinition definition       = ConvertToDefinition(_DB.PluginInfo_GetAll(), 2);
            string                pluginIdentifier = "1.0.0.0, Geckon.Octopus.Plugins.TestPlugin.TestPlugin";

            pluginManager.Install( definition );

            IPlugin plugin = pluginManager.GetPlugin<IPlugin>( pluginIdentifier );

            Assert.IsNotNull( plugin );
        }
Exemplo n.º 29
0
        public MessageProcessor(PluginManager pluginManager, ILogger logger)
        {
            _logger = logger;

            pluginManager.Compose(this, logger);

            _logger.Write($"Found {HandlerInstances.Count} message handlers:");
            foreach (var messageHandler in HandlerInstances)
            {
                _logger.WriteIndented($"{messageHandler.GetType().Name} ({string.Join(", ", messageHandler.Commands)})");
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// 初始化核心
        /// </summary>
        public static void Initialize()
        {
            StartupPath = System.Environment.CurrentDirectory;
            LogManager = new LogManager();
            ConfigManager = new ConfigManager();
            ConfigManager.LoadSettings();
            PluginManager = new PluginManager();
            TaskManager = new TaskManager();

            TaskManager.LoadAllTasks();
            //XmlConfigurator.Configure(new FileInfo(Path.Combine(StartupPath, "LogConfig.xml")));
        }
Exemplo n.º 31
0
 public GraphController(Neo4jService service, PluginManager pluginmanager, ILogger <GraphController> logger)
 {
     this._service       = service;
     this._pluginmanager = pluginmanager;
     this._logger        = logger;
 }
Exemplo n.º 32
0
        protected override bool IsLoaded(string filePath)
        {
            var absolutePath = _stateInfo.AbsoluteDirectory / _stateInfo.FilePath / filePath;

            return(PluginManager.IsLoaded(absolutePath));
        }
Exemplo n.º 33
0
        public override void HandleAddedToManager(PluginManager manager)
        {
            foreach (var field in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                var attributes = field.GetCustomAttributes(typeof(OnlinePlayersAttribute), true);
                if (attributes.Length > 0)
                {
                    var plugin_field = new PluginFieldInfo(this, field);
                    if (plugin_field.GenericArguments.Length != 2 || plugin_field.GenericArguments[0] != typeof(NetUser))
                    {
                        Puts("The {0} field is not a Hash with a NetUser key! (online players will not be tracked)", field.Name);
                        continue;
                    }
                    if (!plugin_field.LookupMethod("Add", plugin_field.GenericArguments))
                    {
                        Puts("The {0} field does not support adding NetUser keys! (online players will not be tracked)", field.Name);
                        continue;
                    }
                    if (!plugin_field.LookupMethod("Remove", typeof(NetUser)))
                    {
                        Puts("The {0} field does not support removing NetUser keys! (online players will not be tracked)", field.Name);
                        continue;
                    }
                    if (plugin_field.GenericArguments[1].GetField("Player") == null)
                    {
                        Puts("The {0} class does not have a public Player field! (online players will not be tracked)", plugin_field.GenericArguments[1].Name);
                        continue;
                    }
                    onlinePlayerFields.Add(plugin_field);
                }
            }

            foreach (var method in GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                var attributes = method.GetCustomAttributes(typeof(ConsoleCommandAttribute), true);
                if (attributes.Length > 0)
                {
                    var attribute = attributes[0] as ConsoleCommandAttribute;
                    if (attribute != null)
                    {
                        cmd.AddConsoleCommand(attribute.Command, this, method.Name);
                    }
                    continue;
                }

                attributes = method.GetCustomAttributes(typeof(ChatCommandAttribute), true);
                if (attributes.Length > 0)
                {
                    var attribute = attributes[0] as ChatCommandAttribute;
                    if (attribute != null)
                    {
                        cmd.AddChatCommand(attribute.Command, this, method.Name);
                    }
                }
            }

            if (onlinePlayerFields.Count > 0)
            {
                foreach (var playerClient in PlayerClient.All)
                {
                    AddOnlinePlayer(playerClient.netUser);
                }
            }

            base.HandleAddedToManager(manager);
        }
Exemplo n.º 34
0
 /// <summary>
 /// Uninstall plugin
 /// </summary>
 public override void Uninstall()
 {
     _context.Uninstall();
     PluginManager.MarkPluginAsUninstalled(this.PluginDescriptor.SystemName);
     base.Uninstall();
 }
Exemplo n.º 35
0
 private void Refresh()
 {
     PluginManager.ReloadData();
 }
Exemplo n.º 36
0
 public ExportService()
 {
     _plugins = PluginManager.GetPlugins <IFileExporter>();
 }
Exemplo n.º 37
0
 private void ReloadPluginsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     PluginManager.RefreshPlugins(this.pluginContainer, this.RefreshPluginsPostProcessing);
 }
Exemplo n.º 38
0
    public BlessMain(string[] args)
    {
        Application.Init();

        //
        Catalog.Init(ConfigureDefines.GETTEXT_PACKAGE, ConfigureDefines.LOCALE_DIR);

        // load main window from glade XML
        Glade.XML gxml = new Glade.XML(FileResourcePath.GetDataPath("bless.glade"), "MainWindow", "bless");
        gxml.Autoconnect(this);

        // set the application icon
        MainWindow.Icon = new Gdk.Pixbuf(FileResourcePath.GetDataPath("bless-48x48.png"));

        string blessConfDir = FileResourcePath.GetUserPath();

        // make sure local configuration directory exists
        try {
            if (!Directory.Exists(blessConfDir))
            {
                Directory.CreateDirectory(blessConfDir);
            }
        }
        catch (Exception ex) {
            ErrorAlert ea = new ErrorAlert(Catalog.GetString("Cannot create user configuration directory"), ex.Message + Catalog.GetString("\n\nSome features of Bless may not work properly."), MainWindow);
            ea.Run();
            ea.Destroy();
        }

        Preferences.Proxy.Enable = false;
        // load default preferences
        Preferences.Default.Load(FileResourcePath.GetDataPath("default-preferences.xml"));
        Preferences.Default["Default.Layout.File"] = FileResourcePath.GetDataPath("bless-default.layout");

        // load user preferences
        LoadPreferences(Path.Combine(blessConfDir, "preferences.xml"));
        Preferences.Instance.AutoSavePath = Path.Combine(blessConfDir, "preferences.xml");

        // add the (empty) Menubar and toolbar
        uiManager = new UIManager();
        MainWindow.AddAccelGroup(uiManager.AccelGroup);
        uiManager.AddUiFromString(uiXml);

        ActionGroup group = new ActionGroup("MainMenuActions");

        group.Add(actionEntries);
        group.Add(new ToggleActionEntry[] {
            new ToggleActionEntry("ToolbarAction", null, "Toolbar", null, null,
                                  new EventHandler(OnViewToolbarToggled), false)
        });

        uiManager.InsertActionGroup(group, 0);

        Widget mb = uiManager.GetWidget("/menubar");

        MainVBox.PackStart(mb, false, false, 0);
        MainVBox.ReorderChild(mb, 0);
        Widget tb = uiManager.GetWidget("/toolbar");

        tb.Visible = false;
        MainVBox.PackStart(tb, false, false, 0);
        MainVBox.ReorderChild(tb, 1);

        // create the DataBook
        dataBook             = new DataBook();
        dataBook.PageAdded  += new DataView.DataViewEventHandler(OnDataViewAdded);
        dataBook.Removed    += new RemovedHandler(OnDataViewRemoved);
        dataBook.SwitchPage += new SwitchPageHandler(OnSwitchPage);

        DataViewBox.PackStart(dataBook);


        // create the widget groups that hold utility widgets
        WidgetGroup widgetGroup0     = new WidgetGroup();
        WidgetGroup widgetGroup1     = new WidgetGroup();
        WidgetGroup sideWidgetGroup0 = new WidgetGroup();
        WidgetGroup sideWidgetGroup1 = new WidgetGroup();

        widgetGroup0.Show();
        widgetGroup1.Show();
        sideWidgetGroup0.Show();
        sideWidgetGroup1.Show();

        MainVBox.PackStart(widgetGroup0, false, false, 0);
        MainVBox.ReorderChild(widgetGroup0, 3);
        MainVBox.PackStart(widgetGroup1, false, false, 0);
        MainVBox.ReorderChild(widgetGroup1, 4);

        DataViewBox.PackStart(sideWidgetGroup0, false, false, 0);
        DataViewBox.ReorderChild(sideWidgetGroup0, 0);
        DataViewBox.PackEnd(sideWidgetGroup1, false, false, 0);
        //MainVBox.ReorderChild(widgetGroup1, 4);


        Services.File    = new FileService(dataBook, MainWindow);
        Services.Session = new SessionService(dataBook, MainWindow);
        Services.UI      = new UIService(uiManager);
        //Services.Info=new InfoService(infobar);

        // Add area plugins
        PluginManager.AddForType(typeof(AreaPlugin), new object[0]);
        PluginManager areaPlugins = PluginManager.GetForType(typeof(AreaPlugin));

        foreach (AreaPlugin p in areaPlugins.Plugins)
        {
            Area.AddFactoryItem(p.Name, p.CreateArea);
        }

        // Load GUI plugins
        PluginManager.AddForType(typeof(GuiPlugin), new object[] { MainWindow, uiManager });
        PluginManager guiPlugins = PluginManager.GetForType(typeof(GuiPlugin));

        foreach (Plugin p in guiPlugins.Plugins)
        {
            guiPlugins.LoadPlugin(p);
        }

        // load recent file history
        try {
            History.Instance.Load(Path.Combine(blessConfDir, "history.xml"));
        }
        catch (Exception e) {
            System.Console.WriteLine(e.Message);
        }

        // if user specified files on the command line
        // try to load them
        if (args.Length > 0)
        {
            Services.File.LoadFiles(args);
        }
        else if (Preferences.Instance["Session.LoadPrevious"] == "True")
        {
            bool   loadIt          = true;
            string prevSessionFile = Path.Combine(blessConfDir, "last.session");

            if (Preferences.Instance["Session.AskBeforeLoading"] == "True" &&
                File.Exists(prevSessionFile))
            {
                MessageDialog md = new MessageDialog(MainWindow,
                                                     DialogFlags.DestroyWithParent,
                                                     MessageType.Question,
                                                     ButtonsType.YesNo, Catalog.GetString("Do you want to load your previous session?"));

                ResponseType result = (ResponseType)md.Run();
                md.Destroy();

                if (result == ResponseType.Yes)
                {
                    loadIt = true;
                }
                else
                {
                    loadIt = false;
                }
            }
            // try to load previous session
            if (loadIt)
            {
                Services.Session.Load(prevSessionFile);
            }
        }

        // if nothing has been loaded, create a new file
        if (dataBook.NPages == 0)
        {
            ByteBuffer bb = Services.File.NewFile();

            // create and setup a  DataView
            DataView dv = Services.File.CreateDataView(bb);

            // append the DataView to the DataBook
            dataBook.AppendView(dv, new CloseViewDelegate(Services.File.CloseFile), Path.GetFileName(bb.Filename));
        }

        PreferencesChangedHandler handler = new PreferencesChangedHandler(OnPreferencesChanged);

        Preferences.Proxy.Subscribe("View.Toolbar.Show", "mainwin", handler);


        // register drag and drop of files
        MainWindow.DragDataReceived += OnDragDataReceived;
        Gtk.Drag.DestSet(MainWindow, DestDefaults.Motion | DestDefaults.Drop, dropTargets, Gdk.DragAction.Copy | Gdk.DragAction.Move);

        DataViewBox.ShowAll();

        Preferences.Proxy.Enable = true;
        // fire the preferences changed event
        // so things are setup according to the preferences
        Preferences.Proxy.NotifyAll();

        Application.Run();
    }
 public VisualizerController(PluginManager plugman)
 {
     this._plugingmanager = plugman;
 }
Exemplo n.º 40
0
        private void QueryResults()
        {
            if (_updateSource != null && !_updateSource.IsCancellationRequested)
            {
                // first condition used for init run
                // second condition used when task has already been canceled in last turn
                _updateSource.Cancel();
                Logger.WoxDebug($"cancel init {_updateSource.Token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId} {QueryText}");
                _updateSource.Dispose();
            }
            var source = new CancellationTokenSource();

            _updateSource = source;
            var token = source.Token;

            ProgressBarVisibility = Visibility.Hidden;

            var queryText = QueryText.Trim();

            Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(queryText))
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    var query  = QueryBuilder.Build(queryText, PluginManager.NonGlobalPlugins);
                    _lastQuery = query;
                    if (query != null)
                    {
                        // handle the exclusiveness of plugin using action keyword
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        Task.Delay(200, token).ContinueWith(_ =>
                        {
                            Logger.WoxTrace($"progressbar visible 1 {token.GetHashCode()} {token.IsCancellationRequested}  {Thread.CurrentThread.ManagedThreadId}  {query} {ProgressBarVisibility}");
                            // start the progress bar if query takes more than 200 ms
                            if (!token.IsCancellationRequested)
                            {
                                ProgressBarVisibility = Visibility.Visible;
                            }
                        }, token);


                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        var plugins = PluginManager.AllPlugins;

                        var option = new ParallelOptions()
                        {
                            CancellationToken = token,
                        };
                        CountdownEvent countdown = new CountdownEvent(plugins.Count);

                        foreach (var plugin in plugins)
                        {
                            Task.Run(() =>
                            {
                                if (token.IsCancellationRequested)
                                {
                                    Logger.WoxTrace($"canceled {token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId}  {queryText} {plugin.Metadata.Name}");
                                    countdown.Signal();
                                    return;
                                }
                                var results = PluginManager.QueryForPlugin(plugin, query);
                                if (token.IsCancellationRequested)
                                {
                                    Logger.WoxTrace($"canceled {token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId}  {queryText} {plugin.Metadata.Name}");
                                    countdown.Signal();
                                    return;
                                }

                                _resultsQueue.Add(new ResultsForUpdate(results, plugin.Metadata, query, token, countdown));
                            }, token).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
                        }

                        Task.Run(() =>
                        {
                            Logger.WoxTrace($"progressbar visible 2 {token.GetHashCode()} {token.IsCancellationRequested}  {Thread.CurrentThread.ManagedThreadId}  {query} {ProgressBarVisibility}");
                            // wait all plugins has been processed
                            try
                            {
                                countdown.Wait(token);
                            }
                            catch (OperationCanceledException)
                            {
                                // todo: why we need hidden here and why progress bar is not working
                                ProgressBarVisibility = Visibility.Hidden;
                                return;
                            }
                            if (!token.IsCancellationRequested)
                            {
                                // used to cancel previous progress bar visible task
                                source.Cancel();
                                source.Dispose();
                                // update to hidden if this is still the current query
                                ProgressBarVisibility = Visibility.Hidden;
                            }
                        });
                    }
                }
                else
                {
                    Results.Clear();
                    Results.Visbility = Visibility.Collapsed;
                }
            }, token).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
        }
Exemplo n.º 41
0
 protected override bool IsLoaded(string filePath)
 {
     return(PluginManager.IsLoaded(filePath));
 }
Exemplo n.º 42
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //screw this app insights
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;

            services.AddApplicationInsightsTelemetry(aiOptions);


            //asp.net core mvc creates an instance of this class
            //so there is no need to make singleton

            //LoggerFactory service
            _loggerFactory.AddDebug();

            //kendo UI
            //services.AddKendo;

            //Themeable Razor View Engine
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ThemeableViewLocationExpander());
            });

            //init plugins
            var mvcCoreBuilder = services.AddMvc();

            //services.AddMvcCore();
            PluginManager.Initialize(mvcCoreBuilder.PartManager);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

            //ctl make it from appSettings.json
            var config = new GrandConfig();

            //register autofac dependencies
            var autofacServiceProvider = this.RegisterDependencies(services, config);

            //register mapper configurations
            this.RegisterMapperConfiguration(config);

            //startup tasks
            if (false)//!config.IgnoreStartupTasks)
            {
                this.RunStartupTasks();
            }

            //Install-Package System.Net.Http.WinHttpHandler -Version 4.3.1
            WinHttpHandler httpHandler = new WinHttpHandler()
            {
                SslProtocols = SslProtocols.Tls12
            };
            HttpClient client = new HttpClient(httpHandler);

            //new
            //return new AutofacServiceProvider(applicationContainer);
            //return autofacServiceProvider;
            //previous
            return(autofacServiceProvider);
        }
Exemplo n.º 43
0
        public MainWindow()
        {
#if !DEBUG
            //     try
            {
#endif
            InitializeComponent();
            MainDescription.MainFrm = this;
            this.notifier           = new Notifier(cfg =>
            {
                cfg.PositionProvider = new WindowPositionProvider(
                    parentWindow: Application.Current.MainWindow,
                    corner: Corner.TopRight,
                    offsetX: 10,
                    offsetY: 10);

                cfg.LifetimeSupervisor = new TimeAndCountBasedLifetimeSupervisor(
                    notificationLifetime: TimeSpan.FromSeconds(3),
                    maximumNotificationCount: MaximumNotificationCount.FromCount(5));

                cfg.Dispatcher = Application.Current.Dispatcher;
            });

            Application.Current.Resources["ThemeDictionary"] = new ResourceDictionary();
            //   this.SetCurrentTheme("ShinyBlue");
            ;
            if (ConfigurationManager.AppSettings["PluginLocationRelative"] == "true")
            {
                pluginPosition = MainStartUpLocation
                                 + ConfigurationManager.AppSettings["MainPluginLocation"];
            }
            else
            {
                pluginPosition = ConfigurationManager.AppSettings["MainPluginLocation"];
            }

            XmlConfigurator.Configure(new FileInfo("log4net.config"));


            string icon = ConfigurationManager.AppSettings["Icon"];
            try
            {
                Icon = new BitmapImage(new Uri(pluginPosition + icon, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                XLogSys.Print.Error(Core.Properties.Resources.IconNotExist);
            }

            PluginManager = new PluginManager();
#if !DEBUG
            Dispatcher.UnhandledException += (s, e) =>
            {
                if (MessageBox.Show("是否保存当前工程的内容?您只有一次机会这样做,", "Hawk由于内部异常而崩溃", MessageBoxButton.YesNoCancel) ==
                    MessageBoxResult.Yes)
                {
                    dynamic process = PluginDictionary["模块管理"];
                    process.SaveCurrentTasks();
                }

                MessageBox.Show("系统出现异常" + e.Exception);
                XLogSys.Print.Fatal(e.Exception);
            };
#endif
            ViewDictionary = new List <ViewItem>();
            Title          = ConfigurationManager.AppSettings["Title"];

            //    this.myDebugSystemUI.MainFrmUI = this;
            PluginManager.MainFrmUI = this;

            //  this.myDebugSystemUI.Init();

            PluginManager.Init(new[] { MainStartUpLocation });
            PluginManager.LoadPlugins();
            PluginManager.LoadView();

            DataContext = this;
            foreach (ICommand action in CommandCollection.Concat(Commands))
            {
                SetCommandKeyBinding(action);
            }
            XLogSys.Print.Info(Title + Core.Properties.Resources.Start);


            Closing += (s, e) =>
            {
                List <IDataProcess> revisedTasks;
                var processmanager = PluginDictionary["模块管理"] as DataProcessManager;
                revisedTasks = processmanager.GetRevisedTasks().ToList();
                if (!revisedTasks.Any())
                {
                    if (MessageBox.Show(Core.Properties.Resources.Closing, Core.Properties.Resources.Tips, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        PluginManager.Close();
                        PluginManager.SaveConfigFile();
                        Process.GetCurrentProcess().Kill();
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
                else
                {
                    var result =
                        MessageBox.Show(
                            $"【{" ".Join(revisedTasks.Select(d => d.Name).ToArray())}】任务可能还没有保存,\n【是】:保存任务并退出, \n【否】:不保存退出,\n【取消】:取消退出", Core.Properties.Resources.Tips,
                            MessageBoxButton.YesNoCancel);
                    if (result == MessageBoxResult.Yes || result == MessageBoxResult.No)
                    {
                        if (result == MessageBoxResult.Yes)
                        {
                            revisedTasks.Execute(d => processmanager.SaveTask(d, false));
                        }
                        PluginManager.Close();
                        PluginManager.SaveConfigFile();
                        Process.GetCurrentProcess().Kill();
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
            };
            //  TestCode();
#if !DEBUG
        }

        // catch (Exception ex)
        {
            //   MessageBox.Show(ex.ToString());
        }
#endif
        }
Exemplo n.º 44
0
 protected override Task <LoadResult> LoadFileInternal(string filePath, Guid pluginId)
 {
     return(pluginId == Guid.Empty ?
            PluginManager.LoadFile(filePath) :
            PluginManager.LoadFile(filePath, pluginId));
 }
Exemplo n.º 45
0
        public static string GetNodeTreeLastImageHtml(SiteInfo siteInfo, ChannelInfo nodeInfo)
        {
            var imageHtml = string.Empty;

            if (nodeInfo.ParentId == 0)
            {
                var treeDirectoryUrl = SiteServerAssets.GetIconUrl("tree");
                if (siteInfo.IsRoot == false)
                {
                    imageHtml =
                        $@"<img align=""absmiddle"" title=""站点"" border=""0"" src=""{PageUtils.Combine(treeDirectoryUrl,
                            "site.gif")}"" />&nbsp;";
                }
                else
                {
                    imageHtml =
                        $@"<img align=""absmiddle"" title=""站点"" border=""0"" src=""{PageUtils.Combine(treeDirectoryUrl,
                            "siteHQ.gif")}"" />&nbsp;";
                }
            }
            if (!string.IsNullOrEmpty(nodeInfo.ContentRelatedPluginIds))
            {
                foreach (var service in PluginContentManager.GetContentPlugins(nodeInfo, false))
                {
                    var iconClass = PluginMenuManager.GetPluginIconClass(service.PluginId);
                    if (!string.IsNullOrEmpty(iconClass))
                    {
                        imageHtml +=
                            $@"<i class=""{iconClass}"" title=""{service.Metadata.Title}"" style=""color: #00b19d;display: inline-block;font-size: 18px;vertical-align: middle;width: 16px;""></i>";
                    }
                    else
                    {
                        imageHtml +=
                            $@"<img align=""absmiddle"" title=""{service.Metadata.Title}"" border=""0"" src=""{PluginManager.GetPluginIconUrl(service)}"" width=""18"" height=""18"" />";
                    }
                }
            }
            return(imageHtml);
        }
Exemplo n.º 46
0
 /// <summary>
 /// Uninstall plugin
 /// </summary>
 public virtual void Uninstall()
 {
     PluginManager.MarkPluginAsUninstalled(this.PluginDescriptor.SystemName);
 }
Exemplo n.º 47
0
        public void UpdateAvailableTsxFiles()
        {
            /////////// Early Out //////////////

            if (GlueState.Self.CurrentElement == null)
            {
                return;
            }

            //////////End Early Out ////////////

            AppState.Self.ProvidedContext.AvailableTsxFiles.Clear();

            List <string> foundFiles = new List <string>();

            var tmxFiles =
                GlueState.Self.CurrentElement.ReferencedFiles
                .Where(item => IsTmx(item))
                .ToList();

            foreach (var rfs in tmxFiles)
            {
                string fullFile = FlatRedBall.Glue.ProjectManager.MakeAbsolute(GetTsxFileFor(rfs), true);


                if (System.IO.File.Exists(fullFile))
                {
                    TiledMapSave tms          = null;
                    string       tmxDirectory = FileManager.GetDirectory(fullFile);

                    bool succeeded = true;

                    try
                    {
                        tms = TiledMapSave.FromFile(fullFile);
                    }
                    catch (Exception e)
                    {
                        var exception = e;

                        if (e.InnerException != null && e.InnerException is FileNotFoundException)
                        {
                            exception = e.InnerException;
                        }

                        PluginManager.ReceiveError("Error trying to load " + GetTsxFileFor(rfs) + ":\n" + exception.ToString());
                        succeeded = false;
                    }

                    if (succeeded)
                    {
                        foreach (var tileset in tms.Tilesets.Where(item => !string.IsNullOrEmpty(item.Source)))
                        {
                            string absoluteSource = tmxDirectory + tileset.Source;

                            absoluteSource = FileManager.RemoveDotDotSlash(absoluteSource);

                            foundFiles.Add(absoluteSource);
                        }
                    }
                }
            }



            AppState.Self.ProvidedContext.AvailableTsxFiles.AddRange(foundFiles.Distinct(StringComparer.InvariantCultureIgnoreCase));
        }
Exemplo n.º 48
0
 public void Disposing(GameApp app, PluginManager pluginManager)
 {
 }
Exemplo n.º 49
0
 public void Configuration(IAppBuilder app)
 {
     PluginManager.LoadPlugins(HostingEnvironment.ApplicationPhysicalPath);
     GlobalConfiguration.Configure(WebApiConfig.Register);
 }
Exemplo n.º 50
0
        public async Task BotInfoAsync()
        {
            string deltaLogo = @"           ____
          /    \
         /      \
        /  _     \
       /  / \     \
      /  /   \     \
     /  /     \     \
    /  /       \     \
   /  /         \     \
  /  /           \     \
 /  /             \     \
/  /_______________\     \
\________________________/";
            var    vernum    = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
            var    app       = await Context.Client.GetApplicationInfoAsync();

            await ReplyAsync($"```\n{deltaLogo} DeltaCORE\n\n/========General Info========\\ \nVersion {vernum}\nOwned by {app.Owner}\nBuilt With Discord.NET version {DiscordConfig.Version}\nRunning on {RuntimeInformation.FrameworkDescription} {RuntimeInformation.ProcessArchitecture} On {RuntimeInformation.OSDescription} {RuntimeInformation.OSArchitecture}\n\n/========Stats========\\ \nHeap Size: {GetHeapSize()}MiB\nGuilds Connected: {Context.Client.Guilds.Count}\nChannels: {Context.Client.Guilds.Sum(g => g.Channels.Count)}\nUsers: {Context.Client.Guilds.Sum(g => g.Users.Count)}\nUptime: {GetUptime()}\nPlugin Number: {PluginManager.PluginList.Count()}\nPlugins Installed:\n{PluginManager.GetPluginList()}\n```");
        }
 public Task ReloadAllPluginData() => PluginManager.ReloadData();
 private void InitXamarinPlugins(CordovaWebView webView, PluginManager pluginManager)
 {
     pluginManager.AddService(new XamarinCordovaPluginEntry <SamplePlugin>("Sample", webView, this));
 }
 public void AddActionKeyword(string pluginId, string newActionKeyword) =>
 PluginManager.AddActionKeyword(pluginId, newActionKeyword);
Exemplo n.º 54
0
 public override ISettingsProvider GetSettingsProvider(PluginManager manager)
 {
     return(SettingsProvider.Open("/settings.json", manager));
 }
Exemplo n.º 55
0
        private async void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                if (HearthStatsManager.SyncInProgress && !_closeAnyway)
                {
                    e.Cancel = true;
                    var result =
                        await
                        this.ShowMessageAsync("WARNING! Sync with HearthStats in progress!",
                                              "Closing Hearthstone Deck Tracker now can cause data inconsistencies. Are you sure?",
                                              MessageDialogStyle.AffirmativeAndNegative,
                                              new MetroDialogSettings
                    {
                        AffirmativeButtonText = "close anyway",
                        NegativeButtonText    = "wait"
                    });

                    if (result == MessageDialogResult.Negative)
                    {
                        while (HearthStatsManager.SyncInProgress)
                        {
                            await Task.Delay(100);
                        }
                        await this.ShowMessage("Sync is complete.", "You can close Hearthstone Deck Tracker now.");
                    }
                    else
                    {
                        _closeAnyway = true;
                        Close();
                    }
                }
                Core.UpdateOverlay = false;
                Core.Update        = false;

                //wait for update to finish, might otherwise crash when overlay gets disposed
                for (var i = 0; i < 100; i++)
                {
                    if (Core.CanShutdown)
                    {
                        break;
                    }
                    await Task.Delay(50);
                }

                ReplayReader.CloseViewers();

                Config.Instance.SelectedTags = Config.Instance.SelectedTags.Distinct().ToList();
                //Config.Instance.ShowAllDecks = DeckPickerList.ShowAll;
                Config.Instance.SelectedDeckPickerClasses = DeckPickerList.SelectedClasses.ToArray();

                Config.Instance.WindowWidth =
                    (int)(Width - (GridNewDeck.Visibility == Visibility.Visible ? GridNewDeck.ActualWidth : 0));
                Config.Instance.WindowHeight      = (int)(Height - _heightChangeDueToSearchBox);
                Config.Instance.TrackerWindowTop  = (int)Top;
                Config.Instance.TrackerWindowLeft = (int)(Left + (_movedLeft.HasValue ? _movedLeft.Value : 0));

                //position of add. windows is NaN if they were never opened.
                if (!double.IsNaN(Core.Windows.PlayerWindow.Left))
                {
                    Config.Instance.PlayerWindowLeft = (int)Core.Windows.PlayerWindow.Left;
                }
                if (!double.IsNaN(Core.Windows.PlayerWindow.Top))
                {
                    Config.Instance.PlayerWindowTop = (int)Core.Windows.PlayerWindow.Top;
                }
                Config.Instance.PlayerWindowHeight = (int)Core.Windows.PlayerWindow.Height;

                if (!double.IsNaN(Core.Windows.OpponentWindow.Left))
                {
                    Config.Instance.OpponentWindowLeft = (int)Core.Windows.OpponentWindow.Left;
                }
                if (!double.IsNaN(Core.Windows.OpponentWindow.Top))
                {
                    Config.Instance.OpponentWindowTop = (int)Core.Windows.OpponentWindow.Top;
                }
                Config.Instance.OpponentWindowHeight = (int)Core.Windows.OpponentWindow.Height;

                if (!double.IsNaN(Core.Windows.TimerWindow.Left))
                {
                    Config.Instance.TimerWindowLeft = (int)Core.Windows.TimerWindow.Left;
                }
                if (!double.IsNaN(Core.Windows.TimerWindow.Top))
                {
                    Config.Instance.TimerWindowTop = (int)Core.Windows.TimerWindow.Top;
                }
                Config.Instance.TimerWindowHeight = (int)Core.Windows.TimerWindow.Height;
                Config.Instance.TimerWindowWidth  = (int)Core.Windows.TimerWindow.Width;

                if (!double.IsNaN(Core.Windows.StatsWindow.Left))
                {
                    Config.Instance.StatsWindowLeft = (int)Core.Windows.StatsWindow.Left;
                }
                if (!double.IsNaN(Core.Windows.StatsWindow.Top))
                {
                    Config.Instance.StatsWindowTop = (int)Core.Windows.StatsWindow.Top;
                }
                Config.Instance.StatsWindowHeight = (int)Core.Windows.StatsWindow.Height;
                Config.Instance.StatsWindowWidth  = (int)Core.Windows.StatsWindow.Width;

                Core.TrayIcon.NotifyIcon.Visible = false;
                Core.Overlay.Close();
                await LogReaderManager.Stop();

                Core.Windows.TimerWindow.Shutdown();
                Core.Windows.PlayerWindow.Shutdown();
                Core.Windows.OpponentWindow.Shutdown();
                Core.Windows.StatsWindow.Shutdown();
                Config.Save();
                DeckList.Save();
                DeckStatsList.Save();
                PluginManager.SavePluginsSettings();
                PluginManager.Instance.UnloadPlugins();
            }
            catch (Exception)
            {
                //doesnt matter
            }
            finally
            {
                Application.Current.Shutdown();
            }
        }
 public void RemoveActionKeyword(string pluginId, string oldActionKeyword) =>
 PluginManager.RemoveActionKeyword(pluginId, oldActionKeyword);
Exemplo n.º 57
0
 public override void createPluginInterfaces(PluginManager pluginManager)
 {
     pluginManager.addPlugin(new OgreOpenVrInterface());
 }
Exemplo n.º 58
0
        /// <summary>
        /// Get mappings for a given button code based on the current conditions
        /// </summary>
        /// <param name="btnCode">Button code (ref: XML file)</param>
        /// <returns>Mapping</returns>
        public Mapping GetMapping(string btnCode)
        {
            RemoteMap button = null;
            Mapping   found  = null;

            foreach (RemoteMap btn in _remoteMaps)
            {
                if (btnCode == btn.Code)
                {
                    button = btn;
                    break;
                }
            }
            if (button != null)
            {
                foreach (Mapping map in button.Mappings)
                {
                    if ((map.Layer == 0) || (map.Layer == _currentLayer))
                    {
                        switch (map.Condition)
                        {
                        case "*": // wildcard, no further condition
                            found = map;
                            break;

                        case "WINDOW": // Window-ID = x
                            if ((!GUIWindowManager.IsOsdVisible &&
                                 (GUIWindowManager.ActiveWindowEx == Convert.ToInt32(map.ConProperty))) ||
                                ((int)GUIWindowManager.VisibleOsd == Convert.ToInt32(map.ConProperty)))
                            {
                                found = map;
                            }
                            break;

                        case "FULLSCREEN": // Fullscreen = true/false
                            if ((GUIGraphicsContext.IsFullScreenVideo == Convert.ToBoolean(map.ConProperty)) &&
                                !GUIWindowManager.IsRouted && !GUIWindowManager.IsOsdVisible)
                            {
                                found = map;
                            }
                            break;

                        case "PLAYER": // Playing TV/DVD/general
                            if (!GUIWindowManager.IsRouted)
                            {
                                switch (map.ConProperty)
                                {
                                case "TV":
                                    if (g_Player.IsTimeShifting || g_Player.IsTV || g_Player.IsTVRecording)
                                    {
                                        found = map;
                                    }
                                    break;

                                case "DVD":
                                    if (g_Player.IsDVD)
                                    {
                                        found = map;
                                    }
                                    break;

                                case "MUSIC":
                                    if (g_Player.Playing && g_Player.IsMusic)
                                    {
                                        found = map;
                                    }

                                    break;

                                case "MEDIA":
                                    if (g_Player.Playing)
                                    {
                                        found = map;
                                    }
                                    break;
                                }
                            }
                            break;

                        case "PLUGIN": // plugin name: ISetupForm.PluginName()
                            if (PluginManager.IsPluginNameEnabled2(map.ConProperty))
                            {
                                found = map;
                            }
                            break;
                        }
                        if (found != null)
                        {
                            return(found);
                        }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 59
0
        //初期処理を行います
        public bool Initialize(PluginCreateParam param)
        {
            //プラグインマネージャーを保持します
            _pluginManager = PluginManager.GetInstance();

            //メニューを作成します
            this.Text = "マクロ";
            {
                var menu = new ToolStripMenuItem("キー操作の記録開始・終了");
                menu.ShortcutKeys = Keys.F9;
                menu.Click       += (sender, e) => {
                    if (_pluginManager.ActivePlugin is IKeyMacroPlugin plugin)
                    {
                        if (plugin.IsRecording() == false)
                        {
                            //キー操作の記録を開始します
                            plugin.StartRecording();
                        }
                        else
                        {
                            //キー操作の記録を停止します
                            plugin.StopRecording();
                        }
                    }
                };
                this.DropDownItems.Add(menu);
            }
            {
                var menu = new ToolStripMenuItem("キー操作の再生");
                menu.ShortcutKeys = Keys.F10;
                menu.Click       += (sender, e) => {
                    if (_pluginManager.ActivePlugin is IKeyMacroPlugin plugin)
                    {
                        plugin.Play();
                    }
                };
                this.DropDownItems.Add(menu);
            }
            {
                var menu = new ToolStripMenuItem("キー操作の出力");
                menu.Click += (sender, e) => {
                    if (_pluginManager.ActivePlugin is IKeyMacroPlugin plugin)
                    {
                        plugin.OutputMacro();
                    }
                };
                this.DropDownItems.Add(menu);
            }
            {
                var menu = new ToolStripMenuItem("キー操作の登録");
                menu.Click += (sender, e) => {
                    if (_pluginManager.ActivePlugin is IKeyMacroPlugin plugin)
                    {
                        plugin.SetMacro();
                    }
                };
                this.DropDownItems.Add(menu);
            }

            return(true);
        }
Exemplo n.º 60
0
        public static async Task Connect(long qqId, string ip, ushort port, string authKey, Action <bool, string> ConnectedEvent)
        {
            try
            {
                // 一套能用的框架, 必须要注册至少一个 Invoker, Parser, Client 和 Handler
                // Invoker 负责消息调度
                // Parser 负责解析消息到具体接口以便调度器调用相关 Handler 下的处理方法
                // Client 负责收发原始数据
                IServiceProvider services = new ServiceCollection().AddMiraiBaseFramework() // 表示使用基于基础框架的构建器
                                            .Services
                                            .AddDefaultMiraiHttpFramework()                 // 表示使用 mirai-api-http 实现的构建器
                                            .AddInvoker <MiraiHttpMessageHandlerInvoker>()  // 使用默认的调度器
                                            .AddHandler <GroupMessage>()                    // 群消息
                                            .AddHandler <FriendMessage>()                   // 好友消息
                                            .AddHandler <TempMessage>()                     // 临时消息
                                            .AddClient <MiraiHttpSession>()                 // 使用默认的客户端
                                            .Services
                                                                                            // 由于 MiraiHttpSession 使用 IOptions<MiraiHttpSessionOptions>, 其作为 Singleton 被注册
                                                                                            // 配置此项将配置基于此 IServiceProvider 全局的连接配置
                                                                                            // 如果你想一个作用域一个配置的话
                                                                                            // 自行做一个实现类, 继承MiraiHttpSession, 构造参数中使用 IOptionsSnapshot<MiraiHttpSessionOptions>
                                                                                            // 并将其传递给父类的构造参数
                                                                                            // 然后在每一个作用域中!先!配置好 IOptionsSnapshot<MiraiHttpSessionOptions>, 再尝试获取 IMiraiHttpSession
                                            .Configure <MiraiHttpSessionOptions>(options =>
                {
                    options.Host    = ip;
                    options.Port    = port;                                                 // 端口
                    options.AuthKey = authKey;                                              // 凭据
                })
                                            .AddLogging()
                                            .BuildServiceProvider();
                await using AsyncServiceScope scope = services.CreateAsyncScope();             // 自 .NET 6.0 起才可以如此操作代替上边两句
                services = scope.ServiceProvider;
                IMiraiHttpSession session = services.GetRequiredService <IMiraiHttpSession>(); // 大部分服务都基于接口注册, 请使用接口作为类型解析

                await session.ConnectAsync(qqId);                                              // 填入期望连接到的机器人QQ号

                Cache.SetTaskAtFixedTime();

                IFriendInfo[] IFriendInfos = await session.GetFriendListAsync();

                string nickname = "未知";

                var self = IFriendInfos.Where(m => m.Id == qqId).FirstOrDefault();  //获取自身昵称失败, 部分QQ号好友中不存在自己?
                if (self != null)
                {
                    nickname = self.Name;
                }

                ConnectedEvent?.Invoke(true, nickname);

                BotInfo.QQId = session.QQNumber.Value;

                BotInfo.IsLogin = true;

                PluginManager.Connected(
                    BotInfo.QQId,
                    async(targetId, msg) => await session.SendFriendMessageAsync(targetId, await msg.ToMiraiApiHttpMessages(session, UploadTarget.Friend)),
                    async(targetId, msg) => await session.SendGroupMessageAsync(targetId, await msg.ToMiraiApiHttpMessages(session, UploadTarget.Group)),
                    async(targetId, targetGroup, msg) => await session.SendTempMessageAsync(targetId, targetGroup, await msg.ToMiraiApiHttpMessages(session, UploadTarget.Temp))
                    );

                RssWorker.StartRssTask(async(msgs, targetId, groupId) =>
                {
                    if (targetId != -1)
                    {
                        _ = session.SendFriendMessageAsync(targetId, await msgs.ToMiraiApiHttpMessages(session, UploadTarget.Friend));
                    }
                    else if (groupId != -1)
                    {
                        _ = session.SendGroupMessageAsync(groupId, await msgs.ToMiraiApiHttpMessages(session, UploadTarget.Group));
                    }
                });

                while (true)
                {
                    BotInfo.IsLogin = true;
                    if (Console.ReadLine() == "exit")
                    {
                        BotInfo.IsLogin = false;
                        PluginManager.Disconnected();
                        session.Dispose();
                        ConnectedEvent?.Invoke(false, "");
                        break;
                    }
                    Task.Delay(100).Wait();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(ex);
                ConnectedEvent?.Invoke(false, ex.Message);
            }
        }