Example #1
0
 public ZapScroller()
 {
     m_firstCommand = new CommandWrapper(First, canFirst);
     m_previousCommand = new CommandWrapper(Previous, canPrevious);
     m_nextCommand = new CommandWrapper(Next, canNext);
     m_lastCommand = new CommandWrapper(Last, canLast);
 }
Example #2
0
        public async Task scoped_handler_function()
        {
            var serviceProvider = TestConfiguration.GetServiceProvider();

            var are      = new AutoResetEvent(false);
            var executor = new Executor <ICommandWrapper, Aggregate>()
                           .AddHandler <CommandWrapper <Increment> >((d, s) =>
            {
                are.Set();
            });

            var data = CommandWrapper.From(new Increment(), "One", 1);

            await executor.ExecuteAsync(data, new Aggregate());
        }
Example #3
0
 public virtual void UpdateStatus()
 {
     if (codon != null)
     {
         if (Image == null && codon.Properties.Contains("icon"))
         {
             try {
                 Image = WinFormsResourceService.GetBitmap(codon.Properties["icon"]);
             } catch (ResourceNotFoundException) {}
         }
         Visible = GetVisible();
         command = CommandWrapper.Unwrap(command);
         Enabled = command != null && MenuService.CanExecuteCommand(command, caller);
     }
 }
Example #4
0
        public DualBootViewModel(IPhone phone, IDialogService dialogService)
        {
            this.phone = phone;
            var isChangingDualBoot = new Subject <bool>();

            UpdateStatusWrapper =
                new CommandWrapper <Unit, DualBootStatus>(this, ReactiveCommand.CreateFromTask(GetStatus, isChangingDualBoot),
                                                          dialogService);

            UpdateStatusWrapper.Command.Subscribe(x =>
            {
                IsCapable = x.CanDualBoot;
                IsEnabled = x.IsEnabled;
                IsUpdated = true;
            });

            var canChangeDualBoot = UpdateStatusWrapper.Command.IsExecuting.Select(isExecuting => !isExecuting);

            EnableDualBootWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                    ReactiveCommand.CreateFromTask(EnableDualBoot,
                                                                                                   this.WhenAnyValue(x => x.IsCapable, x => x.IsEnabled,
                                                                                                                     (isCapable, isEnabled) => isCapable && !isEnabled)
                                                                                                   .Merge(canChangeDualBoot)), dialogService);
            EnableDualBootWrapper.Command.Subscribe(async _ =>
            {
                await dialogService.ShowAlert(this, Resources.Done, Resources.DualBootEnabled);
                IsEnabled = !IsEnabled;
            });

            DisableDualBootWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                     ReactiveCommand.CreateFromTask(DisableDualBoot,
                                                                                                    this.WhenAnyValue(x => x.IsCapable, x => x.IsEnabled,
                                                                                                                      (isCapable, isEnabled) => isCapable && isEnabled)
                                                                                                    .Merge(canChangeDualBoot)), dialogService);

            DisableDualBootWrapper.Command.Subscribe(async _ =>
            {
                await dialogService.ShowAlert(this, Resources.Done, Resources.DualBootDisabled);
                IsEnabled = !IsEnabled;
            });


            DisableDualBootWrapper.Command.IsExecuting.Select(x => !x).Subscribe(isChangingDualBoot);
            EnableDualBootWrapper.Command.IsExecuting.Select(x => !x).Subscribe(isChangingDualBoot);

            IsBusyObservable = Observable.Merge(DisableDualBootWrapper.Command.IsExecuting,
                                                EnableDualBootWrapper.Command.IsExecuting, UpdateStatusWrapper.Command.IsExecuting);
        }
Example #5
0
        /// <summary>
        /// This method is called when the btnEditPostCommand's Click event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        private void btnEditPostCommand_Click(object sender, EventArgs e)
        {
            ListViewItem   li = lvPostCommands.SelectedItems[0];
            CommandWrapper cw = new CommandWrapper {
                Command = li.Text, Arguments = li.SubItems[1].Text
            };

            cw = EditCommand(cw);
            if (cw == null)
            {
                return;
            }
            li.Text             = cw.Command;
            li.SubItems[1].Text = cw.Arguments;
            FixLVSize(lvPostCommands);
        }
        public DualBootViewModel(IDialogCoordinator dialogCoordinator)
        {
            var isChangingDualBoot = new Subject <bool>();

            UpdateStatusWrapper =
                new CommandWrapper <Unit, DualBootStatus>(this, ReactiveCommand.CreateFromTask(GetStatus, isChangingDualBoot),
                                                          dialogCoordinator);

            UpdateStatusWrapper.Command.Subscribe(x =>
            {
                IsCapable = x.CanDualBoot;
                IsEnabled = x.IsEnabled;
                IsUpdated = true;
            });

            var canChangeDualBoot = UpdateStatusWrapper.Command.IsExecuting.Select(isExecuting => !isExecuting);

            EnableDualBootWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                    ReactiveCommand.CreateFromTask(EnableDualBoot,
                                                                                                   this.WhenAnyValue(x => x.IsCapable, x => x.IsEnabled,
                                                                                                                     (isCapable, isEnabled) => isCapable && !isEnabled)
                                                                                                   .Merge(canChangeDualBoot)), dialogCoordinator);
            EnableDualBootWrapper.Command.Subscribe(async _ =>
            {
                await dialogCoordinator.ShowMessageAsync(this, "Done", "Dual Bool Enabled!");
                IsEnabled = !IsEnabled;
            });

            DisableDualBootWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                     ReactiveCommand.CreateFromTask(DisableDualBoot,
                                                                                                    this.WhenAnyValue(x => x.IsCapable, x => x.IsEnabled,
                                                                                                                      (isCapable, isEnabled) => isCapable && isEnabled)
                                                                                                    .Merge(canChangeDualBoot)), dialogCoordinator);

            DisableDualBootWrapper.Command.Subscribe(async _ =>
            {
                await dialogCoordinator.ShowMessageAsync(this, "Done", "Dual Boot Disabled!");
                IsEnabled = !IsEnabled;
            });


            DisableDualBootWrapper.Command.IsExecuting.Select(x => !x).Subscribe(isChangingDualBoot);
            EnableDualBootWrapper.Command.IsExecuting.Select(x => !x).Subscribe(isChangingDualBoot);

            IsBusyObs = Observable.Merge(DisableDualBootWrapper.Command.IsExecuting,
                                         EnableDualBootWrapper.Command.IsExecuting, UpdateStatusWrapper.Command.IsExecuting);
        }
        public AdvancedViewModel(IRaspberryPiSettingsService raspberryPiSettingsService, IFileSystemOperations fileSystemOperations,
                                 UIServices uiServices, IDeploymentContext context, IOperationContext operationContext,
                                 ILogCollector logCollector)
        {
            this.raspberryPiSettingsService = raspberryPiSettingsService;
            this.uiServices   = uiServices;
            this.context      = context;
            this.logCollector = logCollector;

            DeleteDownloadedWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                      ReactiveCommand.CreateFromTask(() => DeleteDownloaded(fileSystemOperations)), uiServices.ContextDialog, operationContext);

            CollectLogsCommmandWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(CollectLogs), uiServices.ContextDialog, operationContext);

            IsBusyObservable = Observable.Merge(DeleteDownloadedWrapper.Command.IsExecuting,
                                                CollectLogsCommmandWrapper.Command.IsExecuting);
        }
