Exemple #1
0
        public Main()
        {
            _settingsStorage = new PluginJsonStorage <ProgramPluginSettings>();
            Settings         = _settingsStorage.Load();

            // This helper class initializes the file system watchers based on the locations to watch
            _win32ProgramRepositoryHelper = new Win32ProgramFileSystemWatchers();

            // Initialize the Win32ProgramRepository with the settings object
            _win32ProgramRepository = new Win32ProgramRepository(_win32ProgramRepositoryHelper.FileSystemWatchers.Cast <IFileSystemWatcherWrapper>().ToList(), new BinaryStorage <IList <Programs.Win32Program> >("Win32"), Settings, _win32ProgramRepositoryHelper.PathsToWatch);

            var a = Task.Run(() =>
            {
                Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _win32ProgramRepository.IndexPrograms);
            });

            var b = Task.Run(() =>
            {
                Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _packageRepository.IndexPrograms);
            });

            Task.WaitAll(a, b);

            Settings.LastIndexTime = DateTime.Today;
        }
Exemple #2
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            Stopwatch.Normal("Startup Time", () =>
            {
                RegisterDispatcherUnhandledException();

                var settingVM = new SettingWindowViewModel();
                _settings     = settingVM.Settings;

                PluginManager.LoadPlugins(_settings.PluginSettings);
                var mainVM = new MainViewModel(_settings);
                var window = new MainWindow(_settings, mainVM);
                API        = new PublicAPIInstance(settingVM, mainVM);
                PluginManager.InitializePlugins(API);

                ImageLoader.PreloadImages();

                Current.MainWindow       = window;
                Current.MainWindow.Title = Infrastructure.Constant.Wox;

                RegisterExitEvents();

                AutoStartup();
                AutoUpdates();

                mainVM.MainWindowVisibility = _settings.HideOnStartup ? Visibility.Hidden : Visibility.Visible;
            });
        }
Exemple #3
0
        public Main()
        {
            _settingsStorage = new PluginJsonStorage <Settings>();
            _settings        = _settingsStorage.Load();

            Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Preload programs cost", () =>
            {
                _win32Storage = new BinaryStorage <Programs.Win32[]>("Win32");
                _win32s       = _win32Storage.TryLoad(new Programs.Win32[] { });

                _packageRepository.Load();
            });
            Log.Info($"|Microsoft.Plugin.Program.Main|Number of preload win32 programs <{_win32s.Length}>");

            var a = Task.Run(() =>
            {
                if (IsStartupIndexProgramsRequired || !_win32s.Any())
                {
                    Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", IndexWin32Programs);
                }
            });

            var b = Task.Run(() =>
            {
                if (IsStartupIndexProgramsRequired || !_packageRepository.Any())
                {
                    Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _packageRepository.IndexPrograms);
                }
            });


            Task.WaitAll(a, b);

            _settings.LastIndexTime = DateTime.Today;
        }
Exemple #4
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            Stopwatch.Debug("Startup Time", () =>
            {
                RegisterDispatcherUnhandledException();

                ImageLoader.PreloadImages();

                var storage = new JsonStrorage <Settings>();
                _settings   = storage.Load();

                PluginManager.LoadPlugins(_settings.PluginSettings);
                var vm     = new MainViewModel(_settings, storage);
                var window = new MainWindow(_settings, vm);
                API        = new PublicAPIInstance(_settings, vm);
                PluginManager.InitializePlugins(API);

                Current.MainWindow       = window;
                Current.MainWindow.Title = Infrastructure.Constant.Wox;

                RegisterExitEvents();

                AutoStartup();
                AutoUpdates();

                window.Show();
            });
        }
