Ejemplo n.º 1
0
        public KeyboardManagerViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc, Func <List <KeysDataModel>, int> filterRemapKeysList)
        {
            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG       = ipcMSGCallBackFunc;
            FilterRemapKeysList = filterRemapKeysList;

            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            if (_settingsUtils.SettingsExists(PowerToyName))
            {
                // Todo: Be more resilient while reading and saving settings.
                Settings = _settingsUtils.GetSettings <KeyboardManagerSettings>(PowerToyName);

                // Load profile.
                if (!LoadProfile())
                {
                    _profile = new KeyboardManagerProfile();
                }
            }
            else
            {
                Settings = new KeyboardManagerSettings(PowerToyName);
                _settingsUtils.SaveSettings(Settings.ToJsonString(), PowerToyName);
            }

            if (_settingsUtils.SettingsExists())
            {
                _generalSettings = _settingsUtils.GetSettings <GeneralSettings>(string.Empty);
            }
            else
            {
                _generalSettings = new GeneralSettings();
                _settingsUtils.SaveSettings(_generalSettings.ToJsonString(), string.Empty);
            }
        }
Ejemplo n.º 2
0
        public PowerLauncherViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc, int defaultKeyCode)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            callback      = (PowerLauncherSettings settings) =>
            {
                // Propagate changes to Power Launcher through IPC
                SendConfigMSG(
                    string.Format("{{ \"powertoys\": {{ \"{0}\": {1} }} }}", PowerLauncherSettings.ModuleName, JsonSerializer.Serialize(settings)));
            };
            if (_settingsUtils.SettingsExists(PowerLauncherSettings.ModuleName))
            {
                settings = _settingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.ModuleName);
            }
            else
            {
                settings = new PowerLauncherSettings();
                settings.Properties.OpenPowerLauncher.Alt  = true;
                settings.Properties.OpenPowerLauncher.Code = defaultKeyCode;
                settings.Properties.MaximumNumberOfResults = 4;
                callback(settings);
            }

            if (_settingsUtils.SettingsExists())
            {
                generalSettings = _settingsUtils.GetSettings <GeneralSettings>();
            }
            else
            {
                generalSettings = new GeneralSettings();
            }
        }
Ejemplo n.º 3
0
 private void ColorHistory_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     if (!_loadingColorsHistory)
     {
         var settings = _settingsUtils.GetSettings <ColorPickerSettings>(ColorPickerModuleName);
         settings.Properties.ColorHistory = ColorHistory.ToList();
         settings.Save(_settingsUtils);
     }
 }
Ejemplo n.º 4
0
        // callback function to launch the URL to check for updates.
        private void CheckForUpdates_Click()
        {
            GeneralSettings settings = _settingsUtils.GetSettings <GeneralSettings>(_settingsConfigFileFolder);

            settings.CustomActionName = "check_for_updates";

            OutGoingGeneralSettings     outsettings  = new OutGoingGeneralSettings(settings);
            GeneralSettingsCustomAction customaction = new GeneralSettingsCustomAction(outsettings);

            SendCheckForUpdatesConfigMSG(customaction.ToString());
        }
