public PullRequestCreationViewModel(
            IModelServiceFactory modelServiceFactory,
            IPullRequestService service,
            INotificationService notifications,
            IMessageDraftStore draftStore,
            IScheduler timerScheduler)
        {
            Guard.ArgumentNotNull(modelServiceFactory, nameof(modelServiceFactory));
            Guard.ArgumentNotNull(service, nameof(service));
            Guard.ArgumentNotNull(notifications, nameof(notifications));
            Guard.ArgumentNotNull(draftStore, nameof(draftStore));
            Guard.ArgumentNotNull(timerScheduler, nameof(timerScheduler));

            this.service             = service;
            this.modelServiceFactory = modelServiceFactory;
            this.draftStore          = draftStore;
            this.timerScheduler      = timerScheduler;

            this.WhenAnyValue(x => x.Branches)
            .WhereNotNull()
            .Where(_ => TargetBranch != null)
            .Subscribe(x =>
            {
                if (!x.Any(t => t.Equals(TargetBranch)))
                {
                    TargetBranch = GitHubRepository.IsFork ? GitHubRepository.Parent.DefaultBranch : GitHubRepository.DefaultBranch;
                }
            });

            SetupValidators();

            var whenAnyValidationResultChanges = this.WhenAny(
                x => x.TitleValidator.ValidationResult,
                x => x.BranchValidator.ValidationResult,
                x => x.IsBusy,
                (x, y, z) => (x.Value?.IsValid ?? false) && (y.Value?.IsValid ?? false) && !z.Value);

            this.WhenAny(x => x.BranchValidator.ValidationResult, x => x.GetValue())
            .WhereNotNull()
            .Where(x => !x.IsValid && x.DisplayValidationError)
            .Subscribe(x => notifications.ShowError(BranchValidator.ValidationResult.Message));

            CreatePullRequest = ReactiveCommand.CreateFromObservable(
                () => service
                .CreatePullRequest(modelService, activeLocalRepo, TargetBranch.Repository, SourceBranch, TargetBranch, PRTitle, Description ?? String.Empty)
                .Catch <IPullRequestModel, Exception>(ex =>
            {
                log.Error(ex, "Error creating pull request");

                //TODO:Will need a uniform solution to HTTP exception message handling
                var apiException = ex as ApiValidationException;
                var error        = apiException?.ApiError?.Errors?.FirstOrDefault();
                notifications.ShowError(error?.Message ?? ex.Message);
                return(Observable.Empty <IPullRequestModel>());
            }),
                whenAnyValidationResultChanges);
            CreatePullRequest.Subscribe(pr =>
            {
                notifications.ShowMessage(String.Format(CultureInfo.CurrentCulture, Resources.PRCreatedUpstream, SourceBranch.DisplayName, TargetBranch.Repository.Owner + "/" + TargetBranch.Repository.Name + "#" + pr.Number,
                                                        TargetBranch.Repository.CloneUrl.ToRepositoryUrl().Append("pull/" + pr.Number)));
                NavigateTo("/pulls?refresh=true");
                Cancel.Execute();
                draftStore.DeleteDraft(GetDraftKey(), string.Empty).Forget();
                Close();
            });

            Cancel = ReactiveCommand.Create(() => { });
            Cancel.Subscribe(_ =>
            {
                Close();
                draftStore.DeleteDraft(GetDraftKey(), string.Empty).Forget();
            });

            isExecuting = CreatePullRequest.IsExecuting.ToProperty(this, x => x.IsExecuting);

            this.WhenAnyValue(x => x.Initialized, x => x.GitHubRepository, x => x.IsExecuting)
            .Select(x => !(x.Item1 && x.Item2 != null && !x.Item3))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => IsBusy = x);
        }
        //private readonly OrderedDictionary

        #endregion

        #region ctors

        public EditArtistsViewModel(IEnumerable <string> initialStrings)
        {
            this._stringsSet = new HashSet <string>(initialStrings);

            var initialStringViewModels = initialStrings.Select(s => new EditArtistViewModel(s));

            this._editArtistViewModelsSourceList = new SourceList <EditArtistViewModel>().DisposeWith(this._disposables);
            this._editArtistViewModelsSourceList.AddRange(initialStringViewModels);

            this._editArtistViewModelsSourceList
            .Connect()
            .Bind(out this._editArtistViewModelsROOC)
            .DisposeMany()
            .Subscribe()
            .DisposeWith(this._disposables);

            this.WhenSelectedEditArtistViewModelChanged = this.WhenAnyValue(x => x.SelectedEditArtistViewModel).DistinctUntilChanged();

            this._hasEditArtistViewModelSelectionOAPH = this.WhenSelectedEditArtistViewModelChanged
                                                        .Select(x => x != null)
                                                        .DistinctUntilChanged()
                                                        .ToProperty(this, nameof(this.HasEditArtistViewModelSelection)
                                                                    //, true // works
                                                                    //, false
                                                                    , scheduler: Scheduler.Immediate
                                                                    )
                                                        .DisposeWith(this._disposables);

            this.WhenSelectedEditArtistViewModelChanged.Subscribe(
                selectedEAVM =>
            {
                if (selectedEAVM != null)
                {
                    this.NewArtistName = null;
                }
            })
            .DisposeWith(this._disposables);

            this.AddNew = ReactiveCommand.Create(
                () =>
            {
                var newEditArtistViewModel = new EditArtistViewModel(this.NewArtistName);
                this.NewArtistName         = null;

                this._editArtistViewModelsSourceList.Edit(list => list.Add(newEditArtistViewModel));
                //this.SelectedEditArtistViewModel = newEditArtistViewModel;

                //return newEditArtistViewModel;
            },
                this.WhenAnyValue(x => x.NewArtistName) /*.Throttle(TimeSpan.FromMilliseconds(200))*/.Select(nan => this.IsValidNewArtistName(nan)))
                          .DisposeWith(this._disposables);

            this.MoveSelectedUp = ReactiveCommand.Create(
                () =>
            {
                var selection = this.SelectedEditArtistViewModel;

                this._editArtistViewModelsSourceList.Edit(list =>
                {
                    var oldIndex = list.IndexOf(selection);
                    if (oldIndex > 0 && list.Remove(selection))
                    {
                        list.Insert(oldIndex - 1, selection);
                    }
                });

                this.SelectedEditArtistViewModel = selection;
            },
                this.WhenSelectedEditArtistViewModelChanged.Select(x => x != null && !this.IsFirst(x)))
                                  .DisposeWith(this._disposables);

            this.MoveSelectedDown = ReactiveCommand.Create(
                () =>
            {
                var selection = this.SelectedEditArtistViewModel;

                this._editArtistViewModelsSourceList.Edit(list =>
                {
                    var oldIndex = list.IndexOf(selection);
                    if (oldIndex < (list.Count - 1) && list.Remove(selection))
                    {
                        list.Insert(oldIndex + 1, selection);
                    }
                });

                this.SelectedEditArtistViewModel = selection;
            },
                this.WhenSelectedEditArtistViewModelChanged.Select(x => x != null && !this.IsLast(x)))
                                    .DisposeWith(this._disposables);

            this.TryRemove = ReactiveCommand.Create(
                (EditArtistViewModel vm) =>
            {
                bool wasRemoved = false;

                this._editArtistViewModelsSourceList.Edit(list =>
                {
                    wasRemoved = list.Remove(vm);
                });

                return(wasRemoved);
            })
                             .DisposeWith(this._disposables);

            this.RemoveSelected = ReactiveCommand.Create(
                () =>
            {
                this._editArtistViewModelsSourceList.Edit(list =>
                {
                    if (!list.Remove(this.SelectedEditArtistViewModel))
                    {
                        // TODO: throw exception if passed element is not contained in the list
                    }
                });
            },
                this.WhenAnyValue(x => x.SelectedEditArtistViewModel).Select(x => x != null))
                                  .DisposeWith(this._disposables);
        }
Exemple #3
0
        internal PcmciaInfoViewModel(byte[] pcmciaCis, Window view)
        {
            if (pcmciaCis == null)
            {
                return;
            }

            cis     = pcmciaCis;
            cisList = new ObservableCollection <PcmciaCisModel>();
            SavePcmciaCisCommand = ReactiveCommand.Create(ExecuteSavePcmciaCisCommand);

            _view = view;

            Tuple[] tuples = CIS.GetTuples(cis);

            if (tuples != null)
            {
                foreach (Tuple tuple in tuples)
                {
                    string tupleCode;
                    string tupleDescription;

                    switch (tuple.Code)
                    {
                    case TupleCodes.CISTPL_NULL:
                    case TupleCodes.CISTPL_END: continue;

                    case TupleCodes.CISTPL_DEVICEGEO:
                    case TupleCodes.CISTPL_DEVICEGEO_A:
                        tupleCode        = "Device Geometry Tuples";
                        tupleDescription = CIS.PrettifyDeviceGeometryTuple(tuple);

                        break;

                    case TupleCodes.CISTPL_MANFID:
                        tupleCode        = "Manufacturer Identification Tuple";
                        tupleDescription = CIS.PrettifyManufacturerIdentificationTuple(tuple);

                        break;

                    case TupleCodes.CISTPL_VERS_1:
                        tupleCode        = "Level 1 Version / Product Information Tuple";
                        tupleDescription = CIS.PrettifyLevel1VersionTuple(tuple);

                        break;

                    case TupleCodes.CISTPL_ALTSTR:
                    case TupleCodes.CISTPL_BAR:
                    case TupleCodes.CISTPL_BATTERY:
                    case TupleCodes.CISTPL_BYTEORDER:
                    case TupleCodes.CISTPL_CFTABLE_ENTRY:
                    case TupleCodes.CISTPL_CFTABLE_ENTRY_CB:
                    case TupleCodes.CISTPL_CHECKSUM:
                    case TupleCodes.CISTPL_CONFIG:
                    case TupleCodes.CISTPL_CONFIG_CB:
                    case TupleCodes.CISTPL_DATE:
                    case TupleCodes.CISTPL_DEVICE:
                    case TupleCodes.CISTPL_DEVICE_A:
                    case TupleCodes.CISTPL_DEVICE_OA:
                    case TupleCodes.CISTPL_DEVICE_OC:
                    case TupleCodes.CISTPL_EXTDEVIC:
                    case TupleCodes.CISTPL_FORMAT:
                    case TupleCodes.CISTPL_FORMAT_A:
                    case TupleCodes.CISTPL_FUNCE:
                    case TupleCodes.CISTPL_FUNCID:
                    case TupleCodes.CISTPL_GEOMETRY:
                    case TupleCodes.CISTPL_INDIRECT:
                    case TupleCodes.CISTPL_JEDEC_A:
                    case TupleCodes.CISTPL_JEDEC_C:
                    case TupleCodes.CISTPL_LINKTARGET:
                    case TupleCodes.CISTPL_LONGLINK_A:
                    case TupleCodes.CISTPL_LONGLINK_C:
                    case TupleCodes.CISTPL_LONGLINK_CB:
                    case TupleCodes.CISTPL_LONGLINK_MFC:
                    case TupleCodes.CISTPL_NO_LINK:
                    case TupleCodes.CISTPL_ORG:
                    case TupleCodes.CISTPL_PWR_MGMNT:
                    case TupleCodes.CISTPL_SPCL:
                    case TupleCodes.CISTPL_SWIL:
                    case TupleCodes.CISTPL_VERS_2:
                        tupleCode        = $"Undecoded tuple ID {tuple.Code}";
                        tupleDescription = $"Undecoded tuple ID {tuple.Code}";

                        break;

                    default:
                        tupleCode        = $"0x{(byte)tuple.Code:X2}";
                        tupleDescription = $"Found unknown tuple ID 0x{(byte)tuple.Code:X2}";

                        break;
                    }

                    cisList.Add(new PcmciaCisModel
                    {
                        Code = tupleCode, Description = tupleDescription
                    });
                }
            }
            else
            {
                AaruConsole.DebugWriteLine("Device-Info command", "PCMCIA CIS returned no tuples");
            }
        }
