Пример #1
0
        public MainViewModel()
        {
            this.activator   = new ViewModelActivator();
            this.exhibitions = new[]
            {
                new ExhibitionViewModel("Fossils Alive!", DateTime.Now.AddSeconds(30)),
                new ExhibitionViewModel("Jurassic Jungle", DateTime.Now.AddMinutes(1)),
                new ExhibitionViewModel("Walk with the Dinosaurs", DateTime.Now.AddMinutes(3))
            }.ToList();

            this
            .WhenActivated(
                disposables =>
            {
                this
                .WhenAnyObservable(x => x.SelectedExhibition.OpenCountdown)
                .Select(
                    timeLeft =>
                {
                    if (timeLeft < TimeSpan.Zero)
                    {
                        return("This exhibition is open!");
                    }
                    else if (timeLeft < TimeSpan.FromSeconds(10))
                    {
                        return("This exhibition is opening very soon...");
                    }
                    else
                    {
                        return($"This exhibition opens in {timeLeft.TotalSeconds:N0} seconds.");
                    }
                })
                .Do(countdown => this.Countdown = countdown)
                .Subscribe()
                .DisposeWith(disposables);
            });
        }
Пример #2
0
        public MainWindowViewModel(MigoProxyService migoProxyService, ConfigProvider configProvider)
        {
            Activator = new ViewModelActivator();

            _cancellationTokenSource = new CancellationTokenSource();
            _migoProxyService        = migoProxyService;
            _configProvider          = configProvider;

            PreheatEnabled     = true;
            PreheatTemperature = 100;
            GcodeFileName      = string.Empty;
            State = "Idle";

            ManualControl      = new ManualControlViewModel(migoProxyService);
            ZOffsetCalibration = new ZOffsetCalibrationModel(migoProxyService);

            Endpoints     = new ObservableCollection <MigoEndpoint>();
            NozzleTValues = new ObservableCollection <TemperaturePoint>();
            BedTValues    = new ObservableCollection <TemperaturePoint>();

            ShowEndpointsDialog        = new Interaction <EndpointsDialogViewModel, EndpointsListModel>();
            ShowEndpointsDialogCommand = ReactiveCommand.CreateFromTask(OnShowEndpointsDialog);

            GCodeFileSelected = ReactiveCommand.CreateFromTask(
                (Func <string, Task>)OnGCodeFileSelected);

            var canStartPrint = this
                                .WhenAnyValue(model => model.GcodeFileName)
                                .Select(x => !string.IsNullOrEmpty(x))
                                .ObserveOn(RxApp.MainThreadScheduler);

            StartPrintCommand = ReactiveCommand.CreateFromTask(StartPrint, canStartPrint);
            StopPrintCommand  = ReactiveCommand.CreateFromTask(StopPrint);

            this.WhenActivated(OnActivated);
        }
        public FeedbackViewModel(ISender sender, IClock clock)
        {
            this.WhenAnyValue(x => x.Idea)
            .Where(selected => selected)
            .Subscribe(x => Issue = false);
            this.WhenAnyValue(x => x.Issue)
            .Where(selected => selected)
            .Subscribe(x => Idea = false);

            var valid = this
                        .WhenAnyValue(
                x => x.Title, x => x.Message,
                x => x.Issue, x => x.Idea,
                x => x.Section,
                (title, message, issue, idea, section) =>
                !string.IsNullOrWhiteSpace(message) &&
                !string.IsNullOrWhiteSpace(title) &&
                (idea || issue) && section >= 0)
                        .Log(this, "Form validity changed")
                        .Publish()
                        .RefCount();

            valid.Subscribe(hasErrors => HasErrors = !hasErrors);
            Submit = ReactiveCommand.CreateFromTask(
                () => sender.Send(Title, Message, Section, Issue),
                valid);

            Activator = new ViewModelActivator();
            this.WhenActivated(disposables =>
            {
                clock.Tick.Select(second => $"{second}s")
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(elapsed => Elapsed = elapsed)
                .DisposeWith(disposables);
            });
        }
Пример #4
0
        public TrackHeaderViewModel(UTrack track)
        {
            this.track          = track;
            SelectSingerCommand = ReactiveCommand.Create <USinger>(singer => {
                if (track.Singer != singer)
                {
                    DocManager.Inst.StartUndoGroup();
                    DocManager.Inst.ExecuteCmd(new TrackChangeSingerCommand(DocManager.Inst.Project, track, singer));
                    DocManager.Inst.EndUndoGroup();
                }
                this.RaisePropertyChanged(nameof(Singer));
                RefreshAvatar();
            });
            SelectPhonemizerCommand = ReactiveCommand.Create <PhonemizerFactory>(factory => {
                if (track.Phonemizer.GetType() != factory.type)
                {
                    DocManager.Inst.StartUndoGroup();
                    DocManager.Inst.ExecuteCmd(new TrackChangePhonemizerCommand(DocManager.Inst.Project, track, factory.Create()));
                    DocManager.Inst.EndUndoGroup();
                }
                this.RaisePropertyChanged(nameof(Phonemizer));
                this.RaisePropertyChanged(nameof(PhonemizerTag));
            });

            Activator = new ViewModelActivator();
            this.WhenActivated((CompositeDisposable disposables) => {
                Disposable.Create(() => {
                    MessageBus.Current.Listen <TracksRefreshEvent>()
                    .Subscribe(_ => {
                        ManuallyRaise();
                    }).DisposeWith(disposables);
                });
            });

            RefreshAvatar();
        }
Пример #5
0
        public MainViewModel()
        {
            var whenAnyColorChanges = this.WhenAny(x => x.Red, x => x.Green, x => x.Blue,
                                                   (r, g, b) => IntegersToColor(r.Value, g.Value, b.Value));

            Activator = new ViewModelActivator();

            this.WhenActivated(d =>
            {
                //create color property
                d(whenAnyColorChanges
                  .Where(c => c != null)
                  .Select(c => new SolidColorBrush(c.Value))
                  .ToProperty(this, x => x.FinalColor, out this.color));

                // create the command
                d(this.SearchCommand = ReactiveCommand.CreateAsyncObservable(
                      whenAnyColorChanges.Select(x => x != null),
                      c => this.GetImages(c as SolidColorBrush).Select(e => e)));

                // subscribe to the result of the command
                d(this.SearchCommand.Select(ie => new ReactiveList <string>(ie)).ToProperty(this, x => x.Images, out this.images));
            });
        }
Пример #6
0
        public MainViewModel()
        {
            this.activator = new ViewModelActivator();
            this.dinosaurModels = new ReactiveList<Data.Dinosaur>(
                Data
                    .Dinosaurs
                    .All
                    .Take(10));
            this.dinosaurs = this
                .dinosaurModels
                .CreateDerivedCollection(
                    selector: dinosaur => new DinosaurViewModel(dinosaur.Name));

            this
                .WhenActivated(
                    disposables =>
                    {
                        Observable
                            .Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
                            .Do(_ => MakeRandomChange())
                            .Subscribe()
                            .DisposeWith(disposables);
                    });
        }