Example #8
0
        public TaskListViewModel(TaskData taskList, Func <Task, bool> filter)
        {
            Util.RequireNotNull(taskList, "taskList");
            m_taskList = taskList;
            ((INotifyCollectionChanged)m_taskList.Tasks).CollectionChanged += (sender, args) => RefreshFilter();

            Util.RequireNotNull(filter, "filter");
            m_filter = filter;

            m_unfilteredTaskList = new ObservableCollectionPlus <TaskViewModel>();
            m_taskList.Tasks.ForEach(t => m_unfilteredTaskList.Add(new TaskViewModel(t)));

            // Tasks
            m_newTaskCommand       = new CommandWrapper(ShowNewTask, () => m_newTask == null);
            m_cancelNewTaskCommand = new CommandWrapper(() => CancelNewTask(), () => m_newTask != null);
            m_deleteTaskCommand    = new CommandWrapper <Task>(task => DeleteTask(task), task => true);
        }
        public AdvancedViewModel(ILumiaSettingsService lumiaSettingsService, IFileSystemOperations fileSystemOperations,
                                 UIServices uiServices, IDeploymentContext context, IOperationContext operationContext,
                                 IList <Meta <IDiskLayoutPreparer> > diskPreparers,
                                 IWindowsDeployer deployer,
                                 ILogCollector logCollector,
                                 IOperationProgress progress)
        {
            this.lumiaSettingsService = lumiaSettingsService;
            this.uiServices           = uiServices;
            this.context      = context;
            this.deployer     = deployer;
            this.logCollector = logCollector;
            this.progress     = progress;

            DiskPreparers = diskPreparers;

            DeleteDownloadedWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                      ReactiveCommand.CreateFromTask(() => DeleteDownloaded(fileSystemOperations)), uiServices.ContextDialog, operationContext);
            ForceDualBootWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(ForceDualBoot),
                                                                   uiServices.ContextDialog, operationContext);
            ForceSingleBootWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                     ReactiveCommand.CreateFromTask(ForceDisableDualBoot), uiServices.ContextDialog, operationContext);

            BackupCommandWrapper =
                new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(Backup), uiServices.ContextDialog, operationContext);
            RestoreCommandWrapper =
                new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(Restore), uiServices.ContextDialog, operationContext);

            CollectLogsCommmandWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(CollectLogs), uiServices.ContextDialog, operationContext);

            IsBusyObservable = Observable.Merge(DeleteDownloadedWrapper.Command.IsExecuting,
                                                BackupCommandWrapper.Command.IsExecuting, RestoreCommandWrapper.Command.IsExecuting,
                                                ForceDualBootWrapper.Command.IsExecuting, ForceSingleBootWrapper.Command.IsExecuting,
                                                CollectLogsCommmandWrapper.Command.IsExecuting);

            preparerUpdater = this.WhenAnyValue(x => x.SelectedPreparer)
                              .Where(x => x != null)
                              .Subscribe(x =>
            {
                context.DiskLayoutPreparer        = x.Value;
                lumiaSettingsService.DiskPreparer = (string)x.Metadata["Name"];
            });

            SelectedPreparer = GetInitialDiskPreparer();
        }
Example #10
0
        public MenuCommand(Codon codon, object caller, bool createCommand, IReadOnlyCollection <ICondition> conditions)
        {
            this.RightToLeft = RightToLeft.Inherit;
            this.caller      = caller;
            this.codon       = codon;
            this.conditions  = conditions;

            if (createCommand)
            {
                this.command = CommandWrapper.CreateCommand(codon, conditions);
            }
            else
            {
                this.command = CommandWrapper.CreateLazyCommand(codon, conditions);
            }

            UpdateText();
        }
Example #11
0
        public DeploymentViewModel(
            IWindowsOptionsProvider optionsProvider,
            IWoaDeployer deployer, UIServices uiServices, AdvancedViewModel advancedViewModel,
            WimPickViewModel wimPickViewModel)
        {
            this.optionsProvider   = optionsProvider;
            this.deployer          = deployer;
            this.uiServices        = uiServices;
            this.advancedViewModel = advancedViewModel;
            this.wimPickViewModel  = wimPickViewModel;

            var isSelectedWim = wimPickViewModel.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                                .Select(metadata => metadata != null);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(Deploy, isSelectedWim), uiServices.Dialog);
            IsBusyObservable = FullInstallWrapper.Command.IsExecuting;
            isBusyHelper     = IsBusyObservable.ToProperty(this, model => model.IsBusy);
        }
Example #12
0
        public string Start()
        {
            if (_commandWrapper != null)
            {
                return(_address);
            }

            var address = Environment.GetEnvironmentVariable("CALCULATOR_SERVICE_LISTEN_ADDRESS") ?? "localhost:0";

            if (address.StartsWith("*:"))
            {
                var hostIpAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(a => a.AddressFamily == AddressFamily.InterNetwork).First();

                address = $"{hostIpAddress}:{address.Split(':', 2)[1]}";
            }

            // TODO add support for linux using https://www.nuget.org/packages/SharpZipLib/ to extract the tarball.

            var processPath = Environment.GetEnvironmentVariable("CALCULATOR_SERVICE_PATH");

            if (processPath == null)
            {
                // NB if you change this, also change it in the Dockerfile.
                var version = "1.0.0";
                var url     = $"https://github.com/rgl/calculator-example-html/releases/download/v{version}/calculator-example-html_{version}_windows_amd64.zip";
                processPath = Path.Combine(Path.GetTempPath(), $"CalculatorServiceLauncherDriver/calculator-example-html-v{version}.exe");

                if (!File.Exists(processPath))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(processPath));

                    using var webClient = new WebClient();
                    var zipData      = webClient.DownloadData(url);
                    var zipArchive   = new ZipArchive(new MemoryStream(zipData), ZipArchiveMode.Read);
                    var processEntry = zipArchive.GetEntry("calculator-example-html.exe");
                    processEntry.ExtractToFile(processPath);
                }
            }

            _commandWrapper = new CommandWrapper();

            return(_address = _commandWrapper.StartAndWaitForListenAddress(processPath, address));
        }
Example #13
0
        public DeploymentViewModel(
            IDeploymentContext context,
            IWoaDeployer deployer, UIServices uiServices, AdvancedViewModel advancedViewModel,
            WimPickViewModel wimPickViewModel, IFileSystemOperations fileSystemOperations, ILumiaSettingsService lumiaSettingsService)
        {
            this.context              = context;
            this.deployer             = deployer;
            this.uiServices           = uiServices;
            this.advancedViewModel    = advancedViewModel;
            this.wimPickViewModel     = wimPickViewModel;
            this.fileSystemOperations = fileSystemOperations;
            this.lumiaSettingsService = lumiaSettingsService;

            var isSelectedWim = wimPickViewModel.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                                .Select(metadata => metadata != null);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(Deploy, isSelectedWim), uiServices.Dialog);
            IsBusyObservable = FullInstallWrapper.Command.IsExecuting;
            isBusyHelper     = IsBusyObservable.ToProperty(this, model => model.IsBusy);
        }
Example #14
0
 protected override void BeginProcessing()
 {
     this.commandWrapper = new CommandWrapper();
     if (string.Equals(base.ParameterSetName, "File", StringComparison.OrdinalIgnoreCase))
     {
         this.commandWrapper.Initialize(base.Context, "out-file", typeof(OutFileCommand));
         this.commandWrapper.AddNamedParameter("filepath", this.fileName);
         this.commandWrapper.AddNamedParameter("append", this.append);
     }
     else if (string.Equals(base.ParameterSetName, "LiteralFile", StringComparison.OrdinalIgnoreCase))
     {
         this.commandWrapper.Initialize(base.Context, "out-file", typeof(OutFileCommand));
         this.commandWrapper.AddNamedParameter("LiteralPath", this.fileName);
         this.commandWrapper.AddNamedParameter("append", this.append);
     }
     else
     {
         this.commandWrapper.Initialize(base.Context, "set-variable", typeof(SetVariableCommand));
         this.commandWrapper.AddNamedParameter("name", this.variable);
     }
 }