Exemple #4
0
        public CommitViewModel(ISessionService applicationService, IActionMenuFactory actionMenuService, IAlertDialogFactory alertDialogFactory)
        {
            Title = "Commit";

            var comments = new ReactiveList <CommentModel>();

            Comments = comments.CreateDerivedCollection(x => new CommitCommentItemViewModel(x));

            this.WhenAnyValue(x => x.Commit)
            .Select(x => new GitHubAvatar(x.GenerateGravatarUrl()))
            .ToProperty(this, x => x.Avatar, out _avatar);

            var files = this.WhenAnyValue(x => x.Commit.Files).IsNotNull();

            files.Select(x => x.Count(y => string.Equals(y.Status, "added")))
            .ToProperty(this, x => x.DiffAdditions, out _diffAdditions);

            files.Select(x => x.Count(y => string.Equals(y.Status, "removed")))
            .ToProperty(this, x => x.DiffDeletions, out _diffDeletions);

            files.Select(x => x.Count(y => string.Equals(y.Status, "modified")))
            .ToProperty(this, x => x.DiffModifications, out _diffModifications);

            GoToAddedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffAdditions).Select(x => x > 0));
            GoToAddedFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Added", Commit.Files.Where(x => string.Equals(x.Status, "added"))))
            .Subscribe(NavigateTo);

            GoToRemovedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffDeletions).Select(x => x > 0));
            GoToRemovedFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Removed", Commit.Files.Where(x => string.Equals(x.Status, "removed"))))
            .Subscribe(NavigateTo);

            GoToModifiedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffModifications).Select(x => x > 0));
            GoToModifiedFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Modified", Commit.Files.Where(x => string.Equals(x.Status, "modified"))))
            .Subscribe(NavigateTo);

            GoToAllFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit.Files).Select(x => x != null));
            GoToAllFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "All Changes", Commit.Files))
            .Subscribe(NavigateTo);

            this.WhenAnyValue(x => x.Commit)
            .IsNotNull()
            .Select(x => x.GenerateCommiterName())
            .ToProperty(this, x => x.CommiterName, out _commiterName);

            this.WhenAnyValue(x => x.Commit)
            .IsNotNull()
            .Select(x => x.Commit.Message ?? string.Empty)
            .Select(x => Emojis.FindAndReplace(x))
            .ToProperty(this, x => x.CommitMessage, out _commitMessage);

            this.WhenAnyValue(x => x.CommitMessage)
            .IsNotNull()
            .Select(x => {
                var firstNewLine = x.IndexOf("\n", StringComparison.Ordinal);
                return(firstNewLine > 0 ? x.Substring(0, firstNewLine) : x);
            })
            .ToProperty(this, x => x.CommitMessageSummary, out _commitMessageSummary);

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit).Select(x => x != null));
            GoToHtmlUrlCommand
            .Select(_ => this.CreateViewModel <WebBrowserViewModel>())
            .Select(x => x.Init(Commit.HtmlUrl))
            .Subscribe(NavigateTo);

            GoToRepositoryCommand = ReactiveCommand.Create();
            GoToRepositoryCommand.Subscribe(_ => {
                var vm = this.CreateViewModel <RepositoryViewModel>();
                vm.Init(RepositoryOwner, RepositoryName);
                NavigateTo(vm);
            });

            AddCommentCommand = ReactiveCommand.Create().WithSubscription(_ => {
                var vm = new ComposerViewModel(async s => {
                    var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.Create(s);
                    comments.Add((await applicationService.Client.ExecuteAsync(request)).Data);
                }, alertDialogFactory);
                NavigateTo(vm);
            });

            var validCommitObservable = this.WhenAnyValue(x => x.Commit).Select(x => x != null);

            var copyShaCommand = ReactiveCommand.Create(validCommitObservable)
                                 .WithSubscription(x => actionMenuService.SendToPasteBoard(this.Commit.Sha));

            var shareCommand = ReactiveCommand.Create(validCommitObservable)
                               .WithSubscription(sender => actionMenuService.ShareUrl(sender, this.Commit.HtmlUrl));

            var browseCodeCommand = ReactiveCommand.Create(validCommitObservable)
                                    .WithSubscription(x =>
            {
                var vm             = this.CreateViewModel <SourceTreeViewModel>();
                vm.RepositoryName  = RepositoryName;
                vm.RepositoryOwner = RepositoryOwner;
                vm.Branch          = this.Commit.Sha;
                NavigateTo(vm);
            });

            ShowMenuCommand = ReactiveCommand.CreateAsyncTask(sender => {
                var menu = actionMenuService.Create();
                menu.AddButton("Add Comment", AddCommentCommand);
                menu.AddButton("Copy SHA", copyShaCommand);
                menu.AddButton("Browse Code", browseCodeCommand);
                menu.AddButton("Share", shareCommand);
                menu.AddButton("Show in GitHub", GoToHtmlUrlCommand);
                return(menu.Show(sender));
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async t => {
                var commentRequest = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.GetAll();
                applicationService.Client.ExecuteAsync(commentRequest).ToBackground(x => comments.Reset(x.Data.Where(y => y.Position.HasValue)));
                Commit = await applicationService.GitHubClient.Repository.Commits.Get(RepositoryOwner, RepositoryName, Node);
            });
        }
Exemple #5
0
        public ResultsViewModel(IScreen screen, TestIndentifier sheet, bool canTest = false) : base(screen)
        {
            Validation         = sheet.ValidationContext;
            CanTest            = canTest;
            ActiveSheet        = sheet;
            FilteredData       = new ObservableCollection <TestAnswer>();
            HasTrue            = sheet.Answers.Any(x => x.Status == CorrectionStatus.True);
            HasFalse           = sheet.Answers.Any(x => x.Status == CorrectionStatus.False);
            HasNotAnswered     = sheet.Answers.Any(x => x.Status == CorrectionStatus.NoEntry);
            Mode               = GraphResultShowModeLookup.Load(HasTrue, HasFalse);
            SelectedMode       = Mode.FirstOrDefault();
            ExportExcelCommand = ReactiveCommand.Create(Export);
            if (canTest)
            {
                NavigateTest = ReactiveCommand.Create(GoToStartUp);
            }

            if (HasNotAnswered)
            {
                Idle = getSustain(CorrectionStatus.NoEntry);
            }

            if (HasTrue)
            {
                _trueReaction = (int)sheet.Answers.Where(x => x.Status == CorrectionStatus.True).Select(x => x.InputSpeed).Average().Value;
                Sustain       = getSustain(CorrectionStatus.True);
            }


            if (HasFalse)
            {
                _falseReaction = (int)sheet.Answers.Where(x => x.Status == CorrectionStatus.False).Select(x => x.InputSpeed).Average().Value;
                Fatigue        = getSustain(CorrectionStatus.False);
            }

            if (HasMixed)
            {
                _mixReaction = (int)sheet.Answers.Where(x => x.Status != CorrectionStatus.NoEntry).Select(x => x.InputSpeed).Average().Value;
            }

            if (true)
            {
            }


            var trueCount  = ActiveSheet.Answers.Count(x => x.Status == CorrectionStatus.True);
            var falseCount = ActiveSheet.Answers.Count(x => x.Status == CorrectionStatus.False);
            var all        = ActiveSheet.Answers.Count;

            Grade      = $"{ trueCount - falseCount} / {all}";
            Percentage = $"{((trueCount - falseCount) * 100) / all}%";


            this.WhenActivated(disposables =>
            {
                this
                .WhenAnyValue(x => x.SelectedMode)
                .WhereNotNull()
                .Subscribe(x =>
                {
                    System.Diagnostics.Debug.WriteLine("Chart Update Requested");
                    FilteredData.Clear();
                    switch (x.Item)
                    {
                    case GraphResultShowMode.Mixed:
                        FilteredData.AddRange(GetMixedList());
                        ReactionTime = _mixReaction.Value;
                        break;

                    case GraphResultShowMode.True:
                        FilteredData.AddRange(GetTrueList());
                        ReactionTime = _trueReaction.Value;
                        break;

                    case GraphResultShowMode.False:
                        FilteredData.AddRange(GetFalseList());
                        ReactionTime = _falseReaction.Value;
                        break;

                    default:
                        break;
                    }
                    MinWindow = FilteredData.Count * 25;
                })
                .DisposeWith(disposables);
            });
            DataFix();
        }
        public SettingViewModel(Action <SettingViewModel, bool> closeCallback, IUserConfig config)
        {
            Config                    = config ?? Locator.Current.GetService <IUserConfig>();
            ContextIntegrated         = RegistryContextManager.IsContextRegistry();
            _initialContextIntegrated = ContextIntegrated;
            FitImagesToScreen         = Config.FitImagesToScreen;
            IsScrollBarVisible        = Config.IsScrollBarVisible;
            OpenChapterOnLoad         = Config.OpenChapterOnLoadChoice;
            SelectedBackground        = Config.Background;
            SelectedTheme             = Config.Theme;

            try
            {
                SelectedInterpolationMode = Config.InterpolationMode;
                SelectedSmoothingMode     = Config.SmoothingMode;
                SelectedPixelOffsetMode   = Config.PixelOffsetMode;
            }
            catch (Exception)
            {
                SelectedInterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                SelectedSmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.Default;
                SelectedPixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.Default;
                Config.InterpolationMode  = SelectedInterpolationMode;
                Config.SmoothingMode      = SelectedSmoothingMode;
                Config.PixelOffsetMode    = SelectedPixelOffsetMode;
                Config.Save();
            }
            _closeCallback = closeCallback;

            Save = ReactiveCommand.Create(() =>
            {
                SaveSettings();
                _closeCallback(this, false);
            });

            SaveAndRefresh = ReactiveCommand.Create(() =>
            {
                SaveSettings();
                _closeCallback(this, true);
            });

            Close = ReactiveCommand.Create(() =>
            {
                _closeCallback(this, false);
                if (SelectedTheme != Config.Theme)
                {
                    // Restore theme
                    ThemeEditor.ModifyTheme(Config.Theme);
                }
                ThemeEditor.ChangePrimaryColor(Config.AccentColor);
            });

            SetAccentColor = ReactiveCommand.Create(() =>
            {
                InitialAccentColor = SelectedColor;
                ThemeEditor.ChangePrimaryColor(SelectedColor);
                IsPopupOpen = false;
            });

            CancelAccentColor = ReactiveCommand.Create(() =>
            {
                SelectedColor = Config.AccentColor;
                IsPopupOpen   = false;
            });

            ResetAccentColor = ReactiveCommand.Create(() =>
            {
                InitialAccentColor = Color.FromArgb(255, 154, 103, 234);
                SelectedColor      = InitialAccentColor;
                ThemeEditor.ChangePrimaryColor(InitialAccentColor);
                IsPopupOpen = false;
            });

            this.WhenValueChanged(x => x.SelectedTheme).Subscribe(x =>
            {
                ThemeEditor.ModifyTheme(x);
            });

            this.WhenAnyValue(x => x.SelectedColor).Subscribe(x =>
            {
                SelectedBrush = new SolidColorBrush(SelectedColor);
            });
        }
