public void Update(LiveSplitState lsState)
        {
            if (Game != null && !Game.HasExited)
            {
                OldState = State.RefreshValues(Game);

                if (lsState.CurrentPhase == TimerPhase.NotRunning)
                {
                    if (Start.Run(lsState, OldState, State) ?? false)
                    {
                        Model.Start();
                    }
                }
                else if (lsState.CurrentPhase == TimerPhase.Running || lsState.CurrentPhase == TimerPhase.Paused)
                {
                    if (Reset.Run(lsState, OldState, State) ?? false)
                    {
                        Model.Reset();
                        return;
                    }
                    else if (Split.Run(lsState, OldState, State) ?? false)
                    {
                        Model.Split();
                    }

                    var isPaused = IsLoading.Run(lsState, OldState, State);
                    if (isPaused != null)
                    {
                        lsState.IsGameTimePaused = isPaused;
                    }

                    var gameTime = GameTime.Run(lsState, OldState, State);
                    if (gameTime != null)
                    {
                        lsState.SetGameTime(gameTime);
                    }
                }
            }
            else
            {
                if (Model == null)
                {
                    Model = new TimerModel()
                    {
                        CurrentState = lsState
                    };
                }
                TryConnect();
            }
        }
        public GameViewModel(IContainer container)
        {
            DcsProcessMonitor.Instance.DcsProcessExited += OnDcsProcessExited;

            _container  = container;
            _controller = container.Resolve <GameController>();

            _profileService  = _container.Resolve <IProfileService>();
            _dcsWorldManager = container.Resolve <IDcsWorldManager>();

            IsUpdateAvailable =
                IsDcsOutOfDate.AsObservable().Merge(
                    IsCheckingLatestVersion.AsObservable().Merge(
                        IsLoading.AsObservable().Merge(
                            FailedVersionCheck.AsObservable()))).Select(_ => IsDcsOutOfDate.Value && !IsLoading.Value && !IsCheckingLatestVersion.Value && !FailedVersionCheck.Value)
                .ToReactiveProperty();

            IsUpdateAvailable.Subscribe(OnIsUpdateAvailableChange);

            var canPlayObservable =
                SelectedInstall
                .Select(_ => Unit.Default)
                .Merge(IsPlayingDcs.Select(_ => Unit.Default))
                .Merge(IsUpdateAvailable.Select(_ => Unit.Default)).Select(_ => CanLaunchDcs());

            LaunchDcsCommand = canPlayObservable.ToReactiveCommand();

            SelectInstallCommand.Subscribe(OnSelectInstall);
            UpdateDcsCommand.Subscribe(OnUpdateDcs);
            RepairDcsCommand.Subscribe(OnRepairDcs);
            LaunchDcsCommand.Subscribe(OnLaunchDcs);
            CheckForUpdatesCommand.Subscribe(OnCheckForUpdates);
            ShowNewsArticleCommand.Subscribe(OnShowNewsArticle);
            CleanShadersCommand.Subscribe(OnCleanShaders);

            _checkPlayingTimer          = new DispatcherTimer();
            _checkPlayingTimer.Interval = TimeSpan.FromSeconds(1);
            _checkPlayingTimer.Tick    += OnCheckPlayingTimerTick;
            _checkPlayingTimer.Start();

            IsUpdatingDcs.Subscribe(OnIsUpdatingDcsChanged);
        }
