public MainWindowViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, IViewModel <MgiStarterControlModel> mgiStarter, IViewModel <AutoFanControlModel> autoFanControl)
            : base(lifetimeScope, dispatcher)
        {
            this.RegisterViewModel("MgiStarter", mgiStarter);
            this.RegisterViewModel("FanControl", autoFanControl);

            NewCommad
            .WithExecute(ShowWindow <LogWindow>)
            .ThenRegister("OpenLogs");
        }
Exemplo n.º 2
0
        public MgiStarterControlModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, ProcessConfig config)
            : base(lifetimeScope, dispatcher)
        {
            Client        = RegisterProperty <Process?>(nameof(Client)).OnChange(UpdateLabel);
            Kernel        = RegisterProperty <Process?>(nameof(Kernel)).OnChange(UpdateLabel);
            Status        = RegisterProperty <string?>(nameof(Status)).OnChange(UpdateLabel);
            InternalStart = RegisterProperty <bool>(nameof(InternalStart)).OnChange(UpdateLabel);
            StatusLabel   = RegisterProperty <string?>(nameof(StatusLabel));

            _localHelper    = new LocalHelper(Context);
            _config         = config;
            _processManager = Context.ActorOf <ProcessManagerActor>("Process-Manager");
            var mgiStarting = Context.ActorOf(Context.DI().Props <MgiStartingActor>(), "Mgi-Starter");

            Receive <ProcessStateChange>(ProcessStateChangeHandler);
            Receive <MgiStartingActor.TryStartResponse>(TryStartResponseHandler);
            Receive <MgiStartingActor.StartStatusUpdate>(StatusUpdate);

            NewCommad
            .WithCanExecute(() => InternalStart == false)
            .WithExecute(() =>
            {
                InternalStart += true;
                mgiStarting.Tell(new MgiStartingActor.TryStart(_config, () =>
                {
                    Client.Value?.Kill(true);
                    Kernel.Value?.Kill(true);
                }));
            }).ThenRegister("TryStart");

            NewCommad
            .WithCanExecute(() => InternalStart == false && (Client != null || Kernel != null))
            .WithExecute(() =>
            {
                Client.Value?.Kill(true);
                Kernel.Value?.Kill(true);
            }).ThenRegister("TryStop");

            UpdateLabel();
        }
        public ProjectViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, LocLocalizer localizer, ProjectFileWorkspace workspace)
            : base(lifetimeScope, dispatcher)
        {
            #region Init

            var loadTrigger = new CommandTrigger();

            Receive <IncommingEvent>(e => e.Action());

            IsEnabled = RegisterProperty <bool>(nameof(IsEnabled)).WithDefaultValue(!workspace.ProjectFile.IsEmpty);

            ProjectEntrys = this.RegisterUiCollection <ProjectEntryModel>(nameof(ProjectEntrys))
                            .AndAsync();
            SelectedIndex = RegisterProperty <int>(nameof(SelectedIndex));

            var self = Context.Self;

            void TryUpdateEntry((string ProjectName, string EntryName, ActiveLanguage Lang, string Content) data)
            {
                var(projectName, entryName, lang, content) = data;
                self.Tell(new UpdateRequest(entryName, lang, content, projectName));
            }

            void TryRemoveEntry((string ProjectName, string EntryName) data)
            {
                var(projectName, entryName) = data;
                self.Tell(new RemoveRequest(entryName, projectName));
            }

            OnPreRestart += (exception, o) => Self.Tell(new InitProjectViewModel(workspace.Get(_project)));

            void InitProjectViewModel(InitProjectViewModel obj)
            {
                _project = obj.Project.ProjectName;

                Languages !.Add(new ProjectViewLanguageModel(localizer.ProjectViewLanguageBoxFirstLabel, true));
                Languages.AddRange(obj.Project.ActiveLanguages.Select(al => new ProjectViewLanguageModel(al.Name, false)));
                SelectedIndex += 0;

                foreach (var projectEntry in obj.Project.Entries.OrderBy(le => le.Key))
                {
                    ProjectEntrys.Add(new ProjectEntryModel(obj.Project, projectEntry, TryUpdateEntry, TryRemoveEntry));
                }

                ImportetProjects !.AddRange(obj.Project.Imports);
                loadTrigger.Trigger();
            }

            Receive <InitProjectViewModel>(InitProjectViewModel);

            #endregion

            #region New Entry

            IEnumerable <NewEntryInfoBase> GetEntrys()
            {
                var list = ImportetProjects.ToList();

                list.Add(_project);

                var allEntrys = list.SelectMany(pro => workspace.Get(pro).Entries.Select(e => e.Key)).ToArray();

                return(allEntrys.Select(e => new NewEntryInfo(e)).OfType <NewEntryInfoBase>()
                       .Concat(allEntrys
                               .Select(s => s.Split('_', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault())
                               .Where(s => !string.IsNullOrWhiteSpace(s))
                               .Distinct(StringComparer.Ordinal)
                               .Select(s => new NewEntrySuggestInfo(s !))));
            }

            void AddEntry(EntryAdd entry)
            {
                if (_project != entry.Entry.Project)
                {
                    return;
                }

                ProjectEntrys.Add(new ProjectEntryModel(workspace.Get(_project), entry.Entry, TryUpdateEntry, TryRemoveEntry));
            }

            NewCommad
            .ThenFlow(this.ShowDialog <INewEntryDialog, NewEntryDialogResult?, IEnumerable <NewEntryInfoBase> >(GetEntrys),
                      b =>
            {
                b.Mutate(workspace.Entrys).With(em => em.EntryAdd, em => res => em.NewEntry(_project, res !.Name)).ToSelf()
                .Then(b2 => b2.Action(AddEntry));
            })
Exemplo n.º 4
0
        public MainWindowViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, IOperationManager operationManager, LocLocalizer localizer, IDialogCoordinator dialogCoordinator,
                                   AppConfig config, IDialogFactory dialogFactory, IViewModel <CenterViewModel> model, IMainWindowCoordinator mainWindowCoordinator, ProjectFileWorkspace workspace)
            : base(lifetimeScope, dispatcher)
        {
            Receive <IncommingEvent>(e => e.Action());

            var last             = QueryProperty.Create <ProjectFile?>();
            var loadingOperation = QueryProperty.Create <OperationController?>();

            var self = Self;

            CenterView = this.RegisterViewModel(nameof(CenterView), model);
            workspace.Source.ProjectReset.RespondOn(null, pr => last.Value = pr.ProjectFile);

            #region Restarting

            OnPreRestart += (exception, o) =>
            {
                if (last != null)
                {
                    Self.Tell(last);
                }
            };
            Receive <ProjectFile>(workspace.Reset);

            #endregion

            #region Operation Manager

            RunningOperations = RegisterProperty <IEnumerable <RunningOperation> >(nameof(RunningOperations)).WithDefaultValue(operationManager.RunningOperations);
            RenctFiles        = RegisterProperty <RenctFilesCollection>(nameof(RenctFiles)).WithDefaultValue(new RenctFilesCollection(config, s => self.Tell(new InternlRenctFile(s))));

            NewCommad.WithExecute(operationManager.Clear, b => operationManager.ShouldClear(b, AddResource)).ThenRegister("ClearOp");
            NewCommad.WithExecute(operationManager.CompledClear, b => operationManager.ShouldCompledClear(b, AddResource)).ThenRegister("ClearAllOp");

            #endregion

            #region Save As

            UpdateSource?SaveAsProject()
            {
                var targetFile = dialogFactory.ShowSaveFileDialog(null, true, false, true, "transp", true,
                                                                  localizer.OpenFileDialogViewDialogFilter, true, true, localizer.MainWindowMainMenuFileSaveAs, Directory.GetCurrentDirectory(), out var result);

                if (result != true && CheckSourceOk(targetFile))
                {
                    return(null);
                }

                return(new UpdateSource(targetFile !));
            }

            bool CheckSourceOk(string?source)
            {
                if (!string.IsNullOrWhiteSpace(source))
                {
                    return(false);
                }
                UICall(() => dialogCoordinator.ShowMessage(localizer.CommonError, localizer.MainWindowModelLoadProjectSourceEmpty !));
                return(true);
            }

            NewCommad.WithCanExecute(b => b.FromProperty(last, file => file != null && !file.IsEmpty))
            .ThenFlow(SaveAsProject, b => b.Send.ToModel(CenterView))
            .ThenRegister("SaveAs");

            #endregion

            #region Open File

            Receive <InternlRenctFile>(o => OpentFileSource(o.File));

            async Task <LoadedProjectFile?> SourceSelectedFunc(SourceSelected s)
            {
                if (s.Mode != OpenFileMode.OpenExistingFile)
                {
                    return(await NewFileSource(s.Source));
                }
                OpentFileSource(s.Source);
                return(null);
            }

            void OpentFileSource(string?source)
            {
                if (CheckSourceOk(source))
                {
                    return;
                }

                mainWindowCoordinator.IsBusy = true;
                loadingOperation.Value       = operationManager.StartOperation(string.Format(localizer.MainWindowModelLoadProjectOperation, Path.GetFileName(source) ?? source));

                if (!workspace.ProjectFile !.IsEmpty)
                {
                    workspace.ProjectFile.Operator.Tell(ForceSave.Force(workspace.ProjectFile));
                }

                ProjectFile.BeginLoad(Context, loadingOperation.Value.Id, source !, "Project_Operator");
            }

            SupplyNewProjectFile?ProjectLoaded(LoadedProjectFile obj)
            {
                if (loadingOperation !.Value != null)
                {
                    if (obj.Ok)
                    {
                        loadingOperation.Value.Compled();
                    }
                    else
                    {
                        mainWindowCoordinator.IsBusy = false;
                        loadingOperation.Value.Failed(obj.ErrorReason?.Message ?? localizer.CommonError);
                        return(null);
                    }
                }

                loadingOperation.Value = null;
                if (obj.Ok)
                {
                    RenctFiles.Value.AddNewFile(obj.ProjectFile.Source);
                }

                last !.Value = obj.ProjectFile;

                return(new SupplyNewProjectFile(obj.ProjectFile));
            }

            NewCommad.WithCanExecute(b => b.NotNull(loadingOperation))
            .ThenFlow(
                SourceSelected.From(this.ShowDialog <IOpenFileDialog, string?>(TypedParameter.From(OpenFileMode.OpenExistingFile)), OpenFileMode.OpenExistingFile),
                b =>
            {
                b.Func(SourceSelectedFunc).ToSelf()
                .Then(b2 => b2.Func(ProjectLoaded !).ToModel(CenterView));
            })
        public ProjectViewModel(ILifetimeScope lifetimeScope, IUIDispatcher dispatcher, LocLocalizer localizer,
                                ProjectFileWorkspace workspace)
            : base(lifetimeScope, dispatcher)
        {
            #region Init

            Languages = this.RegisterUiCollection <ProjectViewLanguageModel>(nameof(Languages))
                        .BindToList(out var languages);
            ProjectEntrys = this.RegisterUiCollection <ProjectEntryModel>(nameof(ProjectEntrys))
                            .BindToList(out var projectEntrys);
            ImportetProjects = this.RegisterUiCollection <string>(nameof(ImportetProjects))
                               .BindToList(out var importprojects);

            var loadTrigger = new Subject <Unit>();

            this.Receive <IncommingEvent>(e => e.Action());

            IsEnabled     = RegisterProperty <bool>(nameof(IsEnabled)).WithDefaultValue(!workspace.ProjectFile.IsEmpty);
            SelectedIndex = RegisterProperty <int>(nameof(SelectedIndex));

            var self = Context.Self;

            void TryUpdateEntry((string ProjectName, string EntryName, ActiveLanguage Lang, string Content) data)
            {
                var(projectName, entryName, lang, content) = data;
                self.Tell(new UpdateRequest(entryName, lang, content, projectName));
            }

            void TryRemoveEntry((string ProjectName, string EntryName) data)
            {
                var(projectName, entryName) = data;
                self.Tell(new RemoveRequest(entryName, projectName));
            }

            Start.Subscribe(_ => Self.Tell(new InitProjectViewModel(workspace.Get(_project))));

            void InitProjectViewModel(InitProjectViewModel obj)
            {
                _project = obj.Project.ProjectName;

                languages.Edit(l =>
                {
                    l.Add(new ProjectViewLanguageModel(localizer.ProjectViewLanguageBoxFirstLabel, true));
                    l.AddRange(obj.Project.ActiveLanguages.Select(al => new ProjectViewLanguageModel(al.Name, false)));
                });
                SelectedIndex += 0;

                projectEntrys.AddRange(obj.Project.Entries.OrderBy(le => le.Key).Select(le
                                                                                        => new ProjectEntryModel(obj.Project, le, TryUpdateEntry, TryRemoveEntry)));

                importprojects.AddRange(obj.Project.Imports);
                loadTrigger.OnNext(Unit.Default);
            }

            this.Receive <InitProjectViewModel>(InitProjectViewModel);

            #endregion

            #region New Entry

            IEnumerable <NewEntryInfoBase> GetEntrys()
            {
                var list = ImportetProjects !.ToList();

                list.Add(_project);

                var allEntrys = list.SelectMany(pro => workspace.Get(pro).Entries.Select(e => e.Key)).ToArray();

                return(allEntrys.Select(e => new NewEntryInfo(e)).OfType <NewEntryInfoBase>()
                       .Concat(allEntrys
                               .Select(s => s.Split('_', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault())
                               .Where(s => !string.IsNullOrWhiteSpace(s))
                               .Distinct(StringComparer.Ordinal)
                               .Select(s => new NewEntrySuggestInfo(s !))));
            }

            void AddEntry(EntryAdd entry)
            {
                if (_project != entry.Entry.Project)
                {
                    return;
                }

                projectEntrys.Add(new ProjectEntryModel(workspace.Get(_project), entry.Entry, TryUpdateEntry,
                                                        TryRemoveEntry));
            }

            NewCommad.WithFlow(ob => ob.Select(_ => GetEntrys())
                               .Dialog(this).Of <INewEntryDialog, NewEntryDialogResult?>()
                               .NotNull()
                               .Mutate(workspace.Entrys).With(em => em.EntryAdd, em => res => em.NewEntry(_project, res.Name))
                               .ObserveOnSelf()
                               .Subscribe(AddEntry))
            .ThenRegister("NewEntry");

            #endregion

            #region Remove Request

            void RemoveEntry(EntryRemove entry)
            {
                if (_project != entry.Entry.Project)
                {
                    return;
                }

                var index = ProjectEntrys !.FindIndex(em => em.EntryName == entry.Entry.Key);

                if (index == -1)
                {
                    return;
                }

                projectEntrys !.RemoveAt(index);
            }

            Receive <RemoveRequest>(obs => obs.Mutate(workspace.Entrys)
                                    .With(em => em.EntryRemove, em => rr => em.RemoveEntry(rr.ProjectName, rr.EntryName))
                                    .ObserveOnSelf()
                                    .Subscribe(RemoveEntry));

            #endregion

            #region Update Request

            void UpdateEntry(EntryUpdate obj)
            {
                if (_project != obj.Entry.Project)
                {
                    return;
                }

                var model = ProjectEntrys !.FirstOrDefault(m => m.EntryName == obj.Entry.Key);

                model?.Update(obj.Entry);
            }

            Receive <UpdateRequest>(obs => obs.Mutate(workspace.Entrys).With(em => em.EntryUpdate,
                                                                             em => ur => em.UpdateEntry(ur.ProjectName, ur.Language, ur.EntryName, ur.Content))
                                    .ObserveOnSelf()
                                    .Subscribe(UpdateEntry));

            #endregion

            #region Imports

            void AddImport(AddImport obj)
            {
                var(projectName, import) = obj;
                if (projectName != _project)
                {
                    return;
                }
                importprojects !.Add(import);
            }

            IEnumerable <string> GetImportableProjects()
            {
                var pro = workspace.Get(_project);

                return(workspace.ProjectFile.Projects.Select(p => p.ProjectName)
                       .Where(p => p != _project && !pro.Imports.Contains(p)));
            }

            ImportSelectIndex = RegisterProperty <int>(nameof(ImportSelectIndex)).WithDefaultValue(-1);

            NewCommad.WithCanExecute(from trigger in loadTrigger
                                     select GetImportableProjects().Any())
            .WithFlow(ob => ob.Select(_ => GetImportableProjects())
                      .Dialog(this).Of <IImportProjectDialog, ImportProjectDialogResult?>()
                      .NotNull()
                      .Mutate(workspace.Projects).With(pm => pm.NewImport, pm => r => pm.AddImport(_project, r.Project))
                      .ObserveOnSelf()
                      .Subscribe(AddImport))
            .ThenRegister("AddImport");

            void RemoveImport(RemoveImport import)
            {
                var(targetProject, toRemove) = import;
                if (_project != targetProject)
                {
                    return;
                }

                importprojects !.Remove(toRemove);
            }

            NewCommad.WithCanExecute(ImportSelectIndex.Select(i => i != -1))
            .WithFlow(ob => ob.Select(_ => new InitImportRemove(ImportetProjects[ImportSelectIndex]))
                      .Mutate(workspace.Projects).With(pm => pm.RemoveImport,
                                                       pm => ir => pm.TryRemoveImport(_project, ir.ToRemove))
                      .Subscribe(RemoveImport))
            .ThenRegister("RemoveImport");

            workspace.Projects.NewImport.ToUnit().Subscribe(loadTrigger).DisposeWith(this);
            workspace.Projects.RemoveImport.ToUnit().Subscribe(loadTrigger).DisposeWith(this);

            #endregion

            #region AddLanguage

            void AddActiveLanguage(AddActiveLanguage language)
            {
                if (language.ProjectName != _project)
                {
                    return;
                }

                languages.Add(new ProjectViewLanguageModel(language.ActiveLanguage.Name, false));

                foreach (var model in ProjectEntrys)
                {
                    model.AddLanguage(language.ActiveLanguage);
                }
            }

            NewCommad.WithFlow(ob => ob
                               .Select(_ => workspace.Get(_project).ActiveLanguages.Select(al => al.ToCulture()).ToArray())
                               .Dialog(this).Of <ILanguageSelectorDialog, AddLanguageDialogResult?>()
                               .NotNull()
                               .Mutate(workspace.Projects)
                               .With(pm => pm.NewLanguage, pm => d => pm.AddLanguage(_project, d.CultureInfo))
                               .Subscribe(AddActiveLanguage))
            .ThenRegister("AddLanguage");

            #endregion
        }
        //TODO Refactor for StateManager

        public SetupBuilderViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, AppConfig config, DeploymentServices deploymentServices, IActionInvoker actionInvoker)
            : base(lifetimeScope, dispatcher, actionInvoker)
        {
            _config        = config;
            _server        = new SetupServer(s => UICall(() => TerminalLines !.Add(s)), Context.System.Settings.Config);
            _deploymentApi = DeploymentApi.CreateProxy(Context.System, "SetupBuilder_DeploymentApi");
            _repositoryApi = RepositoryApi.CreateProxy(Context.System, "SetupBuilder_RepositoryApi");

            AddShortcut   = RegisterProperty <bool>(nameof(AddShortcut));
            CurrentError  = RegisterProperty <string>(nameof(CurrentError));
            AddSeed       = RegisterProperty <bool>(nameof(AddSeed));
            TerminalLines = this.RegisterUiCollection <string>(nameof(TerminalLines)).AndAsync();

            var hostEntrys = new HashSet <string>();

            _api = HostApi.CreateOrGet(Context.System);
            Receive <HostEntryChanged>(e =>
            {
                if (string.IsNullOrWhiteSpace(e.Name))
                {
                    return;
                }

                if (e.Removed)
                {
                    hostEntrys.Remove(e.Name);
                }
                else
                {
                    hostEntrys.Add(e.Name);
                }
            });

            Func <string, string?> HostNameValidator(Func <UIProperty <string> > counterPart)
            {
                return(s =>
                {
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        return LocLocalizer.Inst.SetupBuilderView.ErrorEmptyHostName;
                    }
                    return hostEntrys.Contains(s) || s == counterPart().Value ? LocLocalizer.Inst.SetupBuilderView.ErrorDuplicateHostName : null;
                });
            }

            HostName = RegisterProperty <string>(nameof(HostName))
                       .WithValidator(SetError(HostNameValidator(() => SeedHostName !)))
                       .OnChange(s => SeedHostName += s + "_Seed");

            SeedHostName = RegisterProperty <string>(nameof(SeedHostName))
                           .WithValidator(SetError(HostNameValidator(() => HostName)));

            NewCommad
            .WithCanExecute(b =>
                            b.And(
                                deploymentServices.IsReadyQuery(b),
                                b.FromProperty(_buildRunning, i => i == 0),
                                b.FromProperty(HostName.IsValid),
                                b.Or(
                                    b.FromProperty(AddSeed, s => !s),
                                    b.FromProperty(SeedHostName.IsValid))))
            .WithExecute(ExecuteBuild)
            .ThenRegister("CreateSeupCommand");
        }
        public ConfigurationViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, IActionInvoker actionInvoker)
            : base(lifetimeScope, dispatcher, actionInvoker)
        {
            ErrorText = RegisterProperty <string>(nameof(ErrorText));

            ConfigText = RegisterProperty <string>(nameof(ConfigText))
                         .WithValidator(s =>
            {
                try
                {
                    ConfigurationFactory.ParseString(s);
                    return(null);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
            });

            GetState <ServicesConfigState>().Query(EmptyQuery.Instance)
            .ContinueWith(c => ConfigText.Set(c.Result?.BaseConfiguration));

            IsSetupVisible = RegisterProperty <bool>(nameof(IsSetupVisible));

            Receive <StartConfigurationSetup>(_ => IsSetupVisible += true);

            NewCommad
            .WithExecute(() =>
            {
                IsSetupVisible += false;
                Context.System.EventStream.Publish(StartInitialHostSetup.Get);
            })
            .ThenRegister("SetupNext");

            ConnectionString = RegisterProperty <string>(nameof(ConnectionString))
                               .WithValidator(s =>
            {
                try
                {
                    MongoUrl.Create(s);
                    return(null);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
            });

            void ValidateMongoUrl()
            {
                var result = ServicesConfigState.MongoUrlValidator.Validate(ConnectionString.Value);

                if (result.IsValid)
                {
                    ErrorText += string.Empty;
                }
                else
                {
                    ErrorText += result.Errors.FirstOrDefault()?.ErrorMessage ?? string.Empty;
                }
            }

            NewCommad
            .WithCanExecute(b => b.FromProperty(ConnectionString.IsValid))
            .WithExecute(ValidateMongoUrl)
            .ThenRegister("ValidateConnection");

            NewCommad
            .WithCanExecute(b => b.FromProperty(ConnectionString.IsValid))
            .ToStateAction(() => new ApplyMongoUrlAction(ConnectionString.Value))
            .ThenRegister("ApplyConnection");
        }
Exemplo n.º 8
0
        public MgiStarterControlModel(ILifetimeScope lifetimeScope, IUIDispatcher dispatcher, ProcessConfig config, IDialogFactory dialogFactory)
            : base(lifetimeScope, dispatcher)
        {
            Client        = RegisterProperty <Process?>(nameof(Client)).OnChange(UpdateLabel);
            Kernel        = RegisterProperty <Process?>(nameof(Kernel)).OnChange(UpdateLabel);
            Status        = RegisterProperty <string?>(nameof(Status)).OnChange(UpdateLabel);
            InternalStart = RegisterProperty <bool>(nameof(InternalStart)).OnChange(UpdateLabel);
            StatusLabel   = RegisterProperty <string?>(nameof(StatusLabel));

            _localHelper = new LocalHelper(Context);
            _config      = config;

            _processManager = Context.ActorOf("Process-Manager", ProcessManagerActor.New());
            var mgiStarting = Context.ActorOf("Mgi-Starter", MgiStartingActor.New(dialogFactory));

            var currentStart = new BehaviorSubject <CancellationTokenSource?>(null).DisposeWith(this);

            (from start in currentStart
             from state in InternalStart
             where !state
             select start
            ).SubscribeWithStatus(s => s?.Dispose())
            .DisposeWith(this);

            Receive <ProcessStateChange>(obs => obs.SubscribeWithStatus(ProcessStateChangeHandler));
            Receive <MgiStartingActor.TryStartResponse>(obs => obs.SubscribeWithStatus(_ =>
            {
                currentStart.OnNext(null);
                InternalStart += false;
            }));
            Receive <MgiStartingActor.StartStatusUpdate>(obs => obs.SubscribeWithStatus(s => Status += s.Status));

            NewCommad
            .WithCanExecute(InternalStart.Select(b => !b))
            .WithExecute(() =>
            {
                InternalStart += true;
                currentStart.OnNext(new CancellationTokenSource());

                mgiStarting.Tell(new MgiStartingActor.TryStart(_config, currentStart.Value !.Token,
                                                               () =>
                {
                    Client.Value?.Kill(true);
                    Kernel.Value?.Kill(true);
                }));
            }).ThenRegister("TryStart");

            NewCommad
            .WithCanExecute(from client in Client
                            select client != null)
            .WithCanExecute(from kernel in Kernel
                            select kernel != null)
            .WithExecute(() =>
            {
                currentStart.Value?.Cancel();
                Client.Value?.Kill(true);
                Kernel.Value?.Kill(true);
            }).ThenRegister("TryStop");

            InternalStart += false;
            UpdateLabel();
        }
        public SeedNodeViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, IActionInvoker invoker)
            : base(lifetimeScope, dispatcher, invoker)
        {
            #region Init

            Models = this.RegisterUiCollection <SeedUrlModel>(nameof(Models))
                     .AndAsync();

            GetState <SeedState>().Query(EmptyQuery.Instance)
            .ContinueWith(c =>
            {
                if (c.IsCompletedSuccessfully && c.Result != null)
                {
                    Models.AddRange(c.Result.Seeds.Select(SeedUrlModel.New));
                }

                Log.Warning("Seed Query for Intitial Data failed");
            });


            DispatchAction(new TryJoinAction(), false);

            #endregion ;

            #region Add Seed

            void AddSeedEntry(AddSeedUrlEvent entry)
            {
                entry.SeedUrl.WhenNotEmpty(s =>
                {
                    Log.Info("Add Seed Node to List {URL}", s);
                    Models.Add(
                        new SeedUrlModel(s),
                        c =>
                    {
                        try
                        {
                            Cluster.Get(Context.System).Join(Address.Parse(c.Url));
                        }
                        catch (Exception e)
                        {
                            Log.Error(e, "Faild to Join {Url}", c.Url);
                        }
                    });
                });
            }

            WhenStateChanges <SeedState>().FromEvent(s => s.AddSeed).ToAction(AddSeedEntry);

            NewCommad
            .ThenFlow(
                this.ShowDialog <IAddSeedUrlDialog, DialogSeedEntry, IEnumerable <DialogSeedEntry> >(() => Models.Select(m => new DialogSeedEntry(m.Url))),
                b => b.Action(e => DispatchAction(new AddSeedUrlAction(e.Url))))
            .ThenRegister("AddSeedUrl");

            #endregion

            #region Remove Seed

            void DoRemove(RemoveSeedUrlEvent evt)
            {
                Log.Info("Removing Seed {URL}", evt.SeedUrl);
                Models.Remove(Models.First(m => m.Url == evt.SeedUrl));
            }

            SelectIndex = RegisterProperty <int>(nameof(SelectIndex));

            NewCommad
            .WithCanExecute(b => b.FromProperty(SelectIndex, i => i > -1))
            .ToStateAction(() => new RemoveSeedUrlAction(Models.ElementAt(SelectIndex).Url))
            .ThenRegister("RemoveSeed");

            WhenStateChanges <SeedState>().FromEvent(e => e.RemoveSeed)
            .ToAction(DoRemove);

            #endregion
        }
Exemplo n.º 10
0
        public MainWindowViewModel(ILifetimeScope lifetimeScope, IUIDispatcher dispatcher,
                                   IOperationManager operationManager, LocLocalizer localizer, IDialogCoordinator dialogCoordinator,
                                   AppConfig config, IDialogFactory dialogFactory, IViewModel <CenterViewModel> model,
                                   IMainWindowCoordinator mainWindowCoordinator, ProjectFileWorkspace workspace)
            : base(lifetimeScope, dispatcher)
        {
            this.Receive <IncommingEvent>(e => e.Action());

            var last             = new RxVar <ProjectFile?>(null);
            var loadingOperation = new RxVar <OperationController?>(null);

            var self = Self;

            CenterView = this.RegisterViewModel(nameof(CenterView), model);
            workspace.Source.ProjectReset.RespondOn(null, pr => last.Value = pr.ProjectFile);

            #region Restarting

            Start.Subscribe(_ =>
            {
                if (last != null)
                {
                    Self.Tell(last);
                }
            });
            this.Receive <ProjectFile>(workspace.Reset);

            #endregion

            #region Operation Manager

            RunningOperations = RegisterProperty <IEnumerable <RunningOperation> >(nameof(RunningOperations))
                                .WithDefaultValue(operationManager.RunningOperations);
            RenctFiles = RegisterProperty <RenctFilesCollection>(nameof(RenctFiles))
                         .WithDefaultValue(new RenctFilesCollection(config, s => self.Tell(new InternlRenctFile(s))));

            NewCommad.WithExecute(operationManager.Clear, operationManager.ShouldClear()).ThenRegister("ClearOp");
            NewCommad.WithExecute(operationManager.CompledClear, operationManager.ShouldCompledClear())
            .ThenRegister("ClearAllOp");

            #endregion

            #region Save As

            IObservable <UpdateSource> SaveAsProject()
            {
                var targetFile = dialogFactory.ShowSaveFileDialog(null, true, false, true, "transp", true,
                                                                  localizer.OpenFileDialogViewDialogFilter, true, true, localizer.MainWindowMainMenuFileSaveAs,
                                                                  Directory.GetCurrentDirectory());

                return(targetFile.NotEmpty()
                       .SelectMany(CheckSourceOk)
                       .Where(d => d.Item1)
                       .Select(r => new UpdateSource(r.Item2)));
            }

            async Task <(bool, string)> CheckSourceOk(string source)
            {
                if (!string.IsNullOrWhiteSpace(source))
                {
                    return(true, source);
                }
                await UICall(()
                             => dialogCoordinator.ShowMessage(localizer.CommonError,
                                                              localizer.MainWindowModelLoadProjectSourceEmpty !));

                return(false, source);
            }

            NewCommad.WithCanExecute(last.Select(pf => pf != null && !pf.IsEmpty))
            .WithFlow(ob => ob.SelectMany(_ => SaveAsProject())
                      .ToModel(CenterView))
            .ThenRegister("SaveAs");

            #endregion

            #region Open File

            IDisposable NewProjectFile(IObservable <SourceSelected> source) => source
            .SelectMany(SourceSelectedFunc)
            .NotNull()
            .ObserveOnSelf()
            .Select(ProjectLoaded)
            .ToModel(CenterView !);


            this.Receive <InternlRenctFile>(o => OpentFileSource(o.File));

            IObservable <LoadedProjectFile?> SourceSelectedFunc(SourceSelected s)
            {
                if (s.Mode != OpenFileMode.OpenExistingFile)
                {
                    return(NewFileSource(s.Source));
                }
                OpentFileSource(s.Source);
                return(Observable.Return <LoadedProjectFile?>(null));
            }

            void OpentFileSource(string?rawSource)
            {
                Observable.Return(rawSource)
                .NotEmpty()
                .SelectMany(CheckSourceOk)
                .Select(p => p.Item2)
                .Do(_ => mainWindowCoordinator.IsBusy = true)
                .SelectMany(source => operationManager
                            .StartOperation(string.Format(localizer.MainWindowModelLoadProjectOperation,
                                                          Path.GetFileName(source)))
                            .Do(op => loadingOperation !.Value = op)
                            .Select(operationController => (operationController, source)))
                .Do(_ =>
                {
                    if (!workspace.ProjectFile.IsEmpty)
                    {
                        workspace.ProjectFile.Operator.Tell(ForceSave.Force(workspace.ProjectFile));
                    }
                })
                .ObserveOnSelf()
                .Subscribe(pair
                           => ProjectFile.BeginLoad(Context, pair.operationController.Id, pair.source,
                                                    "Project_Operator"));
            }

            SupplyNewProjectFile?ProjectLoaded(LoadedProjectFile obj)
            {
                try
                {
                    if (loadingOperation !.Value != null)
                    {
                        if (obj.Ok)
                        {
                            loadingOperation.Value.Compled();
                        }
                        else
                        {
                            loadingOperation.Value.Failed(obj.ErrorReason?.Message ?? localizer.CommonError);
                            return(null);
                        }
                    }

                    loadingOperation.Value = null;
                    if (obj.Ok)
                    {
                        RenctFiles !.Value.AddNewFile(obj.ProjectFile.Source);
                    }

                    last !.Value = obj.ProjectFile;

                    return(new SupplyNewProjectFile(obj.ProjectFile));
                }
                finally
                {
                    mainWindowCoordinator.IsBusy = false;
                }
            }

            NewCommad.WithCanExecute(loadingOperation.Select(oc => oc == null))
            .WithFlow(obs => NewProjectFile(obs.Dialog(this, TypedParameter.From(OpenFileMode.OpenExistingFile))
                                            .Of <IOpenFileDialog, string?>()
                                            .Select(s => SourceSelected.From(s, OpenFileMode.OpenExistingFile))))
            .ThenRegister("OpenFile");

            NewProjectFile(Receive <SourceSelected>()).DisposeWith(this);
            Receive <LoadedProjectFile>(ob => ob.Select(ProjectLoaded).ToModel(CenterView !));

            #endregion

            #region New File

            IObservable <LoadedProjectFile?> NewFileSource(string?source)
            {
                source ??= string.Empty;
                var data = new LoadedProjectFile(string.Empty,
                                                 ProjectFile.NewProjectFile(Context, source, "Project_Operator"), null, true);

                if (File.Exists(source))
                {
                    //TODO NewFile Filog Message
                    var result = UICall(async()
                                        => await dialogCoordinator.ShowMessage(localizer.CommonError !, "", null));

                    return(result.Where(b => b == true).Do(_ => mainWindowCoordinator.IsBusy = true).Select(_ => data));
                }

                mainWindowCoordinator.IsBusy = true;
                return(Observable.Return(data));
            }

            NewCommad.WithCanExecute(loadingOperation.Select(oc => oc == null))
            .WithFlow(obs => obs.Dialog(this, TypedParameter.From(OpenFileMode.OpenNewFile))
                      .Of <IOpenFileDialog, string?>()
                      .Select(s => SourceSelected.From(s, OpenFileMode.OpenNewFile))
                      .ToSelf())
            .ThenRegister("NewFile");

            #endregion

            #region Analyzing

            AnalyzerEntries = this.RegisterUiCollection <AnalyzerEntry>(nameof(AnalyzerEntries))
                              .BindToList(out var analyterList);

            var builder = new AnalyzerEntryBuilder(localizer);

            void IssuesChanged(IssuesEvent obj)
            {
                analyterList.Edit(l =>
                {
                    var(ruleName, issues) = obj;
                    l.Remove(AnalyzerEntries.Where(e => e.RuleName == ruleName));
                    l.AddRange(issues.Select(builder.Get));
                });
            }

            this.RespondOnEventSource(workspace.Analyzer.Issues, IssuesChanged);

            #endregion

            #region Build

            var buildModel = lifetimeScope.Resolve <IViewModel <BuildViewModel> >();
            buildModel.InitModel(Context, "Build-View");

            BuildModel = RegisterProperty <IViewModel <BuildViewModel> >(nameof(BuildModel)).WithDefaultValue(buildModel);

            #endregion
        }
Exemplo n.º 11
0
        public MainWindowViewModel(ILifetimeScope lifetimeScope, IUIDispatcher dispatcher, AppSettings settings, ITauronEnviroment enviroment,
                                   ProfileManager profileManager, CalculationManager calculation, SystemClock clock, IEventAggregator aggregator)
            : base(lifetimeScope, dispatcher)
        {
            SnackBarQueue = RegisterProperty <SnackbarMessageQueue?>(nameof(SnackBarQueue));
            dispatcher.InvokeAsync(() => new SnackbarMessageQueue(TimeSpan.FromSeconds(10)))
            .Subscribe(SnackBarQueue);

            CurrentProfile = RegisterProperty <string>(nameof(CurrentProfile));
            AllProfiles    = this.RegisterUiCollection <string>(nameof(AllProfiles))
                             .BindToList(settings.AllProfiles, out var list);

            aggregator.ConsumeErrors().Subscribe(ReportError).DisposeWith(this);

            #region Profile Selection

            IsProcessable = RegisterProperty <bool>(nameof(IsProcessable));
            profileManager.IsProcessable
            .Subscribe(IsProcessable)
            .DisposeWith(this);

            ProfileState = RegisterProperty <string>(nameof(ProfileState));
            profileManager.IsProcessable
            .Select(b => b
                                      ? $"{CurrentProfile.Value} Geladen"
                                      : "nicht Geladen")
            .AutoSubscribe(ProfileState, ReportError);

            var loadTrigger = new Subject <string>();

            (from newProfile in CurrentProfile
             where !list.Items.Contains(newProfile)
             select newProfile)
            .Throttle(TimeSpan.FromSeconds(5))
            .AutoSubscribe(s =>
            {
                if (string.IsNullOrWhiteSpace(s))
                {
                    return;
                }

                settings.AllProfiles = settings.AllProfiles.Add(s);
                list.Add(s);
                loadTrigger.OnNext(s);
            }, ReportError)
            .DisposeWith(this);

            (from profile in CurrentProfile
             where list.Items.Contains(profile)
             select profile)
            .Subscribe(loadTrigger)
            .DisposeWith(this);

            #endregion

            Configurate = NewCommad.WithCanExecute(profileManager.IsProcessable)
                          .WithFlow(obs => (from _ in obs
                                            from res in this.ShowDialogAsync <ConfigurationDialog, Unit, ConfigurationManager>(() => profileManager.ConfigurationManager)
                                            select res)
                                    .AutoSubscribe(ReportError))
                          .ThenRegister(nameof(Configurate));

            profileManager.CreateFileLoadPipeline(loadTrigger).DisposeWith(this);

            HoursAll = RegisterProperty <string>(nameof(HoursAll));
            //profileManager.ProcessableData
            //              .Select(pd => pd.AllHours)
            //              .DistinctUntilChanged()
            //              .Select(i => i.ToString())
            //              .ObserveOn(Scheduler.Default)
            //              .Get(HoursAll).DisposeWith(this);

            #region Entrys

            var isHere = false.ToRx().DisposeWith(this);

            ProfileEntries = this.RegisterUiCollection <UiProfileEntry>(nameof(ProfileEntries))
                             .BindTo(profileManager.ConnectCache()
                                     .Select(entry => new UiProfileEntry(entry, profileManager.ProcessableData, ReportError)));

            profileManager.ConnectCache()
            .AutoSubscribe(_ => CheckHere(), aggregator.ReportError)
            .DisposeWith(this);

            dispatcher.InvokeAsync(() =>
            {
                var view        = (ListCollectionView)CollectionViewSource.GetDefaultView(ProfileEntries.Property.Value);
                view.CustomSort = Comparer <UiProfileEntry> .Default;
            });

            (from data in profileManager.ProcessableData.DistinctUntilChanged(pd => pd.Entries)
             where data.Entries.Count != 0
             select Unit.Default)
            .AutoSubscribe(_ => CheckHere(), ReportError)
            .DisposeWith(this);


            Come = NewCommad
                   .WithCanExecute(profileManager.IsProcessable)
                   .WithCanExecute(from here in isHere
                                   select !here)
                   .WithParameterFlow <ModiferBox>(
                obs => profileManager.Come(from box in obs
                                           select new ComeParameter(clock.NowDate, box != null && box.Keys.HasFlag(ModifierKeys.Control)))
                .AutoSubscribe(b =>
            {
                if (b)
                {
                    CheckHere();
                }
                else
                {
                    SnackBarQueue.Value?.Enqueue("Tag Schon eingetragen");
                }
            }, ReportError))
                   .ThenRegister(nameof(Come));

            Go = NewCommad
                 .WithCanExecute(profileManager.IsProcessable)
                 .WithCanExecute(isHere)
                 .WithFlow(() => clock.NowDate,
                           obs => profileManager.Go(obs)
                           .AutoSubscribe(b =>
            {
                if (b)
                {
                    CheckHere();
                }
                else
                {
                    SnackBarQueue.Value?.Enqueue("Tag nicht gefunden");
                }
            }, ReportError))
                 .ThenRegister(nameof(Go));

            void CheckHere()
            {
                (from item in profileManager.Entries
                 where item.Start != null && item.Finish == null
                 orderby item.Date
                 select item).FirstOrDefault()
                .OptionNotNull()
                .Run(_ => isHere !.Value = true, () => isHere !.Value = false);
            }

            Vacation = NewCommad
                       .WithFlow(obs => (from _ in obs
                                         from data in profileManager.ProcessableData.Take(1)
                                         from result in this.ShowDialogAsync <VacationDialog, DateTime[]?, DateTime>(() => data.CurrentMonth)
                                         where result != null
                                         from res in profileManager.AddVacation(result)
                                         select res)
                                 .AutoSubscribe(ReportError))
                       .WithCanExecute(IsProcessable)
                       .ThenRegister(nameof(Vacation));

            #endregion

            #region Correction

            CurrentEntry = RegisterProperty <UiProfileEntry?>(nameof(CurrentEntry));

            Correct = NewCommad
                      .WithCanExecute(profileManager.IsProcessable)
                      .WithCanExecute(from entry in CurrentEntry
                                      select entry != null)
                      .WithFlow(obs => (from _ in obs
                                        let oldEntry = CurrentEntry.Value
                                                       where oldEntry != null
                                                       from dialogResult in this.ShowDialogAsync <CorrectionDialog, CorrectionResult, ProfileEntry>(() => oldEntry.Entry)
                                                       from result in dialogResult switch
            {
                UpdateCorrectionResult update => profileManager.UpdateEntry(update.Entry, oldEntry.Entry.Date),
                DeleteCorrectionResult delete => profileManager.DeleteEntry(delete.Key).Select(_ => string.Empty),
                _ => Observable.Return(string.Empty)
            }
                                        select result)
                                .AutoSubscribe(s =>
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    SnackBarQueue.Value?.Enqueue(s);
                }
                else
                {
                    CheckHere();
                }
            }, aggregator.ReportError))
                      .ThenRegister(nameof(Correct));

            AddEntry = NewCommad
                       .WithCanExecute(IsProcessable)
                       .WithFlow(obs => (from _ in obs
                                         from data in profileManager.ProcessableData.Take(1)
                                         let parameter = new AddEntryParameter(data.Entries.Select(pe => pe.Value.Date.Day).ToHashSet(), data.CurrentMonth)
                                                         from result in this.ShowDialogAsync <AddEntryDialog, AddEntryResult, AddEntryParameter>(() => parameter)
                                                         from u in result switch
            {
                NewAddEntryResult entry => profileManager.AddEntry(entry.Entry),
                _ => Observable.Return(Unit.Default)
            }
                                         select u)
                                 .AutoSubscribe(_ => CheckHere(), ReportError))
                       .ThenRegister(nameof(AddEntry));

            #endregion

            #region Calculation

            Remaining = RegisterProperty <int>(nameof(Remaining));

            CurrentState = RegisterProperty <MonthState>(nameof(CurrentState))
                           .WithDefaultValue(MonthState.Minus);

            calculation.AllHours
            .Select(ts => ts.TotalHours)
            .Select(h =>
            {
                return(h switch
                {
                    0 when InValidConfig() => "Konfiguration!",
                    0 => string.Empty,
                    _ => h.ToString("F0")
                });

                bool InValidConfig()
                => profileManager.ConfigurationManager.DailyHours == 0 && profileManager.ConfigurationManager.MonthHours == 0;
            })