Exemple #7
0
        public CommitViewModel(IApplicationService applicationService, IActionMenuFactory actionMenuService)
        {
            Title = "Commit";

            var comments = new ReactiveList <Octokit.CommitComment>();

            Comments = comments.CreateDerivedCollection(x => x);

            this.WhenAnyValue(x => x.Commit)
            .IsNotNull()
            .Select(x => x.Commit.Message ?? string.Empty)
            .Select(x =>
            {
                var firstNewLine = x.IndexOf("\n", StringComparison.Ordinal);
                return(firstNewLine > 0 ? x.Substring(0, firstNewLine) : x);
            })
            .ToProperty(this, x => x.CommitMessageSummary, out _commitMessageSummary);

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit).Select(x => x != null));
            GoToHtmlUrlCommand.Select(x => Commit.HtmlUrl).Subscribe(x =>
            {
                var vm = this.CreateViewModel <WebBrowserViewModel>();
                vm.Url = x;
                NavigateTo(vm);
            });

            GoToRepositoryCommand = ReactiveCommand.Create();
            GoToRepositoryCommand.Subscribe(_ =>
            {
                var vm             = this.CreateViewModel <RepositoryViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                NavigateTo(vm);
            });

            GoToCommentCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm             = this.CreateViewModel <CommitCommentViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.Node            = Node;
                vm.SaveCommand.Subscribe(comments.Add);
                NavigateTo(vm);
            });

            GoToFileCommand = ReactiveCommand.Create();
            GoToFileCommand.OfType <Octokit.GitHubCommitFile>().Subscribe(x =>
            {
                if (x.Patch == null)
                {
                    var vm             = this.CreateViewModel <SourceViewModel>();
                    vm.Branch          = Commit.Sha;
                    vm.Path            = x.Filename;
                    vm.RepositoryOwner = RepositoryOwner;
                    vm.RepositoryName  = RepositoryName;
                    vm.Name            = System.IO.Path.GetFileName(x.Filename);
                    vm.ForceBinary     = true;
                    NavigateTo(vm);
                }
                else
                {
                    var vm        = this.CreateViewModel <ChangesetDiffViewModel>();
                    vm.Username   = RepositoryOwner;
                    vm.Repository = RepositoryName;
                    vm.Branch     = Commit.Sha;
                    vm.Filename   = x.Filename;
                    NavigateTo(vm);
                }
            });

            var validCommitObservable = this.WhenAnyValue(x => x.Commit).Select(x => x != null);

            var copyShaCommand = ReactiveCommand.Create(validCommitObservable)
                                 .WithSubscription(x => actionMenuService.SendToPasteBoard(this.Commit.Sha));

            var shareCommand = ReactiveCommand.Create(validCommitObservable)
                               .WithSubscription(x => actionMenuService.ShareUrl(this.Commit.HtmlUrl));

            var browseCodeCommand = ReactiveCommand.Create(validCommitObservable)
                                    .WithSubscription(x =>
            {
                var vm             = this.CreateViewModel <SourceTreeViewModel>();
                vm.RepositoryName  = RepositoryName;
                vm.RepositoryOwner = RepositoryOwner;
                vm.Branch          = this.Commit.Sha;
                NavigateTo(vm);
            });

            ShowMenuCommand = ReactiveCommand.CreateAsyncTask(_ =>
            {
                var menu = actionMenuService.Create(Title);
                menu.AddButton("Add Comment", GoToCommentCommand);
                menu.AddButton("Copy SHA", copyShaCommand);
                menu.AddButton("Browse Code", browseCodeCommand);
                menu.AddButton("Share", shareCommand);
                menu.AddButton("Show in GitHub", GoToHtmlUrlCommand);
                return(menu.Show());
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                applicationService.GitHubClient.Repository.RepositoryComments.GetForCommit(RepositoryOwner, RepositoryName, Node)
                .ToBackground(x => comments.Reset(x));
                Commit = await applicationService.GitHubClient.Repository.Commits.Get(RepositoryOwner, RepositoryName, Node);
            });
        }
Exemple #8
0
        public GitHubPaneViewModel(
            IViewViewModelFactory viewModelFactory,
            ISimpleApiClientFactory apiClientFactory,
            IConnectionManager connectionManager,
            ITeamExplorerContext teamExplorerContext,
            IVisualStudioBrowser browser,
            IUsageTracker usageTracker,
            INavigationViewModel navigator,
            ILoggedOutViewModel loggedOut,
            INotAGitHubRepositoryViewModel notAGitHubRepository,
            INotAGitRepositoryViewModel notAGitRepository)
        {
            Guard.ArgumentNotNull(viewModelFactory, nameof(viewModelFactory));
            Guard.ArgumentNotNull(apiClientFactory, nameof(apiClientFactory));
            Guard.ArgumentNotNull(connectionManager, nameof(connectionManager));
            Guard.ArgumentNotNull(teamExplorerContext, nameof(teamExplorerContext));
            Guard.ArgumentNotNull(browser, nameof(browser));
            Guard.ArgumentNotNull(usageTracker, nameof(usageTracker));
            Guard.ArgumentNotNull(navigator, nameof(navigator));
            Guard.ArgumentNotNull(loggedOut, nameof(loggedOut));
            Guard.ArgumentNotNull(notAGitHubRepository, nameof(notAGitHubRepository));
            Guard.ArgumentNotNull(notAGitRepository, nameof(notAGitRepository));

            this.viewModelFactory     = viewModelFactory;
            this.apiClientFactory     = apiClientFactory;
            this.connectionManager    = connectionManager;
            this.teamExplorerContext  = teamExplorerContext;
            this.browser              = browser;
            this.usageTracker         = usageTracker;
            this.navigator            = navigator;
            this.loggedOut            = loggedOut;
            this.notAGitHubRepository = notAGitHubRepository;
            this.notAGitRepository    = notAGitRepository;

            var contentAndNavigatorContent = Observable.CombineLatest(
                this.WhenAnyValue(x => x.Content),
                navigator.WhenAnyValue(x => x.Content),
                (c, nc) => new { Content = c, NavigatorContent = nc });

            contentOverride = contentAndNavigatorContent
                              .SelectMany(x =>
            {
                if (x.Content == null)
                {
                    return(Observable.Return(ContentOverride.Spinner));
                }
                else if (x.Content == navigator && x.NavigatorContent != null)
                {
                    return(x.NavigatorContent.WhenAnyValue(
                               y => y.IsLoading,
                               y => y.Error,
                               (l, e) =>
                    {
                        if (l)
                        {
                            return ContentOverride.Spinner;
                        }
                        if (e != null)
                        {
                            return ContentOverride.Error;
                        }
                        else
                        {
                            return ContentOverride.None;
                        }
                    }));
                }
                else
                {
                    return(Observable.Return(ContentOverride.None));
                }
            })
                              .ToProperty(this, x => x.ContentOverride);

            // Returns navigator.Content if Content == navigator, otherwise null.
            var currentPage = contentAndNavigatorContent
                              .Select(x => x.Content == navigator ? x.NavigatorContent : null);

            title = currentPage
                    .SelectMany(x => x?.WhenAnyValue(y => y.Title) ?? Observable.Return <string>(null))
                    .Select(x => x ?? "GitHub")
                    .ToProperty(this, x => x.Title);

            isSearchEnabled = currentPage
                              .Select(x => x is ISearchablePageViewModel)
                              .ToProperty(this, x => x.IsSearchEnabled);

            refresh = ReactiveCommand.CreateAsyncTask(
                currentPage.SelectMany(x => x?.WhenAnyValue(
                                           y => y.IsLoading,
                                           y => y.IsBusy,
                                           (loading, busy) => !loading && !busy)
                                       ?? Observable.Return(false)),
                _ => navigator.Content.Refresh());
            refresh.ThrownExceptions.Subscribe();

            showPullRequests = ReactiveCommand.CreateAsyncTask(
                this.WhenAny(x => x.Content, x => x.Value == navigator),
                _ => ShowPullRequests());

            openInBrowser = ReactiveCommand.Create(currentPage.Select(x => x is IOpenInBrowser));
            openInBrowser.Subscribe(_ =>
            {
                var url = ((IOpenInBrowser)navigator.Content).WebUrl;
                if (url != null)
                {
                    browser.OpenUrl(url);
                }
            });

            navigator.WhenAnyObservable(x => x.Content.NavigationRequested)
            .Subscribe(x => NavigateTo(x).Forget());

            this.WhenAnyValue(x => x.SearchQuery)
            .Where(x => navigator.Content is ISearchablePageViewModel)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => ((ISearchablePageViewModel)navigator.Content).SearchQuery = x);
        }
Exemple #9
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);
            });
        }