Exemple #5
0
        public Main()
        {
            _settingsStorage = new PluginJsonStorage <Settings>();
            _settings        = _settingsStorage.Load();

            Stopwatch.Normal("|Wox.Plugin.Program.Main|Preload programs cost", () =>
            {
                _win32Storage = new BinaryStorage <Win32[]>("Win32");
                _win32s       = _win32Storage.TryLoad(new Win32[] { });
                _uwpStorage   = new BinaryStorage <UWP.Application[]>("UWP");
                _uwps         = _uwpStorage.TryLoad(new UWP.Application[] { });
            });
            Log.Info($"|Wox.Plugin.Program.Main|Number of preload win32 programs <{_win32s.Length}>");
            Log.Info($"|Wox.Plugin.Program.Main|Number of preload uwps <{_uwps.Length}>");

            var a = Task.Run(() =>
            {
                if (IsStartupIndexProgramsRequired || !_win32s.Any())
                {
                    Stopwatch.Normal("|Wox.Plugin.Program.Main|Win32Program index cost", IndexWin32Programs);
                }
            });

            var b = Task.Run(() =>
            {
                if (IsStartupIndexProgramsRequired || !_uwps.Any())
                {
                    Stopwatch.Normal("|Wox.Plugin.Program.Main|Win32Program index cost", IndexUWPPrograms);
                }
            });

            Task.WaitAll(a, b);

            _settings.LastIndexTime = DateTime.Today;
        }
Exemple #6
0
        public Main()
        {
            _settingsStorage = new PluginJsonStorage <Settings>();
            _settings        = _settingsStorage.Load();

            Stopwatch.Normal("|Wox.Plugin.Program.Main|Preload programs cost", () => {
                _win32Storage = new BinaryStorage <Win32[]>("Win32");
                _win32s       = _win32Storage.TryLoad(new Win32[] { });
            });
            Log.Info($"|Wox.Plugin.Program.Main|Number of preload win32 programs <{_win32s.Length}>");
        }
Exemple #7
0
 protected override void OnStartup(StartupEventArgs e)
 {
     Stopwatch.Debug("Startup Time", () =>
     {
         base.OnStartup(e);
         RegisterUnhandledException();
         ThreadPool.QueueUserWorkItem(o => { ImageLoader.ImageLoader.PreloadImages(); });
         Window = new MainWindow();
         PluginManager.Init(Window);
         CommandArgsFactory.Execute(e.Args.ToList());
     });
 }
Exemple #8
0
        public void Init(PluginInitContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _context.API.ThemeChanged += OnThemeChanged;

            var a = Task.Run(() =>
            {
                Stopwatch.Normal("Microsoft.Plugin.Program.Main - Win32Program index cost", _win32ProgramRepository.IndexPrograms);
            });

            var b = Task.Run(() =>
            {
                Stopwatch.Normal("Microsoft.Plugin.Program.Main - Package index cost", _packageRepository.IndexPrograms);
                UpdateUWPIconPath(_context.API.GetCurrentTheme());
            });

            Task.WaitAll(a, b);

            Settings.LastIndexTime = DateTime.Today;
        }
Exemple #9
0
        protected override void OnStartup(StartupEventArgs e)
        {
            Stopwatch.Debug("Startup Time", () =>
            {
                base.OnStartup(e);
                RegisterUnhandledException();

                Task.Factory.StartNew(ImageLoader.PreloadImages);

                MainViewModel mainVM = new MainViewModel();
                API = new PublicAPIInstance(mainVM, mainVM._settings);
                PluginManager.InitializePlugins(API);

                mainVM._settings.UpdatePluginSettings();

                Window = new MainWindow(mainVM._settings, mainVM);
                NotifyIconManager notifyIconManager = new NotifyIconManager(API);
                CommandArgsFactory.Execute(e.Args.ToList());
            });
        }