Example #15
0
 /// <summary>
 ///
 /// </summary>
 protected override void BeginProcessing()
 {
     _commandWrapper = new CommandWrapper();
     if (String.Equals(ParameterSetName, "File", StringComparison.OrdinalIgnoreCase))
     {
         _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand));
         _commandWrapper.AddNamedParameter("filepath", _fileName);
         _commandWrapper.AddNamedParameter("append", _append);
     }
     else if (String.Equals(ParameterSetName, "LiteralFile", StringComparison.OrdinalIgnoreCase))
     {
         _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand));
         _commandWrapper.AddNamedParameter("LiteralPath", _fileName);
         _commandWrapper.AddNamedParameter("append", _append);
     }
     else
     {
         // variable parameter set
         _commandWrapper.Initialize(Context, "set-variable", typeof(SetVariableCommand));
         _commandWrapper.AddNamedParameter("name", _variable);
         // Can't use set-var's passthru because it writes the var object to the pipeline, we want just
         // the values to be written
     }
 }
        public PrismModuleStatusViewModel(
            IModuleCatalog moduleCatalog,
            IModuleManager moduleManager)
        {
            IsVisible = AppArguments.Instance.IsDebugMode;
            
            this.moduleManager = moduleManager;
            moduleList
                .Connect()
                .Bind(out var modules)
                .Subscribe()
                .AddTo(Anchors);

            Modules = modules;

            Observable.FromEventPattern<EventHandler<LoadModuleCompletedEventArgs>, LoadModuleCompletedEventArgs>(
                    h => moduleManager.LoadModuleCompleted += h,
                    h => moduleManager.LoadModuleCompleted -= h)
                .StartWithDefault()
                .Select(() => moduleCatalog.Modules.Select(x => new PrismModuleStatus(x)).ToArray())
                .DistinctUntilChanged()
                .Subscribe(
                    items =>
                    {
                        moduleList.Clear();
                        moduleList.AddRange(items);
                    })
                .AddTo(Anchors);

            allModulesLoaded = modules.ToObservableChangeSet()
                .Select(() => modules.Any() && modules.All(x => x.IsLoaded))
                .ToPropertyHelper(this, x => x.AllModulesLoaded)
                .AddTo(Anchors);
            
            LoadModuleCommand = CommandWrapper.Create<PrismModuleStatus>(LoadModuleCommandExecuted, LoadModuleCommandCanExecute);
        }