Exemple #10
0
        public CommitViewModel(
            string username, string repository, string node, bool showRepository = false,
            IApplicationService applicationService = null, IActionMenuService actionMenuService = null,
            IAlertDialogService alertDialogService = null)
        {
            _applicationService = applicationService = applicationService ?? Locator.Current.GetService <IApplicationService>();
            actionMenuService   = actionMenuService ?? Locator.Current.GetService <IActionMenuService>();
            alertDialogService  = alertDialogService ?? Locator.Current.GetService <IAlertDialogService>();

            Username       = username;
            Repository     = repository;
            Node           = node;
            ShowRepository = showRepository;

            var shortNode = node.Substring(0, node.Length > 7 ? 7 : node.Length);

            Title = $"Commit {shortNode}";

            var changesetFiles =
                this.WhenAnyValue(x => x.Changeset)
                .Where(x => x != null)
                .Select(x => x.Files ?? Enumerable.Empty <Client.V1.ChangesetFile>());

            changesetFiles
            .Select(x => x.Count(y => y.Type == "added"))
            .ToProperty(this, x => x.DiffAdditions, out _diffAdditions);

            changesetFiles
            .Select(x => x.Count(y => y.Type == "removed"))
            .ToProperty(this, x => x.DiffDeletions, out _diffDeletions);

            changesetFiles
            .Select(x => x.Count(y => y.Type != "added" && y.Type != "removed"))
            .ToProperty(this, x => x.DiffModifications, out _diffModifications);

            Comments = _comments.CreateDerivedCollection(comment =>
            {
                var name   = comment.User.DisplayName ?? comment.User.Username;
                var avatar = new Avatar(comment.User.Links?.Avatar?.Href);
                return(new CommentItemViewModel(name, avatar, comment.CreatedOn.Humanize(), comment.Content.Raw));
            }, x => x.Inline == null);

            GoToUserCommand = ReactiveCommand.Create <string>(user => NavigateTo(new UserViewModel(user)));

            GoToRepositoryCommand
            .Select(_ => new RepositoryViewModel(username, repository))
            .Subscribe(NavigateTo);

            GoToAddedFiles = ReactiveCommand.Create(
                () => { },
                this.WhenAnyValue(x => x.DiffAdditions).Select(x => x > 0));

            GoToRemovedFiles = ReactiveCommand.Create(
                () => { },
                this.WhenAnyValue(x => x.DiffDeletions).Select(x => x > 0));

            GoToModifiedFiles = ReactiveCommand.Create(
                () => { },
                this.WhenAnyValue(x => x.DiffModifications).Select(x => x > 0));

            var canShowMenu = this.WhenAnyValue(x => x.Commit).Select(x => x != null);

            ShowMenuCommand = ReactiveCommand.Create <object>(sender =>
            {
                var uri  = new Uri($"https://bitbucket.org/{username}/{repository}/commits/{node}");
                var menu = actionMenuService.Create();
                menu.AddButton("Add Comment", _ => AddCommentCommand.ExecuteNow());
                menu.AddButton("Copy SHA", _ => actionMenuService.SendToPasteBoard(node));
                menu.AddButton("Share", x => actionMenuService.ShareUrl(x, uri));
                menu.AddButton("Show In Bitbucket", _ => NavigateTo(new WebBrowserViewModel(uri.AbsoluteUri)));
                menu.Show(sender);
            }, canShowMenu);

            ToggleApproveButton = ReactiveCommand.CreateFromTask(async _ =>
            {
                if (Approved)
                {
                    await applicationService.Client.Commits.Unapprove(username, repository, node);
                }
                else
                {
                    await applicationService.Client.Commits.Approve(username, repository, node);
                }

                var shouldBe        = !Approved;
                var commit          = await applicationService.Client.Commits.Get(username, repository, node);
                var currentUsername = applicationService.Account.Username;
                var me = commit.Participants.FirstOrDefault(
                    y => string.Equals(currentUsername, y?.User?.Username, StringComparison.OrdinalIgnoreCase));
                if (me != null)
                {
                    me.Approved = shouldBe;
                }
                Commit = commit;
            });

            ToggleApproveButton
            .ThrownExceptions
            .Subscribe(x => alertDialogService.Alert("Error", "Unable to approve commit: " + x.Message).ToBackground());

            var commitFiles = new ReactiveList <Client.V1.ChangesetFile>();

            CommitFiles = commitFiles.CreateDerivedCollection(x =>
            {
                var vm = new CommitFileItemViewModel(username, repository, node, Changeset.Parents.FirstOrDefault(), x);
                vm.GoToCommand
                .Select(_ => new ChangesetDiffViewModel(username, repository, node, x))
                .Subscribe(NavigateTo);
                return(vm);
            });

            this.WhenAnyValue(x => x.Commit.Participants)
            .Select(participants =>
            {
                return((participants ?? Enumerable.Empty <CommitParticipant>())
                       .Where(x => x.Approved)
                       .Select(x =>
                {
                    var avatar = new Avatar(x.User?.Links?.Avatar?.Href);
                    var vm = new UserItemViewModel(x.User?.Username, x.User?.DisplayName, avatar);
                    vm.GoToCommand
                    .Select(_ => new UserViewModel(x.User))
                    .Subscribe(NavigateTo);
                    return vm;
                }));
            })
            .Select(x => x.ToArray())
            .ToProperty(this, x => x.Approvals, out _approvals, new UserItemViewModel[0]);

            this.WhenAnyValue(x => x.Changeset)
            .Subscribe(x => commitFiles.Reset(x?.Files ?? Enumerable.Empty <Client.V1.ChangesetFile>()));

            this.WhenAnyValue(x => x.Commit)
            .Subscribe(x =>
            {
                var currentUsername = applicationService.Account.Username;
                Approved            = x?.Participants
                                      ?.FirstOrDefault(y => string.Equals(currentUsername, y?.User?.Username, StringComparison.OrdinalIgnoreCase))
                                      ?.Approved ?? false;
            });

            LoadCommand = ReactiveCommand.CreateFromTask(_ =>
            {
                var commit = applicationService.Client.Commits.Get(username, repository, node)
                             .OnSuccess(x => Commit = x);
                var changeset = applicationService.Client.Commits.GetChangeset(username, repository, node)
                                .OnSuccess(x => Changeset = x);
                applicationService.Client.AllItems(x => x.Commits.GetComments(username, repository, node))
                .ToBackground(_comments.Reset);
                return(Task.WhenAll(commit, changeset));
            });
        }
Exemple #11
0
 protected override void InitializeCommands()
 {
     LearnMoreCommand = ReactiveCommand.Create <object>(x => OnLearnMore(x));
     AddToCartCommand = ReactiveCommand.Create <object>(x => OnAddToCart(x));
 }
Exemple #12
0
        private void CreateCommands()
        {
            Add = ReactiveCommand.Create(ExecuteAdd);

            //get existing jobs and tags/instruments
            Load = ReactiveCommand.CreateFromTask(async _ =>
            {
                var dataUpdateJobs        = _client.GetaDataUpdateJobs();
                var econReleaseUpdateJobs = _client.GetEconomicReleaseUpdateJobs();
                var dividendUpdateJobs    = _client.GetDividendUpdateJobs();
                var earningsUpdateJobs    = _client.GetEarningsUpdateJobs();
                var tags               = _client.GetTags();
                var instruments        = _client.GetInstruments();
                var econReleaseSources = _client.GetEconomicReleaseDataSources();
                var dividendSources    = _client.GetDividendDataSources();
                var earningsSources    = _client.GetEarningsDataSources();

                await Task.WhenAll(dataUpdateJobs, econReleaseUpdateJobs, dividendUpdateJobs,
                                   tags, instruments, econReleaseSources, dividendSources, earningsUpdateJobs, earningsSources).ConfigureAwait(false);

                var responses = new ApiResponse[] { dataUpdateJobs.Result, econReleaseUpdateJobs.Result, dividendUpdateJobs.Result, tags.Result, instruments.Result, econReleaseSources.Result, dividendSources.Result, earningsUpdateJobs.Result, earningsSources.Result };
                if (await responses.DisplayErrors(this, DialogCoordinator).ConfigureAwait(true))
                {
                    return(null);
                }

                Tags.AddRange(tags.Result.Result);
                Instruments.AddRange(instruments.Result.Result);
                EconomicReleaseDataSources.AddRange(econReleaseSources.Result.Result);
                DividendDataSources.AddRange(dividendSources.Result.Result);
                EarningsDataSources.AddRange(earningsSources.Result.Result);

                var jobs = new List <IJobSettings>();
                jobs.AddRange(dataUpdateJobs.Result.Result);
                jobs.AddRange(econReleaseUpdateJobs.Result.Result);
                jobs.AddRange(dividendUpdateJobs.Result.Result);
                jobs.AddRange(earningsUpdateJobs.Result.Result);

                return(jobs);
            });
            Load.Subscribe(jobs =>
            {
                if (jobs == null)
                {
                    return;
                }

                foreach (var job in jobs)
                {
                    Jobs.Add(GetJobViewModel(job));
                }
            });

            //Delete job
            var deleteCanExecute = this
                                   .WhenAnyValue(x => x.SelectedJob)
                                   .Select(x => x != null && !string.IsNullOrEmpty(x.PreChangeName));

            Delete = ReactiveCommand.CreateFromTask(async _ =>
            {
                //Give a dialog to confirm the deletion
                MessageDialogResult dialogResult = await DialogCoordinator.ShowMessageAsync(this,
                                                                                            "Delete Job",
                                                                                            string.Format("Are you sure you want to delete {0}?", SelectedJob.Name),
                                                                                            MessageDialogStyle.AffirmativeAndNegative);

                if (dialogResult != MessageDialogResult.Affirmative)
                {
                    return;
                }

                //If the name has changed but hasn't been saved, we change it back to be in sync with the server
                SelectedJob.Name = SelectedJob.PreChangeName;

                //Request deletion
                var response = await SelectedJob.Delete.Execute();
                if (await response.DisplayErrors(this, DialogCoordinator))
                {
                    return;
                }

                //if it was successful, remove the VM from the list
                Jobs.Remove(SelectedJob);
                SelectedJob = null;
            },
                                                    deleteCanExecute);
        }
Exemple #13
0
        public CopyrightPageViewModel(INavigationService navigationService,
                                      IDialogService dialogService
                                      ) : base(navigationService, dialogService)
        {
            Title = "版权信息";

            this.Load = ReactiveCommand.Create(() =>
            {
                var lists = new List <Copyright>()
                {
                    new Copyright()
                    {
                        Name = "Acr.UserDialogs", Version = "7.1.0.442", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "akavache", Version = "6.10.20", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "EasyNetQ", Version = "5.2.0", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Microsoft.CognitiveServices.Speech", Version = "1.12.1", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Microsoft.CSharp", Version = "4.7.0", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "NETStandard.Library", Version = "2.0.3", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Newtonsoft.Json", Version = "12.0.3", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "NLog", Version = "4.7.2", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Prism.DryIoc.Forms", Version = "7.2.0.1422", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Prism.Plugin.Popups", Version = "7.2.0.1046", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "ReactiveUI.Fody", Version = "11.4.17", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "ReactiveUI.Validation", Version = "1.4.15", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Refractored.XamForms.PullToRefresh", Version = "2.4.1", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "SkiaSharp.Views.Forms", Version = "1.68.3", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "System.Reactive", Version = "4.4.1", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "System.Reactive.Linq", Version = "4.4.1", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "System.ValueTuple", Version = "4.5.0", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xam.Plugin.Connectivity", Version = "3.2.0", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xam.Plugin.Iconize.FontAwesome", Version = "3.5.0.114", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xam.Plugin.Media", Version = "5.0.1", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xam.Plugins.Forms.ImageCircle", Version = "3.0.0.5", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xam.Plugins.Settings", Version = "3.1.1", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xamarin.Essentials", Version = "1.5.3.2", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xamarin.FFImageLoading.Forms", Version = "2.4.11.982", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xamarin.FFImageLoading.Svg.Forms", Version = "2.4.11.982", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xamarin.FFImageLoading.Transformations", Version = "2.4.11.982", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xamarin.Forms", Version = "4.6.0.967", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "Xamarin.Forms.PancakeView", Version = "1.4.2", Licence = "MIT", IsChenged = "否"
                    },
                    new Copyright()
                    {
                        Name = "ZXing.Net.Mobile.Forms", Version = "2.4.1", Licence = "MIT", IsChenged = "否"
                    },
                };
                CopyrightSeries = new ObservableCollection <Copyright>(lists);
            });
            BindBusyCommand(Load);
        }