Пример #7
0
        public DinosaurDetailsViewModel(
            int id,
            IBitmapLoader bitmapLoader = null,
            IApi api = null)
        {
            bitmapLoader = bitmapLoader ?? Locator.Current.GetService <IBitmapLoader>();
            api          = api ?? Locator.Current.GetService <IApi>();

            this.id        = id;
            this.api       = api;
            this.activator = new ViewModelActivator();

            var publishedIsActivated = this
                                       .GetIsActivated()
                                       .Publish();

            this.getCommand = ReactiveCommand.CreateFromObservable(
                this.GetDinosaur);

            this.saveCommand = ReactiveCommand.CreateFromObservable(
                this.SaveDinosaur);

            this.confirmDeleteInteraction = new Interaction <Unit, bool>();

            var canDelete = publishedIsActivated
                            .Select(
                isActivated =>
            {
                if (!isActivated)
                {
                    return(Observable.Empty <bool>());
                }

                // For the purposes of this sample, we assume IsAuditingAvailable ticks on the main thread. Otherwise, we'd need an ObserveOn.
                return(this.api.IsAuditingAvailable);
            })
                            .Switch();

            this.deleteCommand = ReactiveCommand.CreateFromObservable(
                this.DeleteDinosaur,
                canDelete);

            this.isBusy = Observable
                          .CombineLatest(
                this.getCommand.IsExecuting,
                this.saveCommand.IsExecuting,
                this.deleteCommand.IsExecuting,
                (isGetting, isSaving, isDeleting) => isGetting || isSaving || isDeleting)
                          .ToProperty(this, x => x.IsBusy);

            this.validatedWeight = this
                                   .WhenAnyValue(x => x.Weight)
                                   .Select(
                weight =>
            {
                if (int.TryParse(weight, out var validatedWeight))
                {
                    return(Validated <int> .WithValue(validatedWeight));
                }

                return(Validated <int> .WithError($"'{weight}' is not a valid weight. Please enter whole numbers only."));
            })
                                   .ToProperty(this, x => x.ValidatedWeight);

            this.image = this
                         .WhenAnyValue(x => x.ImageData)
                         .SelectMany(
                imageData =>
                Observable
                .Using(
                    () => new MemoryStream(imageData ?? Array.Empty <byte>()),
                    stream => bitmapLoader.Load(stream, null, null).ToObservable()))
                         .ToProperty(this, x => x.Image);

            this
            .getCommand
            .Subscribe(this.PopulateFrom);

            publishedIsActivated
            .Where(isActivated => isActivated)
            .Select(_ => Unit.Default)
            .InvokeCommand(this.getCommand);

            var shouldSave = Observable
                             .Merge(
                this
                .WhenAnyValue(x => x.Name, x => x.ValidatedWeight, x => x.Image, IsValid)
                .Skip(1)
                .Where(isValid => isValid)
                .Throttle(TimeSpan.FromSeconds(2), RxApp.MainThreadScheduler)
                .Select(_ => Unit.Default),
                publishedIsActivated
                .Where(isActivated => !isActivated)
                .Select(_ => Unit.Default));

            shouldSave
            .InvokeCommand(this.saveCommand);

            publishedIsActivated
            .Connect();

            this.error = Observable
                         .Merge(
                this
                .getCommand
                .ThrownExceptions
                .Select(ex => new Error(ex, this.getCommand)),
                this
                .getCommand
                .Select(_ => (Error)null),
                this
                .saveCommand
                .ThrownExceptions
                .Select(ex => new Error(ex, this.saveCommand)),
                this
                .saveCommand
                .Select(_ => (Error)null),
                this
                .deleteCommand
                .ThrownExceptions
                .Select(ex => new Error(ex, this.deleteCommand)),
                this
                .deleteCommand
                .Select(_ => (Error)null))
                         .ToProperty(this, x => x.Error);
        }
Пример #8
0
        public ExerciseViewModel(
            IScheduler scheduler,
            Exercise model,
            IObservable <ExecutionContext> executionContext)
        {
            Ensure.ArgumentNotNull(scheduler, nameof(scheduler));
            Ensure.ArgumentNotNull(model, nameof(model));
            Ensure.ArgumentNotNull(executionContext, nameof(executionContext));

            this.activator = new ViewModelActivator();
            this.model     = model;

            var isActivated = this
                              .GetIsActivated();

            var activeExecutionContext = isActivated
                                         .Select(
                activated =>
            {
                if (activated)
                {
                    return(executionContext);
                }
                else
                {
                    return(Observable <ExecutionContext> .Default);
                }
            })
                                         .Switch()
                                         .Publish()
                                         .RefCount();

            this.executionContext = activeExecutionContext
                                    .ToProperty(this, x => x.ExecutionContext, scheduler: scheduler);

            this.progressTimeSpan = activeExecutionContext
                                    .Select(
                ec =>
                ec == null
                            ? Observable.Return(TimeSpan.Zero)
                            : ec
                .WhenAnyValue(x => x.CurrentExerciseProgress)
                .Where(_ => ec.CurrentExercise == this.model)
                .StartWith(TimeSpan.Zero))
                                    .Switch()
                                    .ToProperty(this, x => x.ProgressTimeSpan, scheduler: scheduler);

            this.progress = this
                            .WhenAny(
                x => x.Duration,
                x => x.ProgressTimeSpan,
                (duration, progressTimeSpan) => progressTimeSpan.Value.TotalMilliseconds / duration.Value.TotalMilliseconds)
                            .Select(progressRatio => double.IsNaN(progressRatio) || double.IsInfinity(progressRatio) ? 0d : progressRatio)
                            .Select(progressRatio => Math.Min(1d, progressRatio))
                            .Select(progressRatio => Math.Max(0d, progressRatio))
                            .ToProperty(this, x => x.Progress, scheduler: scheduler);

            this.isActive = Observable
                            .CombineLatest(
                this
                .WhenAnyValue(x => x.ExecutionContext)
                .Select(ec => ec == null ? Observable <TimeSpan> .Never : ec.WhenAnyValue(x => x.SkipAhead))
                .Switch(),
                this
                .WhenAnyValue(x => x.ExecutionContext)
                .Select(ec => ec == null ? Observable <Exercise> .Never : ec.WhenAnyValue(x => x.CurrentExercise))
                .Switch(),
                (skip, current) => skip == TimeSpan.Zero && current == this.model)
                            .ToProperty(this, x => x.IsActive, scheduler: scheduler);
        }
Пример #9
0
        public MainViewModel()
        {
            this.activator = new ViewModelActivator();

            myQ = DependencyService.Get <IMyQService>(DependencyFetchTarget.GlobalInstance);

            canToggleDoor = this.WhenAnyValue(x => x.Door, y => y.DoorState,
                                              (x, y) => x != null && (y == DoorState.Open || y == DoorState.Closed))
                            .ToProperty(this, x => x.CanToggleDoor);

            GetDevicesCommand = ReactiveCommand.CreateFromTask <object, Unit>(
                async _ =>
            {
                if (myQ.IsAuthenticated)
                {
                    var devices = await myQ.GetDevices();
                    if (devices == null)
                    {
                        myQ.SetSecurityToken(string.Empty);
                        ApplicationStore.SecurityToken = string.Empty;
                        await Nav.PushModalAsync(new LoginView());
                    }
                    else
                    {
                        Door      = devices.First();
                        DoorState = await myQ.GetDoorState(devices.First().MyQDeviceId);
                    }
                }
                else
                {
                    await Nav.PushModalAsync(new LoginView());
                }
                return(Unit.Default);
            });


            var canExecuteToggle =
                this.WhenAnyValue(x => x.CanToggleDoor, (arg) => arg == true);

            ToggleDoorCommand = ReactiveCommand.CreateFromTask <object, Unit>(
                async _ =>
            {
                await ToggleDoor();
                return(Unit.Default);
            }, canExecuteToggle);

            SettingsCommand = ReactiveCommand.CreateFromTask <object, Unit>(
                async _ =>
            {
                await Nav.PushModalAsync(new SettingsView());
                return(Unit.Default);
            }
                );

            VoiceCommand = ReactiveCommand.CreateFromTask <string, Unit>(
                async(phrase) =>
            {
                await ProcessSpeechCommand(phrase);
                return(Unit.Default);
            }
                );

            this.WhenActivated(
                d =>
            {
                // this isn't useful but it gets rid of the ambiguous compile error
                IsActiveCount++;
                d(Disposable.Create(() => IsActiveCount--));

                if (string.IsNullOrEmpty(ApplicationStore.SecurityToken) && !myQ.IsAuthenticated)
                {
                    Nav.PushModalAsync(new LoginView());
                }
                else
                {
                    myQ.SetSecurityToken(ApplicationStore.SecurityToken);
                    OnGetDevices();
                }
            });
        }