Ejemplo n.º 5
0
        public ShortcutGuideViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc, string configFileSubfolder = "")
        {
            // Update Settings file folder:
            _settingsConfigFileFolder = configFileSubfolder;
            _settingsUtils            = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            try
            {
                Settings = _settingsUtils.GetSettings <ShortcutGuideSettings>(GetSettingsSubPath());
            }
            catch
            {
                Settings = new ShortcutGuideSettings();
                _settingsUtils.SaveSettings(Settings.ToJsonString(), GetSettingsSubPath());
            }

            GeneralSettings generalSettings;

            try
            {
                generalSettings = _settingsUtils.GetSettings <GeneralSettings>(string.Empty);
            }
            catch
            {
                generalSettings = new GeneralSettings();
                _settingsUtils.SaveSettings(generalSettings.ToJsonString(), string.Empty);
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            _isEnabled = generalSettings.Enabled.ShortcutGuide;
            _pressTime = Settings.Properties.PressTime.Value;
            _opacity   = Settings.Properties.OverlayOpacity.Value;

            string theme = Settings.Properties.Theme.Value;

            if (theme == "dark")
            {
                _themeIndex = 0;
            }

            if (theme == "light")
            {
                _themeIndex = 1;
            }

            if (theme == "system")
            {
                _themeIndex = 2;
            }
        }
Ejemplo n.º 6
0
        public PowerRenameViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, string configFileSubfolder = "")
        {
            // Update Settings file folder:
            _settingsConfigFileFolder = configFileSubfolder;
            _settingsUtils            = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            try
            {
                PowerRenameLocalProperties localSettings = _settingsUtils.GetSettings <PowerRenameLocalProperties>(GetSettingsSubPath(), "power-rename-settings.json");
                Settings = new PowerRenameSettings(localSettings);
            }
            catch
            {
                PowerRenameLocalProperties localSettings = new PowerRenameLocalProperties();
                Settings = new PowerRenameSettings(localSettings);
                _settingsUtils.SaveSettings(localSettings.ToJsonString(), GetSettingsSubPath(), "power-rename-settings.json");
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            _powerRenameEnabledOnContextMenu         = Settings.Properties.ShowIcon.Value;
            _powerRenameEnabledOnContextExtendedMenu = Settings.Properties.ExtendedContextMenuOnly.Value;
            _powerRenameRestoreFlagsOnLaunch         = Settings.Properties.PersistState.Value;
            _powerRenameMaxDispListNumValue          = Settings.Properties.MaxMRUSize.Value;
            _autoComplete       = Settings.Properties.MRUEnabled.Value;
            _powerRenameEnabled = GeneralSettingsConfig.Enabled.PowerRename;
        }
Ejemplo n.º 7
0
        public ColorPickerViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc)
        {
            // Obtain the general PowerToy settings configurations
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
            if (_settingsUtils.SettingsExists(ColorPickerSettings.ModuleName))
            {
                _colorPickerSettings = _settingsUtils.GetSettings <ColorPickerSettings>(ColorPickerSettings.ModuleName);
            }
            else
            {
                _colorPickerSettings = new ColorPickerSettings();
            }

            _isEnabled = GeneralSettingsConfig.Enabled.ColorPicker;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            bool            isEnabled       = (bool)value;
            GeneralSettings generalSettings = settingsUtils.GetSettings <GeneralSettings>(string.Empty);

            var defaultTheme = new Windows.UI.ViewManagement.UISettings();
            var uiTheme      = defaultTheme.GetColorValue(Windows.UI.ViewManagement.UIColorType.Background).ToString();

            string selectedTheme = generalSettings.Theme.ToLower();

            if (selectedTheme == "dark" || (selectedTheme == "system" && uiTheme == "#FF000000"))
            {
                // DARK
                if (isEnabled)
                {
                    return((SolidColorBrush)Application.Current.Resources["DarkForegroundBrush"]);
                }
                else
                {
                    return((SolidColorBrush)Application.Current.Resources["DarkForegroundDisabledBrush"]);
                }
            }
            else
            {
                // LIGHT
                if (isEnabled)
                {
                    return((SolidColorBrush)Application.Current.Resources["LightForegroundBrush"]);
                }
                else
                {
                    return((SolidColorBrush)Application.Current.Resources["LightForegroundDisabledBrush"]);
                }
            }
        }