Exemple #10
0
        public Main()
        {
            _settingsStorage = new PluginJsonStorage <Settings>();
            _settings        = _settingsStorage.Load();
            // This helper class initializes the file system watchers based on the locations to watch
            _win32ProgramRepositoryHelper = new Win32ProgramFileSystemWatchers();

            // Initialize the Win32ProgramRepository with the settings object
            _win32ProgramRepository = new Win32ProgramRepository(_win32ProgramRepositoryHelper._fileSystemWatchers.Cast <IFileSystemWatcherWrapper>().ToList(), new BinaryStorage <IList <Programs.Win32> >("Win32"), _settings, _win32ProgramRepositoryHelper._pathsToWatch);

            Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Preload programs cost", () =>
            {
                _win32ProgramRepository.Load();
                _packageRepository.Load();
            });
            Log.Info($"|Microsoft.Plugin.Program.Main|Number of preload win32 programs <{_win32ProgramRepository.Count()}>");

            var a = Task.Run(() =>
            {
                if (IsStartupIndexProgramsRequired || !_win32ProgramRepository.Any())
                {
                    Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _win32ProgramRepository.IndexPrograms);
                }
            });

            var b = Task.Run(() =>
            {
                if (IsStartupIndexProgramsRequired || !_packageRepository.Any())
                {
                    Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _packageRepository.IndexPrograms);
                }
            });


            Task.WaitAll(a, b);

            _settings.LastIndexTime = DateTime.Today;
        }
Exemple #11
0
        /// <summary>
        /// This method is called from <see cref="MainWindow.OnSourceInitialized"/> to initialize a list of protected environment variables right after the PT Run process has been invoked.
        /// Protected variables are environment variables that must not be changed on process level when updating the environment variables with changes on machine and/or user level.
        /// We cache the relevant variable names in the private, static and readonly variable <see cref="_protectedProcessVariables"/> of this class.
        /// </summary>
        internal static void GetProtectedEnvironmentVariables()
        {
            IDictionary processVars;
            var         machineAndUserVars = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            Stopwatch.Normal("EnvironmentHelper.GetProtectedEnvironmentVariables - Duration cost", () =>
            {
                // Adding some well known variables that must kept unchanged on process level.
                // Changes of this variables may lead to incorrect values
                _protectedProcessVariables.Add("USERNAME");
                _protectedProcessVariables.Add("PROCESSOR_ARCHITECTURE");

                // Getting environment variables
                processVars = GetEnvironmentVariablesWithErrorLog(EnvironmentVariableTarget.Process);
                GetMergedMachineAndUserVariables(machineAndUserVars);

                // Adding names of variables that are different on process level or existing only on process level
                foreach (DictionaryEntry pVar in processVars)
                {
                    string pVarKey   = (string)pVar.Key;
                    string pVarValue = (string)pVar.Value;

                    if (machineAndUserVars.ContainsKey(pVarKey))
                    {
                        if (machineAndUserVars[pVarKey] != pVarValue)
                        {
                            // Variable value for this process differs form merged machine/user value.
                            _protectedProcessVariables.Add(pVarKey);
                        }
                    }
                    else
                    {
                        // Variable exists only for this process
                        _protectedProcessVariables.Add(pVarKey);
                    }
                }
            });
        }