Пример #10
0
        public ProviderViewModel(
            CreateFolderViewModelFactory createFolder,
            RenameFileViewModelFactory createRename,
            FileViewModelFactory createFile,
            IAuthViewModel authViewModel,
            IFileManager fileManager,
            IProvider provider,
            IScheduler current,
            IScheduler main)
        {
            _provider = provider;
            Folder    = createFolder(this);
            Rename    = createRename(this);

            var canInteract = this
                              .WhenAnyValue(
                x => x.Folder.IsVisible,
                x => x.Rename.IsVisible,
                (folder, rename) => !folder && !rename);

            _canInteract = canInteract
                           .DistinctUntilChanged()
                           .ToProperty(this, x => x.CanInteract, scheduler: current);

            _refresh = ReactiveCommand.CreateFromTask(
                () => provider.Get(CurrentPath),
                canInteract, main);

            _files = _refresh
                     .Select(files => files
                             .Select(file => createFile(file, this))
                             .OrderByDescending(file => file.IsFolder)
                             .ThenBy(file => file.Name)
                             .ToList())
                     .StartWithEmpty()
                     .Where(files => Files == null ||
                            files.Count != Files.Count() ||
                            !files.All(x => Files.Any(y => x.Path == y.Path &&
                                                      x.Modified == y.Modified)))
                     .ToProperty(this, x => x.Files, scheduler: current);

            _isLoading = _refresh
                         .IsExecuting
                         .ToProperty(this, x => x.IsLoading, scheduler: current);

            _isReady = _refresh
                       .IsExecuting
                       .Select(executing => !executing)
                       .Skip(1)
                       .ToProperty(this, x => x.IsReady, scheduler: current);

            var canOpenCurrentPath = this
                                     .WhenAnyValue(x => x.SelectedFile)
                                     .Select(file => file != null && file.IsFolder)
                                     .CombineLatest(_refresh.IsExecuting, (folder, busy) => folder && !busy)
                                     .CombineLatest(canInteract, (open, interact) => open && interact);

            _open = ReactiveCommand.Create(
                () => Path.Combine(CurrentPath, SelectedFile.Name),
                canOpenCurrentPath, main);

            var canCurrentPathGoBack = this
                                       .WhenAnyValue(x => x.CurrentPath)
                                       .Select(path => path.Length > provider.InitialPath.Length)
                                       .CombineLatest(_refresh.IsExecuting, (valid, busy) => valid && !busy)
                                       .CombineLatest(canInteract, (back, interact) => back && interact);

            _back = ReactiveCommand.Create(
                () => Path.GetDirectoryName(CurrentPath),
                canCurrentPathGoBack, main);

            _currentPath = _open
                           .Merge(_back)
                           .DistinctUntilChanged()
                           .Log(this, $"Current path changed in {provider.Name}")
                           .ToProperty(this, x => x.CurrentPath, provider.InitialPath, scheduler: current);

            this.WhenAnyValue(x => x.CurrentPath)
            .Skip(1)
            .Select(path => Unit.Default)
            .InvokeCommand(_refresh);

            this.WhenAnyValue(x => x.CurrentPath)
            .Subscribe(path => SelectedFile = null);

            _isCurrentPathEmpty = this
                                  .WhenAnyValue(x => x.Files)
                                  .Skip(1)
                                  .Where(files => files != null)
                                  .Select(files => !files.Any())
                                  .ToProperty(this, x => x.IsCurrentPathEmpty, scheduler: current);

            _hasErrors = _refresh
                         .ThrownExceptions
                         .Select(exception => true)
                         .Merge(_refresh.Select(x => false))
                         .ToProperty(this, x => x.HasErrors, scheduler: current);

            var canUploadToCurrentPath = this
                                         .WhenAnyValue(x => x.CurrentPath)
                                         .Select(path => path != null)
                                         .CombineLatest(_refresh.IsExecuting, (up, loading) => up && !loading)
                                         .CombineLatest(canInteract, (upload, interact) => upload && interact);

            _uploadToCurrentPath = ReactiveCommand.CreateFromObservable(
                () => Observable
                .FromAsync(fileManager.OpenRead)
                .Where(response => response.Name != null && response.Stream != null)
                .Select(x => _provider.UploadFile(CurrentPath, x.Stream, x.Name))
                .SelectMany(task => task.ToObservable()),
                canUploadToCurrentPath,
                main);

            _uploadToCurrentPath.InvokeCommand(_refresh);

            var canDownloadSelectedFile = this
                                          .WhenAnyValue(x => x.SelectedFile)
                                          .Select(file => file != null && !file.IsFolder)
                                          .CombineLatest(_refresh.IsExecuting, (down, loading) => down && !loading)
                                          .CombineLatest(canInteract, (download, interact) => download && interact);

            _downloadSelectedFile = ReactiveCommand.CreateFromObservable(
                () => Observable
                .FromAsync(() => fileManager.OpenWrite(SelectedFile.Name))
                .Where(stream => stream != null)
                .Select(stream => _provider.DownloadFile(SelectedFile.Path, stream))
                .SelectMany(task => task.ToObservable()),
                canDownloadSelectedFile,
                main);

            var isAuthEnabled = provider.SupportsDirectAuth || provider.SupportsOAuth;
            var canLogout     = provider
                                .IsAuthorized
                                .Select(loggedIn => loggedIn && isAuthEnabled)
                                .DistinctUntilChanged()
                                .CombineLatest(canInteract, (logout, interact) => logout && interact)
                                .ObserveOn(main);

            _logout    = ReactiveCommand.CreateFromTask(provider.Logout, canLogout);
            _canLogout = canLogout
                         .ToProperty(this, x => x.CanLogout, scheduler: current);

            var canDeleteSelection = this
                                     .WhenAnyValue(x => x.SelectedFile)
                                     .Select(file => file != null && !file.IsFolder)
                                     .CombineLatest(_refresh.IsExecuting, (del, loading) => del && !loading)
                                     .CombineLatest(canInteract, (delete, interact) => delete && interact);

            _deleteSelectedFile = ReactiveCommand.CreateFromTask(
                () => provider.Delete(SelectedFile.Path, SelectedFile.IsFolder),
                canDeleteSelection);

            _deleteSelectedFile.InvokeCommand(Refresh);

            var canUnselectFile = this
                                  .WhenAnyValue(x => x.SelectedFile)
                                  .Select(selection => selection != null)
                                  .CombineLatest(_refresh.IsExecuting, (sel, loading) => sel && !loading)
                                  .CombineLatest(canInteract, (unselect, interact) => unselect && interact);

            _unselectFile = ReactiveCommand.Create(
                () => { SelectedFile = null; },
                canUnselectFile);

            _uploadToCurrentPath
            .ThrownExceptions
            .Merge(_deleteSelectedFile.ThrownExceptions)
            .Merge(_downloadSelectedFile.ThrownExceptions)
            .Merge(_refresh.ThrownExceptions)
            .Log(this, $"Exception occured in provider {provider.Name}")
            .Subscribe();

            Auth      = authViewModel;
            Activator = new ViewModelActivator();
            this.WhenActivated(disposable =>
            {
                this.WhenAnyValue(x => x.Auth.IsAuthenticated)
                .Where(authenticated => authenticated)
                .Select(ignore => Unit.Default)
                .InvokeCommand(_refresh)
                .DisposeWith(disposable);

                var interval = TimeSpan.FromSeconds(1);
                Observable.Timer(interval, interval)
                .Select(unit => RefreshingIn - 1)
                .Where(value => value >= 0)
                .ObserveOn(main)
                .Subscribe(x => RefreshingIn = x)
                .DisposeWith(disposable);

                this.WhenAnyValue(x => x.RefreshingIn)
                .Skip(1)
                .Where(refreshing => refreshing == 0)
                .Log(this, $"Refreshing provider {provider.Name} path {CurrentPath}")
                .Select(value => Unit.Default)
                .InvokeCommand(_refresh)
                .DisposeWith(disposable);

                const int refreshPeriod = 30;
                _refresh.Select(results => refreshPeriod)
                .StartWith(refreshPeriod)
                .Subscribe(x => RefreshingIn = x)
                .DisposeWith(disposable);

                this.WhenAnyValue(x => x.CanInteract)
                .Skip(1)
                .Where(interact => interact)
                .Select(x => Unit.Default)
                .InvokeCommand(_refresh);
            });
        }