Example #17
0
        public MainWindowViewModel(
            [NotNull] IAppArguments appArguments,
            [NotNull] IFactory <IStartupManager, StartupManagerArgs> startupManagerFactory,
            [NotNull] IMicrophoneControllerEx microphoneController,
            [NotNull] IMicSwitchOverlayViewModel overlay,
            [NotNull] IAudioNotificationsManager audioNotificationsManager,
            [NotNull] IFactory <IAudioNotificationSelectorViewModel> audioSelectorFactory,
            [NotNull] IApplicationUpdaterViewModel appUpdater,
            [NotNull][Dependency(WellKnownWindows.MainWindow)] IWindowTracker mainWindowTracker,
            [NotNull] IConfigProvider <MicSwitchConfig> configProvider,
            [NotNull] IComplexHotkeyTracker hotkeyTracker,
            [NotNull] IMicrophoneProvider microphoneProvider,
            [NotNull] IImageProvider imageProvider,
            [NotNull] IViewController viewController,
            [NotNull][Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler)
        {
            var startupManagerArgs = new StartupManagerArgs
            {
                UniqueAppName   = $"{appArguments.AppName}{(appArguments.IsDebugMode ? "-debug" : string.Empty)}",
                ExecutablePath  = appUpdater.GetLatestExecutable().FullName,
                CommandLineArgs = appArguments.StartupArgs,
                AutostartFlag   = appArguments.AutostartFlag
            };

            this.startupManager = startupManagerFactory.Create(startupManagerArgs);

            this.appArguments         = appArguments;
            this.microphoneController = microphoneController;

            ApplicationUpdater     = appUpdater;
            this.mainWindowTracker = mainWindowTracker;
            this.configProvider    = configProvider;
            this.imageProvider     = imageProvider;
            this.RaiseWhenSourceValue(x => x.IsActive, mainWindowTracker, x => x.IsActive).AddTo(Anchors);

            AudioSelectorWhenMuted   = audioSelectorFactory.Create();
            AudioSelectorWhenUnmuted = audioSelectorFactory.Create();

            Observable.Merge(
                AudioSelectorWhenMuted.ObservableForProperty(x => x.SelectedValue, skipInitial: true),
                AudioSelectorWhenUnmuted.ObservableForProperty(x => x.SelectedValue, skipInitial: true))
            .Subscribe(() => this.RaisePropertyChanged(nameof(AudioNotification)), Log.HandleException)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.Notification)
            .ObserveOn(uiScheduler)
            .Subscribe(cfg =>
            {
                Log.Debug($"Applying new notification configuration: {cfg.DumpToTextRaw()} (current: {AudioNotification.DumpToTextRaw()})");
                AudioNotification = cfg;
            }, Log.HandleException)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.IsPushToTalkMode)
            .ObserveOn(uiScheduler)
            .Subscribe(x =>
            {
                IsPushToTalkMode = x;
                if (isPushToTalkMode)
                {
                    MuteMicrophoneCommand.Execute(true);
                }
            }, Log.HandleException)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.SuppressHotkey)
            .ObserveOn(uiScheduler)
            .Subscribe(x => SuppressHotkey = x, Log.HandleException)
            .AddTo(Anchors);

            Observable.Merge(configProvider.ListenTo(x => x.MicrophoneHotkey), configProvider.ListenTo(x => x.MicrophoneHotkeyAlt))
            .Select(x => new
            {
                Hotkey    = (HotkeyGesture) new HotkeyConverter().ConvertFrom(configProvider.ActualConfig.MicrophoneHotkey ?? string.Empty),
                HotkeyAlt = (HotkeyGesture) new HotkeyConverter().ConvertFrom(configProvider.ActualConfig.MicrophoneHotkeyAlt ?? string.Empty),
            })
            .ObserveOn(uiScheduler)
            .Subscribe(cfg =>
            {
                Log.Debug($"Setting new hotkeys configuration: {cfg.DumpToTextRaw()} (current: {hotkey}, alt: {hotkeyAlt})");
                Hotkey    = cfg.Hotkey;
                HotkeyAlt = cfg.HotkeyAlt;
            }, Log.HandleException)
            .AddTo(Anchors);

            Overlay = overlay;

            this.RaiseWhenSourceValue(x => x.RunAtLogin, startupManager, x => x.IsRegistered, uiScheduler).AddTo(Anchors);
            this.RaiseWhenSourceValue(x => x.MicrophoneVolume, microphoneController, x => x.VolumePercent, uiScheduler).AddTo(Anchors);
            this.RaiseWhenSourceValue(x => x.MicrophoneMuted, microphoneController, x => x.Mute, uiScheduler).AddTo(Anchors);
            ImageProvider = imageProvider;

            microphoneProvider.Microphones
            .ToObservableChangeSet()
            .ObserveOn(uiScheduler)
            .Bind(out var microphones)
            .Subscribe()
            .AddTo(Anchors);
            Microphones = microphones;

            this.ObservableForProperty(x => x.MicrophoneMuted, skipInitial: true)
            .DistinctUntilChanged()
            .Where(x => !MicrophoneLine.IsEmpty)
            .Skip(1)     // skip initial setup
            .Subscribe(x =>
            {
                var cfg = configProvider.ActualConfig.Notification;
                var notificationToPlay = x.Value ? cfg.On : cfg.Off;
                Log.Debug($"Playing notification {notificationToPlay} (cfg: {cfg.DumpToTextRaw()})");
                audioNotificationsManager.PlayNotification(notificationToPlay);
            }, Log.HandleUiException)
            .AddTo(Anchors);

            this.WhenAnyValue(x => x.MicrophoneLine)
            .DistinctUntilChanged()
            .Subscribe(x => microphoneController.LineId = x, Log.HandleUiException)
            .AddTo(Anchors);

            Observable.Merge(
                configProvider.ListenTo(x => x.MicrophoneLineId).ToUnit(),
                Microphones.ToObservableChangeSet().ToUnit())
            .Select(_ => configProvider.ActualConfig.MicrophoneLineId)
            .ObserveOn(uiScheduler)
            .Subscribe(configLineId =>
            {
                Log.Debug($"Microphone line configuration changed, lineId: {configLineId}, known lines: {Microphones.DumpToTextRaw()}");

                var micLine = Microphones.FirstOrDefault(line => line.Equals(configLineId));
                if (micLine.IsEmpty)
                {
                    Log.Debug($"Selecting first one of available microphone lines, known lines: {Microphones.DumpToTextRaw()}");
                    micLine = Microphones.FirstOrDefault();
                }
                MicrophoneLine = micLine;
                MuteMicrophoneCommand.ResetError();
            }, Log.HandleUiException)
            .AddTo(Anchors);

            hotkeyTracker
            .WhenAnyValue(x => x.IsActive)
            .ObserveOn(uiScheduler)
            .Subscribe(async isActive =>
            {
                if (isPushToTalkMode)
                {
                    await MuteMicrophoneCommandExecuted(!isActive);
                }
                else
                {
                    await MuteMicrophoneCommandExecuted(!MicrophoneMuted);
                }
            }, Log.HandleUiException)
            .AddTo(Anchors);

            ToggleOverlayLockCommand = CommandWrapper.Create(
                () =>
            {
                if (overlay.IsLocked && overlay.UnlockWindowCommand.CanExecute(null))
                {
                    overlay.UnlockWindowCommand.Execute(null);
                }
                else if (!overlay.IsLocked && overlay.LockWindowCommand.CanExecute(null))
                {
                    overlay.LockWindowCommand.Execute(null);
                }
            });

            ExitAppCommand = CommandWrapper.Create(
                () =>
            {
                Log.Debug("Closing application");
                configProvider.Save(configProvider.ActualConfig);
                Application.Current.Shutdown();
            });

            this.WhenAnyValue(x => x.WindowState)
            .Subscribe(x => ShowInTaskbar = x != WindowState.Minimized, Log.HandleUiException)
            .AddTo(Anchors);

            ShowAppCommand = CommandWrapper.Create(
                () =>
            {
                if (Visibility != Visibility.Visible)
                {
                    viewController.Show();
                }
                else
                {
                    viewController.Hide();
                }
            });

            OpenAppDataDirectoryCommand = CommandWrapper.Create(OpenAppDataDirectory);

            ResetOverlayPositionCommand = CommandWrapper.Create(ResetOverlayPositionCommandExecuted);

            RunAtLoginToggleCommand          = CommandWrapper.Create <bool>(RunAtLoginCommandExecuted);
            MuteMicrophoneCommand            = CommandWrapper.Create <bool>(MuteMicrophoneCommandExecuted);
            SelectMicrophoneIconCommand      = CommandWrapper.Create(SelectMicrophoneIconCommandExecuted);
            SelectMutedMicrophoneIconCommand = CommandWrapper.Create(SelectMutedMicrophoneIconCommandExecuted);
            ResetMicrophoneIconsCommand      = CommandWrapper.Create(ResetMicrophoneIconsCommandExecuted);

            var executingAssemblyName = Assembly.GetExecutingAssembly().GetName();

            Title = $"{(appArguments.IsDebugMode ? "[D]" : "")} {executingAssemblyName.Name} v{executingAssemblyName.Version}";

            WindowState = WindowState.Minimized;
            viewController
            .WhenLoaded
            .Take(1)
            .Select(() => configProvider.ListenTo(y => y.StartMinimized))
            .Switch()
            .Take(1)
            .ObserveOn(uiScheduler)
            .Subscribe(
                x =>
            {
                if (x)
                {
                    Log.Debug($"StartMinimized option is active - minimizing window, current state: {WindowState}");
                    StartMinimized = true;
                    viewController.Hide();
                }
                else
                {
                    Log.Debug($"StartMinimized option is not active - showing window as Normal, current state: {WindowState}");
                    StartMinimized = false;
                    viewController.Show();
                }
            }, Log.HandleUiException)
            .AddTo(Anchors);

            // config processing
            Observable.Merge(
                this.ObservableForProperty(x => x.MicrophoneLine, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.IsPushToTalkMode, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.AudioNotification, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.HotkeyAlt, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.Hotkey, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.SuppressHotkey, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.StartMinimized, skipInitial: true).ToUnit())
            .Throttle(ConfigThrottlingTimeout)
            .ObserveOn(uiScheduler)
            .Subscribe(() =>
            {
                var config = configProvider.ActualConfig.CloneJson();
                config.IsPushToTalkMode    = IsPushToTalkMode;
                config.MicrophoneHotkey    = (Hotkey ?? new HotkeyGesture()).ToString();
                config.MicrophoneHotkeyAlt = (HotkeyAlt ?? new HotkeyGesture()).ToString();
                config.MicrophoneLineId    = MicrophoneLine;
                config.Notification        = AudioNotification;
                config.SuppressHotkey      = SuppressHotkey;
                config.StartMinimized      = StartMinimized;
                configProvider.Save(config);
            }, Log.HandleUiException)
            .AddTo(Anchors);
        }
    static void AddTransitionalParameter(IContainSagaData sagaData, RuntimeSagaInfo sagaInfo, CommandWrapper command)
    {
        if (!sagaInfo.HasTransitionalCorrelationProperty)
        {
            return;
        }
        var transitionalId = sagaInfo.TransitionalAccessor(sagaData);

        if (transitionalId == null)
        {
            //TODO: validate non default for value types
            throw new Exception($"Null transitionalCorrelationProperty is not allowed. SagaDataType: {sagaData.GetType().FullName}.");
        }
        command.AddParameter("TransitionalCorrelationId", transitionalId);
    }
Example #19
0
 internal virtual object BuildSagaData(CommandWrapper command, RuntimeSagaInfo sagaInfo, IContainSagaData sagaData)
 {
     return(sagaInfo.ToJson(sagaData));
 }