Exemple #12
0
        /// <summary>
        /// This method updates the environment of PT Run's process when called. It is called when we receive a special WindowMessage.
        /// </summary>
        internal static void UpdateEnvironment()
        {
            Stopwatch.Normal("EnvironmentHelper.UpdateEnvironment - Duration cost", () =>
            {
                // Caching existing process environment and getting updated environment variables
                IDictionary oldProcessEnvironment = GetEnvironmentVariablesWithErrorLog(EnvironmentVariableTarget.Process);
                var newEnvironment = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                GetMergedMachineAndUserVariables(newEnvironment);

                // Determine deleted variables and add them with a "string.Empty" value as marker to the dictionary
                foreach (DictionaryEntry pVar in oldProcessEnvironment)
                {
                    // We must compare case insensitive (see dictionary assignment) to avoid false positives when the variable name has changed (Example: "path" -> "Path")
                    if (!newEnvironment.ContainsKey((string)pVar.Key) & !_protectedProcessVariables.Contains((string)pVar.Key))
                    {
                        newEnvironment.Add((string)pVar.Key, string.Empty);
                    }
                }

                // Remove unchanged variables from the dictionary
                // Later we only like to recreate the changed ones
                foreach (string varName in newEnvironment.Keys.ToList())
                {
                    // To be able to detect changed names correctly we have to compare case sensitive
                    if (oldProcessEnvironment.Contains(varName))
                    {
                        if (oldProcessEnvironment[varName].Equals(newEnvironment[varName]))
                        {
                            newEnvironment.Remove(varName);
                        }
                    }
                }

                // Update PT Run's process environment now
                foreach (KeyValuePair <string, string> kv in newEnvironment)
                {
                    // Initialize variables for length of environment variable name and value. Using this variables prevent us from null value exceptions.
                    // => We added this because of the issue #13172 where a user reported System.ArgumentNullException from "Environment.SetEnvironmentVariable()".
                    int varNameLength  = kv.Key == null ? 0 : kv.Key.Length;
                    int varValueLength = kv.Value == null ? 0 : kv.Value.Length;

                    // The name of environment variables must not be null, empty or have a length of zero.
                    // But if the value of the environment variable is null or an empty string then the variable is explicit defined for deletion. => Here we don't need to check anything.
                    // => We added the if statement (next line) because of the issue #13172 where a user reported System.ArgumentNullException from "Environment.SetEnvironmentVariable()".
                    if (!string.IsNullOrEmpty(kv.Key) & varNameLength > 0)
                    {
                        try
                        {
                            // If the variable is not listed as protected/don't override on process level, then update it. (See method "GetProtectedEnvironmentVariables" of this class.)
                            if (!_protectedProcessVariables.Contains(kv.Key))
                            {
                                // We have to delete the variables first that we can update their name if changed by the user. (Example: "path" => "Path")
                                // The machine and user variables that have been deleted by the user having an empty string as variable value. Because of this we check the values of the variables in our dictionary against "null" and "string.Empty". This check prevents us from invoking a (second) delete command.
                                // The dotnet method doesn't throw an exception if the variable which should be deleted doesn't exist.
                                Environment.SetEnvironmentVariable(kv.Key, null, EnvironmentVariableTarget.Process);
                                if (!string.IsNullOrEmpty(kv.Value))
                                {
                                    Environment.SetEnvironmentVariable(kv.Key, kv.Value, EnvironmentVariableTarget.Process);
                                }
                            }
                            else
                            {
                                // Don't log for the variable "USERNAME" if the variable's value is "System". (Then it is a false positive because per default the variable only exists on machine level with the value "System".)
                                if (!kv.Key.Equals("USERNAME", StringComparison.OrdinalIgnoreCase) & !kv.Value.Equals("System", StringComparison.Ordinal))
                                {
                                    Log.Warn($"Skipping update of the environment variable [{kv.Key}] for the PT Run process. This variable is listed as protected process variable and changing them can cause unexpected behavior. (The variable value has a length of [{varValueLength}].)", typeof(PowerLauncher.Helper.EnvironmentHelper));
                                }
                            }
                        }
#pragma warning disable CA1031 // Do not catch general exception types
                        catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                        {
                            // The dotnet method "System.Environment.SetEnvironmentVariable" has it's own internal method to check the input parameters. Here we catch the exceptions that we don't check before updating the environment variable and log it to avoid crashes of PT Run.
                            Log.Exception($"Unhandled exception while updating the environment variable [{kv.Key}] for the PT Run process. (The variable value has a length of [{varValueLength}].)", ex, typeof(PowerLauncher.Helper.EnvironmentHelper));
                        }
                    }
                    else
                    {
                        // Log the error when variable name is null, empty or has a length of zero.
                        Log.Error($"Failed to update the environment variable [{kv.Key}] for the PT Run process. Their name is null or empty. (The variable value has a length of [{varValueLength}].)", typeof(PowerLauncher.Helper.EnvironmentHelper));
                    }
                }
            });
        }