Пример #11
0
        public ScopeChannelVM(int channelNumber)
        {
            Activator = new ViewModelActivator();
            Protocol  = new ChannelProtocol(null, channelNumber);
            Model     = new ScopeChannel();

            if (App.Mock)
            {
                MockModel = new ScopeChannel();
            }

            ChannelNumber = channelNumber;
            Name          = $"CH{channelNumber}";
            switch (channelNumber)
            {
            case 1: Color = "#F8FC00"; break;

            case 2: Color = "#00FCF8"; break;

            case 3: Color = "#F800F8"; break;

            case 4: Color = "#007CF8"; break;
            }

            Display  = new ScopeCommand <bool>(this, Protocol.Display, "OFF");
            BWLimit  = new ScopeCommand <bool>(this, Protocol.BWLimit, "OFF");
            Coupling = new ScopeCommand <string>(this, Protocol.Coupling, "AC");
            Invert   = new ScopeCommand <bool>(this, Protocol.Invert, "OFF");
            Offset   = new ScopeCommand <double>(this, Protocol.Offset, "0V".ToReal());
            // Use Scale //Range = new ScopeCommand<double>(this, Protocol.Range, "8V".ToReal());
            TCal    = new ScopeCommand <double>(this, Protocol.TCal, "0s".ToReal());
            Scale   = new ScopeCommand <double>(this, Protocol.Scale, "1V".ToReal());
            Probe   = new ScopeCommand <string>(this, Protocol.Probe, "10".ToReal());
            Vernier = new ScopeCommand <bool>(this, Protocol.Vernier, "OFF");
            Units   = new ScopeCommand <string>(this, Protocol.Units, "VOLT");

            AllCommands = new List <IScopeCommand>()
            {
                Display, BWLimit, Coupling, Invert, Offset, TCal,
                Scale, Probe, Units, Vernier
            };

            SelectChannel = ReactiveCommand.CreateFromTask(SelectChannelExecute);

            // Offset units, based on Units
            this.WhenValueChanged(x => x.Units)
            .Subscribe(x => UpdateUnits());

            #region Get/Set All
            var GetAllMessage = ReactiveCommand.Create(() =>
                                                       Debug.WriteLine($"------- Retrieving all CHANNEL{ChannelNumber} values from device ---------"));
            GetAll = ReactiveCommand.Create(async() =>
            {
                AppLocator.TelnetService.AutoGetScreenshotAfterCommand = false;
                try
                {
                    await GetAllMessage.Execute();
                    foreach (var command in AllCommands)
                    {
                        await command.GetCommand.Execute();
                    }
                }
                finally
                {
                    AppLocator.TelnetService.AutoGetScreenshotAfterCommand = true;
                }
            });

            var SetAllMessage = ReactiveCommand.Create(() =>
                                                       Debug.WriteLine($"------- Setting all CHANNEL{ChannelNumber} values on device ---------"));
            SetAll = ReactiveCommand.Create(async() =>
            {
                AppLocator.TelnetService.AutoGetScreenshotAfterCommand = false;
                try
                {
                    await GetAllMessage.Execute();
                    foreach (var command in AllCommands)
                    {
                        await command.SetCommand.Execute();
                    }
                }
                finally
                {
                    AppLocator.TelnetService.AutoGetScreenshotAfterCommand = true;
                }
            });
            #endregion

            // watch our own properties and call commands that update the model

            //this.WhenPropertyChanged(x => x.IsActive)
            //    .InvokeCommand(SetIsActiveCommand);
            this.WhenActivated(disposables =>
            {
                this.HandleActivation();

                Disposable
                .Create(() => this.HandleDeactivation())
                .DisposeWith(disposables);

                foreach (var scopeCommand in AllCommands)
                {
                    scopeCommand.WhenActivated(disposables);
                }

                // update Offset when probe or scale are changed
                this.WhenAnyValue(x => x.Probe.Value, y => y.Scale.Value)
                .Where(x => x.Item1 != null && x.Item1.Length > 0)
                .SubscribeOnUI()
                .Subscribe(x =>
                {
                    var options = this.Protocol.Offset.Options as RealOptions;
                    options.SetChannelOffset(x.Item1, x.Item2);
                });

                // update Scale when probe is changed
                this.WhenAnyValue(vm => vm.Probe.Value)
                .Where(x => x != null && x.Length > 0)
                .SubscribeOnUI()
                .Subscribe((x) => {
                    var options = Protocol.Scale.Options as RealOptions;
                    options.SetChannelScale(x);
                });
#if TCAL
                this.WhenValueChanged(x => x.TCal)
                .ToSignal()
                .InvokeCommand(this, x => x.SetTCalCommand)
                .DisposeWith(disposables);
#endif
            });
        }
        public CreateProjectProgressViewModel(FlutnetAppSettings appSettings, FlutnetProjectSettings projectSettings, NewProjectViewModel screen = null) : base("newprj_progress", screen)
        {
            _appSettings     = appSettings;
            _projectSettings = projectSettings;

            Title                = "New Project";
            Description          = "The project will take some time to generate.\nWait until the procedure finish.\n";
            IsDescriptionVisible = false;

            NextText     = "Finish";
            BackVisible  = false;
            IsFinishPage = true;

            OutputLines = new ObservableCollection <string>();
            // Observe any changes in the observable collection.
            // Note that the property has no public setters, so we
            // assume the collection is mutated by using the Add(),
            // Delete(), Clear() and other similar methods.
            OutputLines
            // Convert the collection to a stream of chunks,
            // so we have IObservable<IChangeSet<TKey, TValue>>
            // type also known as the DynamicData monad.
            .ToObservableChangeSet()
            // Each time the collection changes, we get
            // all updated items at once.
            .ToCollection()
            // Aggregate all the elements in the collection
            // into a multi-line string.
            .Select(lines => string.Join(Environment.NewLine, lines))
            // Then, we convert the multi-line string to the
            // property a multi-line TextBox can bind.
            .ToProperty(this, x => x.Output, out _output, scheduler: RxApp.MainThreadScheduler);

            // Create the command that calls Flutnet CLI
            CreateProject = ReactiveCommand.CreateFromTask(async ct =>
            {
                NewProjectInArg arguments = BuildCommandLineArg();

                CommandLineCallResult callResult = await CommandLineTools.Call <NewProjectOutArg>(arguments, ct, line =>
                {
                    OutputLines.Add(line);
                });

                // This is not the proper way to change property values and raise property change notifications:
                // we should return a public object and subscribe to the command observable
                // so that we can use ReactiveUI framework methods such as ToProperty, BindTo etc.
                if (callResult.Canceled)
                {
                    IsCanceled = true;
                }
                else if (callResult.Failed)
                {
                    IsFailed = true;
                }
                else
                {
                    OutArg result = callResult.CommandResult;
                    if (!result.Success)
                    {
                        IsFailed = true;
                    }
                    else
                    {
                        IsCompletedSuccessfully = true;
                    }
                }
            });

            CreateProject.IsExecuting.ToProperty(this, x => x.IsInProgress, out _isInProgress);
            CreateProject.IsExecuting.BindTo(this, x => x.IsBusy);

            BrowseProject = ReactiveCommand.Create(
                execute: () => Launcher.OpenFolder(Path.Combine(projectSettings.Location, projectSettings.SolutionName)),
                canExecute: this.WhenAnyValue(t => t.IsCompletedSuccessfully));

            // Execute the command when the View is activated
            Activator = new ViewModelActivator();
            this.WhenActivated(disposables =>
            {
                CreateProject.Execute(Unit.Default).Subscribe().DisposeWith(disposables);
            });

            this.WhenAnyValue(t => t.IsInProgress, t => !t).BindTo(this, t => t.NextEnabled);
        }