Example #20
0
        public MicrophoneControllerViewModel(
            IMicrophoneControllerEx microphoneController,
            IMicrophoneProvider microphoneProvider,
            IComplexHotkeyTracker hotkeyTracker,
            IFactory <IHotkeyTracker> hotkeyTrackerFactory,
            IFactory <IHotkeyEditorViewModel> hotkeyEditorFactory,
            IConfigProvider <MicSwitchConfig> configProvider,
            IConfigProvider <MicSwitchHotkeyConfig> hotkeyConfigProvider,
            [Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler)
        {
            microphoneProvider.Microphones
            .ToObservableChangeSet()
            .ObserveOn(uiScheduler)
            .Bind(out var microphones)
            .SubscribeToErrors(Log.HandleUiException)
            .AddTo(Anchors);
            Microphones = microphones;

            this.microphoneController = microphoneController;
            this.hotkeyTrackerFactory = hotkeyTrackerFactory;
            this.hotkeyEditorFactory  = hotkeyEditorFactory;
            this.hotkeyConfigProvider = hotkeyConfigProvider;
            this.uiScheduler          = uiScheduler;
            MuteMicrophoneCommand     = CommandWrapper.Create <object>(MuteMicrophoneCommandExecuted);
            Hotkey           = PrepareHotkey("Mute/Un-mute microphone", x => x.Hotkey, (config, hotkeyConfig) => config.Hotkey = hotkeyConfig);
            HotkeyToggle     = PrepareHotkey("Toggle microphone state", x => x.HotkeyForToggle, (config, hotkeyConfig) => config.HotkeyForToggle = hotkeyConfig);
            HotkeyMute       = PrepareHotkey("Mute microphone", x => x.HotkeyForMute, (config, hotkeyConfig) => config.HotkeyForMute = hotkeyConfig);
            HotkeyUnmute     = PrepareHotkey("Un-mute microphone", x => x.HotkeyForUnmute, (config, hotkeyConfig) => config.HotkeyForUnmute = hotkeyConfig);
            HotkeyPushToMute = PrepareHotkey("Push-To-Mute", x => x.HotkeyForPushToMute, (config, hotkeyConfig) => config.HotkeyForPushToMute = hotkeyConfig);
            HotkeyPushToTalk = PrepareHotkey("Push-To-Talk", x => x.HotkeyForPushToTalk, (config, hotkeyConfig) => config.HotkeyForPushToTalk = hotkeyConfig);

            PrepareTracker(HotkeyMode.Click, HotkeyToggle)
            .ObservableForProperty(x => x.IsActive, skipInitial: true)
            .SubscribeSafe(x =>
            {
                Log.Debug($"[{x.Sender}] Toggling microphone state: {microphoneController}");
                microphoneController.Mute = !microphoneController.Mute;
            }, Log.HandleUiException)
            .AddTo(Anchors);

            PrepareTracker(HotkeyMode.Hold, HotkeyMute)
            .ObservableForProperty(x => x.IsActive, skipInitial: true)
            .Where(x => x.Value)
            .SubscribeSafe(x =>
            {
                Log.Debug($"[{x.Sender}] Muting microphone: {microphoneController}");
                microphoneController.Mute = true;
            }, Log.HandleUiException)
            .AddTo(Anchors);

            PrepareTracker(HotkeyMode.Hold, HotkeyUnmute)
            .ObservableForProperty(x => x.IsActive, skipInitial: true)
            .Where(x => x.Value)
            .SubscribeSafe(x =>
            {
                Log.Debug($"[{x.Sender}] Un-muting microphone: {microphoneController}");
                microphoneController.Mute = false;
            }, Log.HandleUiException)
            .AddTo(Anchors);

            PrepareTracker(HotkeyMode.Hold, HotkeyPushToTalk)
            .ObservableForProperty(x => x.IsActive, skipInitial: true)
            .SubscribeSafe(x =>
            {
                Log.Debug($"[{x.Sender}] Processing push-to-talk hotkey for microphone: {microphoneController}");
                microphoneController.Mute = !x.Value;
            }, Log.HandleUiException)
            .AddTo(Anchors);

            PrepareTracker(HotkeyMode.Hold, HotkeyPushToMute)
            .ObservableForProperty(x => x.IsActive, skipInitial: true)
            .SubscribeSafe(x =>
            {
                Log.Debug($"[{x.Sender}] Processing push-to-mute hotkey for microphone: {microphoneController}");
                microphoneController.Mute = x.Value;
            }, Log.HandleUiException)
            .AddTo(Anchors);

            this.RaiseWhenSourceValue(x => x.MicrophoneVolume, microphoneController, x => x.VolumePercent, uiScheduler).AddTo(Anchors);
            this.RaiseWhenSourceValue(x => x.MicrophoneMuted, microphoneController, x => x.Mute, uiScheduler).AddTo(Anchors);

            this.WhenAnyValue(x => x.MicrophoneLine)
            .DistinctUntilChanged()
            .SubscribeSafe(x => microphoneController.LineId = x, Log.HandleUiException)
            .AddTo(Anchors);

            hotkeyConfigProvider.ListenTo(x => x.MuteMode)
            .ObserveOn(uiScheduler)
            .Subscribe(x =>
            {
                Log.Debug($"Mute mode loaded from config: {x}");
                MuteMode = x;
            })
            .AddTo(Anchors);

            hotkeyConfigProvider.ListenTo(x => x.EnableAdvancedHotkeys)
            .ObserveOn(uiScheduler)
            .Subscribe(x => EnableAdditionalHotkeys = x)
            .AddTo(Anchors);

            hotkeyConfigProvider.ListenTo(x => x.InitialMicrophoneState)
            .ObserveOn(uiScheduler)
            .Subscribe(x => InitialMicrophoneState = x)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.VolumeControlEnabled)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(x => MicrophoneVolumeControlEnabled = x, Log.HandleException)
            .AddTo(Anchors);

            Observable.Merge(
                configProvider.ListenTo(x => x.MicrophoneLineId).ToUnit(),
                Microphones.ToObservableChangeSet().ToUnit())
            .Select(_ => configProvider.ActualConfig.MicrophoneLineId)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(configLineId =>
            {
                Log.Debug($"Microphone line configuration changed, lineId: {configLineId}, known lines: {Microphones.DumpToTextRaw()}");

                var micLine = Microphones.FirstOrDefault(line => line.Equals(configLineId));
                if (micLine.IsEmpty)
                {
                    Log.Debug($"Selecting first one of available microphone lines, known lines: {Microphones.DumpToTextRaw()}");
                    micLine = Microphones.FirstOrDefault();
                }
                MicrophoneLine = micLine;
                MuteMicrophoneCommand.ResetError();
            }, Log.HandleUiException)
            .AddTo(Anchors);

            this.WhenAnyValue(x => x.MuteMode, x => x.InitialMicrophoneState)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(_ =>
            {
                Log.Debug($"Processing muteMode: {muteMode}, {microphoneController}.Mute: {microphoneController.Mute}");
                switch (muteMode)
                {
                case MuteMode.PushToTalk:
                    Log.Debug($"{muteMode} mute mode is enabled, un-muting microphone");
                    microphoneController.Mute = true;
                    break;

                case MuteMode.PushToMute:
                    microphoneController.Mute = false;
                    Log.Debug($"{muteMode} mute mode is enabled, muting microphone");
                    break;

                case MuteMode.ToggleMute when initialMicrophoneState == MicrophoneState.Mute:
                    Log.Debug($"{muteMode} enabled, muting microphone");
                    microphoneController.Mute = true;
                    break;

                case MuteMode.ToggleMute when initialMicrophoneState == MicrophoneState.Unmute:
                    Log.Debug($"{muteMode} enabled, un-muting microphone");
                    microphoneController.Mute = false;
                    break;

                default:
                    Log.Debug($"{muteMode} enabled, action is not needed");
                    break;
                }
            }, Log.HandleUiException)
            .AddTo(Anchors);

            hotkeyTracker
            .WhenAnyValue(x => x.IsActive)
            .Skip(1)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(async isActive =>
            {
                Log.Debug($"Handling hotkey press (isActive: {isActive}), mute mode: {muteMode}");
                switch (muteMode)
                {
                case MuteMode.PushToTalk:
                    microphoneController.Mute = !isActive;
                    break;

                case MuteMode.PushToMute:
                    microphoneController.Mute = isActive;
                    break;

                case MuteMode.ToggleMute:
                    microphoneController.Mute = !microphoneController.Mute;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(muteMode), muteMode, @"Unsupported mute mode");
                }
            }, Log.HandleUiException)
            .AddTo(Anchors);

            Observable.Merge(
                this.ObservableForProperty(x => x.MuteMode, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.EnableAdditionalHotkeys, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.InitialMicrophoneState, skipInitial: true).ToUnit(),
                Hotkey.ObservableForProperty(x => x.Properties, skipInitial: true).ToUnit())
            .Throttle(ConfigThrottlingTimeout)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(() =>
            {
                var hotkeyConfig      = hotkeyConfigProvider.ActualConfig.CloneJson();
                hotkeyConfig.Hotkey   = Hotkey.Properties;
                hotkeyConfig.MuteMode = muteMode;
                hotkeyConfig.EnableAdvancedHotkeys  = enableAdvancedHotkeys;
                hotkeyConfig.InitialMicrophoneState = initialMicrophoneState;
                hotkeyConfigProvider.Save(hotkeyConfig);
            }, Log.HandleUiException)
            .AddTo(Anchors);

            Observable.Merge(
                this.ObservableForProperty(x => x.MicrophoneLine, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.MicrophoneVolumeControlEnabled, skipInitial: true).ToUnit())
            .Throttle(ConfigThrottlingTimeout)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(() =>
            {
                var config = configProvider.ActualConfig.CloneJson();
                config.MicrophoneLineId     = microphoneLine;
                config.VolumeControlEnabled = microphoneVolumeControlEnabled;
                configProvider.Save(config);
            }, Log.HandleUiException)
            .AddTo(Anchors);
        }