Exemple #14
0
        public OptionsDialogViewModel(IUpdater updateService)
        {
            this.updater = updateService;

            this.Tabs = new List <string>
            {
                OptionsRes.GeneralTab,                                  // 0
                OptionsRes.FileNamingTab,                               // 1
                OptionsRes.ProcessTab,                                  // 2
                OptionsRes.AdvancedTab,                                 // 3
            };

            if (Utilities.SupportsUpdates)
            {
                this.Tabs.Add(OptionsRes.UpdatesTab);                 // 4
            }

            // UpdateStatus
            this.updater
            .WhenAnyValue(x => x.State)
            .Select(state =>
            {
                switch (state)
                {
                case UpdateState.NotStarted:
                    return(string.Empty);

                case UpdateState.DownloadingInfo:
                    return(OptionsRes.DownloadingInfoStatus);

                case UpdateState.DownloadingInstaller:
                    return(string.Format(OptionsRes.DownloadingStatus, this.updater.LatestVersion));

                case UpdateState.UpToDate:
                    return(OptionsRes.UpToDateStatus);

                case UpdateState.InstallerReady:
                    return(string.Format(OptionsRes.UpdateReadyStatus, this.updater.LatestVersion));

                case UpdateState.Failed:
                    return(OptionsRes.UpdateFailedStatus);

                default:
                    throw new ArgumentOutOfRangeException();
                }
            })
            .ToProperty(this, x => x.UpdateStatus, out this.updateStatus);

            // UpdateDownloading
            this.updater
            .WhenAnyValue(x => x.State)
            .Select(state => state == UpdateState.DownloadingInstaller)
            .ToProperty(this, x => x.UpdateDownloading, out this.updateDownloading);

            // UpdateProgressPercent
            this.updater
            .WhenAnyValue(x => x.UpdateDownloadProgressFraction)
            .Select(downloadFraction => downloadFraction * 100)
            .ToProperty(this, x => x.UpdateProgressPercent, out this.updateProgressPercent);

            // CpuThrottlingDisplay
            this.WhenAnyValue(x => x.CpuThrottlingCores, x => x.CpuThrottlingMaxCores, (cores, maxCores) =>
            {
                double currentFraction = (double)cores / maxCores;
                return(currentFraction.ToString("p0"));
            }).ToProperty(this, x => x.CpuThrottlingDisplay, out this.cpuThrottlingDisplay);

            this.SaveSettings = ReactiveCommand.Create();
            this.SaveSettings.Subscribe(_ => this.SaveSettingsImpl());

            this.BrowseVideoPlayer = ReactiveCommand.Create(this.WhenAnyValue(x => x.UseCustomVideoPlayer));
            this.BrowseVideoPlayer.Subscribe(_ => this.BrowseVideoPlayerImpl());

            this.BrowseCompletionSound = ReactiveCommand.Create(this.WhenAnyValue(x => x.UseCustomCompletionSound));
            this.BrowseCompletionSound.Subscribe(_ => this.BrowseCompletionSoundImpl());

            this.BrowsePath = ReactiveCommand.Create();
            this.BrowsePath.Subscribe(_ => this.BrowsePathImpl());

            this.BrowsePreviewFolder = ReactiveCommand.Create();
            this.BrowsePreviewFolder.Subscribe(_ => this.BrowsePreviewFolderImpl());

            this.OpenAddProcessDialog = ReactiveCommand.Create();
            this.OpenAddProcessDialog.Subscribe(_ => this.OpenAddProcessDialogImpl());

            this.RemoveProcess = ReactiveCommand.Create(this.WhenAnyValue(x => x.SelectedProcess).Select(selectedProcess => selectedProcess != null));
            this.RemoveProcess.Subscribe(_ => this.RemoveProcessImpl());

            bool logFolderExists = Directory.Exists(Utilities.LogsFolder);

            this.OpenLogFolder = ReactiveCommand.Create(MvvmUtilities.CreateConstantObservable(logFolderExists));
            this.OpenLogFolder.Subscribe(_ => this.OpenLogFolderImpl());

            this.CheckUpdate = ReactiveCommand.Create(this.updater.WhenAnyValue(x => x.State).Select(state =>
            {
                return(Config.UpdatesEnabled &&
                       (state == UpdateState.Failed ||
                        state == UpdateState.NotStarted ||
                        state == UpdateState.UpToDate));
            }));
            this.CheckUpdate.Subscribe(_ => this.CheckUpdateImpl());

            this.updatesEnabledConfig                 = Config.UpdatesEnabled;
            this.defaultPath                          = Config.AutoNameOutputFolder;
            this.customFormat                         = Config.AutoNameCustomFormat;
            this.customFormatString                   = Config.AutoNameCustomFormatString;
            this.outputToSourceDirectory              = Config.OutputToSourceDirectory;
            this.preserveFolderStructureInBatch       = Config.PreserveFolderStructureInBatch;
            this.useCustomPreviewFolder               = Config.UseCustomPreviewFolder;
            this.previewOutputFolder                  = Config.PreviewOutputFolder;
            this.whenFileExists                       = CustomConfig.WhenFileExists;
            this.whenFileExistsBatch                  = CustomConfig.WhenFileExistsBatch;
            this.minimizeToTray                       = Config.MinimizeToTray;
            this.useCustomVideoPlayer                 = Config.UseCustomVideoPlayer;
            this.customVideoPlayer                    = Config.CustomVideoPlayer;
            this.useBuiltInPlayerForPreviews          = Config.UseBuiltInPlayerForPreviews;
            this.playSoundOnCompletion                = Config.PlaySoundOnCompletion;
            this.useCustomCompletionSound             = Config.UseCustomCompletionSound;
            this.customCompletionSound                = Config.CustomCompletionSound;
            this.workerProcessPriority                = Config.WorkerProcessPriority;
            this.logVerbosity                         = Config.LogVerbosity;
            this.copyLogToOutputFolder                = Config.CopyLogToOutputFolder;
            this.previewCount                         = Config.PreviewCount;
            this.rememberPreviousFiles                = Config.RememberPreviousFiles;
            this.showAudioTrackNameField              = Config.ShowAudioTrackNameField;
            this.enableLibDvdNav                      = Config.EnableLibDvdNav;
            this.deleteSourceFilesOnClearingCompleted = Config.DeleteSourceFilesOnClearingCompleted;
            this.preserveModifyTimeFiles              = Config.PreserveModifyTimeFiles;
            this.resumeEncodingOnRestart              = Config.ResumeEncodingOnRestart;
            this.useWorkerProcess                     = Config.UseWorkerProcess;
            this.minimumTitleLengthSeconds            = Config.MinimumTitleLengthSeconds;
            this.autoPauseProcesses                   = new ObservableCollection <string>();
            this.videoFileExtensions                  = Config.VideoFileExtensions;
            this.cpuThrottlingCores                   = (int)Math.Round(this.CpuThrottlingMaxCores * Config.CpuThrottlingFraction);
            if (this.cpuThrottlingCores < 1)
            {
                this.cpuThrottlingCores = 1;
            }

            if (this.cpuThrottlingCores > this.CpuThrottlingMaxCores)
            {
                this.cpuThrottlingCores = this.CpuThrottlingMaxCores;
            }

            List <string> autoPauseList = CustomConfig.AutoPauseProcesses;

            if (autoPauseList != null)
            {
                foreach (string process in autoPauseList)
                {
                    this.autoPauseProcesses.Add(process);
                }
            }

            // List of language codes and names: http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

            this.languageChoices =
                new List <InterfaceLanguage>
            {
                new InterfaceLanguage {
                    CultureCode = string.Empty, Display = OptionsRes.UseOSLanguage
                },
                new InterfaceLanguage {
                    CultureCode = "en-US", Display = "English"
                },
                new InterfaceLanguage {
                    CultureCode = "id-ID", Display = "Bahasa Indonesia / Indonesian"
                },
                new InterfaceLanguage {
                    CultureCode = "bs-Latn-BA", Display = "bosanski (Bosna i Hercegovina) / Bosnian (Latin)"
                },
                new InterfaceLanguage {
                    CultureCode = "cs-CZ", Display = "čeština / Czech"
                },
                new InterfaceLanguage {
                    CultureCode = "de-DE", Display = "Deutsch / German"
                },
                new InterfaceLanguage {
                    CultureCode = "es-ES", Display = "Español / Spanish"
                },
                new InterfaceLanguage {
                    CultureCode = "eu-ES", Display = "Euskara / Basque"
                },
                new InterfaceLanguage {
                    CultureCode = "fr-FR", Display = "Français / French"
                },
                new InterfaceLanguage {
                    CultureCode = "it-IT", Display = "italiano / Italian"
                },
                new InterfaceLanguage {
                    CultureCode = "hu-HU", Display = "Magyar / Hungarian"
                },
                new InterfaceLanguage {
                    CultureCode = "nl-BE", Display = "Nederlands / Dutch"
                },
                new InterfaceLanguage {
                    CultureCode = "pl-PL", Display = "polski / Polish"
                },
                new InterfaceLanguage {
                    CultureCode = "pt-PT", Display = "Português / Portuguese"
                },
                new InterfaceLanguage {
                    CultureCode = "pt-BR", Display = "Português (Brasil) / Portuguese (Brazil)"
                },
                new InterfaceLanguage {
                    CultureCode = "tr-TR", Display = "Türkçe / Turkish"
                },
                new InterfaceLanguage {
                    CultureCode = "ka-GE", Display = "ქართული / Georgian"
                },
                new InterfaceLanguage {
                    CultureCode = "ru-RU", Display = "русский / Russian"
                },
                new InterfaceLanguage {
                    CultureCode = "ko-KO", Display = "한국어 / Korean"
                },
                new InterfaceLanguage {
                    CultureCode = "zh-Hans", Display = "中文(简体) / Chinese (Simplified)"
                },
                new InterfaceLanguage {
                    CultureCode = "zh-Hant", Display = "中文(繁體) / Chinese (Traditional)"
                },
                new InterfaceLanguage {
                    CultureCode = "ja-JP", Display = "日本語 / Japanese"
                },
            };

            this.priorityChoices = new List <ComboChoice>
            {
                new ComboChoice("High", OptionsRes.Priority_High),
                new ComboChoice("AboveNormal", OptionsRes.Priority_AboveNormal),
                new ComboChoice("Normal", OptionsRes.Priority_Normal),
                new ComboChoice("BelowNormal", OptionsRes.Priority_BelowNormal),
                new ComboChoice("Idle", OptionsRes.Priority_Idle),
            };

            this.interfaceLanguage = this.languageChoices.FirstOrDefault(l => l.CultureCode == Config.InterfaceLanguageCode);
            if (this.interfaceLanguage == null)
            {
                this.interfaceLanguage = this.languageChoices[0];
            }

            this.playerChoices = Players.All;
            if (this.playerChoices.Count > 0)
            {
                this.selectedPlayer = this.playerChoices[0];

                foreach (IVideoPlayer player in this.playerChoices)
                {
                    if (player.Id == Config.PreferredPlayer)
                    {
                        this.selectedPlayer = player;
                        break;
                    }
                }
            }

            if (!CommonUtilities.Beta)
            {
                Task.Run(async() =>
                {
                    this.betaInfo = await Updater.GetUpdateInfoAsync(beta: true);

                    this.betaInfoAvailable = false;
                    if (this.betaInfo != null)
                    {
                        if (this.betaInfo.LatestVersion.FillInWithZeroes() > Utilities.CurrentVersion)
                        {
                            this.betaInfoAvailable = true;
                        }

                        await DispatchUtilities.InvokeAsync(() =>
                        {
                            this.RaisePropertyChanged(nameof(this.BetaChangelogUrl));
                            this.RaisePropertyChanged(nameof(this.BetaSectionVisible));
                        });
                    }
                });
            }

            int tabIndex = Config.OptionsDialogLastTab;

            if (tabIndex >= this.Tabs.Count)
            {
                tabIndex = 0;
            }

            this.SelectedTabIndex = tabIndex;
        }
        public TransactionViewerViewModel() : base("Transaction")
        {
            Global = Locator.Current.GetService <Global>();

            OpenTransactionBroadcaster = ReactiveCommand.Create(() => IoC.Get <IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel()));

            CopyBase64Psbt = ReactiveCommand.CreateFromTask(async() =>
            {
                await Application.Current.Clipboard.SetTextAsync(PsbtBase64Text);
                NotificationHelpers.Information("PSBT Base64 string copied to clipboard!");
            });

            CopyTransactionHex = ReactiveCommand.CreateFromTask(async() =>
            {
                await Application.Current.Clipboard.SetTextAsync(TransactionHexText);
                NotificationHelpers.Information("Transaction hex string copied to clipboard!");
            });

            ExportBinaryPsbt = ReactiveCommand.CreateFromTask(async() =>
            {
                var psbtExtension = "psbt";
                var sfd           = new SaveFileDialog
                {
                    DefaultExtension = psbtExtension,
                    InitialFileName  = TransactionDetails.TransactionId.Substring(0, 7),
                    Title            = "Export Binary PSBT"
                };

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    var initialDirectory = Path.Combine("/media", Environment.UserName);
                    if (!Directory.Exists(initialDirectory))
                    {
                        initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    }
                    sfd.Directory = initialDirectory;
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    sfd.Directory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                }

                var window          = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow;
                string fileFullName = await sfd.ShowAsync(window, fallBack: true);
                if (!string.IsNullOrWhiteSpace(fileFullName))
                {
                    var ext = Path.GetExtension(fileFullName);
                    if (string.IsNullOrWhiteSpace(ext))
                    {
                        fileFullName = $"{fileFullName}.{psbtExtension}";
                    }
                    await File.WriteAllBytesAsync(fileFullName, PsbtBytes);

                    NotificationHelpers.Success("PSBT file was exported.");
                }
            });

            Observable
            .Merge(CopyBase64Psbt.ThrownExceptions)
            .Merge(CopyTransactionHex.ThrownExceptions)
            .Merge(ExportBinaryPsbt.ThrownExceptions)
            .Merge(OpenTransactionBroadcaster.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                Logger.LogError(ex);
                NotificationHelpers.Error(ex.ToUserFriendlyString());
            });
        }
 public MainWindowViewModel()
 {
     StartDownloadWizard = ReactiveCommand.Create <IWindow, Unit>(StartDownload);
 }