Пример #13
0
        public SearchViewModel(
            Func <FeedlyItem, SearchItemViewModel> factory,
            INavigationService navigationService,
            ICategoryManager categoryManager,
            ISearchService searchService)
        {
            _factory           = factory;
            _categoryManager   = categoryManager;
            _navigationService = navigationService;
            _searchService     = searchService;

            Feeds  = new ReactiveList <SearchItemViewModel>();
            Search = ReactiveCommand.CreateFromTask(
                () => _searchService.Search(SearchQuery),
                this.WhenAnyValue(x => x.SearchQuery)
                .Select(x => !string.IsNullOrWhiteSpace(x)));

            Feeds.IsEmptyChanged
            .Subscribe(x => IsEmpty = x);
            Search.Select(response => response.Results.Select(_factory))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Do(feeds => Feeds.Clear())
            .Subscribe(Feeds.AddRange);

            Search.IsExecuting.Skip(1)
            .Subscribe(x => IsLoading = x);
            Search.IsExecuting.Skip(1)
            .Select(executing => false)
            .Subscribe(x => IsGreeting = x);
            Search.IsExecuting
            .Where(executing => executing)
            .Subscribe(x => SelectedFeed = null);

            Search.IsExecuting
            .Where(executing => executing)
            .Select(executing => false)
            .Subscribe(x => HasErrors = x);
            Search.ThrownExceptions
            .Select(exception => true)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => HasErrors = x);
            Search.ThrownExceptions
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => Feeds.Clear());

            Categories        = new ReactiveList <Category>();
            ViewCategories    = ReactiveCommand.CreateFromTask(_navigationService.Navigate <ChannelViewModel>);
            RefreshCategories = ReactiveCommand.CreateFromTask(_categoryManager.GetAll);
            RefreshCategories
            .ObserveOn(RxApp.MainThreadScheduler)
            .Do(categories => Categories.Clear())
            .Subscribe(Categories.AddRange);

            this.WhenAnyValue(x => x.SearchQuery)
            .Throttle(TimeSpan.FromSeconds(0.8))
            .Select(query => query?.Trim())
            .DistinctUntilChanged()
            .Where(text => !string.IsNullOrWhiteSpace(text))
            .Select(query => Unit.Default)
            .InvokeCommand(Search);

            this.WhenAnyValue(x => x.SelectedFeed)
            .Do(feed => Feeds.ToList().ForEach(x => x.IsSelected = false))
            .Where(selection => selection != null)
            .Subscribe(x => x.IsSelected = true);

            Added = new Interaction <Unit, bool>();
            Add   = ReactiveCommand.CreateFromTask(DoAdd,
                                                   this.WhenAnyValue(x => x.SelectedCategory, x => x.SelectedFeed)
                                                   .Select(sel => sel.Item1 != null && sel.Item2 != null)
                                                   .DistinctUntilChanged());

            Activator = new ViewModelActivator();
            this.WhenActivated((CompositeDisposable disposables) =>
                               RefreshCategories.Execute().Subscribe());
        }
Пример #14
0
 public ViewModelBase()
 {
     Activator = new ViewModelActivator();
 }
Пример #15
0
        public RemindConnectViewModel()
        {
            Activator = new ViewModelActivator();

            this.Connect = ReactiveCommand.CreateFromObservable(
                ConnectImpl
                , this.WhenAnyValue(u => u.Status).Select(p => p == ConnectStatus.Disconnected)
                );

            this.ContinueConnectWithPin =
                ReactiveCommand.CreateFromObservable <string, Unit>(ContinueConnectWithPinImpl);

            this.CancelConnect =
                ReactiveCommand.CreateFromObservable(CancelConectImpl);


            this.WhenActivated((d) =>
            {
                var totalTime = 5;

                //完成倒计时
                this.WhenAnyValue(u => u.IsSuccess)
                .Merge(this.WhenAnyValue(u => u.IsFail))
                .Where(u => u)
                .SelectMany(_ => Observable.Interval(TimeSpan.FromSeconds(1)))
                .Take(totalTime + 1)
                .Select(u =>
                {
                    return((int)(totalTime - u));
                })
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.RemainCloseSecond, 5)
                .DisposeWith(d);

                this.WhenAnyValue(u => u.RemainCloseSecond)
                .Select(u => u == 0)
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.NeedClose)
                .DisposeWith(d);

                this.WhenAnyValue(u => u.IsNotRemindMeLater)
                .Subscribe(x =>
                {
                    this.Global.Setting.AutoConnect = x;
                })
                .DisposeWith(d);


                var mayCausedError = Observable.Merge(
                    this.Connect.ThrownExceptions,
                    this.ContinueConnectWithPin.ThrownExceptions
                    );

                mayCausedError.Where(u => (u is ConnectionException))
                .Select(u =>
                {
                    var t = ((ConnectionException)u).ErrorType;
                    if (t == ConnectionError.InvalidPin || t == ConnectionError.LostPin)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                })
                .Delay(TimeSpan.FromMilliseconds(50))
                .Merge(this.ContinueConnectWithPin.IsExecuting.Select(u => false))
                .Merge(this.CancelConnect.Select(u => false))
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.RequirePin, false)
                .DisposeWith(d);


                var passErrStream = mayCausedError.Where(u => (u is ConnectionException))
                                    .Select(u =>
                {
                    var t = ((ConnectionException)u).ErrorType;
                    if (t == ConnectionError.InvalidCredient)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                });

                mayCausedError.Select(u => u.Message)
                .Merge(this.CancelConnect.Select(_ => "您已取消连接"))
                .ToPropertyEx(this, x => x.FailMessage)
                .DisposeWith(d);

                mayCausedError.Where(u => (u is ConnectionException))
                .Select(u =>
                {
                    var t = ((ConnectionException)u).ErrorType;
                    if (t == ConnectionError.Unclear || t == ConnectionError.NotConnected)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                })
                .Merge(passErrStream)
                .Merge(this.CancelConnect.Select(_ => true))
                .ToPropertyEx(this, x => x.IsFail, false)
                .DisposeWith(d);

                this.WhenAnyValue(u => u.Global.ConnectStatus)
                .Select(u => u == ConnectStatus.Connected)
                .ToPropertyEx(this, x => x.IsSuccess)
                .DisposeWith(d);

                this.WhenAnyValue(u => u.Global.ConnectStatus)
                .ToPropertyEx(this, x => x.Status)
                .DisposeWith(d);
            });
        }
Пример #16
0
        public MessageListViewModel(string folderId,
                                    FolderType folderType,
                                    MailBoxViewModel mailBox,
                                    IProfileDataQueryFactory queryFactory,
                                    IMailService mailService,
                                    ViewModelActivator activator)
        {
            var canExecute = this.WhenAnyObservable(x => x.Cache.SelectionChanged)
                             .Select(x => x.IndexCount() > 0)
                             .Publish();

            Activator = activator;

            Archive = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                await mailService.MoveMessage(messageIds, FolderType.Archive);
            }, canExecute);

            Delete = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                if (folderType != FolderType.DeletedItems)
                {
                    await mailService.MoveMessage(messageIds, FolderType.DeletedItems);
                }
            }, canExecute);

            MarkAsRead = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                await mailService.UpdateMessage(messageIds)
                .Set(m => m.IsRead, true)
                .ExecuteAsync();
            }, canExecute);

            MarkAsUnread = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                await mailService.UpdateMessage(messageIds)
                .Set(m => m.IsRead, false)
                .ExecuteAsync();
            }, canExecute);

            SetFlag = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                await mailService.UpdateMessage(messageIds)
                .Set(m => m.IsFlagged, true)
                .ExecuteAsync();
            }, canExecute);

            ClearFlag = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                await mailService.UpdateMessage(messageIds)
                .Set(m => m.IsFlagged, false)
                .ExecuteAsync();
            }, canExecute);

            Move = ReactiveCommand.CreateFromTask <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);

                var selectionResult = await mailBox.PromptUserToSelectFolder(
                    messageIds.Count == 1 ? "Move a message" : $"Move {messageIds.Count} messages",
                    "Select another folder to move to:",
                    includeRoot: false,
                    destinationFolder => CanMoveTo(folderId, destinationFolder));

                if (!selectionResult.IsCancelled)
                {
                    await mailService.MoveMessage(messageIds, selectionResult.SelectedFolder.Id);
                }
            }, canExecute);

            MoveToJunk = ReactiveCommand.CreateFromTask <IReadOnlyList <string> >(async messageIds =>
            {
                PrepareMessageIds(ref messageIds);
                await mailService.MoveMessage(messageIds, FolderType.Junk);
            }, canExecute);

            this.WhenActivated(disposables =>
            {
                canExecute.Connect()
                .DisposeWith(disposables);

                Archive.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                Delete.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                SetFlag.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                ClearFlag.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                MarkAsRead.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                MarkAsUnread.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                Move.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                MoveToJunk.ThrownExceptions
                .Do(this.Log().Error)
                .Subscribe()
                .DisposeWith(disposables);

                Observable.CombineLatest(
                    this.WhenAnyValue(x => x.Order),
                    this.WhenAnyValue(x => x.Filter),
                    (order, filter) => (Order: order, Filter: filter))
                .DistinctUntilChanged()
                .Where(x => x.Order != MessageOrder.Sender)
                .Subscribe(x =>
                {
                    Cache?.Dispose();
                    Cache = new VirtualizingCache <MessageSummary, MessageSummaryViewModel, string>(
                        new PersistentVirtualizingSource <MessageSummary, string>(queryFactory,
                                                                                  GetItemSpecification(folderId, x.Order, x.Filter),
                                                                                  GetIndexSpecification(folderId, x.Order, x.Filter)),
                        mailService.MessageChanges
                        .Select(changes => FilterChanges(changes.ForFolder(folderId), x.Filter)),
                        state => new MessageSummaryViewModel(state, this, queryFactory));
                })
                .DisposeWith(disposables);

                this.WhenAnyObservable(x => x.Cache.SelectionChanged)
                .Select(ranges => ranges.Sum(r => r.Length))
                .Do(x => SelectionCount = x)
                .Subscribe()
                .DisposeWith(disposables);

                Disposable.Create(() =>
                {
                    Filter = MessageFilter.None;
                    Cache?.Dispose();
                    Cache          = null;
                    IsSelecting    = false;
                    SelectionCount = 0;
                })
                .DisposeWith(disposables);
            });
        }