Example #21
0
 private static void OnCommandHandlerAdded(CommandWrapper commandHandler)
 {
     SortedCommandList.Add(commandHandler);
     ResortRecentCommandList();
 }
Example #22
0
        /// <summary>
        /// Execute the command and save to the careKeeper.
        /// </summary>
        /// <param name="parameter">Data Payload that is composed of the table name and a observable collection</param>
        public void Do(object parameter)
        {
            var cw = new CommandWrapper(this, parameter);

            this._careKeeperService.Do(cw);
        }
Example #23
0
 /// <summary>
 /// Handles the <see cref="E:CommandCanExecuteChanged" /> event.
 /// </summary>
 /// <param name="commandWrapper">The command wrapper.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 private static void OnCommandCanExecuteChanged(CommandWrapper commandWrapper, object sender, EventArgs e)
 {
     ((IActionCommand)commandWrapper.Command).RaiseCanExecuteChanged();
 }
Example #24
0
 public override bool CanExecute(object parameter)
 {
     return(CommandWrapper.CanExecute(parameter));
 }
Example #25
0
 public CommandViewModel(Action <BaseViewModel> updateViewModel, Action <CommandModel> addCommandsToList, CommandWrapper cmd = null)
 {
     _updateViewModel   = updateViewModel;
     _addCommandsToList = addCommandsToList;
     _cmd = cmd?.CommandModel ?? new CommandModel();
 }
Example #26
0
        public MainWindowViewModel(
            IAppArguments appArguments,
            IApplicationAccessor applicationAccessor,
            IFactory <IStartupManager, StartupManagerArgs> startupManagerFactory,
            IMicSwitchOverlayViewModel overlay,
            IMicrophoneControllerViewModel microphoneControllerViewModel,
            IOverlayWindowController overlayWindowController,
            IWaveOutDeviceSelectorViewModel waveOutDeviceSelector,
            IAudioNotificationsManager audioNotificationsManager,
            IFactory <IAudioNotificationSelectorViewModel> audioSelectorFactory,
            IApplicationUpdaterViewModel appUpdater,
            [Dependency(WellKnownWindows.MainWindow)] IWindowTracker mainWindowTracker,
            IConfigProvider <MicSwitchConfig> configProvider,
            IConfigProvider <MicSwitchOverlayConfig> overlayConfigProvider,
            IImageProvider imageProvider,
            IErrorMonitorViewModel errorMonitor,
            IAudioNotificationsManager notificationsManager,
            IWindowViewController viewController,
            [Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler)
        {
            Title = $"{(appArguments.IsDebugMode ? "[D]" : "")} {appArguments.AppName} v{appArguments.Version}";

            this.appArguments          = appArguments;
            this.applicationAccessor   = applicationAccessor;
            this.MicrophoneController  = microphoneControllerViewModel.AddTo(Anchors);
            this.mainWindowTracker     = mainWindowTracker;
            this.configProvider        = configProvider;
            this.overlayConfigProvider = overlayConfigProvider;
            this.notificationsManager  = notificationsManager;
            this.viewController        = viewController;
            ApplicationUpdater         = appUpdater.AddTo(Anchors);
            WaveOutDeviceSelector      = waveOutDeviceSelector;
            ImageProvider            = imageProvider;
            ErrorMonitor             = errorMonitor;
            AudioSelectorWhenMuted   = audioSelectorFactory.Create().AddTo(Anchors);
            AudioSelectorWhenUnmuted = audioSelectorFactory.Create().AddTo(Anchors);
            WindowState = WindowState.Minimized;
            Overlay     = overlay.AddTo(Anchors);

            try
            {
                var startupManagerArgs = new StartupManagerArgs
                {
                    UniqueAppName   = $"{appArguments.AppName}{(appArguments.IsDebugMode ? "-debug" : string.Empty)}",
                    ExecutablePath  = appUpdater.LauncherExecutable.FullName,
                    CommandLineArgs = appArguments.StartupArgs,
                    AutostartFlag   = appArguments.AutostartFlag
                };
                this.startupManager     = startupManagerFactory.Create(startupManagerArgs);
                RunAtLoginToggleCommand = CommandWrapper.Create <bool>(RunAtLoginCommandExecuted, Observable.Return(startupManager?.IsReady ?? false));
            }
            catch (Exception e)
            {
                Log.Warn("Failed to initialize startup manager", e);
            }

            this.RaiseWhenSourceValue(x => x.IsActive, mainWindowTracker, x => x.IsActive, uiScheduler).AddTo(Anchors);
            this.RaiseWhenSourceValue(x => x.RunAtLogin, startupManager, x => x.IsRegistered, uiScheduler).AddTo(Anchors);
            this.RaiseWhenSourceValue(x => x.ShowOverlaySettings, Overlay, x => x.OverlayVisibilityMode).AddTo(Anchors);

            audioNotificationSource = Observable.Merge(
                AudioSelectorWhenMuted.ObservableForProperty(x => x.SelectedValue, skipInitial: true),
                AudioSelectorWhenUnmuted.ObservableForProperty(x => x.SelectedValue, skipInitial: true))
                                      .Select(x => new TwoStateNotification
            {
                On  = AudioSelectorWhenUnmuted.SelectedValue,
                Off = AudioSelectorWhenMuted.SelectedValue
            })
                                      .ToProperty(this, x => x.AudioNotification)
                                      .AddTo(Anchors);

            this.WhenAnyValue(x => x.AudioNotificationVolume)
            .Subscribe(x =>
            {
                AudioSelectorWhenUnmuted.Volume = AudioSelectorWhenMuted.Volume = x;
            })
            .AddTo(Anchors);

            MicrophoneController.ObservableForProperty(x => x.MicrophoneMuted, skipInitial: true)
            .DistinctUntilChanged()
            .Where(x => !MicrophoneController.MicrophoneLine.IsEmpty)
            .Select(isMuted => (isMuted.Value ? AudioNotification.Off : AudioNotification.On) ?? default(AudioNotificationType).ToString())
            .Where(notificationToPlay => !string.IsNullOrEmpty(notificationToPlay))
            .Select(notificationToPlay => Observable.FromAsync(async token =>
            {
                Log.Debug($"Playing notification {notificationToPlay}, volume: {audioNotificationVolume}");
                try
                {
                    await audioNotificationsManager.PlayNotification(notificationToPlay, audioNotificationVolume, waveOutDeviceSelector.SelectedItem, token);
                    Log.Debug($"Played notification {notificationToPlay}");
                }
                catch (Exception ex)
                {
                    Log.Debug($"Failed to play notification {notificationToPlay}", ex);
                }
            }))
            .Switch()
            .SubscribeToErrors(Log.HandleUiException)
            .AddTo(Anchors);

            this.WhenAnyValue(x => x.WindowState)
            .SubscribeSafe(x => ShowInTaskbar = x != WindowState.Minimized, Log.HandleUiException)
            .AddTo(Anchors);

            viewController
            .WhenClosing
            .SubscribeSafe(x => HandleWindowClosing(viewController, x), Log.HandleUiException)
            .AddTo(Anchors);

            ToggleOverlayLockCommand         = CommandWrapper.Create(ToggleOverlayCommandExecuted);
            ExitAppCommand                   = CommandWrapper.Create(ExitAppCommandExecuted);
            ShowAppCommand                   = CommandWrapper.Create(ShowAppCommandExecuted);
            OpenAppDataDirectoryCommand      = CommandWrapper.Create(OpenAppDataDirectory);
            ResetOverlayPositionCommand      = CommandWrapper.Create(ResetOverlayPositionCommandExecuted);
            RunAtLoginToggleCommand          = CommandWrapper.Create <bool>(RunAtLoginCommandExecuted, startupManager.WhenAnyValue(x => x.IsReady));
            SelectMicrophoneIconCommand      = CommandWrapper.Create(SelectMicrophoneIconCommandExecuted);
            SelectMutedMicrophoneIconCommand = CommandWrapper.Create(SelectMutedMicrophoneIconCommandExecuted);
            ResetMicrophoneIconsCommand      = CommandWrapper.Create(ResetMicrophoneIconsCommandExecuted);
            AddSoundCommand                  = CommandWrapper.Create(AddSoundCommandExecuted);

            Observable.Merge(configProvider.ListenTo(x => x.Notifications).ToUnit(), configProvider.ListenTo(x => x.NotificationVolume).ToUnit())
            .Select(_ => new { configProvider.ActualConfig.Notifications, configProvider.ActualConfig.NotificationVolume })
            .ObserveOn(uiScheduler)
            .SubscribeSafe(cfg =>
            {
                Log.Debug($"Applying new notification configuration: {cfg.DumpToTextRaw()} (current: {AudioNotification.DumpToTextRaw()}, volume: {AudioNotificationVolume})");
                AudioSelectorWhenMuted.SelectedValue   = cfg.Notifications.Off;
                AudioSelectorWhenUnmuted.SelectedValue = cfg.Notifications.On;
                AudioNotificationVolume = cfg.NotificationVolume;
            }, Log.HandleException)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.MinimizeOnClose)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(x => MinimizeOnClose = x, Log.HandleException)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.OutputDeviceId)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(x => WaveOutDeviceSelector.SelectById(x), Log.HandleException)
            .AddTo(Anchors);

            viewController
            .WhenLoaded
            .Take(1)
            .Select(_ => configProvider.ListenTo(y => y.StartMinimized))
            .Switch()
            .Take(1)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(
                x =>
            {
                if (x)
                {
                    Log.Debug($"StartMinimized option is active - minimizing window, current state: {WindowState}");
                    StartMinimized = true;
                    viewController.Hide();
                }
                else
                {
                    Log.Debug($"StartMinimized option is not active - showing window as Normal, current state: {WindowState}");
                    StartMinimized = false;
                    viewController.Show();
                }
            }, Log.HandleUiException)
            .AddTo(Anchors);

            Observable.Merge(
                microphoneControllerViewModel.ObservableForProperty(x => x.MuteMode, skipInitial: true).ToUnit(),
                waveOutDeviceSelector.ObservableForProperty(x => x.SelectedItem, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.AudioNotification, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.MinimizeOnClose, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.Width, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.Height, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.Top, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.Left, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.AudioNotificationVolume, skipInitial: true).ToUnit(),
                this.ObservableForProperty(x => x.StartMinimized, skipInitial: true).ToUnit())
            .Throttle(ConfigThrottlingTimeout)
            .ObserveOn(uiScheduler)
            .SubscribeSafe(() =>
            {
                var config                = configProvider.ActualConfig.CloneJson();
                config.Notifications      = AudioNotification;
                config.NotificationVolume = AudioNotificationVolume;
                config.StartMinimized     = StartMinimized;
                config.MinimizeOnClose    = MinimizeOnClose;
                config.OutputDeviceId     = waveOutDeviceSelector.SelectedItem?.Id;
                config.MainWindowBounds   = new Rect(Left, Top, Width, Height);
                configProvider.Save(config);
            }, Log.HandleUiException)
            .AddTo(Anchors);

            viewController.WhenLoaded
            .SubscribeSafe(() =>
            {
                Log.Debug($"Main window loaded - loading overlay, current process({CurrentProcess.ProcessName} 0x{CurrentProcess.Id:x8}) main window: {CurrentProcess.MainWindowHandle} ({CurrentProcess.MainWindowTitle})");
                overlayWindowController.RegisterChild(Overlay).AddTo(Anchors);
                Log.Debug("Overlay loaded successfully");
            }, Log.HandleUiException)
            .AddTo(Anchors);

            configProvider.ListenTo(x => x.MainWindowBounds)
            .WithPrevious()
            .ObserveOn(uiScheduler)
            .SubscribeSafe(x =>
            {
                Log.Debug($"Main window config bounds updated: {x}");

                Rect bounds;
                if (x.Current == null)
                {
                    var monitorBounds = UnsafeNative.GetMonitorBounds(Rectangle.Empty).ScaleToWpf();
                    var monitorCenter = monitorBounds.Center();
                    bounds            = new Rect(
                        monitorCenter.X - DefaultSize.Width / 2f,
                        monitorCenter.Y - DefaultSize.Height / 2f,
                        DefaultSize.Width,
                        DefaultSize.Height);
                }
                else
                {
                    bounds = x.Current.Value;
                }

                Left   = bounds.Left;
                Top    = bounds.Top;
                Width  = bounds.Width;
                Height = bounds.Height;
            }, Log.HandleUiException)
            .AddTo(Anchors);

            var theme = Theme.Create(
                Theme.Light,
                primary: SwatchHelper.Lookup[(MaterialDesignColor)PrimaryColor.BlueGrey],
                accent: SwatchHelper.Lookup[(MaterialDesignColor)SecondaryColor.LightBlue]);
            var paletteHelper = new PaletteHelper();

            paletteHelper.SetTheme(theme);
        }