Пример #3
0
        public Index()
        {
            InitFields();

            DisplayName = "Сбис";
            CurrentItem
            .Select(x => {
                if (x == null)
                {
                    return(Observable.Return <string>(null));
                }
                return(Observable.StartAsync(async() => {
                    var dir = FileHelper.MakeRooted("sbis");
                    Directory.CreateDirectory(dir);
                    var filename = Directory.GetFiles(dir, $"{x.Attachment.Идентификатор}.*").FirstOrDefault();
                    if (!String.IsNullOrEmpty(filename))
                    {
                        return filename;
                    }

                    var result = await client.JsonRpc("СБИС.ПрочитатьДокумент", new {
                        Документ = new {
                            Идентификатор = x.Message.Идентификатор,
                        }
                    });
                    var attachments = result["result"]["Вложение"].ToObject <Attach[]>();
                    var attachment = attachments.FirstOrDefault(y => y.Идентификатор == x.Attachment.Идентификатор);
                    if (attachment == null)
                    {
                        throw new Exception($"Не удалось найти вложение с идентификатором {x.Attachment.Идентификатор}");
                    }

                    x.Attachment = attachment;
                    filename = Path.Combine(dir, x.Attachment.Идентификатор + Path.GetExtension(x.FileName));
                    await LoadToFile(filename, attachment.Файл.Ссылка);
                    return filename;
                }).Catch <string, Exception>(y => {
                    Log.Error("Не удалось загрузить документ", y);
                    return Observable.Return <string>(null);
                }));
            })
            .Switch()
            .ObserveOn(UiScheduler)
            .CatchSubscribe(x => {
                if (CurrentItem.Value != null)
                {
                    CurrentItem.Value.LocalFilename = x;
                }
                Filename.Value = x;
            });
            Filename.Select(x => {
                if (x == null)
                {
                    return(Observable.Return <string>(null));
                }

                var attachment = CurrentItem.Value;
                if (fileformats.Contains(Path.GetExtension(x) ?? "", StringComparer.CurrentCultureIgnoreCase))
                {
                    return(Observable.Return(x));
                }

                return(Observable
                       .StartAsync(async() => await LoadPrintPdf(attachment))
                       .Catch <string, Exception>(y => {
                    Log.Error("Не удалось загрузить pdf");
                    return Observable.Return <string>(null);
                }));
            })
            .Switch()
            .ObserveOn(UiScheduler)
            .Subscribe(PreviewFilename);

            CurrentItem.Select(x => (x?.CanSign()).GetValueOrDefault())
            .Subscribe(CanSign);
            CurrentItem.Select(x => (x?.CanSign()).GetValueOrDefault())
            .Subscribe(CanReject);

            Filename.Select(x => x != null)
            .Subscribe(CanOpen);
            Filename.Select(x => x != null)
            .Subscribe(CanSave);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanDelete);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanDeleteItem);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanPrintItem);

            SearchTerm
            .Throttle(Consts.TextInputLoadTimeout, Scheduler)
            .Select(x => String.IsNullOrEmpty(x)
                                        ? items.ToObservableCollection()
                                        : items.Where(y => y.FileName.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    .ToObservableCollection())
            .Subscribe(Items);
            //CurrentItem.Select(x => AttachmentHistory.Collect(x))
            //	.Subscribe(History);
            IsLoading.Select(x => !x).Subscribe(IsLoaded);
            IsLoading.Select(x => !x).Subscribe(CanPrev);
            IsLoading.Select(x => !x).Subscribe(CanNext);
            IsLoading.Select(x => !x).Subscribe(CanReload);
        }
Пример #4
0
        public async Task LoadProfilesAsync(bool isLatest)
        {
            lock (_locker)
            {
                if (IsLoading.Value)
                {
                    return;
                }

                IsLoading.TurnOn();
            }

            Debug.WriteLine("Load start!");

            try
            {
                var oldProfileIndices = Enumerable.Range(0, Profiles.Count).Reverse().ToList();                 // Reverse method is to start removing from the tail.
                var newProfiles       = new List <ProfileItem>();

                foreach (var newProfile in await _worker.GetProfilesAsync(isLatest, _loadingTimeoutDuration))
                {
                    var isExisting = false;

                    for (int index = 0; (index < Profiles.Count) && !isExisting; index++)
                    {
                        var oldProfile = Profiles[index];
                        if (!oldProfile.Id.Equals(newProfile.Id, StringComparison.Ordinal))
                        {
                            continue;
                        }

                        // Copy changeable values.
                        oldProfile.Position    = newProfile.Position;
                        oldProfile.IsAutomatic = newProfile.IsAutomatic;
                        oldProfile.Signal      = newProfile.Signal;
                        oldProfile.IsConnected = newProfile.IsConnected;

                        oldProfileIndices.Remove(index);
                        isExisting = true;
                    }

                    if (!isExisting)
                    {
                        newProfiles.Add(newProfile);
                    }
                }

                oldProfileIndices.ForEach(x => Profiles.RemoveAt(x));
                newProfiles.ForEach(x => Profiles.Add(x));

                // Calculate count of positions for each interface.
                Profiles
                .GroupBy(x => x.InterfaceId)
                .ToList()
                .ForEach(profilesGroup =>
                {
                    var count = profilesGroup.Count();

                    foreach (var profile in profilesGroup)
                    {
                        profile.PositionCount = count;
                    }
                });

                Debug.WriteLine(Profiles.Any()
                                        ? Profiles
                                .Select(x => $"Profile {x.Name} -> Position: {x.Position}, AutoConnection {x.IsAutomatic}, Signal: {x.Signal}, IsConnected {x.IsConnected}")
                                .Aggregate((work, next) => work + Environment.NewLine + next)
                                        : "No Profile");
            }
            finally
            {
                IsLoading.TurnOff();
            }
        }