Ejemplo n.º 9
0
        public ImageResizerViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            try
            {
                Settings = _settingsUtils.GetSettings <ImageResizerSettings>(ModuleName);
            }
            catch
            {
                Settings = new ImageResizerSettings();
                _settingsUtils.SaveSettings(Settings.ToJsonString(), ModuleName);
            }

            GeneralSettings generalSettings;

            try
            {
                generalSettings = _settingsUtils.GetSettings <GeneralSettings>(string.Empty);
            }
            catch
            {
                generalSettings = new GeneralSettings();
                _settingsUtils.SaveSettings(generalSettings.ToJsonString(), string.Empty);
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            _isEnabled          = generalSettings.Enabled.ImageResizer;
            _advancedSizes      = Settings.Properties.ImageresizerSizes.Value;
            _jpegQualityLevel   = Settings.Properties.ImageresizerJpegQualityLevel.Value;
            _pngInterlaceOption = Settings.Properties.ImageresizerPngInterlaceOption.Value;
            _tiffCompressOption = Settings.Properties.ImageresizerTiffCompressOption.Value;
            _fileName           = Settings.Properties.ImageresizerFileName.Value;
            _keepDateModified   = Settings.Properties.ImageresizerKeepDateModified.Value;
            _encoderGuidId      = GetEncoderIndex(Settings.Properties.ImageresizerFallbackEncoder.Value);

            int i = 0;

            foreach (ImageSize size in _advancedSizes)
            {
                size.Id = i;
                i++;
                size.PropertyChanged += Size_PropertyChanged;
            }
        }
Ejemplo n.º 10
0
        private void LoadSettingsFromJson()
        {
            // TODO this IO call should by Async, update GetFileWatcher helper to support async
            lock (_loadingSettingsLock)
            {
                {
                    var retry      = true;
                    var retryCount = 0;

                    while (retry)
                    {
                        try
                        {
                            retryCount++;

                            if (!_settingsUtils.SettingsExists(ColorPickerModuleName))
                            {
                                Logger.LogInfo("ColorPicker settings.json was missing, creating a new one");
                                var defaultColorPickerSettings = new ColorPickerSettings();
                                defaultColorPickerSettings.Save(_settingsUtils);
                            }

                            var settings = _settingsUtils.GetSettings <ColorPickerSettings>(ColorPickerModuleName);
                            if (settings != null)
                            {
                                ChangeCursor.Value              = settings.Properties.ChangeCursor;
                                ActivationShortcut.Value        = settings.Properties.ActivationShortcut.ToString();
                                CopiedColorRepresentation.Value = settings.Properties.CopiedColorRepresentation;
                            }

                            retry = false;
                        }
                        catch (IOException ex)
                        {
                            if (retryCount > MaxNumberOfRetry)
                            {
                                retry = false;
                            }

                            Logger.LogError("Failed to read changed settings", ex);
                            Thread.Sleep(500);
                        }
#pragma warning disable CA1031 // Do not catch general exception types
                        catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                        {
                            if (retryCount > MaxNumberOfRetry)
                            {
                                retry = false;
                            }

                            Logger.LogError("Failed to read changed settings", ex);
                            Thread.Sleep(500);
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public PowerLauncherViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, int defaultKeyCode)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            // To obtain the general Settings configurations of PowerToys
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            callback      = (PowerLauncherSettings settings) =>
            {
                // Propagate changes to Power Launcher through IPC
                // Using InvariantCulture as this is an IPC message
                SendConfigMSG(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
                        PowerLauncherSettings.ModuleName,
                        JsonSerializer.Serialize(settings)));
            };

            if (_settingsUtils.SettingsExists(PowerLauncherSettings.ModuleName))
            {
                settings = _settingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.ModuleName);
            }
            else
            {
                settings = new PowerLauncherSettings();
                settings.Properties.OpenPowerLauncher.Alt  = true;
                settings.Properties.OpenPowerLauncher.Code = defaultKeyCode;
                settings.Properties.MaximumNumberOfResults = 4;
                callback(settings);
            }

            switch (settings.Properties.Theme)
            {
            case Theme.Light:
                _isLightThemeRadioButtonChecked = true;
                break;

            case Theme.Dark:
                _isDarkThemeRadioButtonChecked = true;
                break;

            case Theme.System:
                _isSystemThemeRadioButtonChecked = true;
                break;
            }
        }
Ejemplo n.º 12
0
        public ColorPickerViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
            if (_settingsUtils.SettingsExists(ColorPickerSettings.ModuleName))
            {
                _colorPickerSettings = _settingsUtils.GetSettings <ColorPickerSettings>(ColorPickerSettings.ModuleName);
            }
            else
            {
                _colorPickerSettings = new ColorPickerSettings();
            }

            if (_settingsUtils.SettingsExists())
            {
                var generalSettings = _settingsUtils.GetSettings <GeneralSettings>();
                _isEnabled = generalSettings.Enabled.ColorPicker;
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
        }
        public ImageResizerViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, Func <string, string> resourceLoader)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            // To obtain the general settings configurations of PowerToys.
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            try
            {
                Settings = _settingsUtils.GetSettings <ImageResizerSettings>(ModuleName);
            }
            catch (Exception e)
            {
                Logger.LogError($"Exception encountered while reading {ModuleName} settings.", e);
#if DEBUG
                if (e is ArgumentException || e is ArgumentNullException || e is PathTooLongException)
                {
                    throw;
                }
#endif
                Settings = new ImageResizerSettings(resourceLoader);
                _settingsUtils.SaveSettings(Settings.ToJsonString(), ModuleName);
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            _isEnabled          = GeneralSettingsConfig.Enabled.ImageResizer;
            _advancedSizes      = Settings.Properties.ImageresizerSizes.Value;
            _jpegQualityLevel   = Settings.Properties.ImageresizerJpegQualityLevel.Value;
            _pngInterlaceOption = Settings.Properties.ImageresizerPngInterlaceOption.Value;
            _tiffCompressOption = Settings.Properties.ImageresizerTiffCompressOption.Value;
            _fileName           = Settings.Properties.ImageresizerFileName.Value;
            _keepDateModified   = Settings.Properties.ImageresizerKeepDateModified.Value;
            _encoderGuidId      = GetEncoderIndex(Settings.Properties.ImageresizerFallbackEncoder.Value);

            int i = 0;
            foreach (ImageSize size in _advancedSizes)
            {
                size.Id = i;
                i++;
                size.PropertyChanged += SizePropertyChanged;
            }
        }