Exemple #13
0
        private void OnThemeTabSelected()
        {
            Stopwatch.Debug("theme load", () =>
            {
                var s = Fonts.SystemFontFamilies;
            });

            if (themeTabLoaded)
            {
                return;
            }

            themeTabLoaded = true;
            if (!string.IsNullOrEmpty(_settings.QueryBoxFont) &&
                Fonts.SystemFontFamilies.Count(o => o.FamilyNames.Values.Contains(_settings.QueryBoxFont)) > 0)
            {
                cbQueryBoxFont.Text = _settings.QueryBoxFont;

                cbQueryBoxFontFaces.SelectedItem =
                    SyntaxSugars.CallOrRescueDefault(
                        () => ((FontFamily)cbQueryBoxFont.SelectedItem).ConvertFromInvariantStringsOrNormal(
                            _settings.QueryBoxFontStyle,
                            _settings.QueryBoxFontWeight,
                            _settings.QueryBoxFontStretch
                            ));
            }
            if (!string.IsNullOrEmpty(_settings.ResultFont) &&
                Fonts.SystemFontFamilies.Count(o => o.FamilyNames.Values.Contains(_settings.ResultFont)) > 0)
            {
                ResultFontComboBox.Text = _settings.ResultFont;

                ResultFontFacesComboBox.SelectedItem =
                    SyntaxSugars.CallOrRescueDefault(
                        () => ((FontFamily)ResultFontComboBox.SelectedItem).ConvertFromInvariantStringsOrNormal(
                            _settings.ResultFontStyle,
                            _settings.ResultFontWeight,
                            _settings.ResultFontStretch
                            ));
            }

            ResultListBoxPreview.AddResults(new List <Result>
            {
                new Result
                {
                    Title           = "Wox is an effective launcher for windows",
                    SubTitle        = "Wox provide bundles of features let you access infomations quickly.",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                },
                new Result
                {
                    Title           = "Search applications",
                    SubTitle        = "Search applications, files (via everything plugin) and browser bookmarks",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                },
                new Result
                {
                    Title           = "Search web contents with shortcuts",
                    SubTitle        = "e.g. search google with g keyword or youtube keyword)",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                },
                new Result
                {
                    Title           = "clipboard history ",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                },
                new Result
                {
                    Title           = "Themes support",
                    SubTitle        = "get more themes from http://www.getwox.com/theme",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                },
                new Result
                {
                    Title           = "Plugins support",
                    SubTitle        = "get more plugins from http://www.getwox.com/plugin",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                },
                new Result
                {
                    Title           = "Wox is an open-source software",
                    SubTitle        = "Wox benefits from the open-source community a lot",
                    IcoPath         = "Images/app.png",
                    PluginDirectory = Path.GetDirectoryName(Infrastructure.Constant.ProgramDirectory)
                }
            });

            foreach (string theme in ThemeManager.Instance.LoadAvailableThemes())
            {
                string themeName = Path.GetFileNameWithoutExtension(theme);
                themeComboBox.Items.Add(themeName);
            }

            themeComboBox.SelectedItem = _settings.Theme;

            var wallpaper = WallpaperPathRetrieval.GetWallpaperPath();

            if (wallpaper != null && File.Exists(wallpaper))
            {
                var memStream = new MemoryStream(File.ReadAllBytes(wallpaper));
                var bitmap    = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = memStream;
                bitmap.EndInit();
                var brush = new ImageBrush(bitmap);
                brush.Stretch           = Stretch.UniformToFill;
                PreviewPanel.Background = brush;
            }
            else
            {
                var wallpaperColor = WallpaperPathRetrieval.GetWallpaperColor();
                PreviewPanel.Background = new SolidColorBrush(wallpaperColor);
            }
        }