Пример #5
0
        public MainWindowViewModel()
        {
            Op = new Operation(
                //new MockWorker() ??
                //new NetshWorker() ??
                new NativeWifiWorker() as IWlanWorker);

            this.Profiles = Op.Profiles.ToReadOnlyReactiveCollection(x => new ProfileItemViewModel(x));

            #region AutoReloadEnabled/Suspended/ConfigMode

            IsAutoReloadEnabled = Op
                                  .ToReactivePropertyAsSynchronized(x => x.IsAutoReloadEnabled);

            IsSuspended = Op
                          .ToReactivePropertyAsSynchronized(x => x.IsSuspended);

            IsConfigMode = new ReactiveProperty <bool>();

            IsAutoReloadEnabled
            .Merge(IsSuspended)
            .Where(x => x)
            .Subscribe(_ => IsConfigMode.Value = false);

            IsConfigMode
            .Where(x => x)
            .Subscribe(_ => IsAutoReloadEnabled.Value = false);

            #endregion

            #region Load

            IsLoading = Op.IsLoading
                        .Where(_ => !Op.IsWorking.Value)
                        //.Select(x => Observable.Empty<bool>()
                        //	.Delay(TimeSpan.FromMilliseconds(10))
                        //	.StartWith(x))
                        //.Concat()
                        .ObserveOnUIDispatcher()
                        .ToReadOnlyReactiveProperty();

            ReloadCommand = IsLoading
                            .Select(x => !x)
                            .ToReactiveCommand();
            ReloadCommand
            .Subscribe(async _ => await Op.LoadProfilesAsync(true));

            Profiles
            .ObserveElementObservableProperty(x => x.Position)
            .Throttle(TimeSpan.FromMilliseconds(10))
            .ObserveOn(SynchronizationContext.Current)
            .Subscribe(_ => ProfilesView.Refresh());                     // ListCollectionView.Refresh method seems not thread-safe.

            #endregion

            #region Work

            IsNotWorking = Op.IsWorking
                           .Select(x => !x)
                           .StartWith(true)      // This is necessary for initial query.
                           .ObserveOnUIDispatcher()
                           .ToReadOnlyReactiveProperty();

            // Query for a profile which is selected.
            var querySelectedProfiles = Profiles
                                        .ObserveElementObservableProperty(x => x.IsSelected)
                                        .Where(x => x.Value)
                                        .Select(x => x.Instance)
                                        .Publish();

            // Query for the selected profile which is connected or disconnected.
            var queryConnectedProfiles = Profiles
                                         .ObserveElementObservableProperty(x => x.IsConnected)
                                         .Where(x => x.Instance.IsSelected.Value)
                                         .Select(x => x.Instance)
                                         .Publish();

            // Query for the selected profile which changes to be available or unavailable.
            var queryAvailableProfiles = Profiles
                                         .ObserveElementObservableProperty(x => x.IsAvailable)
                                         .Where(x => x.Instance.IsSelected.Value)
                                         .Select(x => x.Instance)
                                         .Publish();

            #region MoveUp

            var queryMoveUp = querySelectedProfiles
                              .Select(x => x.Position.Value > 0);

            MoveUpCommand = new[] { IsNotWorking, queryMoveUp }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand();
            MoveUpCommand
            .Subscribe(async _ => await Op.MoveUpProfileAsync());

            #endregion

            #region MoveDown

            var queryMoveDown = querySelectedProfiles
                                .Select(x => x.Position.Value < x.PositionCount.Value - 1);

            MoveDownCommand = new[] { IsNotWorking, queryMoveDown }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand();
            MoveDownCommand
            .Subscribe(async _ => await Op.MoveDownProfileAsync());

            #endregion

            #region Delete

            DeleteCommand = IsNotWorking
                            .ToReactiveCommand();
            DeleteCommand
            .Subscribe(async _ => await Op.DeleteProfileAsync());

            #endregion

            #region Connect

            var queryConnect = Observable.Merge(querySelectedProfiles, queryConnectedProfiles, queryAvailableProfiles)
                               .Select(x => !x.IsConnected.Value && x.IsAvailable.Value);

            ConnectCommand = new[] { IsNotWorking, queryConnect }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand();
            ConnectCommand
            .Subscribe(async _ => await Op.ConnectNetworkAsync());

            #endregion

            #region Disconnect

            var queryDisconnect = Observable.Merge(querySelectedProfiles, queryConnectedProfiles)
                                  .Select(x => x.IsConnected.Value);

            DisconnectCommand = new[] { IsNotWorking, queryDisconnect }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand();
            DisconnectCommand
            .Subscribe(async _ => await Op.DisconnectNetworkAsync());

            #endregion

            querySelectedProfiles.Connect();
            queryConnectedProfiles.Connect();
            queryAvailableProfiles.Connect();

            #endregion
        }