Exemple #17
0
        protected InstallationModelBase(
            IWixStateProvider wixStateProvider,
            ISession session,
            string[] args
            )
        {
            this.Session = session;

            this._wixStateProvider = wixStateProvider ?? throw new ArgumentNullException(nameof(wixStateProvider));

            this.NextButtonText = TextResources.SetupView_NextText;

            var canMoveForwards = this.WhenAny(vm => vm.TabSelectedIndex, vm => vm.TabSelectionMax,
                                               (i, max) => i.GetValue() < max.GetValue());

            this.Next = ReactiveCommand.Create(canMoveForwards);
            this.Next.Subscribe(i =>
            {
                this.TabSelectedIndex = Math.Min(this.Steps.Count - 1, this.TabSelectedIndex + 1);
            });

            var canMoveBackwards = this.WhenAny(vm => vm.TabSelectedIndex, i => i.GetValue() > 0);

            this.Back = ReactiveCommand.Create(canMoveBackwards);
            this.Back.Subscribe(i =>
            {
                this.TabSelectedIndex = Math.Max(0, this.TabSelectedIndex - 1);
            });

            this.Help                  = ReactiveCommand.Create();
            this.ShowLicenseBlurb      = ReactiveCommand.Create();
            this.ShowCurrentStepErrors = ReactiveCommand.Create();
            this.RefreshCurrentStep    = ReactiveCommand.Create();
            this.RefreshCurrentStep.Subscribe(x => { this.Steps[this.TabSelectedIndex].Refresh(); });
            this.Exit = ReactiveCommand.Create();

            this.WhenAny(vm => vm.TabSelectedIndex, v => v.GetValue())
            .Subscribe(i =>
            {
                var c = this.Steps.Count;
                if (i == (c - 1))
                {
                    this.NextButtonText = TextResources.SetupView_ExitText;
                }
                else if (i == (c - 2))
                {
                    this.NextButtonText = TextResources.SetupView_InstallText;
                }
                else
                {
                    this.NextButtonText = TextResources.SetupView_NextText;
                }
            });

            this.WhenAnyValue(view => view.ValidationFailures)
            .Subscribe(failures =>
            {
                this.PrerequisiteFailures = (failures ?? Enumerable.Empty <ValidationFailure>())
                                            .Where(v => PrerequisiteProperties.Contains(v.PropertyName))
                                            .ToList();
            });
        }
        public CoinJoinTabViewModel(WalletViewModel walletViewModel)
            : base("CoinJoin", walletViewModel)
        {
            Password = "";

            CoinsList = new CoinListViewModel();

            Observable.FromEventPattern(CoinsList, nameof(CoinsList.DequeueCoinsPressed)).Subscribe(_ => OnCoinsListDequeueCoinsPressedAsync());

            AmountQueued = Money.Zero;             // Global.ChaumianClient.State.SumAllQueuedCoinAmounts();

            EnqueueCommand = ReactiveCommand.CreateFromTask(async() => await DoEnqueueAsync(CoinsList.Coins.Where(c => c.IsSelected)));

            DequeueCommand = ReactiveCommand.CreateFromTask(async() => await DoDequeueAsync(CoinsList.Coins.Where(c => c.IsSelected)));

            PrivacySomeCommand = ReactiveCommand.Create(() => TargetPrivacy = TargetPrivacy.Some);

            PrivacyFineCommand = ReactiveCommand.Create(() => TargetPrivacy = TargetPrivacy.Fine);

            PrivacyStrongCommand = ReactiveCommand.Create(() => TargetPrivacy = TargetPrivacy.Strong);

            TargetButtonCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                switch (TargetPrivacy)
                {
                case TargetPrivacy.None:
                    TargetPrivacy = TargetPrivacy.Some;
                    break;

                case TargetPrivacy.Some:
                    TargetPrivacy = TargetPrivacy.Fine;
                    break;

                case TargetPrivacy.Fine:
                    TargetPrivacy = TargetPrivacy.Strong;
                    break;

                case TargetPrivacy.Strong:
                    TargetPrivacy = TargetPrivacy.Some;
                    break;
                }
                Global.Config.MixUntilAnonymitySet = CoinJoinUntilAnonimitySet;
                await Global.Config.ToFileAsync();
            });

            this.WhenAnyValue(x => x.Password).Subscribe(async x =>
            {
                try
                {
                    if (x.NotNullAndNotEmpty())
                    {
                        char lastChar = x.Last();
                        if (lastChar == '\r' || lastChar == '\n')                         // If the last character is cr or lf then act like it'd be a sign to do the job.
                        {
                            Password = x.TrimEnd('\r', '\n');
                            await DoEnqueueAsync(CoinsList.Coins.Where(c => c.IsSelected));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogTrace(ex);
                }
            });

            this.WhenAnyValue(x => x.IsEnqueueBusy)
            .Select(x => x ? EnqueuingButtonTextString : EnqueueButtonTextString)
            .Subscribe(text => EnqueueButtonText = text);

            this.WhenAnyValue(x => x.IsDequeueBusy)
            .Select(x => x ? DequeuingButtonTextString : DequeueButtonTextString)
            .Subscribe(text => DequeueButtonText = text);

            this.WhenAnyValue(x => x.TargetPrivacy).Subscribe(target =>
            {
                CoinJoinUntilAnonimitySet = GetTargetLevel(target);
            });
        }
Exemple #19
0
        public MainViewModel(MainState state, IProviderFactory factory, ProviderViewModelFactory createViewModel)
        {
            _factory = factory;
            Refresh  = ReactiveCommand.Create(state.Providers.Refresh);

            _isLoading = Refresh
                         .IsExecuting
                         .ToProperty(this, x => x.IsLoading);

            _isReady = Refresh
                       .IsExecuting
                       .Select(executing => !executing)
                       .ToProperty(this, x => x.IsReady);

            state.Providers.Connect()
            .Transform(ps => createViewModel(ps, factory.CreateProvider(ps.Parameters)))
            .Sort(SortExpressionComparer <IProviderViewModel> .Descending(x => x.Created))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out _providers)
            .Subscribe();

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

            Remove = ReactiveCommand.Create(
                () => state.Providers.RemoveKey(SelectedProvider.Id),
                canRemove);

            var canAddProvider = this
                                 .WhenAnyValue(x => x.SelectedSupportedType)
                                 .Select(type => Enum.IsDefined(typeof(ProviderType), type));

            Add = ReactiveCommand.Create(
                () => state.Providers.AddOrUpdate(new ProviderState {
                Type = 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(() => Unit.Default, canUnselect);
            Unselect.Subscribe(unit => SelectedProvider = null);

            var outputCollectionChanges = Providers
                                          .ToObservableChangeSet(x => x.Id)
                                          .Publish()
                                          .RefCount();

            outputCollectionChanges
            .Filter(provider => provider.Id == state.SelectedProviderId)
            .ObserveOn(RxApp.MainThreadScheduler)
            .OnItemAdded(provider => SelectedProvider = provider)
            .Subscribe();

            outputCollectionChanges
            .OnItemRemoved(provider => SelectedProvider = null)
            .Subscribe();

            this.WhenAnyValue(x => x.SelectedProvider)
            .Skip(1)
            .Select(provider => provider?.Id ?? Guid.Empty)
            .Subscribe(id => state.SelectedProviderId = id);

            SelectedSupportedType = state.SelectedSupportedType ?? SupportedTypes.First();
            this.WhenAnyValue(x => x.SelectedSupportedType)
            .Subscribe(type => state.SelectedSupportedType = type);
        }
 public LogViewModel()
 {
     this.logs  = LogService.Instance;
     this.Show  = ReactiveCommand.Create <LogItem>(item => UserDialogs.Instance.Alert(item.Message));
     this.Clear = ReactiveCommand.Create(this.logs.Clear);
 }
        public ModListMetadataVM(ModListGalleryVM parent, ModlistMetadata metadata)
        {
            _parent            = parent;
            Metadata           = metadata;
            Location           = Path.Combine(Consts.ModListDownloadFolder, Metadata.Links.MachineURL + Consts.ModListExtension);
            IsBroken           = metadata.ValidationSummary.HasFailures;
            OpenWebsiteCommand = ReactiveCommand.Create(() => Utils.OpenWebsite($"https://www.wabbajack.org/modlist/{Metadata.Links.MachineURL}"));
            ExecuteCommand     = ReactiveCommand.CreateFromObservable <Unit, Unit>(
                canExecute: this.WhenAny(x => x.IsBroken).Select(x => !x),
                execute: (unit) =>
                Observable.Return(unit)
                .WithLatestFrom(
                    this.WhenAny(x => x.Exists),
                    (_, e) => e)
                // Do any download work on background thread
                .ObserveOn(RxApp.TaskpoolScheduler)
                .SelectTask(async(exists) =>
            {
                if (!exists)
                {
                    try
                    {
                        var success = await Download();
                        if (!success)
                        {
                            Error = ErrorResponse.Fail("Download was marked unsuccessful");
                            return(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ErrorResponse.Fail(ex);
                        return(false);
                    }
                    // Return an updated check on exists
                    return(File.Exists(Location));
                }
                return(exists);
            })
                .Where(exists => exists)
                // Do any install page swap over on GUI thread
                .ObserveOnGuiThread()
                .Select(_ =>
            {
                _parent.MWVM.OpenInstaller(Path.GetFullPath(Location));

                // Wait for modlist member to be filled, then open its readme
                return(_parent.MWVM.Installer.Value.WhenAny(x => x.ModList)
                       .NotNull()
                       .Take(1)
                       .Do(modList =>
                {
                    try
                    {
                        modList.OpenReadmeWindow();
                    }
                    catch (Exception ex)
                    {
                        Utils.Error(ex);
                    }
                }));
            })
                .Switch()
                .Unit());

            _Exists = Observable.Interval(TimeSpan.FromSeconds(0.5))
                      .Unit()
                      .StartWith(Unit.Default)
                      .FlowSwitch(_parent.WhenAny(x => x.IsActive))
                      .Select(_ =>
            {
                try
                {
                    return(!metadata.NeedsDownload(Location));
                }
                catch (Exception)
                {
                    return(true);
                }
            })
                      .ToGuiProperty(this, nameof(Exists));

            var imageObs = Observable.Return(Metadata.Links.ImageUri)
                           .DownloadBitmapImage((ex) => Utils.Log($"Error downloading modlist image {Metadata.Title}"));

            _Image = imageObs
                     .ToGuiProperty(this, nameof(Image));

            _LoadingImage = imageObs
                            .Select(x => false)
                            .StartWith(true)
                            .ToGuiProperty(this, nameof(LoadingImage));
        }
        public CreateViewModel(INavigationService navigationService)
        {
            this.Title = "Create Region";

            this.EstimoteDefaults = ReactiveCommand.Create(() =>
            {
                this.Identifier = "XamDevSummit";
                this.Uuid       = "FDA50693-A4E2-4FB1-AFCF-C6EB07647825";
                //this.Identifier = "Estimote";
                //this.Uuid = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
            });

            this.WhenAnyValue(x => x.Major)
            .Select(x => !x.IsEmpty() && UInt16.TryParse(x, out _))
            .ToPropertyEx(this, x => x.IsMajorSet);

            this.Create = ReactiveCommand.CreateFromTask(
                () => navigationService.GoBack(false, (
                                                   nameof(BeaconRegion),
                                                   new BeaconRegion(
                                                       this.Identifier,
                                                       Guid.Parse(this.Uuid),
                                                       GetNumberAddress(this.Major),
                                                       GetNumberAddress(this.Minor)
                                                       )
            {
                NotifyOnEntry = this.NotifyOnEntry,
                NotifyOnExit = this.NotifyOnExit
            }
                                                   )),
                this.WhenAny(
                    x => x.Identifier,
                    x => x.Uuid,
                    x => x.Major,
                    x => x.Minor,
                    x => x.NotifyOnEntry,
                    x => x.NotifyOnExit,
                    (idValue, uuidValue, majorValue, minorValue, entry, exit) =>
            {
                if (this.ForMonitoring)
                {
                    var atLeast1Notification = entry.GetValue() || exit.GetValue();
                    if (!atLeast1Notification)
                    {
                        return(false);
                    }
                }
                if (String.IsNullOrWhiteSpace(idValue.GetValue()))
                {
                    return(false);
                }

                var uuid = uuidValue.GetValue();
                if (!uuid.IsEmpty() && !Guid.TryParse(uuid, out _))
                {
                    return(false);
                }

                var result = ValidateNumberAddress(this.Major);
                if (!result)
                {
                    return(false);
                }

                result = ValidateNumberAddress(this.Minor);
                if (!result)
                {
                    return(false);
                }

                return(true);
            }
                    )
                );
        }
Exemple #23
0
 /// <summary>
 /// Initializes the Commands that can be executed from this view model. The commands are initialized
 /// before the <see cref="PopulateContextMenu"/> is invoked
 /// </summary>
 protected override void InitializeCommands()
 {
     base.InitializeCommands();
     this.CreateCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanCreateRdlElement));
     this.CreateCommand.Subscribe(_ => this.ExecuteCreateCommand <Constant>());
 }
Exemple #24
0
 /// <summary>
 ///     Constructs a new <see cref="MockPlayerTransportViewModel" />.
 /// </summary>
 public MockPlayerTransportViewModel()
 {
     Play  = ReactiveCommand.Create(() => { }, Observable.Return(true));
     Pause = ReactiveCommand.Create(() => { }, Observable.Return(false));
     Stop  = ReactiveCommand.Create(() => { }, Observable.Return(false));
 }
Exemple #25
0
 public RecordTypeVm(MainVM mvm, RecordType recordType)
 {
     RecordType    = recordType;
     DeleteCommand = ReactiveCommand.Create(() => mvm.SkippedRecordTypes.Remove(this));
 }
        public TaskEditorViewModel(ICachedService service, IMapper mapper, IShell shell)
        {
            cachedService = service;
            this.mapper   = mapper;
            validator     = new TaskEditorValidator();
            IsValid       = true;
            Shell         = shell as CachedServiceShell;

            taskParameters   = new SourceList <TaskParameter>();
            taskDependencies = new SourceList <DesktopTaskDependence>();
            bindedOpers      = new SourceList <DesktopOperation>();
            incomingPackages = new SourceList <string>();
            tasks            = new SourceList <DesktopTaskNameId>();

            DataImporters       = cachedService.DataImporters;
            DataExporters       = cachedService.DataExporters;
            implementationTypes = new SourceList <string>();

            var canSave = this.WhenAnyValue(tvm => tvm.IsDirty, tvm => tvm.IsValid,
                                            (isd, isv) => isd && isv).Concat(Shell.CanEdit);

            SaveChangesCommand = ReactiveCommand.CreateFromTask(async() => await Save(),
                                                                canSave);

            CancelCommand = ReactiveCommand.CreateFromTask(Cancel);

            ClipBoardFillCommand = ReactiveCommand.Create <string>(Clipboard.SetText);

            OpenCurrentTaskViewCommand = ReactiveCommand //todo: make without interface blocking
                                         .CreateFromTask(async() =>
                                                         cachedService.OpenPageInBrowser(
                                                             await cachedService.GetCurrentTaskViewById(Id)));

            RemoveOperationCommand = ReactiveCommand.Create <DesktopOperation>(to =>
            {
                if (SelectedOperation?.Id == to.Id)
                {
                    ClearSelections();
                }
                bindedOpers.Remove(to);
            }, Shell.CanEdit);

            RemoveParameterCommand = ReactiveCommand
                                     .Create <TaskParameter>(par => taskParameters.Remove(par), Shell.CanEdit);

            RemoveDependenceCommand = ReactiveCommand
                                      .Create <DesktopTaskDependence>(dep => taskDependencies.Remove(dep), Shell.CanEdit);

            AddParameterCommand = ReactiveCommand.Create(() => taskParameters.Add(new TaskParameter
            {
                Name = "@RepPar"
            }), Shell.CanEdit);

            AddDependenceCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                if (tasks.Count == 0)
                {
                    await Shell.ShowMessageAsync("No any existing tasks in service");
                    return;
                }

                tasks
                .Connect()
                .Bind(out var cachedTasks)
                .Subscribe();

                var dependence = new DesktopTaskDependence {
                    Tasks = cachedTasks, TaskId = cachedTasks.First().Id
                };
                taskDependencies.Add(dependence);
            }, Shell.CanEdit);

            AddOperationCommand = ReactiveCommand.CreateFromTask(AddOperation, Shell.CanEdit);


            CreateOperConfigCommand = ReactiveCommand.CreateFromTask(CreateOperConfig, Shell.CanEdit);

            OpenTemplatesListCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                if (SelectedOperationConfig != null && Shell.Role == ServiceUserRole.Editor)
                {
                    if (!await Shell.ShowWarningAffirmativeDialogAsync
                            ("All unsaved operation configuration changes will be lost. Close window?"))
                    {
                        return;
                    }
                }

                await SelectOperFromTemplates();
            }, Shell.CanEdit);

            SelectOperationCommand = ReactiveCommand.CreateFromTask <DesktopOperation>
                                         (SelectOperation);

            this.ObservableForProperty(s => s.Mode)
            .Subscribe(mode =>
            {
                var templates = mode?.Value == OperMode.Exporter
                        ? DataExporters.Select(pair => pair.Key)
                        : DataImporters.Select(pair => pair.Key);

                implementationTypes.ClearAndAddRange(templates);
                Type = implementationTypes.Items.FirstOrDefault();
            });

            this.ObservableForProperty(s => s.Type)
            .Where(type => type.Value != null)
            .Subscribe(type =>
            {
                var operType = Mode == OperMode.Exporter
                        ? DataExporters[type.Value]
                        : DataImporters[type.Value];
                if (operType == null)
                {
                    return;
                }

                SelectedOperationConfig = Activator.CreateInstance(operType);
                mapper.Map(cachedService, SelectedOperationConfig);
            });

            this.WhenAnyValue(tvm => tvm.SelectedOperationConfig)
            .Where(selop => selop != null)
            .Subscribe(conf =>
                       IncomingPackages = incomingPackages.SpawnCollection());
        }
 public static ReactiveCommand <object> ToCommand(this IObservable <bool> canExecute)
 {
     return(ReactiveCommand.Create(canExecute));
 }
        public override void Activation()
        {
            var manager = IoC.Get <IDebugManager2>();

            command = ReactiveCommand.Create(() => manager.StepInto(), manager.CanStep);
        }