Example #27
0
 protected ServerMonitorBaseViewModel(ICommand refreshCommand, IEqualityComparer <TK> comparer)
 {
     _comparer      = comparer;
     RefreshCommand = new CommandWrapper(refreshCommand, this);
     FilterCommand  = new ActionCommand(UpdateData);
 }
Example #28
0
 private static void OnCommandHandlerRemoved(CommandWrapper commandHandler)
 {
     SortedCommandList.Remove(commandHandler);
     ResortRecentCommandList();
 }
Example #29
0
        public MainViewModel(IObservable <LogEvent> logEvents, ICollection <DeployerItem> deployersItems,
                             ICollection <DriverPackageImporterItem> driverPackageImporterItems, ViewServices viewServices,
                             Func <Task <Phone> > getPhoneFunc)
        {
            DualBootViewModel = new DualBootViewModel(viewServices.DialogCoordinator);

            DeployersItems = deployersItems;

            this.driverPackageImporterItems = driverPackageImporterItems;
            this.viewServices = viewServices;
            this.getPhoneFunc = getPhoneFunc;

            ShowWarningCommand = ReactiveCommand.CreateFromTask(() =>
                                                                viewServices.DialogCoordinator.ShowMessageAsync(this, Resources.TermsOfUseTitle,
                                                                                                                Resources.WarningNotice));

            SetupPickWimCommand();

            var isDeployerSelected =
                this.WhenAnyValue(model => model.SelectedDeployerItem, (DeployerItem x) => x != null);
            var isSelectedWim = this.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                                .Select(metadata => metadata != null);

            var canDeploy =
                isSelectedWim.CombineLatest(isDeployerSelected, (hasWim, hasDeployer) => hasWim && hasDeployer);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(DeployUefiAndWindows, canDeploy), viewServices.DialogCoordinator);
            WindowsInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                    ReactiveCommand.CreateFromTask(DeployWindows, canDeploy), viewServices.DialogCoordinator);
            InjectDriversWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                   ReactiveCommand.CreateFromTask(InjectPostOobeDrivers, isDeployerSelected),
                                                                   viewServices.DialogCoordinator);

            ImportDriverPackageWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                         ReactiveCommand.CreateFromTask(ImportDriverPackage), viewServices.DialogCoordinator);

            var isBusyObs = Observable.Merge(FullInstallWrapper.Command.IsExecuting,
                                             WindowsInstallWrapper.Command.IsExecuting,
                                             InjectDriversWrapper.Command.IsExecuting,
                                             ImportDriverPackageWrapper.Command.IsExecuting);

            var dualBootIsBusyObs = DualBootViewModel.IsBusyObs;

            isBusyHelper = Observable.Merge(isBusyObs, dualBootIsBusyObs)
                           .ToProperty(this, model => model.IsBusy);

            progressHelper = progressSubject
                             .Where(d => !double.IsNaN(d))
                             .ObserveOnDispatcher()
                             .ToProperty(this, model => model.Progress);

            isProgressVisibleHelper = progressSubject
                                      .Select(d => !double.IsNaN(d))
                                      .ToProperty(this, x => x.IsProgressVisible);

            statusHelper = logEvents
                           .Where(x => x.Level == LogEventLevel.Information)
                           .Select(x => new RenderedLogEvent
            {
                Message = x.RenderMessage(),
                Level   = x.Level
            })
                           .ToProperty(this, x => x.Status);

            logLoader = logEvents
                        .Where(x => x.Level == LogEventLevel.Information)
                        .ToObservableChangeSet()
                        .Transform(x => new RenderedLogEvent
            {
                Message = x.RenderMessage(),
                Level   = x.Level
            })
                        .Bind(out this.logEvents)
                        .DisposeMany()
                        .Subscribe();

            hasWimHelper = this.WhenAnyValue(model => model.WimMetadata, (WimMetadataViewModel x) => x != null)
                           .ToProperty(this, x => x.HasWim);
        }