Ejemplo n.º 14
0
        public bool LoadProfile()
        {
            var success = true;

            try
            {
                using (var profileFileMutex = Mutex.OpenExisting(ProfileFileMutexName))
                {
                    if (profileFileMutex.WaitOne(ProfileFileMutexWaitTimeoutMilliseconds))
                    {
                        // update the UI element here.
                        try
                        {
                            string fileName = Settings.Properties.ActiveConfiguration.Value + JsonFileType;

                            if (_settingsUtils.SettingsExists(PowerToyName, fileName))
                            {
                                _profile = _settingsUtils.GetSettings <KeyboardManagerProfile>(PowerToyName, fileName);
                            }
                            else
                            {
                                // The KBM process out of runner creates the default.json file if it does not exist.
                                success = false;
                            }

                            FilterRemapKeysList(_profile?.RemapKeys?.InProcessRemapKeys);
                        }
                        finally
                        {
                            // Make sure to release the mutex.
                            profileFileMutex.ReleaseMutex();
                        }
                    }
                    else
                    {
                        success = false;
                    }
                }
            }
            catch (Exception e)
            {
                // Failed to load the configuration.
                Logger.LogError($"Exception encountered when loading {PowerToyName} profile", e);
                success = false;
            }

            return(success);
        }
Ejemplo n.º 15
0
        public ColorPickerViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc)
        {
            // Obtain the general PowerToy settings configurations
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            SelectableColorRepresentations = new Dictionary <ColorRepresentationType, string>
            {
                { ColorRepresentationType.CMYK, "CMYK - cmyk(100%, 50%, 75%, 0%)" },
                { ColorRepresentationType.HEX, "HEX - #FFAA00" },
                { ColorRepresentationType.HSB, "HSB - hsb(100, 50%, 75%)" },
                { ColorRepresentationType.HSI, "HSI - hsi(100, 50%, 75%)" },
                { ColorRepresentationType.HSL, "HSL - hsl(100, 50%, 75%)" },
                { ColorRepresentationType.HSV, "HSV - hsv(100, 50%, 75%)" },
                { ColorRepresentationType.HWB, "HWB - hwb(100, 50%, 75%)" },
                { ColorRepresentationType.NCol, "NCol - R10, 50%, 75%" },
                { ColorRepresentationType.RGB, "RGB - rgb(100, 50, 75)" },
            };

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
            if (_settingsUtils.SettingsExists(ColorPickerSettings.ModuleName))
            {
                _colorPickerSettings = _settingsUtils.GetSettings <ColorPickerSettings>(ColorPickerSettings.ModuleName);
            }
            else
            {
                _colorPickerSettings = new ColorPickerSettings();
            }

            _isEnabled = GeneralSettingsConfig.Enabled.ColorPicker;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            _delayedTimer           = new Timer();
            _delayedTimer.Interval  = SaveSettingsDelayInMs;
            _delayedTimer.Elapsed  += DelayedTimer_Tick;
            _delayedTimer.AutoReset = false;

            InitializeColorFormats();
        }