Пример #17
0
 protected BaseViewModel()
 {
     _viewModelActivator = new ViewModelActivator();
 }
Пример #18
0
 protected SubScreenViewModel(IScreen hostScreen)
 {
     this.hostScreen = hostScreen;
     activator       = new ViewModelActivator();
 }
Пример #19
0
        public ResultListVM(IScreen screen) : base(screen)
        {
            Title         = ConstTitle;
            resultsSource = new SourceCache <ResultItemVM, string>(x => x.ID);

            AddResultVM = ReactiveCommand.Create((ResultItemVM item) =>
            {
                if (item != null)
                {
                    resultsSource.AddOrUpdate(item);
                }
            }, Observable.Return(true));
            RemoveResultVM = ReactiveCommand.Create((ResultItemVM item) =>
            {
                if (item != null)
                {
                    resultsSource.Remove(item);
                }
            }, Observable.Return(true));

            resultTypes = new ObservableCollection <ResultTypeVM>();
            var languateEnumValues = ((LanguageType[])Enum.GetValues(typeof(LanguageType))).Except(
                new LanguageType[]
            {
                LanguageType.None,
            }
                );

            foreach (var languageType in languateEnumValues)
            {
                resultTypes.Add(new ResultTypeVM()
                {
                    LanguageType = languageType,
                });
            }

            Activator = new ViewModelActivator();
            this.WhenActivated((CompositeDisposable disposables) =>
            {
                foreach (var languageType in languateEnumValues)
                {
                    var resultTypeVM = resultTypes.FirstOrDefault(x => x.LanguageType == languageType);
                    if (resultTypeVM != null)
                    {
                        resultsSource
                        .Connect()
                        .Filter(x => x?.Origin == languageType)
                        .Bind(out var resultsObservable)
                        .Subscribe()
                        .DisposeWith(disposables);
                        resultTypeVM.Results = resultsObservable;
                    }
                }
                // TODO: this code can probably be refactored without two change sets.
                Observable
                .Merge(ResultTypes.Select(x => x.SelectedResults.ToObservableChangeSet()))
                .Bind(out selectedResultsObservable)
                .Do(x => Console.WriteLine(x?.Count))
                .Subscribe()
                .DisposeWith(disposables);
            });
        }
Пример #20
0
        public MainPageViewModel()
        {
            Activator = new ViewModelActivator();

            this.ForceDisconnect = ReactiveCommand.CreateFromTask <string, Unit>(ForceDisconnectImpl);

            this.CancelConnect = ReactiveCommand.Create(() =>
            {
                Global.ConnectStatus = ConnectStatus.Disconnected;
            });

            this.ContinueConnectWithPin = ReactiveCommand.CreateFromTask <string>(async(pin) =>
            {
                await Global.DoConnect.Execute(pin);
            });

            this.ContinueConnectWithPassword = ReactiveCommand.CreateFromTask <string>(async(password) =>
            {
                IUserStorageService service = Locator.Current.GetService <IUserStorageService>();
                try
                {
                    await service.ResetUserPassword(Global.CurrentUser.Username, password, "");
                }
                catch
                {
                    throw new Exception("新密码保存错误");
                }
                await Global.DoConnect.Execute("");
            });

            this.Toggle = ReactiveCommand.CreateFromTask(async() =>
            {
                await Global.Toggle.Execute();
            });

            this.WhenActivated(d =>
            {
                this.WhenAnyValue(x => x.Global.CurrentUser)
                .ToPropertyEx(this, x => x.SelectedUser)
                .DisposeWith(d);

                this.WhenAnyValue(x => x.Global.ConnectStatus)
                .ToPropertyEx(this, x => x.ConnectStatus)
                .DisposeWith(d);

                var errorSource = Observable.Merge(
                    this.ContinueConnectWithPin.ThrownExceptions,
                    this.Toggle.ThrownExceptions,
                    this.ContinueConnectWithPassword.ThrownExceptions
                    );

                var errorStream = errorSource
                                  .Where(u => u is ConnectionException);


                this.WhenAnyValue(x => x.ConnectStatus)
                .Where(u => u == ConnectStatus.Connected)
                .Select(u => Unit.Default)
                .Merge(Observable.Interval(TimeSpan.FromMinutes(10)).Select(p => Unit.Default))
                .SelectMany(async _ => await Locator.Current.GetService <IInternetGatewayService>().GetAccountInfo())
                .Catch(Observable.Return(new AccountInfo
                {
                    Name     = "获取失败",
                    Plan     = "N/A",
                    UsedTime = TimeSpan.FromMinutes(0)
                }))
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.AccountInfo);

                errorStream
                .Select(u => ((ConnectionException)u).ErrorType)
                .Where(u => u == ConnectionError.LostPin || u == ConnectionError.InvalidPin)
                .Select(u => true)
                .Delay(TimeSpan.FromMilliseconds(100), RxApp.MainThreadScheduler)
                .Merge(this.CancelConnect.Select(_ => false))
                .Merge(this.ContinueConnectWithPin.IsExecuting.Select(_ => false))
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.PinRequired)
                .DisposeWith(d);


                errorStream
                .Select(u => ((ConnectionException)u).ErrorType)
                .Where(u => u == ConnectionError.InvalidCredient)
                .Select(u => true)
                .Delay(TimeSpan.FromMilliseconds(100), RxApp.MainThreadScheduler)
                .Merge(this.CancelConnect.Select(_ => false))
                .Merge(this.ContinueConnectWithPassword.IsExecuting.Select(_ => false))
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.PasswordRequired)
                .DisposeWith(d);


                var errorFromDriver = errorSource.Where(u =>
                                                        ((u is ConnectionException ce) && ce.ErrorType == ConnectionError.Unclear) ||
                                                        (!(u is ConnectionException)))
                                      .Select(u => u.Message);


                errorFromDriver
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.AlertMessage)
                .DisposeWith(d);


                errorFromDriver
                .Select(u => true)
                .Merge(
                    errorFromDriver
                    .Delay(TimeSpan.FromMilliseconds(100))
                    .Select(u => false)
                    )
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToPropertyEx(this, x => x.AlertRequired, false)
                .DisposeWith(d);


                errorFromDriver
                .Subscribe(x =>
                {
                    this.Global.ConnectStatus = ConnectStatus.Disconnected;
                })
                .DisposeWith(d);
            });
        }