Example #30
0
        void SpellerOperation(object sender, EventArgs e)
        {
            CommandWrapper cw = (CommandWrapper)sender;
            string         checkpath;

            if (cw.CommandID.Guid.Equals(Commands.CommandGroup))
            {
                DocumentSpellChecker ds = (DocumentSpellChecker)EnsureSpellCheckerExists(cw.TargetEditor);
                switch ((SpellCommand)cw.ID)
                {
                case SpellCommand.RemoveHighLight:
                    EnsureSpellCheckerExists(cw.TargetEditor).RemoveWordCheckingHighlights();
                    break;

                case SpellCommand.ClearBuffer:
                    EnsureSpellCheckerExists(cw.TargetEditor).MisSpelledWords.Clear();
                    break;

                case SpellCommand.StopBackground:
                    IsInBackground = false;
                    EnsureSpellCheckerExists(cw.TargetEditor).BackgroundService = false;
                    IsInCheck = false;
                    break;

                case SpellCommand.StartBackground:
                    IsInBackground = true;
                    if (ds.Spelling.Dictionary.DictionaryFolder == null)
                    {
                        ds.Spelling.Dictionary.DictionaryFolder = "Dictionary";
                    }
                    checkpath = Path.Combine(ds.Spelling.Dictionary.DictionaryFolder, ds.Spelling.Dictionary.DictionaryFile);
                    if (!File.Exists(checkpath))
                    {
                        ds.Spelling.Dictionary.DictionaryFile = String.Format("{0}.dic", EnsurePropertiesExists(cw.TargetEditor).LanguageType);
                    }
                    ds.Spelling.SuggestionMode        = EnsurePropertiesExists(cw.TargetEditor).SuggestionType;
                    ds.Spelling.IgnoreAllCapsWords    = EnsurePropertiesExists(cw.TargetEditor).IgnoreUpperCaseWords;
                    ds.Spelling.IgnoreWordsWithDigits = EnsurePropertiesExists(cw.TargetEditor).IgnoreWordsWithDigits;
                    ds.Spelling.MaxSuggestions        = EnsurePropertiesExists(cw.TargetEditor).MaxSuggestionsCount;
                    ds.Spelling.IgnoreHtml            = EnsurePropertiesExists(cw.TargetEditor).IgnoreHtml;
                    ds.Spelling.IgnoreList.AddRange(EnsurePropertiesExists(cw.TargetEditor).IgnoreList);
                    foreach (KeyValuePair <string, string> de in EnsurePropertiesExists(cw.TargetEditor).ReplaceList)
                    {
                        ds.Spelling.ReplaceList[de.Key] = de.Value;
                    }
                    IsInCheck = true;
                    EnsureSpellCheckerExists(cw.TargetEditor).DoWordCheckingHighlights(EnsurePropertiesExists(cw.TargetEditor).HighLightStyle, true);
                    break;

                case SpellCommand.StartWordByWord:
                    if (ds.Spelling.Dictionary.DictionaryFolder == null)
                    {
                        ds.Spelling.Dictionary.DictionaryFolder = "Dictionary";
                    }
                    checkpath = Path.Combine(ds.Spelling.Dictionary.DictionaryFolder, ds.Spelling.Dictionary.DictionaryFile);
                    if (!File.Exists(checkpath))
                    {
                        ds.Spelling.Dictionary.DictionaryFile = String.Format("{0}.dic", EnsurePropertiesExists(cw.TargetEditor).LanguageType);
                    }
                    ds.Spelling.Dictionary.DictionaryFile = String.Format("{0}.dic", EnsurePropertiesExists(cw.TargetEditor).LanguageType);
                    ds.Spelling.SuggestionMode            = EnsurePropertiesExists(cw.TargetEditor).SuggestionType;
                    ds.Spelling.IgnoreAllCapsWords        = EnsurePropertiesExists(cw.TargetEditor).IgnoreUpperCaseWords;
                    ds.Spelling.IgnoreWordsWithDigits     = EnsurePropertiesExists(cw.TargetEditor).IgnoreWordsWithDigits;
                    ds.Spelling.MaxSuggestions            = EnsurePropertiesExists(cw.TargetEditor).MaxSuggestionsCount;
                    ds.Spelling.IgnoreHtml = EnsurePropertiesExists(cw.TargetEditor).IgnoreHtml;
                    ds.Spelling.IgnoreList.AddRange(EnsurePropertiesExists(cw.TargetEditor).IgnoreList);
                    foreach (KeyValuePair <string, string> de in EnsurePropertiesExists(cw.TargetEditor).ReplaceList)
                    {
                        ds.Spelling.ReplaceList[de.Key] = de.Value;
                    }
                    IsInCheck = true;
                    ds.DoWordCheckingHighlights(ds.HighLightStyle, false);
                    break;

                case SpellCommand.StopWordByWord:
                    IsInCheck = false;
                    break;

                case SpellCommand.StopBlock:
                    IsInCheck = false;
                    break;

                case SpellCommand.StartBlock:
                    ds.Spelling.SuggestionMode        = EnsurePropertiesExists(cw.TargetEditor).SuggestionType;
                    ds.Spelling.IgnoreAllCapsWords    = EnsurePropertiesExists(cw.TargetEditor).IgnoreUpperCaseWords;
                    ds.Spelling.IgnoreWordsWithDigits = EnsurePropertiesExists(cw.TargetEditor).IgnoreWordsWithDigits;
                    ds.Spelling.MaxSuggestions        = EnsurePropertiesExists(cw.TargetEditor).MaxSuggestionsCount;
                    IsInCheck = true;
                    ds.DoBlockCheckingHighlights(EnsurePropertiesExists(cw.TargetEditor).HighLightStyle);
                    break;
                }
            }
        }
Example #31
0
 public override void Execute(object parameter)
 {
     CommandWrapper.Execute(parameter, "DeprovisionServer");
 }
Example #32
0
        /// <summary>
        /// Disables a command
        /// </summary>
        /// <param name="command">The command to disable</param>
        public static void DisableCommand(PointBlankCommand command)
        {
            CommandWrapper wrapper = CM.Commands.FirstOrDefault(a => a.CommandClass == command);

            wrapper?.Disable();
        }