Ejemplo n.º 16
0
        public KeyboardManagerViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, Func <List <KeysDataModel>, int> filterRemapKeysList)
        {
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG       = ipcMSGCallBackFunc;
            FilterRemapKeysList = filterRemapKeysList;

            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            if (_settingsUtils.SettingsExists(PowerToyName))
            {
                try
                {
                    Settings = _settingsUtils.GetSettings <KeyboardManagerSettings>(PowerToyName);
                }
                catch (Exception e)
                {
                    Logger.LogError($"Exception encountered while reading {PowerToyName} settings.", e);
#if DEBUG
                    if (e is ArgumentException || e is ArgumentNullException || e is PathTooLongException)
                    {
                        throw;
                    }
#endif
                }

                // Load profile.
                if (!LoadProfile())
                {
                    _profile = new KeyboardManagerProfile();
                }
            }
            else
            {
                Settings = new KeyboardManagerSettings();
                _settingsUtils.SaveSettings(Settings.ToJsonString(), PowerToyName);
            }
        }
Ejemplo n.º 17
0
        public PowerPreviewViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc, string configFileSubfolder = "")
        {
            // Update Settings file folder:
            _settingsConfigFileFolder = configFileSubfolder;
            _settingsUtils            = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            try
            {
                Settings = _settingsUtils.GetSettings <PowerPreviewSettings>(GetSettingsSubPath());
            }
            catch
            {
                Settings = new PowerPreviewSettings();
                _settingsUtils.SaveSettings(Settings.ToJsonString(), GetSettingsSubPath());
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            _svgRenderIsEnabled    = Settings.Properties.EnableSvgPreview;
            _svgThumbnailIsEnabled = Settings.Properties.EnableSvgThumbnail;
            _mdRenderIsEnabled     = Settings.Properties.EnableMdPreview;
        }
Ejemplo n.º 18
0
        public bool LoadProfile()
        {
            var success = true;

            try
            {
                using (var profileFileMutex = Mutex.OpenExisting(ProfileFileMutexName))
                {
                    if (profileFileMutex.WaitOne(ProfileFileMutexWaitTimeoutMilliseconds))
                    {
                        // update the UI element here.
                        try
                        {
                            _profile = _settingsUtils.GetSettings <KeyboardManagerProfile>(PowerToyName, Settings.Properties.ActiveConfiguration.Value + JsonFileType);
                            FilterRemapKeysList(_profile.RemapKeys.InProcessRemapKeys);
                        }
                        finally
                        {
                            // Make sure to release the mutex.
                            profileFileMutex.ReleaseMutex();
                        }
                    }
                    else
                    {
                        success = false;
                    }
                }
            }
            catch (Exception)
            {
                // Failed to load the configuration.
                success = false;
            }

            return(success);
        }
Ejemplo n.º 19
0
        public VideoConferenceViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, string configFileSubfolder = "")
        {
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            SendConfigMSG = ipcMSGCallBackFunc;

            _settingsConfigFileFolder = configFileSubfolder;

            try
            {
                Settings = _settingsUtils.GetSettings <VideoConferenceSettings>(GetSettingsSubPath());
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch
#pragma warning restore CA1031 // Do not catch general exception types
            {
                Settings = new VideoConferenceSettings();
                _settingsUtils.SaveSettings(Settings.ToJsonString(), GetSettingsSubPath());
            }

            CameraNames     = interop.CommonManaged.GetAllVideoCaptureDeviceNames();
            MicrophoneNames = interop.CommonManaged.GetAllActiveMicrophoneDeviceNames();
            MicrophoneNames.Insert(0, "[All]");

            var shouldSaveSettings = false;

            if (string.IsNullOrEmpty(Settings.Properties.SelectedCamera.Value) && CameraNames.Count != 0)
            {
                _selectedCameraIndex = 0;
                Settings.Properties.SelectedCamera.Value = CameraNames[0];
                shouldSaveSettings = true;
            }
            else
            {
                _selectedCameraIndex = CameraNames.FindIndex(name => name == Settings.Properties.SelectedCamera.Value);
            }

            if (string.IsNullOrEmpty(Settings.Properties.SelectedMicrophone.Value))
            {
                _selectedMicrophoneIndex = 0;
                Settings.Properties.SelectedMicrophone.Value = MicrophoneNames[0];
                shouldSaveSettings = true;
            }
            else
            {
                _selectedMicrophoneIndex = MicrophoneNames.FindIndex(name => name == Settings.Properties.SelectedMicrophone.Value);
            }

            _isEnabled = GeneralSettingsConfig.Enabled.VideoConference;
            _cameraAndMicrophoneMuteHotkey = Settings.Properties.MuteCameraAndMicrophoneHotkey.Value;
            _mirophoneMuteHotkey           = Settings.Properties.MuteMicrophoneHotkey.Value;
            _cameraMuteHotkey      = Settings.Properties.MuteCameraHotkey.Value;
            CameraImageOverlayPath = Settings.Properties.CameraOverlayImagePath.Value;
            SelectOverlayImage     = new ButtonClickCommand(SelectOverlayImageAction);
            ClearOverlayImage      = new ButtonClickCommand(ClearOverlayImageAction);

            _hideToolbarWhenUnmuted = Settings.Properties.HideToolbarWhenUnmuted.Value;

            switch (Settings.Properties.ToolbarPosition.Value)
            {
            case "Top left corner":
                _toolbarPositionIndex = 0;
                break;

            case "Top center":
                _toolbarPositionIndex = 1;
                break;

            case "Top right corner":
                _toolbarPositionIndex = 2;
                break;

            case "Bottom left corner":
                _toolbarPositionIndex = 3;
                break;

            case "Bottom center":
                _toolbarPositionIndex = 4;
                break;

            case "Bottom right corner":
                _toolbarPositionIndex = 5;
                break;
            }

            switch (Settings.Properties.ToolbarMonitor.Value)
            {
            case "Main monitor":
                _toolbarMonitorIndex = 0;
                break;

            case "All monitors":
                _toolbarMonitorIndex = 1;
                break;
            }

            if (shouldSaveSettings)
            {
                _settingsUtils.SaveSettings(Settings.ToJsonString(), ModuleName);
            }
        }
Ejemplo n.º 20
0
        public void OverloadSettings()
        {
            Monitor.Enter(_watcherSyncObject);
            var retry      = true;
            var retryCount = 0;

            while (retry)
            {
                try
                {
                    retryCount++;
                    CreateSettingsIfNotExists();

                    var overloadSettings = _settingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.ModuleName);

                    var openPowerlauncher = ConvertHotkey(overloadSettings.Properties.OpenPowerLauncher);
                    if (_settings.Hotkey != openPowerlauncher)
                    {
                        _settings.Hotkey = openPowerlauncher;
                    }

                    var shell = PluginManager.AllPlugins.Find(pp => pp.Metadata.Name == "Shell");
                    if (shell != null)
                    {
                        var shellSettings = shell.Plugin as ISettingProvider;
                        shellSettings.UpdateSettings(overloadSettings);
                    }

                    if (_settings.MaxResultsToShow != overloadSettings.Properties.MaximumNumberOfResults)
                    {
                        _settings.MaxResultsToShow = overloadSettings.Properties.MaximumNumberOfResults;
                    }

                    if (_settings.IgnoreHotkeysOnFullscreen != overloadSettings.Properties.IgnoreHotkeysInFullscreen)
                    {
                        _settings.IgnoreHotkeysOnFullscreen = overloadSettings.Properties.IgnoreHotkeysInFullscreen;
                    }

                    // Using OrdinalIgnoreCase since this is internal
                    var indexer = PluginManager.AllPlugins.Find(p => p.Metadata.Name.Equals("Windows Indexer", StringComparison.OrdinalIgnoreCase));
                    if (indexer != null)
                    {
                        var indexerSettings = indexer.Plugin as ISettingProvider;
                        indexerSettings.UpdateSettings(overloadSettings);
                    }

                    if (_settings.ClearInputOnLaunch != overloadSettings.Properties.ClearInputOnLaunch)
                    {
                        _settings.ClearInputOnLaunch = overloadSettings.Properties.ClearInputOnLaunch;
                    }

                    if (_settings.Theme != overloadSettings.Properties.Theme)
                    {
                        _settings.Theme = overloadSettings.Properties.Theme;
                        _themeManager.ChangeTheme(_settings.Theme, _settings.Theme == Theme.System);
                    }

                    retry = false;
                }

                // the settings application can hold a lock on the settings.json file which will result in a IOException.
                // This should be changed to properly synch with the settings app instead of retrying.
                catch (IOException e)
                {
                    if (retryCount > MaxRetries)
                    {
                        retry = false;
                        Log.Exception($"Failed to Deserialize PowerToys settings, Retrying {e.Message}", e, GetType());
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                catch (JsonException e)
                {
                    if (retryCount > MaxRetries)
                    {
                        retry = false;
                        Log.Exception($"Failed to Deserialize PowerToys settings, Creating new settings as file could be corrupted {e.Message}", e, GetType());

                        // Settings.json could possibly be corrupted. To mitigate this we delete the
                        // current file and replace it with a correct json value.
                        _settingsUtils.DeleteSettings(PowerLauncherSettings.ModuleName);
                        CreateSettingsIfNotExists();
                        ErrorReporting.ShowMessageBox(Properties.Resources.deseralization_error_title, Properties.Resources.deseralization_error_message);
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
            }

            Monitor.Exit(_watcherSyncObject);
        }
Ejemplo n.º 21
0
        public GeneralViewModel(ISettingsUtils settingsUtils, string runAsAdminText, string runAsUserText, bool isElevated, bool isAdmin, Func <string, int> updateTheme, Func <string, int> ipcMSGCallBackFunc, Func <string, int> ipcMSGRestartAsAdminMSGCallBackFunc, Func <string, int> ipcMSGCheckForUpdatesCallBackFunc, string configFileSubfolder = "")
        {
            CheckFoUpdatesEventHandler        = new ButtonClickCommand(CheckForUpdates_Click);
            RestartElevatedButtonEventHandler = new ButtonClickCommand(Restart_Elevated);
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            try
            {
                GeneralSettingsConfigs = _settingsUtils.GetSettings <GeneralSettings>(string.Empty);

                if (Helper.CompareVersions(GeneralSettingsConfigs.PowertoysVersion, Helper.GetProductVersion()) < 0)
                {
                    // Update settings
                    GeneralSettingsConfigs.PowertoysVersion = Helper.GetProductVersion();
                    _settingsUtils.SaveSettings(GeneralSettingsConfigs.ToJsonString(), string.Empty);
                }
            }
            catch (FormatException e)
            {
                // If there is an issue with the version number format, don't migrate settings.
                Debug.WriteLine(e.Message);
            }
            catch
            {
                GeneralSettingsConfigs = new GeneralSettings();
                _settingsUtils.SaveSettings(GeneralSettingsConfigs.ToJsonString(), string.Empty);
            }

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            SendCheckForUpdatesConfigMSG = ipcMSGCheckForUpdatesCallBackFunc;
            SendRestartAsAdminConfigMSG  = ipcMSGRestartAsAdminMSGCallBackFunc;

            // set the callback function value to update the UI theme.
            UpdateUIThemeCallBack = updateTheme;
            UpdateUIThemeCallBack(GeneralSettingsConfigs.Theme.ToLower());

            // Update Settings file folder:
            _settingsConfigFileFolder = configFileSubfolder;

            switch (GeneralSettingsConfigs.Theme.ToLower())
            {
            case "light":
                _isLightThemeRadioButtonChecked = true;
                break;

            case "dark":
                _isDarkThemeRadioButtonChecked = true;
                break;

            case "system":
                _isSystemThemeRadioButtonChecked = true;
                break;
            }

            _startup             = GeneralSettingsConfigs.Startup;
            _autoDownloadUpdates = GeneralSettingsConfigs.AutoDownloadUpdates;
            _isElevated          = isElevated;
            _runElevated         = GeneralSettingsConfigs.RunElevated;

            RunningAsUserDefaultText  = runAsUserText;
            RunningAsAdminDefaultText = runAsAdminText;

            _isAdmin = isAdmin;
        }
Ejemplo n.º 22
0
        public FancyZonesViewModel(ISettingsUtils settingsUtils, Func <string, int> ipcMSGCallBackFunc, string configFileSubfolder = "")
        {
            settingsConfigFileFolder = configFileSubfolder;
            _settingsUtils           = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            try
            {
                Settings = _settingsUtils.GetSettings <FancyZonesSettings>(GetSettingsSubPath());
            }
            catch
            {
                Settings = new FancyZonesSettings();
                _settingsUtils.SaveSettings(Settings.ToJsonString(), GetSettingsSubPath());
            }

            LaunchEditorEventHandler = new ButtonClickCommand(LaunchEditor);

            _shiftDrag                       = Settings.Properties.FancyzonesShiftDrag.Value;
            _mouseSwitch                     = Settings.Properties.FancyzonesMouseSwitch.Value;
            _overrideSnapHotkeys             = Settings.Properties.FancyzonesOverrideSnapHotkeys.Value;
            _moveWindowsAcrossMonitors       = Settings.Properties.FancyzonesMoveWindowsAcrossMonitors.Value;
            _moveWindowsBasedOnPosition      = Settings.Properties.FancyzonesMoveWindowsBasedOnPosition.Value;
            _displayChangemoveWindows        = Settings.Properties.FancyzonesDisplayChangeMoveWindows.Value;
            _zoneSetChangeMoveWindows        = Settings.Properties.FancyzonesZoneSetChangeMoveWindows.Value;
            _appLastZoneMoveWindows          = Settings.Properties.FancyzonesAppLastZoneMoveWindows.Value;
            _openWindowOnActiveMonitor       = Settings.Properties.FancyzonesOpenWindowOnActiveMonitor.Value;
            _restoreSize                     = Settings.Properties.FancyzonesRestoreSize.Value;
            _useCursorPosEditorStartupScreen = Settings.Properties.UseCursorposEditorStartupscreen.Value;
            _showOnAllMonitors               = Settings.Properties.FancyzonesShowOnAllMonitors.Value;
            _spanZonesAcrossMonitors         = Settings.Properties.FancyzonesSpanZonesAcrossMonitors.Value;
            _makeDraggedWindowTransparent    = Settings.Properties.FancyzonesMakeDraggedWindowTransparent.Value;
            _highlightOpacity                = Settings.Properties.FancyzonesHighlightOpacity.Value;
            _excludedApps                    = Settings.Properties.FancyzonesExcludedApps.Value;
            EditorHotkey                     = Settings.Properties.FancyzonesEditorHotkey.Value;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            string inactiveColor = Settings.Properties.FancyzonesInActiveColor.Value;

            _zoneInActiveColor = inactiveColor != string.Empty ? inactiveColor : "#F5FCFF";

            string borderColor = Settings.Properties.FancyzonesBorderColor.Value;

            _zoneBorderColor = borderColor != string.Empty ? borderColor : "#FFFFFF";

            string highlightColor = Settings.Properties.FancyzonesZoneHighlightColor.Value;

            _zoneHighlightColor = highlightColor != string.Empty ? highlightColor : "#0078D7";

            GeneralSettings generalSettings;

            try
            {
                generalSettings = _settingsUtils.GetSettings <GeneralSettings>(string.Empty);
            }
            catch
            {
                generalSettings = new GeneralSettings();
                _settingsUtils.SaveSettings(generalSettings.ToJsonString(), string.Empty);
            }

            _isEnabled = generalSettings.Enabled.FancyZones;
        }