Exemple #29
0
        public AllocationPageViewModel(INavigationService navigationService,
                                       IGlobalService globalService,
                                       IDialogService dialogService,
                                       IAllocationService allocationService,
                                       IAdvanceReceiptService advanceReceiptService,
                                       IReceiptCashService receiptCashService,
                                       ICostContractService costContractService,
                                       ICostExpenditureService costExpenditureService,
                                       IInventoryService inventoryService,
                                       IPurchaseBillService purchaseBillService,
                                       IReturnReservationBillService returnReservationBillService,
                                       IReturnBillService returnBillService,
                                       ISaleReservationBillService saleReservationBillService,
                                       ISaleBillService saleBillService
                                       ) : base(navigationService, globalService, allocationService, advanceReceiptService, receiptCashService, costContractService, costExpenditureService, inventoryService, purchaseBillService, returnReservationBillService, returnBillService, saleReservationBillService, saleBillService, dialogService)
        {
            Title = "调拨单";

            this.BillType = BillTypeEnum.AllocationBill;

            this.Load = ReactiveCommand.Create(async() =>
            {
                ItemTreshold = 1;
                PageCounter  = 0;

                try
                {
                    Bills?.Clear();
                    string billNumber  = Filter.SerchKey;
                    DateTime?startTime = Filter.StartTime ?? DateTime.Now.AddMonths(-1);
                    DateTime?endTime   = Filter.EndTime ?? DateTime.Now;

                    int?makeuserId          = Settings.UserId;
                    int businessUserId      = Filter.BusinessUserId;
                    int?shipmentWareHouseId = 0;
                    int?incomeWareHouseId   = 0;
                    //获取未审核
                    bool?auditedStatus     = false;
                    bool?showReverse       = null;
                    bool?sortByAuditedTime = null;

                    var pending = new List <AllocationBillModel>();


                    var result = await _allocationService.GetAllocationsAsync(makeuserId, businessUserId, shipmentWareHouseId, incomeWareHouseId, billNumber, "", auditedStatus, startTime, endTime, showReverse, sortByAuditedTime, 0, PageSize, this.ForceRefresh, new System.Threading.CancellationToken());
                    if (result != null)
                    {
                        pending = result?.Select(s =>
                        {
                            var sm    = s;
                            sm.IsLast = !(result.LastOrDefault()?.BillNumber == s.BillNumber);
                            return(sm);
                        }).ToList();
                    }
                    if (pending.Any())
                    {
                        Bills = new System.Collections.ObjectModel.ObservableCollection <AllocationBillModel>(pending);
                    }
                    UpdateTitle();
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                int pageIdex = 0;
                if (Bills?.Count != 0)
                {
                    pageIdex = Bills.Count / (PageSize == 0 ? 1 : PageSize);
                }

                if (PageCounter < pageIdex)
                {
                    PageCounter = pageIdex;
                    using (var dig = UserDialogs.Instance.Loading("加载中..."))
                    {
                        try
                        {
                            string billNumber  = Filter.SerchKey;
                            DateTime?startTime = Filter.StartTime ?? DateTime.Now.AddMonths(-1);
                            DateTime?endTime   = Filter.EndTime ?? DateTime.Now;


                            int?makeuserId          = Settings.UserId;
                            int businessUserId      = Filter.BusinessUserId;
                            int?shipmentWareHouseId = 0;
                            int?incomeWareHouseId   = 0;
                            //获取未审核
                            bool?auditedStatus     = false;
                            bool?showReverse       = null;
                            bool?sortByAuditedTime = null;


                            var items = await _allocationService.GetAllocationsAsync(makeuserId, businessUserId, shipmentWareHouseId, incomeWareHouseId, billNumber, "", auditedStatus, startTime, endTime, showReverse, sortByAuditedTime, pageIdex, PageSize, this.ForceRefresh, new System.Threading.CancellationToken());
                            if (items != null)
                            {
                                foreach (var item in items)
                                {
                                    if (Bills.Count(s => s.Id == item.Id) == 0)
                                    {
                                        Bills.Add(item);
                                    }
                                }

                                foreach (var s in Bills)
                                {
                                    s.IsLast = !(Bills.LastOrDefault()?.BillNumber == s.BillNumber);
                                }
                            }
                            UpdateTitle();
                        }
                        catch (Exception ex)
                        {
                            Crashes.TrackError(ex);
                        }
                    }
                }
            }, this.WhenAny(x => x.Bills, x => x.GetValue().Count > 0));

            //选择单据
            this.SelectedCommand = ReactiveCommand.Create <AllocationBillModel>(async x =>
            {
                if (x != null)
                {
                    await NavigateAsync(nameof(AllocationBillPage), ("Bill", x), ("IsSubmitBill", true));
                }
            });

            //菜单选择
            this.SubscribeMenus((x) =>
            {
                //获取当前UTC时间
                DateTime dtime = DateTime.Now;
                switch (x)
                {
                case MenuEnum.TODAY:
                    {
                        Filter.StartTime = DateTime.Parse(dtime.ToString("yyyy-MM-dd 00:00:00"));
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.YESTDAY:
                    {
                        Filter.StartTime = dtime.AddDays(-1);
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.OTHER:
                    {
                        SelectDateRang();
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.SUBMIT30:
                    {
                        Filter.StartTime = dtime.AddMonths(-1);
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case Enums.MenuEnum.CLEARHISTORY:    //清空一个月历史单据
                    {
                        ClearHistory(() => _globalService.UpdateHistoryBillStatusAsync((int)this.BillType));
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;
                }
            }, string.Format(Constants.MENU_VIEW_KEY, 4));


            this.BindBusyCommand(Load);
        }
        public PrTabViewModel(SimulationOptions simulationOptions) : base("ІПРАЙ")
        {
            var logger = Logger.New(typeof(PrTabViewModel));

            using (logger.LogPerf("Init"))
            {
                m_SimulationOptions = simulationOptions;

                m_Simulator = new PrSimulator(m_SimulationOptions);

                m_VisualizationProvider = GridDataVisualizationProvider.Table();

                m_Player = new Player(() =>
                {
                    using (logger.LogPerf("Step simulation"))
                    {
                        m_Simulator.SimulateSteps();
                    }
                }, () =>
                {
                    using (logger.LogPerf("Auto simulation"))
                    {
                        m_Simulator.SimulateSteps(5);
                    }
                }, () =>
                {
                    UpdateVisualization.Execute().Subscribe();
                }, TimeSpan.FromMilliseconds(10), DispatcherPriority.ContextIdle);

                UpdateVisualization = ReactiveCommand.Create(() =>
                {
                    using (logger.LogPerf("Visualization"))
                    {
                        Visualization  = m_VisualizationProvider.ProvideVisualization(m_Simulator.GetData());
                        SimulationInfo = m_Simulator.SimulationInfo;
                    }
                });

                var notRunningOrPlaying = m_Player.WhenAny(x => x.RunningOrPlaying, r => !r.Value);

                var notSingleStepRunning = m_Player.WhenAny(x => x.SingleStepRunning, r => !r.Value);

                Step = ReactiveCommand.Create(() =>
                {
                    m_Player.StepOnce();
                }, notRunningOrPlaying);

                PlayPause = new ReactivePlayPauseCommand("Програти", "Пауза", notSingleStepRunning);

                PlayPause.Subscribe(p =>
                {
                    if (p)
                    {
                        m_Player.Start();
                    }
                    else
                    {
                        m_Player.Stop();
                    }
                });

                Restart = ReactiveCommand.Create(() =>
                {
                    m_Simulator.Reset();
                }, notRunningOrPlaying);

                Restart.InvokeCommand(UpdateVisualization);

                VisualTypeSelector = new ReactiveSelectorCommand <string>(x => (string)x, "Table");

                VisualTypeSelector.Selected
                .Subscribe(option =>
                {
                    switch (option)
                    {
                    case "Table":
                        m_VisualizationProvider = GridDataVisualizationProvider.Table();
                        break;

                    case "2D":
                        m_VisualizationProvider = GridDataVisualizationProvider.Color();
                        break;

                    case "3D":
                        m_VisualizationProvider = GridDataVisualizationProvider.Model3D(m_SimulationOptions.Size);
                        break;
                    }
                });

                VisualTypeSelector.Selected
                .ToSignal()
                .InvokeCommand(UpdateVisualization);

                OpenSimulationOptions = ReactiveCommand.Create(() =>
                {
                    SimulationOptionsDialog dialog = new SimulationOptionsDialog(m_SimulationOptions);
                    dialog.ShowDialog();

                    if (!dialog.DialogResult.GetValueOrDefault(false))
                    {
                        return;
                    }

                    m_SimulationOptions     = dialog.SimulationOptions;
                    m_Simulator             = new PrSimulator(m_SimulationOptions);
                    m_VisualizationProvider = m_VisualizationProvider.Copy(m_SimulationOptions.Size);
                }, notRunningOrPlaying);

                OpenSimulationOptions
                .InvokeCommand(UpdateVisualization);

                ExportToCsv = ReactiveCommand.Create(() =>
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog()
                    {
                        Filter = "Файл CSV (*.csv)|*.csv"
                    };
                    if (saveFileDialog.ShowDialog(Application.Current.MainWindow).GetValueOrDefault())
                    {
                        CsvUtil.ExportToFile(m_Simulator.GetData(), saveFileDialog.FileName);
                    }
                });

                Settings.SettingsChange
                .InvokeCommand(UpdateVisualization);

                Settings.SettingsChange
                .Subscribe(_ =>
                {
                    Pallete = Settings.Current.VisualizationOptions.Pallete;
                });

                Pallete = Settings.Current.VisualizationOptions.Pallete;
            }
        }