Пример #6
0
        public Index()
        {
            DisplayName = "Диадок";
            InitFields();

            CurrentItem.Subscribe(LoadFiles);
            CurrentItem
            .Select(x => {
                if (x == null)
                {
                    return(Observable.Return <string>(null));
                }
                return(Observable.Start(() => {
                    var dir = FileHelper.MakeRooted("diadok");
                    Directory.CreateDirectory(dir);
                    var filename = Directory.GetFiles(dir, $"{x.Entity.EntityId}.*").FirstOrDefault();
                    if (!String.IsNullOrEmpty(filename))
                    {
                        return filename;
                    }

                    var bytes = x.Entity.Content.Data
                                ?? api.GetEntityContent(token, box.BoxId, x.Entity.DocumentInfo.MessageId, x.Entity.EntityId);
                    filename = Path.Combine(dir, x.Entity.EntityId + Path.GetExtension(x.Entity.FileName));
                    File.WriteAllBytes(filename, bytes);
                    return filename;
                }, Scheduler).DefaultIfFail());
            })
            .Switch()
            .ObserveOn(UiScheduler)
            .CatchSubscribe(x => {
                if (CurrentItem.Value != null)
                {
                    CurrentItem.Value.LocalFilename = x;
                }
                Filename.Value = x;
            });
            Filename.Select(x => {
                if (x == null)
                {
                    return(Observable.Return <string>(null));
                }

                var attachment = CurrentItem.Value;
                if (fileformats.Contains(Path.GetExtension(x) ?? "", StringComparer.CurrentCultureIgnoreCase))
                {
                    return(Observable.Return(x));
                }

                return(Observable.Start(() => LoadPrintPdf(attachment), Scheduler).DefaultIfFail());
            })
            .Switch()
            .ObserveOn(UiScheduler)
            .Subscribe(PreviewFilename);

            CurrentItem.Select(x => (x?.CanSign()).GetValueOrDefault())
            .Subscribe(CanSign);
            CurrentItem.Select(x => (x?.CanSign()).GetValueOrDefault())
            .Subscribe(CanReject);
            CurrentItem.Select(x => (x?.CanSign()).GetValueOrDefault())
            .Subscribe(CanRequestSign);
            CurrentItem.Select(x => x != null &&
                               !(x.Entity.DocumentInfo.NonformalizedDocumentMetadata?.DocumentStatus == NonformalizedDocumentStatus.InboundRecipientSignatureRequestRejected ||
                                 x.Entity.DocumentInfo.RevocationStatus != RevocationStatus.RevocationStatusNone))
            .Subscribe(CanRevoke);

            Filename.Select(x => x != null)
            .Subscribe(CanOpen);
            Filename.Select(x => x != null)
            .Subscribe(CanSave);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanDelete);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanDeleteItem);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanRequestResolution);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanApprove);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanDisapprove);
            CurrentItem.Select(x => x != null)
            .Subscribe(CanPrintItem);

            SearchTerm
            .Throttle(Consts.TextInputLoadTimeout, Scheduler)
            .Select(x => String.IsNullOrEmpty(x)
                                        ? items.ToObservableCollection()
                                        : items.Where(y => y.FileName.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    .ToObservableCollection())
            .Subscribe(Items);
            CurrentItem.Select(x => AttachmentHistory.Collect(x))
            .Subscribe(History);
            IsLoading.Select(x => !x).Subscribe(IsLoaded);
            IsLoading.Select(x => !x).Subscribe(CanPrev);
            IsLoading.Select(x => !x).Subscribe(CanNext);
            IsLoading.Select(x => !x).Subscribe(CanReload);
        }
 /// <inheritdoc />
 public override int GetHashCode()
 {
     return(Request?.GetHashCode() ?? 0 ^ Data?.GetHashCode() ?? 0 ^ IsLoading.GetHashCode());
 }