Пример #21
0
        public TriggerVM()
        {
            Activator = new ViewModelActivator();
            Protocol  = new TriggerProtocol(null);

            Sweep      = new ScopeCommand <string>(this, Protocol.Sweep, "AUTO");
            Mode       = new ScopeCommand <string>(this, Protocol.Mode, nameof(ModeStringOptions.Edge));
            EdgeSource = new ScopeCommand <string>(this, Protocol.Edge.Source, "CHAN1");
            EdgeSlope  = new ScopeCommand <string>(this, Protocol.Edge.Slope, "POS");
            EdgeLevel  = new ScopeCommand <double>(this, Protocol.Edge.Level, "0");

            AllScopeCommands = new List <IScopeCommand>()
            {
                Sweep, Mode, EdgeSource, EdgeSlope, EdgeLevel,
            };

            var GetAllMessage = ReactiveCommand.Create(() =>
                                                       Debug.WriteLine("------- Retrieving all TRIGGER values from device ---------"));

            GetAll = ReactiveCommand.CreateCombined(new[]
            {
                GetAllMessage,
                Sweep.GetCommand,
                Mode.GetCommand,
                EdgeSource.GetCommand,
                EdgeSlope.GetCommand,
                EdgeLevel.GetCommand,
            });

            var SetAllMessage = ReactiveCommand.Create(() =>
                                                       Debug.WriteLine("------- Setting all TRIGGER values on device ---------"));

            SetAll = ReactiveCommand.CreateCombined(new[]
            {
                SetAllMessage,
                Sweep.SetCommand,
                Mode.SetCommand,
                EdgeSource.SetCommand,
                EdgeSlope.SetCommand,
                EdgeLevel.SetCommand,
            });


            this.WhenActivated(disposables =>
            {
                this.HandleActivation();

                Disposable
                .Create(() => this.HandleDeactivation())
                .DisposeWith(disposables);

                foreach (var scopeCommand in AllScopeCommands)
                {
                    scopeCommand.WhenActivated(disposables);
                }

                // Make visible the panel that corresponds to the selected trigger mode
                this.WhenAnyValue(
                    x => x.Mode.Value,
                    x => x == nameof(ModeStringOptions.Edge))
                .ToPropertyEx(this, x => x.IsEdgeMode);

                // Range of edge level trigger is:
                //   (-5x Vertical Scale - Offset) to (+5x Vertical Scale - Offset)
                Timebase.WhenAnyValue(
                    vm => vm.Scale.Value,
                    vm => vm.Offset.Value,
                    (x, y) => {
                    Protocol.Edge.SetLevelRange(x, y);
                    return(0.0);
                });
            });
        }
Пример #22
0
 public BaseViewModel(IScreen hostScreen = null)
 {
     _viewModelActivator = new ViewModelActivator();
     HostScreen = hostScreen ?? Locator.Current.GetService<IScreen>();
 }
        public MainViewModel()
        {
            Activator = new ViewModelActivator();

            IsTimerRunning = false;

            this.WhenActivated(
                disposables => {
                Disposable
                // https://stackoverflow.com/a/5838632/12207453
                .Create(() => BuddyAvatarBitmap?.Dispose())
                .DisposeWith(disposables);
            });

            var canInitiateNewFetch =
                this.WhenAnyValue(vm => vm.Fetching, fetching => !fetching);

            // https://reactiveui.net/docs/handbook/commands/
            // https://reactiveui.net/docs/handbook/scheduling/
            // https://blog.jonstodle.com/task-toobservable-observable-fromasync-task/
            // https://github.com/reactiveui/ReactiveUI/issues/1245
            StalkCommand =
                ReactiveCommand.CreateFromObservable(
                    () => Observable.StartAsync(Stalk),
                    canInitiateNewFetch,
                    RxApp.MainThreadScheduler
                    );

            ContinueCommand =
                ReactiveCommand.CreateFromObservable(
                    () => Observable.StartAsync(Continue),
                    canInitiateNewFetch,
                    RxApp.MainThreadScheduler
                    );

            // Run the "Continue" command once in the beginning in order to fetch the first buddy.
            // https://reactiveui.net/docs/handbook/when-activated/#no-need
            ContinueCommand.Execute().Subscribe();

            // https://reactiveui.net/docs/handbook/commands/canceling#canceling-via-another-observable
            var startTimerCommand = ReactiveCommand.CreateFromObservable(
                () =>
                Observable
                .Return(Unit.Default)
                .Delay(TimeSpan.FromMilliseconds(DecisionTimeMilliseconds))
                .TakeUntil(
                    TriggeringTheTimer
                    .Where(trigger => trigger == TimerTrigger.Stop)));

            startTimerCommand.Subscribe(_ => ContinueCommand.Execute().Subscribe());

            this
            .WhenAnyObservable(vm => vm.TriggeringTheTimer)
            .Do(trigger => {
                if (trigger == TimerTrigger.Start)
                {
                    startTimerCommand.Execute().Subscribe();
                    IsTimerRunning = true;
                }
                else
                {
                    IsTimerRunning = false;
                }
            })
            .Subscribe();
        }
Пример #24
0
        public ContentViewModel(IPlayShellViewModel shellVM, GamesViewModel games, ServersViewModel servers,
                                MissionsViewModel missions, ModsViewModel mods, HomeViewModel home, IUpdateManager updateManager,
                                Func <RepoAppsContextMenu> contextMenu,
                                IViewModelFactory factory, IDialogManager dialogManager)
        {
            _dialogManager = dialogManager;
            HostScreen     = shellVM;
            Games          = games;
            Servers        = servers;
            Missions       = missions;
            Mods           = mods;
            Home           = home;
            UpdateManager  = updateManager;
            Factory        = factory;

            RepoAppsContextMenu = contextMenu();

            Activator = new ViewModelActivator();

            _overlay = this.WhenAnyValue(x => x.ActiveItem.Overlay.ActiveItem)
                       .ToProperty(this, x => x.Overlay, null, Scheduler.Immediate);

            var once = false;

            this.WhenActivated(d => {
                d(this.WhenAnyValue(x => x.ActiveItem.DisplayName)
                  .BindTo(this, x => x.DisplayName));

                d(Games.DoubleClickedCommand.Subscribe(GameBrowserDoubleClicked));

                d(UpdateManager.StateChange.ObserveOn(RxApp.MainThreadScheduler).Subscribe(data => {
                    var customModSet = data.Item1 as CustomCollection;
                    RepoAppsContextMenu.Refresh(customModSet);
                    if (((IIsEmpty)RepoAppsContextMenu).IsEmpty())
                    {
                        IsServerAppsEnabled = 0;
                    }
                    else
                    {
                        IsServerAppsEnabled = null;
                    }
                }));

                d(DomainEvilGlobal.SelectedGame.WhenAnyValue(x => x.ActiveGame)
                  .Subscribe(GameChanged));

                /*            this.WhenAnyValue(x => x.ActiveGame.Mods.LibraryVM.ActiveItem)
                 *          .Where(x => x != null)
                 *          .Subscribe(ActiveItemChanged);*/
                d(ReactiveCommand.Create().SetNewCommand(this, x => x.SwitchMenuOpen)
                  .Select(_ => !IsMenuOpen)
                  .BindTo(this, x => x.IsMenuOpen));

                var observable = shellVM.WhenAnyValue(x => x.GridMode)
                                 .Where(x => x.HasValue)
                                 .Select(x => x.Value ? ViewType.Grid : ViewType.List);

                d(observable.BindTo(Missions, x => x.LibraryVM.ViewType));
                d(observable.BindTo(Mods, x => x.LibraryVM.ViewType));
                d(observable.BindTo(Servers, x => x.LibraryVM.ViewType));

                if (once)
                {
                    return;
                }
                InitializeModules();
                once = true;
            });
        }
Пример #25
0
        private async Task <bool> DeactivatePreviousViewModelsAsync(NavigationType navigationType, Type newViewModelTypeOverride, DeactivationParameters parameters)
        {
            IEnumerable <State> stack = await this.statePersistor.GetAllStatesAsync();

            bool navigationTypeOverriden = false;

            if (stack.Any())
            {
                var viewModelsToDeactivate = stack
                                             .SkipWhile(i => i.ViewModelType != newViewModelTypeOverride)
                                             .Select(i => i.ViewModelType)
                                             .Reverse()
                                             .ToList();

                if (viewModelsToDeactivate.Count == 0)
                {
                    viewModelsToDeactivate.Add(stack.Last().ViewModelType);
                }
                else
                {
                    // target ViewModel already exists on the stack, meaning from the perspective of the existing ViewModels, the navigation is going back
                    navigationType          = NavigationType.Backward;
                    navigationTypeOverriden = true;
                }

                // first check if all can deactivate
                foreach (var viewModelType in viewModelsToDeactivate)
                {
                    var viewModel = await this.viewModelLocator.GetInstanceAsync(viewModelType);

                    if (!await ViewModelActivator.CanDeactivateViewModelAsync(viewModel, navigationType, parameters))
                    {
                        return(false);
                    }
                }

                // if all can deactivate, do so
                foreach (var viewModelType in viewModelsToDeactivate)
                {
                    var viewModel = await this.viewModelLocator.GetInstanceAsync(viewModelType);

                    await ViewModelActivator.DeactivateViewModelAsync(viewModel, navigationType, parameters);
                }

                if (navigationTypeOverriden)
                {
                    foreach (var viewModelType in viewModelsToDeactivate)
                    {
                        // pop the extra ViewModels from the persistence stack
                        await this.statePersistor.PopStateAsync();

                        // when navigating forward to existing ViewModel (large screen with the first View visible) we must manually unhook existing ViewTypes, since they are no longer active
                        var viewType = await this.viewLocator.GetViewTypeAsync(viewModelType);

                        //this.platformNavigator.UnhookType(viewType);
                        this.platformNavigator.GoBack(viewModelType, viewType);
                    }
                }
            }

            return(true);
        }
Пример #26
0
        public MainWindowViewModel()
        {
            DatabaseReady = false;

            Router    = new RoutingState();
            Activator = new ViewModelActivator();

            ShowMenu = false;

            dialogManager   = Locator.Current.GetService <IDialogManager>();
            saftValidator   = Locator.Current.GetService <ISaftValidator>();
            databaseService = Locator.Current.GetService <IDatabaseService>();

            var canOpen = this.WhenValueChanged(x => x.DatabaseReady)
                          .ObserveOn(RxApp.MainThreadScheduler);

            var canClearFiles = this.WhenAnyValue(x => x.RecentFiles, recentFiles => recentFiles != null && recentFiles.Count() > 0);

            ExitCommand          = ReactiveCommand.Create(OnExit);
            OpenSaftCommand      = ReactiveCommand.CreateFromTask(OnOpenSaft, canOpen);
            OpenTransportCommand = ReactiveCommand.Create(OnOpenTransport, canOpen);
            OpenStocksCommand    = ReactiveCommand.CreateFromTask(OnOpenStocks, canOpen);

            OpenRecentFileCommand    = ReactiveCommand.CreateFromTask <string>(OnOpenRecentSaftFile);
            OpenMenuSaftCommand      = ReactiveCommand.Create <string>(OnOpenMenuSaft);
            OpenMenuStocksCommand    = ReactiveCommand.Create <string>(OnOpenMenuStocks);
            OpenMenuTransportCommand = ReactiveCommand.Create <string>(OnOpenMenuTransport);
            ClearRecentFilesCommand  = ReactiveCommand.Create(OnClearRecentFiles);
            OpenPemDialogCommand     = ReactiveCommand.CreateFromTask(OnOpenPemDialog);
            OpenHashDialogCommand    = ReactiveCommand.CreateFromTask(OnOpenHashDialog);

            MenuHeader = new string[]
            {
                "Erros",
                "Cabeçalho"
            };
            MenuTables = new string[]
            {
                "Clientes",
                "Fornecedores",
                "Produtos",
                "Impostos"
            };
            MenuInvoices = new string[]
            {
                "Documentos Faturação",
                "Pagamentos",
                "Documentos Conferência",
                "Documentos Movimentação"
            };
            MenuStock = new string[]
            {
                "Cabeçalho",
                "Produtos",
            };

            this.WhenActivated(disposables =>
            {
                this.WhenValueChanged(x => x.SelectedSaftMenu)
                .InvokeCommand(OpenMenuSaftCommand)
                .DisposeWith(disposables);

                this.WhenValueChanged(x => x.SelectedStocksMenu)
                .InvokeCommand(OpenMenuStocksCommand)
                .DisposeWith(disposables);
            });

            dialogManager.AddMessage("A iniciar base de dados");
            Task.Run(() =>
            {
                databaseService.InitDatabase();
                dialogManager.AddMessage("");

                var recentFiles = databaseService.GetRecentFiles();

                var recentMenu = new List <MenuItemViewModel>(
                    recentFiles.Select(r => new MenuItemViewModel {
                    Header = r, Command = OpenRecentFileCommand, CommandParameter = r
                }))
                {
                    new MenuItemViewModel {
                        Header = "Limpar", Command = ClearRecentFilesCommand
                    }
                };

                RecentFiles         = new ObservableCollection <MenuItemViewModel>();
                var recentFilesMenu = new MenuItemViewModel[]
                {
                    new MenuItemViewModel
                    {
                        Header = "_Recentes",
                        Items  = recentMenu
                    }
                };
                RecentFiles.AddRange(recentFilesMenu);

                DatabaseReady = true;
            });

            dialogManager.UpdateVersionInfo(databaseService.GetAppVersion());
        }
Пример #27
0
        public MainViewModel(
            ProviderViewModelFactory providerFactory,
            AuthViewModelFactory authFactory,
            IProviderStorage storage,
            IFileManager files,
            IScheduler current,
            IScheduler main)
        {
            _storage = storage;
            _refresh = ReactiveCommand.CreateFromTask(
                storage.Refresh,
                outputScheduler: main);

            var providers = storage.Providers();

            providers.Transform(x => providerFactory(x, files, authFactory(x)))
            .ObserveOn(RxApp.MainThreadScheduler)
            .StartWithEmpty()
            .Bind(out _providers)
            .Subscribe();

            _isLoading = _refresh
                         .IsExecuting
                         .ToProperty(this, x => x.IsLoading, scheduler: current);

            _isReady = _refresh
                       .IsExecuting
                       .Skip(1)
                       .Select(executing => !executing)
                       .ToProperty(this, x => x.IsReady, scheduler: current);

            providers.Where(changes => changes.Any())
            .ObserveOn(RxApp.MainThreadScheduler)
            .OnItemAdded(x => SelectedProvider   = Providers.LastOrDefault())
            .OnItemRemoved(x => SelectedProvider = null)
            .Subscribe();

            var canRemove = this
                            .WhenAnyValue(x => x.SelectedProvider)
                            .Select(provider => provider != null);

            _remove = ReactiveCommand.CreateFromTask(
                () => storage.Remove(SelectedProvider.Id),
                canRemove);

            var canAddProvider = this
                                 .WhenAnyValue(x => x.SelectedSupportedType)
                                 .Select(type => !string.IsNullOrWhiteSpace(type));

            _add = ReactiveCommand.CreateFromTask(
                () => storage.Add(SelectedSupportedType),
                canAddProvider);

            _welcomeScreenVisible = this
                                    .WhenAnyValue(x => x.SelectedProvider)
                                    .Select(provider => provider == null)
                                    .ToProperty(this, x => x.WelcomeScreenVisible);

            _welcomeScreenCollapsed = this
                                      .WhenAnyValue(x => x.WelcomeScreenVisible)
                                      .Select(visible => !visible)
                                      .ToProperty(this, x => x.WelcomeScreenCollapsed);

            var canUnSelect = this
                              .WhenAnyValue(x => x.SelectedProvider)
                              .Select(provider => provider != null);

            _unselect = ReactiveCommand.Create(
                () => { SelectedProvider = null; },
                canUnSelect);

            Activator = new ViewModelActivator();
            this.WhenActivated(disposables =>
            {
                SelectedSupportedType = SupportedTypes.FirstOrDefault();
                _refresh.Execute()
                .Subscribe()
                .DisposeWith(disposables);
            });
        }
Пример #28
0
 protected BaseViewModel() : base()
 {
     Activator = new ViewModelActivator();
 }
 public ViewModelBase(ISampleScreen screen = null)
 {
     Activator   = new ViewModelActivator();
     _HostScreen = screen;
 }
Пример #30
0
 protected ViewModel()
 {
     Activator = new ViewModelActivator();
 }