public MainViewModel()
        {
            _directoryToMonitor = new DirectoryInfo(Properties.Settings.Default.DirectoryToObserve);
            _fileEndingFilters = Properties.Settings.Default.FileFilters.Split(' ');
            SearchTerm = new ReactiveProperty<string>();
            _episodes = new ObservableCollection<Episode>();
            _allEpisodes = new List<Episode>();

            var loadedEpisodes = from _ in Observable.Interval(TimeSpan.FromSeconds(5)).Merge(Observable.Return(0L))
                              let files = GetFiles(_directoryToMonitor.ToString(), _fileEndingFilters, SearchOption.AllDirectories)
                              select files.Select(file => new Episode(new FileInfo(file))).ToList();

            loadedEpisodes.Subscribe(files =>
                {
                    _allEpisodes = files;
                });

            var searchClickEvents = SearchTerm.Throttle(TimeSpan.FromMilliseconds(100));

            searchClickEvents.ObserveOn(SynchronizationContext.Current).Subscribe(_ =>
                {
                    var episodes = from episode in _allEpisodes
                                   where IsContainedInFilter(episode.File.Name)
                                   select episode;

                    _episodes.Clear();
                    foreach (var episode in episodes)
                        _episodes.Add(episode);
                });
        }
		public SettingsPageViewModel(PageManager pageManager, IReactiveFolderSettings settings)
			: base(pageManager)
		{
			Settings = settings;

			ReactionCheckInterval = new ReactiveProperty<string>(settings.DefaultMonitorIntervalSeconds.ToString());

			ReactionCheckInterval.Subscribe(x =>
			{
				settings.DefaultMonitorIntervalSeconds = int.Parse(x);
				settings.Save();
			});

			ReactionCheckInterval.SetValidateNotifyError(x => 
			{
				int temp;
				if (false == int.TryParse(x, out temp))
				{
					return "Number Only";
				}

				return null;
			});

		}
        public AsynchronousViewModel()
        {
            // Notifier of network connecitng status/count
            var connect = new CountNotifier();
            // Notifier of network progress report
            var progress = new ScheduledNotifier<Tuple<long, long>>(); // current, total

            // skip initialValue on subscribe
            SearchTerm = new ReactiveProperty<string>(mode: ReactivePropertyMode.DistinctUntilChanged);

            // Search asynchronous & result direct bind
            // if network error, use OnErroRetry
            // that catch exception and do action and resubscript.
            SearchResults = SearchTerm
                .Select(async term =>
                {
                    using (connect.Increment()) // network open
                    {
                        return await WikipediaModel.SearchTermAsync(term, progress);
                    }
                })
                .Switch() // flatten
                .OnErrorRetry((HttpRequestException ex) => ProgressStatus.Value = "error occured")
                .ToReactiveProperty();

            // CountChangedStatus : Increment(network open), Decrement(network close), Empty(all complete)
            SearchingStatus = connect
                .Select(x => (x != CountChangedStatus.Empty) ? "loading..." : "complete")
                .ToReactiveProperty();

            ProgressStatus = progress
                .Select(x => string.Format("{0}/{1} {2}%", x.Item1, x.Item2, ((double)x.Item1 / x.Item2) * 100))
                .ToReactiveProperty();
        }
Ejemplo n.º 4
0
        public void ToReactiveProperty()
        {
            {
                var rxProp = new ReactiveProperty<int>();
                var calledCount = 0;

                var readRxProp = rxProp.ToReactiveProperty();
                readRxProp.Subscribe(x => calledCount++);

                calledCount.Is(1);
                rxProp.Value = 10;
                calledCount.Is(2);
                rxProp.Value = 10;
                calledCount.Is(2);

                rxProp.SetValueAndForceNotify(10);
                calledCount.Is(2);
            }
            {
                var rxProp = new ReactiveProperty<int>();
                var calledCount = 0;

                var readRxProp = rxProp.ToSequentialReadOnlyReactiveProperty();
                readRxProp.Subscribe(x => calledCount++);

                calledCount.Is(1);
                rxProp.Value = 10;
                calledCount.Is(2);
                rxProp.Value = 10;
                calledCount.Is(2);

                rxProp.SetValueAndForceNotify(10);
                calledCount.Is(3);
            }
        }
Ejemplo n.º 5
0
    public MonsterModel(int id)
    {
        this.monsterId = id;

        isSelected = new ReactiveProperty<bool> (false);

        switch (monsterId)
        {
        case 1:
            this.materialColor = Color.red;
            break;
        case 2:
            this.materialColor = Color.green;
            break;
        case 3:
            this.materialColor = Color.blue;
            break;
        case 4:
            this.materialColor = Color.yellow;
            break;
        default:
            this.materialColor = Color.black;
            break;
        }
    }
Ejemplo n.º 6
0
        public MainPageViewModel()
        {
            Message = new ReactiveProperty<string> ();
            Message.Value = "Hello World";

            CateCollection = new List<CateClass>(30).ToObservable().ToReactiveCollection();
        }
Ejemplo n.º 7
0
        public RepositoryOutlinerVm(RepositoryVm repos)
            : base(string.Empty, RepositoryOutlinerItemType.Root, null, repos, null)
        {
            Debug.Assert(repos != null);
            _repos = repos;

            SelectedItem = new ReactiveProperty<RepositoryOutlinerItemVm>()
                .AddTo(MultipleDisposable);

            // 各項目のルートノードを配置する
            _localBranch =
                new RepositoryOutlinerItemVm("Local", RepositoryOutlinerItemType.LocalBranchRoot, null, repos, this)
                    .AddTo(MultipleDisposable);

            _remoteBranch =
                new RepositoryOutlinerItemVm("Remote", RepositoryOutlinerItemType.RemoteBranchRoot, null, repos, this)
                    .AddTo(MultipleDisposable);

            Children.AddOnScheduler(_localBranch);
            Children.AddOnScheduler(_remoteBranch);

            UpdateBranchNodes(_localBranch, repos.LocalBranches, false);
            UpdateBranchNodes(_remoteBranch, repos.RemoteBranches, true);

            repos.LocalBranches.CollectionChangedAsObservable()
                .Subscribe(_ => UpdateBranchNodes(_localBranch, repos.LocalBranches, false))
                .AddTo(MultipleDisposable);

            repos.RemoteBranches.CollectionChangedAsObservable()
                .Subscribe(_ => UpdateBranchNodes(_remoteBranch, repos.RemoteBranches, true))
                .AddTo(MultipleDisposable);

            SwitchBranchCommand = new ReactiveCommand().AddTo(MultipleDisposable);
            SwitchBranchCommand.Subscribe(_ => SwitchBranch()).AddTo(MultipleDisposable);
        }
 public void NoRaiseLatestValueOnSubscribe()
 {
     var rp = new ReactiveProperty<string>(mode: ReactivePropertyMode.DistinctUntilChanged);
     var called = false;
     rp.Subscribe(_ => called = true);
     called.Is(false);
 }
Ejemplo n.º 9
0
            public GambitList( GambitListInfo gambitListInfo )
            {
                this._gambitListInfo = gambitListInfo;

                moveInput = new Subject<Vector3>();
                targets = new ReactiveProperty<object>();
            }
        public SerializationViewModel()
        {
            // Observable sequence to ObservableCollection
            Items = Observable.Interval(TimeSpan.FromSeconds(1))
                .Take(30)
                .ToReactiveCollection();
            IsChecked = new ReactiveProperty<bool>();
            SelectedIndex = new ReactiveProperty<int>();
            Text = new ReactiveProperty<string>();
            SliderPosition = new ReactiveProperty<int>();

            var serializedString = new ReactiveProperty<string>(mode: ReactivePropertyMode.RaiseLatestValueOnSubscribe);
            Serialize = serializedString.Select(x => x == null).ToReactiveCommand();
            Deserialize = serializedString.Select(x => x != null).ToReactiveCommand();

            // Click Serialize Button
            Serialize.Subscribe(_ =>
            {
                // Serialize ViewModel's all ReactiveProperty Values.
                // return value is string that Serialize by DataContractSerializer.
                serializedString.Value = SerializeHelper.PackReactivePropertyValue(this); // this = ViewModel
            });

            // Click Deserialize Button
            Deserialize.Subscribe(_ =>
            {
                // Deserialize to target ViewModel.
                // Deseirlization order is same as DataContract.
                // Can control DataMemberAttribute's Order Property.
                // more info see http://msdn.microsoft.com/en-us/library/ms729813.aspx
               SerializeHelper.UnpackReactivePropertyValue(this, serializedString.Value);

                serializedString.Value = null; // push to command canExecute
            });
        }
        public ReactivePropertyBasicsPageViewModel()
        {
            // mode is Flags. (default is all)
            // DistinctUntilChanged is no push value if next value is same as current
            // RaiseLatestValueOnSubscribe is push value when subscribed
            var allMode = ReactivePropertyMode.DistinctUntilChanged | ReactivePropertyMode.RaiseLatestValueOnSubscribe;

            // binding value from UI Control
            // if no set initialValue then initialValue is default(T). int:0, string:null...
            InputText = new ReactiveProperty<string>(initialValue: "", mode: allMode);

            // send value to UI Control
            DisplayText = InputText
                .Select(s => s.ToUpper())       // rx query1
                .Delay(TimeSpan.FromSeconds(1)) // rx query2
                .ToReactiveProperty();          // convert to ReactiveProperty

            ReplaceTextCommand = InputText
                .Select(s => !string.IsNullOrEmpty(s))   // condition sequence of CanExecute
                .ToReactiveCommand(); // convert to ReactiveCommand

            // ReactiveCommand's Subscribe is set ICommand's Execute
            // ReactiveProperty.Value set is push(& set) value
            ReplaceTextCommand.Subscribe(_ => InputText.Value = "Hello, ReactiveProperty!");
        }
        public void CombineLatestValuesAreAllTrueTest()
        {
            var m = ReactivePropertyMode.RaiseLatestValueOnSubscribe;
            var recorder = new TestScheduler().CreateObserver<bool>();

            var x = new ReactiveProperty<bool>(mode: m);
            var y = new ReactiveProperty<bool>(mode: m);
            var z = new ReactiveProperty<bool>(mode: m);

            new[] { x, y, z }.CombineLatestValuesAreAllTrue().Subscribe(recorder);
            recorder.Messages.First().Is(OnNext(0, false));

            x.Value = true; recorder.Messages.Last().Is(OnNext(0, false));
            y.Value = true; recorder.Messages.Last().Is(OnNext(0, false));
            z.Value = true; recorder.Messages.Last().Is(OnNext(0, true));
            y.Value = false; recorder.Messages.Last().Is(OnNext(0, false));
            z.Value = false; recorder.Messages.Last().Is(OnNext(0, false));
            x.Value = true; recorder.Messages.Last().Is(OnNext(0, false));
            z.Value = true; recorder.Messages.Last().Is(OnNext(0, false));
            y.Value = true; recorder.Messages.Last().Is(OnNext(0, true));
            x.Value = false; recorder.Messages.Last().Is(OnNext(0, false));
            y.Value = false; recorder.Messages.Last().Is(OnNext(0, false));
            z.Value = false; recorder.Messages.Last().Is(OnNext(0, false));
            z.Value = true; recorder.Messages.Last().Is(OnNext(0, false));
        }
 public void Basic()
 {
     var prop = new ReactiveProperty<int>(3);
     IReadOnlyObservableList<int> coll = prop.ToLiveLinq<int>().ToReadOnlyObservableList();
     coll.Count.Should().Be(1);
     coll[0].Should().Be(3);
     prop.Value = 4;
     coll[0].Should().Be(4);
 }
 public EventToReactiveCommandViewModel()
 {
     // command called, after converter
     this.SelectFileCommand = new ReactiveCommand<string>();
     // create ReactiveProperty from ReactiveCommand
     this.Message = this.SelectFileCommand
         .Select(x => x + " selected.")
         .ToReactiveProperty();
 }
Ejemplo n.º 15
0
        void Awake()
        {
            var editPresenter = EditNotesPresenter.Instance;

            this.UpdateAsObservable()
                .Where(_ => Input.GetKeyDown(KeyCode.Escape))
                .Subscribe(_ => Application.Quit());

            var saveActionObservable = this.UpdateAsObservable()
                .Where(_ => KeyInput.CtrlPlus(KeyCode.S))
                .Merge(saveButton.OnClickAsObservable());

            mustBeSaved = Observable.Merge(
                    EditData.BPM.Select(_ => true),
                    EditData.OffsetSamples.Select(_ => true),
                    EditData.MaxBlock.Select(_ => true),
                    editPresenter.RequestForEditNote.Select(_ => true),
                    editPresenter.RequestForAddNote.Select(_ => true),
                    editPresenter.RequestForRemoveNote.Select(_ => true),
                    editPresenter.RequestForChangeNoteStatus.Select(_ => true),
                    Audio.OnLoad.Select(_ => false),
                    saveActionObservable.Select(_ => false))
                .SkipUntil(Audio.OnLoad.DelayFrame(1))
                .Do(unsaved => saveButton.GetComponent<Image>().color = unsaved ? unsavedStateButtonColor : savedStateButtonColor)
                .ToReactiveProperty();

            mustBeSaved.SubscribeToText(messageText, unsaved => unsaved ? "保存が必要な状態" : "");

            saveActionObservable.Subscribe(_ => Save());

            dialogSaveButton.AddListener(
                EventTriggerType.PointerClick,
                (e) =>
                {
                    mustBeSaved.Value = false;
                    saveDialog.SetActive(false);
                    Save();
                    Application.Quit();
                });

            dialogDoNotSaveButton.AddListener(
                EventTriggerType.PointerClick,
                (e) =>
                {
                    mustBeSaved.Value = false;
                    saveDialog.SetActive(false);
                    Application.Quit();
                });

            dialogCancelButton.AddListener(
                EventTriggerType.PointerClick,
                (e) =>
                {
                    saveDialog.SetActive(false);
                });
        }
    public MonsterListModel()
    {
        monsters = new ReactiveCollection<MonsterModel> ();
        focusMonster = new ReactiveProperty<MonsterModel> ();
        selectedMosnters = new ReactiveCollection<MonsterModel> ();
        selectDone = new ReactiveProperty<bool> ();

        selectedMosnters.ObserveAdd ().Subscribe (this.OnSelectedMonsterAdded);
        selectedMosnters.ObserveRemove ().Subscribe (this.OnSelectedMonsterRemoved);
    }
Ejemplo n.º 17
0
 public LoginViewModel()
 {
     TantoushaCd = new ReactiveProperty<string>(initialValue: string.Empty);
     Password = new ReactiveProperty<string>(initialValue: string.Empty);
     LoginCommand = new ReactiveCommand();
     LoginCommand.Subscribe(_ =>
     {
         new Unsou.Views.Unsou().Show();
     });
 }
 public void NoDistinctUntilChanged()
 {
     var rp = new ReactiveProperty<string>(mode: ReactivePropertyMode.RaiseLatestValueOnSubscribe);
     var list = new List<string>();
     rp.Subscribe(list.Add);
     rp.Value = "Hello world";
     rp.Value = "Hello world";
     rp.Value = "Hello japan";
     list.Is(null, "Hello world", "Hello world", "Hello japan");
 }
Ejemplo n.º 19
0
		public FilterViewModelBase()
		{
			IncludeFilterText = new ReactiveProperty<string>("");
			ExcludeFilterText = new ReactiveProperty<string>("");

			var temp = new ObservableCollection<string>();
			IncludeFilterPatterns = temp.ToReadOnlyReactiveCollection();
			ExcludeFilterPatterns = temp.ToReadOnlyReactiveCollection();
			SampleItems = temp.ToReadOnlyReactiveCollection();
		}
Ejemplo n.º 20
0
        protected override void Initialize()
        {
            var image = this.GetComponent<Image>();

            Message = new ReactiveProperty<string>("");
            Message.SubscribeToText(text);

            Color = new ReactiveProperty<UnityEngine.Color>();
            Color.Subscribe(x => image.color = x);
        }
Ejemplo n.º 21
0
        public ValidationViewModel()
        {
            // null is success(have no error), string is error message
            ValidationData = new ReactiveProperty<string>()
                .SetValidateNotifyError((string s) => !string.IsNullOrEmpty(s) && s.Cast<char>().All(Char.IsUpper) ? null : "not all uppercase");

            // async validation
            // first argument is self observable sequence
            // null is success(have no error), IEnumerable is error messages
            ValidationNotify = new ReactiveProperty<string>("foo!", ReactivePropertyMode.RaiseLatestValueOnSubscribe)
                .SetValidateNotifyError(self => self
                    .Delay(TimeSpan.FromSeconds(3)) // asynchronous validation...
                    .Select(s => string.IsNullOrEmpty(s) ? null : "not empty string"));

            // both validation
            ValidationBoth = new ReactiveProperty<string>()
                .SetValidateNotifyError(s => !string.IsNullOrEmpty(s) && s.Cast<char>().All(Char.IsLower) ? null : "not all lowercase")
                .SetValidateNotifyError(self => self
                    .Delay(TimeSpan.FromSeconds(1)) // asynchronous validation...
                    .Select(s => string.IsNullOrEmpty(s) || s.Length <= 5 ? null : (IEnumerable)new[] { "length 5" }));

            // Validation result is pushed to ObserveErrors
            var errors = new[]
                {
                    ValidationData.ObserveErrorChanged,
                    ValidationBoth.ObserveErrorChanged,
                    ValidationNotify.ObserveErrorChanged
                }
                .CombineLatest();

            // Use OfType, choose error source
            ErrorInfo = errors
                .SelectMany(x => x)
                .Where(x => x != null)
                .Select(x => x.OfType<string>())
                .Select(x => x.FirstOrDefault())
                .ToReactiveProperty();

            // Validation is view initialized not run in default.
            // If want to validate on view initialize,
            // use ReactivePropertyMode.RaiseLatestValueOnSubscribe to ReactiveProperty
            // that mode is validate values on initialize.
            NextCommand =
                new[]
                {
                    ValidationData.ObserveHasErrors,
                    ValidationBoth.ObserveHasErrors,
                    ValidationNotify.ObserveHasErrors
                }
                .CombineLatestValuesAreAllFalse()
                .ToReactiveCommand();
            this.AlertMessage = NextCommand.Select(_ => "Can go to next!").ToReactiveProperty(
                initialValue: "Can go to next!",
                mode: ReactivePropertyMode.None);
        }
 public GameModel(PlayerModel player)
 {
     _player = player;
     RxGameState = new ReactiveProperty<GameState>(GameState.WaitingToStart);
     _player.RxPlayerState
         .Where(x => x == PlayerModel.PlayerState.Dead)
         .Subscribe(x =>
         {
             RxGameState.Value = GameState.GameOver;
         });
 }
Ejemplo n.º 23
0
    public Character()
    {
        Location = new ReactiveProperty<Coord>();
        Health = new ReactiveProperty<int>();

        Location.Subscribe(coord =>
        {
            X = coord.x;
            Y = coord.y;
        })
        .AddTo(disposables);
    }
		public InstantActionPageViewModel(PageManager pageManager, IEventAggregator ea, IAppPolicyManager appPolicyManager, IInstantActionManager instantActionManager, IFolderReactionMonitorModel monitor, IHistoryManager historyManager)
			: base(pageManager)
		{
			_EventAggregator = ea;
			AppPolicyManger = appPolicyManager;
			InstantActionManager = instantActionManager;
			Monitor = monitor;
			HistoryManager = historyManager;

			InstantActionVM = new ReactiveProperty<InstantActionStepViewModel>();
				
		}
        public void ObserveErrors()
        {
            var rp = new ReactiveProperty<string>()
                .SetValidateNotifyError(x => x == null ? "Error" : null);
            var results = new List<IEnumerable>();

            rp.ObserveErrorChanged.Subscribe(x => results.Add(x));
            rp.Value = "OK";

            results.Count.Is(2);
            results[0].OfType<string>().Is("Error");
            results[1].IsNull();
        }
        public void Invoke()
        {
            var etr = new EventToReactive();
            var rp = new ReactiveProperty<int>(mode: ReactivePropertyMode.None);

            etr.ReactiveProperty = rp;

            etr.AsDynamic().Invoke((object)100);
            rp.Value.Is(100);

            etr.AsDynamic().Invoke((object)1000);
            rp.Value.Is(1000);
        }
        public void ObserveHasError()
        {
            var rp = new ReactiveProperty<string>()
                .SetValidateNotifyError(x => x == null ? "Error" : null);
            var results = new List<bool>();

            rp.ObserveHasErrors.Subscribe(x => results.Add(x));
            rp.Value = "OK";

            results.Count.Is(2);
            results[0].IsTrue();
            results[1].IsFalse();
        }
        public void ShredReactivePropertyCase()
        {
            var rp = new ReactiveProperty<bool>(false);

            var taskSource1 = new TaskCompletionSource<object>();
            var taskSource2 = new TaskCompletionSource<object>();

            var canExecutedCounter1 = 0;
            var canExecutedCounter2 = 0;

            var command1 = rp.ToAsyncReactiveCommand();
            command1.CanExecuteChanged += (_, __) => canExecutedCounter1++;
            command1.Subscribe(_ => taskSource1.Task);
            var command2 = rp.ToAsyncReactiveCommand();
            command2.CanExecuteChanged += (_, __) => canExecutedCounter2++;
            command2.Subscribe(_ => taskSource2.Task);

            command1.CanExecute().IsFalse();
            command2.CanExecute().IsFalse();

            rp.Value = true;
            command1.CanExecute().IsTrue();
            command2.CanExecute().IsTrue();
            canExecutedCounter1.Is(1);
            canExecutedCounter2.Is(1);

            command1.Execute();
            command1.CanExecute().IsFalse();
            canExecutedCounter1.Is(2);
            command2.CanExecute().IsFalse();
            canExecutedCounter1.Is(2);

            taskSource1.SetResult(null);
            command1.CanExecute().IsTrue();
            canExecutedCounter1.Is(3);
            command2.CanExecute().IsTrue();
            canExecutedCounter1.Is(3);

            command2.Execute();
            command1.CanExecute().IsFalse();
            canExecutedCounter1.Is(4);
            command2.CanExecute().IsFalse();
            canExecutedCounter1.Is(4);

            taskSource2.SetResult(null);
            command1.CanExecute().IsTrue();
            canExecutedCounter1.Is(5);
            command2.CanExecute().IsTrue();
            canExecutedCounter1.Is(5);

        }
Ejemplo n.º 29
0
        void Start()
        {
            if (alreadyStarted) return;

            alreadyStarted = true;

            var image = this.GetComponent<Image>();

            Message = new ReactiveProperty<string>("");
            Message.SubscribeToText(text);

            Color = new ReactiveProperty<UnityEngine.Color>();
            Color.Subscribe(x => image.color = x);
        }
    public PlayerModel(Settings playerSettings, ShipModel.Factory shipFactory)
    {
        //order of initilaization is based on object graph, if object A is injected into B A is initalized first !

        ModelSettings = playerSettings;

        RxPlayerName = new ReactiveProperty<string>(playerSettings.playerName);
        RxPlayerScore = new ReactiveProperty<int>(playerSettings.initialScore);
        RxPlayerState = new ReactiveProperty<PlayerState>(PlayerState.Inactive);

        PlayerShip = shipFactory.Create(this, playerSettings.shipSettings);

        PlayerShip.RxShipState.Where(x => x == ShipModel.ShipState.Dead).Subscribe(x => { Deactivate(); });
    }
Ejemplo n.º 31
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainWindowViewModel()
        {
            this.Tree = this.Model.Content
                        .Tree
                        .ToReadOnlyReactiveCollection(x => new NodeViewModel(x));

            this.WindowTitle = this.Model.ObserveProperty(x => x.FilePath)
                               .Select(x => string.IsNullOrWhiteSpace(x) ? "" : System.IO.Path.GetFileName(x))
                               .Select(x => "Quartet Editor" + (string.IsNullOrWhiteSpace(x) ? "" : $" - {x}"))
                               .CombineLatest(this.Model.ObserveProperty(x => x.IsEdited), (title, flg) => title + (flg ? "(変更あり)" : ""))
                               .ToReactiveProperty()
                               .AddTo(this.Disposable);

            // エラーメッセージ表示要求の処理
            this.Model.ShowErrorMessageRequest.Subscribe(async message =>
            {
                var arg = new DialogArg
                {
                    Title   = "エラー",
                    Message = message,
                    Style   = MessageDialogStyle.Affirmative
                };

                await this._MessageDialogRequest.RaiseAsync(new Confirmation
                {
                    Content = arg
                });
                return;
            });

            #region Content

            // VM -> M 一方向バインド
            this.SelectedNode = ReactiveProperty.FromObject(
                this.Model.Content,
                x => x.SelectedNode,
                convert: x => (NodeViewModel)null, // M -> VMの変換処理
                convertBack: x => x?.Model);       // VM -> Mの変換処理
            this.SelectedNode.Subscribe(_ =>
            {
                // 選択状態が変わったときにTreeViewからフォーカスが外れるのを避ける
                this.setFocusRequest.Raise(new Confirmation {
                    Content = "_NodeView"
                });
            });

            // M -> VM 一方向バインド
            this.TextContent = this.Model.Content
                               .ObserveProperty(x => x.TextContent)
                               .ToReactiveProperty()
                               .AddTo(this.Disposable);

            this.ParentTextContent = this.Model.Content
                                     .ObserveProperty(x => x.ParentTextContent)
                                     .ToReactiveProperty()
                                     .AddTo(this.Disposable);

            this.PrevTextContent = this.Model.Content
                                   .ObserveProperty(x => x.PrevTextContent)
                                   .ToReactiveProperty()
                                   .AddTo(this.Disposable);

            this.NextTextContent = this.Model.Content
                                   .ObserveProperty(x => x.NextTextContent)
                                   .ToReactiveProperty()
                                   .AddTo(this.Disposable);

            #endregion Content

            #region Panel

            this.LeftPanelOpen = this.Config
                                 .ToReactivePropertyAsSynchronized(x => x.LeftPanelOpen)
                                 .AddTo(this.Disposable);

            this.TopPanelOpen = this.Config
                                .ToReactivePropertyAsSynchronized(x => x.TopPanelOpen)
                                .AddTo(this.Disposable);

            this.BottomPanelOpen = this.Config
                                   .ToReactivePropertyAsSynchronized(x => x.BottomPanelOpen)
                                   .AddTo(this.Disposable);

            // パネルの開閉状態が変わったときはRisePanelStateを呼び出す
            new[] { this.LeftPanelOpen, this.TopPanelOpen, this.BottomPanelOpen }
            .Select(x => INotifyPropertyChangedExtensions.PropertyChangedAsObservable(x))
            .Merge()
            .Subscribe(_ =>
            {
                this.RisePanelState();
                this.Model.Content.UpdatePanelReffer();
                // ReleaseでビルドするとなぜかReactivePropertyが反応しないので…
            })
            .AddTo(this.Disposable);

            this.PanelChangeCommand.Subscribe(kind =>
            {
                switch (kind)
                {
                case PanelKind.Left:
                    this.LeftPanelOpen.Value = !this.LeftPanelOpen.Value;
                    return;

                case PanelKind.Top:
                    this.TopPanelOpen.Value = !this.TopPanelOpen.Value;
                    return;

                case PanelKind.Bottom:
                    this.BottomPanelOpen.Value = !this.BottomPanelOpen.Value;
                    return;

                default:
                    return;
                }
            });

            #endregion Panel

            #region DragDrop

            Observable.FromEvent <Action <DragEventArgs>, DragEventArgs>(
                h => (e) => h(e),
                h => this.DragAcceptDescription.DragOverAction += h,
                h => this.DragAcceptDescription.DragOverAction -= h).Subscribe(arg =>
            {
                var fe = arg.OriginalSource as FrameworkElement;
                if (fe == null)
                {
                    return;
                }
                var target = fe.DataContext as NodeViewModel;
                var data   = arg.Data.GetData(typeof(NodeViewModel)) as NodeViewModel;

                if (data == null)
                {
                    if (!arg.Data.GetDataPresent(DataFormats.FileDrop, true))
                    {
                        return;
                    }

                    // ファイルドロップの場合
                    if (arg.AllowedEffects.HasFlag(System.Windows.DragDropEffects.Move))
                    {
                        arg.Effects = System.Windows.DragDropEffects.Move;
                    }
                }
                else
                {
                    if (data.IsNameEditMode.Value)
                    {
                        return;
                    }

                    if (arg.AllowedEffects.HasFlag(System.Windows.DragDropEffects.Move) && !KeyboardUtility.IsCtrlKeyPressed)
                    {
                        arg.Effects = System.Windows.DragDropEffects.Move;
                    }
                    else if (arg.AllowedEffects.HasFlag(System.Windows.DragDropEffects.Copy) && KeyboardUtility.IsCtrlKeyPressed)
                    {
                        arg.Effects = System.Windows.DragDropEffects.Copy;
                    }
                    else
                    {
                        return;
                    }
                }

                this.Model.Content.DragOverAction(target?.Model, data?.Model);
            }).AddTo(this.Disposable);

            Observable.FromEvent <Action <DragEventArgs>, DragEventArgs>(
                h => (e) => h(e),
                h => this.DragAcceptDescription.DragEnterAction += h,
                h => this.DragAcceptDescription.DragEnterAction -= h).Subscribe(arg =>
            {
                var fe = arg.OriginalSource as FrameworkElement;
                if (fe == null)
                {
                    return;
                }
                var target = fe.DataContext as NodeViewModel;
                var data   = arg.Data.GetData(typeof(NodeViewModel)) as NodeViewModel;

                this.Model.Content.DragEnterAction(target?.Model, data?.Model);
            }).AddTo(this.Disposable);

            Observable.FromEvent <Action <DragEventArgs>, DragEventArgs>(
                h => (e) => h(e),
                h => this.DragAcceptDescription.DragLeaveAction += h,
                h => this.DragAcceptDescription.DragLeaveAction -= h).Subscribe(arg =>
            {
                var fe = arg.OriginalSource as FrameworkElement;
                if (fe == null)
                {
                    return;
                }
                var target = fe.DataContext as NodeViewModel;
                this.Model.Content.DragLeaveAction(target?.Model);
            }).AddTo(this.Disposable);

            Observable.FromEvent <Action <DragEventArgs>, DragEventArgs>(
                h => (e) => h(e),
                h => this.DragAcceptDescription.DragDropAction += h,
                h => this.DragAcceptDescription.DragDropAction -= h).Subscribe(arg =>
            {
                var fe = arg.OriginalSource as FrameworkElement;
                if (fe == null)
                {
                    return;
                }
                var target = fe.DataContext as NodeViewModel;
                var data   = arg.Data.GetData(typeof(NodeViewModel)) as NodeViewModel;

                this.Model.Content.DragDropAction(arg, target?.Model, data?.Model, KeyboardUtility.IsCtrlKeyPressed);
            }).AddTo(this.Disposable);

            #endregion DragDrop

            #region AboutFlyout

            // AboutCommand
            this.OpenAboutCommand.Subscribe(_ => this.IsAboutOpen = true).AddTo(this.Disposable);

            #endregion AboutFlyout

            #region Focus
            // SetFocusCommand
            this.SetFocusCommand.Subscribe(param =>
            {
                // Viewにリクエストを投げる
                this.setFocusRequest.Raise(new Confirmation {
                    Content = param
                });
            }).AddTo(this.Disposable);
            #endregion Focus

            #region NodeManipulation

            this.NameEditCommand.Subscribe(_ => this.Model.Content.CallNameEditMode()).AddTo(this.Disposable);

            this.UndoCommand = new ReactiveCommand(this.Model.Content.ChangedCanUndo, false);
            this.UndoCommand.Subscribe(_ =>
            {
                this.Model.Content.Undo();
            }).AddTo(this.Disposable);

            this.RedoCommand = new ReactiveCommand(this.Model.Content.ChangedCanRedo, false);
            this.RedoCommand.Subscribe(_ => this.Model.Content.Redo()).AddTo(this.Disposable);

            this.DeleteNodeCommand.Subscribe(_ => this.Model.Content.DeleteNode()).AddTo(this.Disposable);

            this.AddNodeSameCommand.Subscribe(_ => this.Model.Content.AddNodeSame()).AddTo(this.Disposable);

            this.AddNodeLowerCommand.Subscribe(_ => this.Model.Content.AddNodeLower()).AddTo(this.Disposable);

            this.ReproduceCommand.Subscribe(_ => this.Model.Content.Reproduce()).AddTo(this.Disposable);

            this.AddNodeFromHeaderCommand.Subscribe(_ => this.Model.Content.AddNodeFromHeader()).AddTo(this.Disposable);

            this.MoveUpCommand = new ReactiveCommand(this.Model.Content.ChangedCanMoveUp, false);
            this.MoveUpCommand.Subscribe(_ => this.Model.Content.MoveUp()).AddTo(this.Disposable);

            this.MoveDownCommand = new ReactiveCommand(this.Model.Content.ChangedCanMoveDown, false);
            this.MoveDownCommand.Subscribe(_ => this.Model.Content.MoveDown()).AddTo(this.Disposable);

            this.MoveChildCommand = new ReactiveCommand(this.Model.Content.ChangedCanMoveChild, false);
            this.MoveChildCommand.Subscribe(_ => this.Model.Content.MoveChild()).AddTo(this.Disposable);

            this.MoveParentCommand = new ReactiveCommand(this.Model.Content.ChangedCanMoveParent, false);
            this.MoveParentCommand.Subscribe(_ => this.Model.Content.MoveParent()).AddTo(this.Disposable);

            #endregion NodeManipulation

            #region File

            // ファイルのドロップイベント処理
            Observable.FromEvent <Action <DragEventArgs>, DragEventArgs>(
                h => (e) => h(e),
                h => this.DraggedFileAcceptDescription.DragOverAction += h,
                h => this.DraggedFileAcceptDescription.DragOverAction -= h).Subscribe(arg =>
            {
                if (arg.Data.GetDataPresent(DataFormats.FileDrop, true))
                {
                    arg.Effects = DragDropEffects.Copy;
                    arg.Handled = true;
                }
            }).AddTo(this.Disposable);;

            Observable.FromEvent <Action <DragEventArgs>, DragEventArgs>(
                h => (e) => h(e),
                h => this.DraggedFileAcceptDescription.DragDropAction += h,
                h => this.DraggedFileAcceptDescription.DragDropAction -= h).Subscribe(arg =>
            {
                string[] files = arg.Data.GetData(DataFormats.FileDrop) as string[];

                if (files != null && files.Count() == 1)
                {
                    this.Model.Load(files[0]);
                }
            }).AddTo(this.Disposable);

            this.SaveCommand.Subscribe(_ => this.Model.SaveOverwrite()).AddTo(this.Disposable);
            this.RenameSaveCommand.Subscribe(_ => this.Model.SaveAs()).AddTo(this.Disposable);
            this.Model.SavePathRequest.Subscribe(act =>
            {
                if (this.SaveDialogViewAction == null)
                {
                    return;
                }

                var dialog          = new SaveFileDialog();
                dialog.Title        = "QEDファイルを保存";
                dialog.Filter       = "QEDファイル(*.qed)|*.qed|全てのファイル(*.*)|*.*";
                dialog.AddExtension = true;
                dialog.DefaultExt   = "qed";
                dialog.FileName     = "新規";
                string path         = this.SaveDialogViewAction(dialog);
                act(path);
            }).AddTo(this.Disposable);
            this.OpenCommand.Subscribe(_ => this.Model.OpenQED()).AddTo(this.Disposable);
            this.Model.OpenPathRequest.Subscribe(act =>
            {
                if (this.OpenDialogViewAction == null)
                {
                    return;
                }

                var dialog    = new OpenFileDialog();
                dialog.Title  = "QEDファイルを開く";
                dialog.Filter = "QEDファイル(*.qed)|*.qed|階層付きテキスト(*.txt)|*.txt|全てのファイル(*.*)|*.*";
                string path   = this.OpenDialogViewAction(dialog);
                act(path);
            }).AddTo(this.Disposable);

            #endregion File

            #region Export

            this.OpenExportDialogCommand.Subscribe(_ =>
            {
                this.ExportDialogViewAction();
            }).AddTo(this.Disposable);

            this.Model.ExportSavePathRequest.Subscribe(tuple =>
            {
                if (this.SaveDialogViewAction == null)
                {
                    return;
                }

                var dialog          = new SaveFileDialog();
                dialog.Title        = "エクスポート";
                dialog.Filter       = tuple.Item1;
                dialog.AddExtension = true;
                dialog.DefaultExt   = tuple.Item2;
                dialog.FileName     = string.IsNullOrWhiteSpace(this.Model.FilePath) ? "新規" : System.IO.Path.GetFileNameWithoutExtension(this.Model.FilePath);
                string path         = this.SaveDialogViewAction(dialog);
                tuple.Item3(path);
            }).AddTo(this.Disposable);

            #endregion Export

            #region FindAndReplace

            this.OpenFindDialogCommand.Subscribe(_ =>
            {
                this._FindReplaceDialogRequest.Raise(new Confirmation
                {
                    Content = new FindReplaceDialogRequestEntity()
                    {
                        RequestKind = FindReplaceDialogRequestEntity.DialogRequest.OpenFind
                    }
                });
            }).AddTo(this.Disposable);

            this.OpenReplaceDialogCommand.Subscribe(_ =>
            {
                this._FindReplaceDialogRequest.Raise(new Confirmation
                {
                    Content = new FindReplaceDialogRequestEntity()
                    {
                        RequestKind = FindReplaceDialogRequestEntity.DialogRequest.OpenReplace
                    }
                });
            }).AddTo(this.Disposable);

            this.FindNextCommand.Subscribe(_ =>
            {
                this._FindReplaceDialogRequest.Raise(new Confirmation
                {
                    Content = new FindReplaceDialogRequestEntity()
                    {
                        RequestKind = FindReplaceDialogRequestEntity.DialogRequest.FindNext
                    }
                });
            }).AddTo(this.Disposable);

            this.FindPrevCommand.Subscribe(_ =>
            {
                this._FindReplaceDialogRequest.Raise(new Confirmation
                {
                    Content = new FindReplaceDialogRequestEntity()
                    {
                        RequestKind = FindReplaceDialogRequestEntity.DialogRequest.FindPrev
                    }
                });
            }).AddTo(this.Disposable);

            #endregion FindAndReplace

            #region ScrolledLine

            this.CenterScrolledLine = new ReactiveProperty <int?>().AddTo(this.Disposable);
            this.CenterScrolledLine.Subscribe(t =>
            {
                if (this.Model?.Content?.SelectedNode != null && this.Config.RestoreCenterScrolledLine)
                {
                    this.Model.Content.SelectedNode.LastScrolledLine = t;
                }
            }).AddTo(this.Disposable);

            this.ParentScrolledLine = new ReactiveProperty <int?>().AddTo(this.Disposable);
            this.ParentScrolledLine.Subscribe(t =>
            {
                if (this.Model?.Content?.ParentNode != null && this.Config.RestoreLeftScrolledLine)
                {
                    this.Model.Content.ParentNode.LastScrolledLine = t;
                }
            }).AddTo(this.Disposable);

            this.PrevScrolledLine = new ReactiveProperty <int?>().AddTo(this.Disposable);
            this.PrevScrolledLine.Subscribe(t =>
            {
                if (this.Model?.Content?.PrevNode != null && this.Config.RestoreTopBottomScrolledLine)
                {
                    this.Model.Content.PrevNode.LastScrolledLine = t;
                }
            }).AddTo(this.Disposable);

            this.NextScrolledLine = new ReactiveProperty <int?>().AddTo(this.Disposable);
            this.NextScrolledLine.Subscribe(t =>
            {
                if (this.Model?.Content?.NextNode != null && this.Config.RestoreTopBottomScrolledLine)
                {
                    this.Model.Content.NextNode.LastScrolledLine = t;
                }
            }).AddTo(this.Disposable);

            this.SelectedNode.Subscribe(_ =>
            {
                // { [編集パネル], [左パネル], [上パネル], [下パネル] }
                var val = new int?[4];
                if (this.Model?.Content?.SelectedNode?.LastScrolledLine.HasValue == true &&
                    this.Config.RestoreCenterScrolledLine)
                {
                    val[0] = this.Model.Content.SelectedNode.LastScrolledLine.Value;
                }

                if (this.Model?.Content?.ParentNode?.LastScrolledLine.HasValue == true &&
                    this.Config.RestoreLeftScrolledLine)
                {
                    val[1] = this.Model.Content.ParentNode.LastScrolledLine.Value;
                }

                if (this.Model?.Content?.PrevNode?.LastScrolledLine.HasValue == true &&
                    this.Config.RestoreTopBottomScrolledLine)
                {
                    val[2] = this.Model.Content.PrevNode.LastScrolledLine.Value;
                }

                if (this.Model?.Content?.NextNode?.LastScrolledLine.HasValue == true &&
                    this.Config.RestoreTopBottomScrolledLine)
                {
                    val[3] = this.Model.Content.NextNode.LastScrolledLine.Value;
                }

                this.setScrollRequest.Raise(new Confirmation
                {
                    Content = val
                });
            })
            .AddTo(this.Disposable);

            #endregion ScrolledLine
        }
        public MainWindowViewModel()
        {
            // MainWindow
            Width      = window.Width.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(Disposable);
            Height     = window.Height.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(Disposable);
            Left       = window.Left.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(Disposable);
            Top        = window.Top.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(Disposable);
            IsPaneOpen = pane.IsPaneOpen.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(Disposable);
            PaneWidth  = pane.PaneWidth.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(Disposable);

            // Commands
            SearchText                         = new ReactiveProperty <string>("").AddTo(Disposable);
            ShowLogWindowCommand               = new ReactiveCommand().WithSubscribe(WindowManager.ShowLogWindow).AddTo(Disposable);
            ShowPluginWindowCommand            = new ReactiveCommand().WithSubscribe(WindowManager.ShowPluginWindow).AddTo(Disposable);
            ShowOptionWindowCommand            = new ReactiveCommand().WithSubscribe(WindowManager.ShowOptionWindow).AddTo(Disposable);
            ShowUsersSettingWindowCommand      = new ReactiveCommand().WithSubscribe(WindowManager.ShowUsersSettingWindow).AddTo(Disposable);
            ApplicationShutdownCommand         = new ReactiveCommand().WithSubscribe(WindowManager.ApplicationShutdown).AddTo(Disposable);
            EnterCommand                       = new ReactiveCommand <string>().WithSubscribe(x => mcc.AddURL(x)).AddTo(Disposable);
            ActivateCommand                    = new ReactiveCommand <ConnectionData>().WithSubscribe(x => mcc.Activate(x)).AddTo(Disposable);
            InactivateCommand                  = new ReactiveCommand <ConnectionData>().WithSubscribe(mcc.Inactivate).AddTo(Disposable);
            DeleteCommand                      = new ReactiveCommand <ConnectionData>().WithSubscribe(mcc.RemoveConnection).AddTo(Disposable);
            ToggleCommand                      = new ReactiveCommand <ConnectionData>().WithSubscribe(mcc.ToggleConnection).AddTo(Disposable);
            ColumnHeaderUserClickCommand       = new ReactiveCommand <RoutedEventArgs>().WithSubscribe(UserHeader_Click).AddTo(Disposable);
            ColumnHeaderConnectionClickCommand = new ReactiveCommand <RoutedEventArgs>().WithSubscribe(ConnectionHeader_Click).AddTo(Disposable);
            CellItemUserClickCommand           = new ReactiveCommand <RoutedEventArgs>().WithSubscribe(x => WindowManager.ShowUserDataWindow((x.Source as PackIconMaterial).DataContext as CommentDataEx)).AddTo(Disposable);
            ShowUserSettingCommand             = new ReactiveCommand <object>().WithSubscribe(x => WindowManager.ShowUserSettingWindow(x as CommentDataEx)).AddTo(Disposable);
            ShowUserDataCommand                = new ReactiveCommand <object>().WithSubscribe(x => WindowManager.ShowUserDataWindow(x as CommentDataEx)).AddTo(Disposable);
            MenuItemOpenedCommand              = new ReactiveCommand <MenuItem>().WithSubscribe(MenuItemCopy_Opened).AddTo(Disposable);

            // フィルター
            ConnectionView            = new() { Source = ConnectionManager.Instance };
            CommentFilterView         = new() { Source = CommentManager.Instance };
            CommentFilterView.Filter += CommentFilter_Filter;

            // Theme
            theme.IsDarkMode.Subscribe(x => ThemeHelper.ThemeChange(theme.ThemeColor.Value.ToArgb(), x)).AddTo(Disposable);
            theme.ThemeColor.Subscribe(x => ThemeHelper.ThemeChange(x.ToArgb(), theme.IsDarkMode.Value)).AddTo(Disposable);

            // プラグインメニュー作成
            ParentMenuPlugins = new ReactiveCollection <MenuItem>().AddTo(Disposable);
            CreateMenuItemPlugins();

            // コメントフィルタリング
            SearchText.Subscribe(x =>
            {
                if (x is null)
                {
                    SearchText.Value = string.Empty;
                }
                CommentFilterView.View.Refresh();
            }).AddTo(Disposable);
            MessageBroker.Default.Subscribe <MessageArgs>(x => { if (x.Identifier is "Refresh.Comment.View")
                                                                 {
                                                                     CommentFilterView.View.Refresh();
                                                                 }
                                                          }).AddTo(Disposable);
        }

        private void CommentFilter_Filter(object _, FilterEventArgs e)
        {
            var item     = e.Item as CommentDataEx;
            var userData = UserDataManager.Instance.Find(item);
            var word     = SearchText.Value.ToLower();

            if (userData is not null && userData.HideUser)
            {
                e.Accepted = false;
            }
Ejemplo n.º 33
0
        public ItemCountAndPricePopup()
        {
            var currency = States.Instance.GoldBalanceState.Gold.Currency;

            Price = new ReactiveProperty <FungibleAssetValue>(new FungibleAssetValue(currency, 10, 0));
        }
Ejemplo n.º 34
0
 public GameStateManager()
 {
     CurrentState = new ReactiveProperty <GameStateType>();
 }
Ejemplo n.º 35
0
 public void Start(BaseState <T> initialState)
 {
     CurrentState = new ReactiveProperty <BaseState <T> >(initialState);
     CurrentState.Value.Enter(this);
 }
Ejemplo n.º 36
0
        public OperationItemViewModel(ReactiveProperty <ObservablePhotonPeer> peer, ReactiveProperty <string> log, OperationInfo info)
        {
            Info           = info;
            ParameterItems = info.FlatternedParameters
                             .Select(x =>
            {
                var piv = new ParameterItemViewModel
                {
                    Name                   = x.Name,
                    TypeName               = x.TypeName,
                    Comment                = x.Comment,
                    IsNeedTemplate         = x.IsNeedTemplate,
                    InsertButtonVisibility = x.IsNeedTemplate ? Visibility.Visible : Visibility.Hidden,
                    Template               = (x.IsNeedTemplate) ? x.Template : null
                };
                if (x.DefaultValue != null)
                {
                    piv.ParameterValue.Value = x.DefaultValue.ToString();
                }
                return(piv);
            })
                             .ToArray();

            CopyCommand = new ReactiveCommand(Observable.Return(ParameterItems.Any()));
            CopyCommand.Subscribe(_ =>
            {
                var data = new ClipboardData
                {
                    HubName       = Info.Hub.HubName,
                    OperationName = Info.OperationName,
                    Data          = ParameterItems.Select(x => x.ParameterValue.Value).ToArray()
                };
                var value = JsonConvert.SerializeObject(data);

                Clipboard.SetText(value, TextDataFormat.UnicodeText);
            });

            if (!ParameterItems.Any())
            {
                PasteCommand = new ReactiveCommand(Observable.Return(false));
            }
            else
            {
                PasteCommand = ClipboardMonitor.CurrentClipboard
                               .Select(text =>
                {
                    try
                    {
                        if (text.Contains(nameof(ClipboardData.HubName)) && text.Contains(nameof(ClipboardData.OperationName)))
                        {
                            var cd = JsonConvert.DeserializeObject <ClipboardData>(text);
                            if (cd.HubName == Info.Hub.HubName && cd.OperationName == Info.OperationName)
                            {
                                return(true);
                            }
                        }

                        return(false);
                    }
                    catch
                    {
                        return(false);
                    }
                })
                               .ToReactiveCommand(initialValue: false);
                PasteCommand.Subscribe(_ =>
                {
                    try
                    {
                        if (Clipboard.ContainsText(TextDataFormat.UnicodeText))
                        {
                            var text = Clipboard.GetText();

                            var cd = JsonConvert.DeserializeObject <ClipboardData>(text);

                            var index = 0;
                            foreach (var item in cd.Data)
                            {
                                ParameterItems[index].ParameterValue.Value = item;
                                index++;
                            }
                        }
                    }
                    catch { }
                });
            }

            SendCommand = new ReactiveCommand();
            SendCommand.Subscribe(async _ =>
            {
                try
                {
                    byte opCode   = Info.OperationId;
                    var parameter = new System.Collections.Generic.Dictionary <byte, object>();
                    parameter.Add(ReservedParameterNo.RequestHubId, Info.Hub.HubId);

                    // grouping
                    var grouping = ParameterItems.GroupBy(x =>
                    {
                        var split = x.Name.Split('.');
                        return(split[0]);
                    });

                    var index = 0;
                    foreach (var item in grouping)
                    {
                        if (item.Count() == 1)
                        {
                            var p = item.First();
                            parameter.Add((byte)index, JsonPhotonSerializer.Serialize(p.TypeName, p.ParameterValue.Value));
                        }
                        else
                        {
                            // Object
                            var p = BuildJson(item);
                            parameter.Add((byte)index, Encoding.UTF8.GetBytes(p)); // send byte[]
                        }
                        index++;
                    }

                    var response = await peer.Value.OpCustomAsync(opCode, parameter, true);
                    var result   = response[ReservedParameterNo.ResponseId];

                    var deserialized = JsonPhotonSerializer.Deserialize(result);
                    log.Value       += "+ " + Info.Hub.HubName + "/" + Info.OperationName + ":" + deserialized + "\r\n";
                }
                catch (Exception ex)
                {
                    log.Value += "Send Error:" + ex.ToString() + "\r\n";
                }
            });
        }
Ejemplo n.º 37
0
 private void PrimaryInitialize()
 {
     isRewarded = new ReactiveProperty <bool>();
     onVideoCompletedSubject = new Subject <Unit>();
 }
        public SearchSettingsFlyoutViewModel()
        {
            Model = new SearchSettingsFlyoutModel();

            Tokens     = Model.ToReactivePropertyAsSynchronized(x => x.Tokens);
            IconSource = new ReactiveProperty <string>("http://localhost/");

            StatusSearchWords = new ReactiveProperty <string>();
            UserSearchWords   = new ReactiveProperty <string>();

            PivotSelectedIndex = new ReactiveProperty <int>(0);
            PivotSelectedIndex.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x =>
            {
                if (x == 2)
                {
                    await Model.UpdateSavedSearches();
                    await Model.UpdateTrends();
                }
            });

            SavedSearchesScreenName = Model.ObserveProperty(x => x.SavedSearchesScreenName).ToReactiveProperty();
            TrendPlace = Model.ObserveProperty(x => x.TrendsPlace).ToReactiveProperty();

            AdvancedSearchOpen           = new ReactiveProperty <bool>();
            AdvancedSearchContentOpen    = new ReactiveProperty <bool>();
            AdvancedSearchEngagementOpen = new ReactiveProperty <bool>();

            AdvancedSearchContentRetweetsOption    = new ReactiveProperty <int>(0);
            AdvancedSearchContentShowingOption     = new ReactiveProperty <int>(0);
            AdvancedSearchContentWrittenInOption   = new ReactiveProperty <int>(0);
            AdvancedSearchEngagementFavoritesCount = new ReactiveProperty <int>(0);
            AdvancedSearchEngagementRetweetsCount  = new ReactiveProperty <int>(0);

            UpdatingStatusSearch = Model.ObserveProperty(x => x.UpdatingStatusSearch).ToReactiveProperty();
            UpdatingUserSearch   = Model.ObserveProperty(x => x.UpdatingUserSearch).ToReactiveProperty();

            StatusSuggestion = new ReactiveCollection <string>();
            UserSuggestion   = new ReactiveCollection <string>();

            ClearCommand = new ReactiveCommand();
            ClearCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(x =>
            {
                if (AdvancedSearchOpen.Value)
                {
                    AdvancedSearchContentOpen.Value    = false;
                    AdvancedSearchEngagementOpen.Value = false;
                    AdvancedSearchOpen.Value           = false;
                }

                StatusSearchWords.Value = "";
                UserSearchWords.Value   = "";

                PivotSelectedIndex.Value = 0;
                Model.Statuses.Clear();
                Model.Users.Clear();
            });

            UpdateStatusSearchCommand = new ReactiveCommand();
            UpdateStatusSearchCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x =>
            {
                var e = x as AutoSuggestBoxQuerySubmittedEventArgs;
                if (!string.IsNullOrWhiteSpace(e?.QueryText))
                {
                    StatusSearchWords.Value = e.QueryText;
                }

                if (string.IsNullOrWhiteSpace(StatusSearchWords.Value))
                {
                    Model.Statuses.Clear();
                    Model.StatusSearchWords = "";
                    return;
                }

                var searchWords = StatusSearchWords.Value;

                switch (AdvancedSearchContentShowingOption.Value)
                {
                case 1:
                    searchWords += " filter:images";
                    break;

                case 2:
                    searchWords += " filter:videos";
                    break;

                case 3:
                    searchWords += " filter:vine";
                    break;

                case 4:
                    searchWords += " filter:media";
                    break;

                case 5:
                    searchWords += " filter:links";
                    break;
                }

                switch (AdvancedSearchContentWrittenInOption.Value)
                {
                case 1:
                    searchWords += " lang:en";
                    break;

                case 2:
                    searchWords += " lang:ja";
                    break;
                }

                switch (AdvancedSearchContentRetweetsOption.Value)
                {
                case 1:
                    searchWords += " exclude:retweets";
                    break;
                }

                if (AdvancedSearchEngagementRetweetsCount.Value != 0)
                {
                    searchWords += " min_retweets:" + AdvancedSearchEngagementRetweetsCount.Value.ToString();
                }

                if (AdvancedSearchEngagementFavoritesCount.Value != 0)
                {
                    searchWords += " min_faves:" + AdvancedSearchEngagementFavoritesCount.Value.ToString();
                }

                if (Model.StatusSearchWords == searchWords)
                {
                    await Model.UpdateStatuses(clear: false);
                }
                else
                {
                    Model.StatusSearchWords = searchWords;
                    await Model.UpdateStatuses();
                }
            });

            UpdateUserSearchCommand = new ReactiveCommand();
            UpdateUserSearchCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x =>
            {
                var e = x as AutoSuggestBoxQuerySubmittedEventArgs;
                if (!string.IsNullOrWhiteSpace(e?.QueryText))
                {
                    UserSearchWords.Value = e.QueryText;
                }

                if (string.IsNullOrWhiteSpace(UserSearchWords.Value))
                {
                    Model.Users.Clear();
                    Model.UserSearchWords = "";
                    return;
                }

                Model.UserSearchWords = UserSearchWords.Value;

                await Model.UpdateUsers();
            });

            TextChangedStatusSearchCommand = new ReactiveCommand();
            TextChangedStatusSearchCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(y =>
            {
                var e = y as AutoSuggestBoxTextChangedEventArgs;
                if (e == null || string.IsNullOrWhiteSpace(StatusSearchWords.Value))
                {
                    StatusSuggestion.ClearOnScheduler();
                    return;
                }

                IEnumerable <string> suggestHashtags;
                lock (Connecter.Instance.TweetCollecter[Tokens.Value.UserId].EntitiesObjectsLock)
                {
                    suggestHashtags = Connecter.Instance.TweetCollecter[Tokens.Value.UserId]
                                      .HashTagObjects.Where(x => x.StartsWith(StatusSearchWords.Value.TrimStart('#')))
                                      .OrderBy(x => x).Select(x => "#" + x);
                }
                if (suggestHashtags.Any())
                {
                    StatusSuggestion.ClearOnScheduler();
                    StatusSuggestion.AddRangeOnScheduler(suggestHashtags);
                }
                else
                {
                    StatusSuggestion.ClearOnScheduler();
                }
            });

            TextChangedUserSearchCommand = new ReactiveCommand();
            TextChangedUserSearchCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(y =>
            {
                var e = y as AutoSuggestBoxTextChangedEventArgs;
                if (e == null || string.IsNullOrWhiteSpace(UserSearchWords.Value) &&
                    UserSearchWords.Value.Length <= 1)
                {
                    UserSuggestion.ClearOnScheduler();
                    return;
                }

                IEnumerable <string> suggestUsers;
                lock (Connecter.Instance.TweetCollecter[Tokens.Value.UserId].EntitiesObjectsLock)
                {
                    suggestUsers = Connecter.Instance.TweetCollecter[Tokens.Value.UserId]
                                   .ScreenNameObjects.Where(x => x.StartsWith(UserSearchWords.Value.TrimStart('@')))
                                   .OrderBy(x => x);
                }
                if (suggestUsers.Any())
                {
                    UserSuggestion.ClearOnScheduler();
                    UserSuggestion.AddRangeOnScheduler(suggestUsers);
                }
                else
                {
                    UserSuggestion.ClearOnScheduler();
                }
            });

            SaveSearchCommand = new ReactiveCommand();
            SaveSearchCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x =>
            {
                if (string.IsNullOrWhiteSpace(Model.StatusSearchWords))
                {
                    return;
                }

                await Model.CreateSavedSearches(Model.StatusSearchWords);
            });

            DeleteHistoryCommand = new ReactiveCommand();
            DeleteHistoryCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(x =>
            {
                var manager = new SearchSuggestionManager();
                manager.ClearHistory();
            });

            StatusesIncrementalLoadCommand = new ReactiveCommand();
            StatusesIncrementalLoadCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x =>
            {
                if (Model.Statuses.Count <= 0)
                {
                    return;
                }

                var id     = Model.Statuses.Last().Id;
                var status = Model.Statuses.Last();
                if (status.HasRetweetInformation)
                {
                    id = status.RetweetInformation.Id;
                }

                await Model.UpdateStatuses(id);
            });

            UsersIncrementalLoadCommand = new ReactiveCommand();
            UsersIncrementalLoadCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x => { await Model.UpdateUsers(true); });

            SavedSearchesSelectCommand = new ReactiveCommand();
            SavedSearchesSelectCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(x =>
            {
                var e = x as ItemClickEventArgs;
                if (e == null)
                {
                    return;
                }

                var searchQuery         = e.ClickedItem as SearchQueryViewModel;
                StatusSearchWords.Value = searchQuery.Model.Name;

                UpdateStatusSearchCommand.Execute();

                PivotSelectedIndex.Value = 0;
            });

            TrendsSelectCommand = new ReactiveCommand();
            TrendsSelectCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(x =>
            {
                var e = x as ItemClickEventArgs;
                if (e == null)
                {
                    return;
                }

                var trend = e.ClickedItem as TrendViewModel;
                StatusSearchWords.Value = trend.Model.Name;

                UpdateStatusSearchCommand.Execute();

                PivotSelectedIndex.Value = 0;
            });

            Notice.Instance.SearchSettingsFlyoutDeleteSearchQueryCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(async x =>
            {
                var searchQuery = x as SearchQueryViewModel;
                if (searchQuery == null || searchQuery.Model.Id == 0)
                {
                    return;
                }

                await Model.DestroySavedSearches(searchQuery.Model.Id);
            });

            AdvancedSearchCommand = new ReactiveCommand();
            AdvancedSearchCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(_ =>
            {
                if (AdvancedSearchOpen.Value)
                {
                    AdvancedSearchContentOpen.Value    = false;
                    AdvancedSearchEngagementOpen.Value = false;
                }
                AdvancedSearchOpen.Value = !AdvancedSearchOpen.Value;
            });
            AdvancedSearchContentCommand = new ReactiveCommand();
            AdvancedSearchContentCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(_ => AdvancedSearchContentOpen.Value = !AdvancedSearchContentOpen.Value);
            AdvancedSearchEngagementCommand = new ReactiveCommand();
            AdvancedSearchEngagementCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(_ => AdvancedSearchEngagementOpen.Value = !AdvancedSearchEngagementOpen.Value);

            AddColumnCommand = new ReactiveCommand();
            AddColumnCommand.SubscribeOn(ThreadPoolScheduler.Default)
            .Subscribe(x =>
            {
                if (string.IsNullOrWhiteSpace(Model.StatusSearchWords))
                {
                    return;
                }

                var columnSetting = new ColumnSetting
                {
                    Action      = SettingSupport.ColumnTypeEnum.Search,
                    AutoRefresh = false,
                    AutoRefreshTimerInterval = 180.0,
                    Filter                = "()",
                    Name                  = "Search : " + Model.StatusSearchWords,
                    Parameter             = Model.StatusSearchWords,
                    Streaming             = false,
                    Index                 = -1,
                    DisableStartupRefresh = false,
                    FetchingNumberOfTweet = 40
                };
                Notice.Instance.AddColumnCommand.Execute(columnSetting);
            });

            Statuses      = Model.Statuses.ToReadOnlyReactiveCollection(x => new StatusViewModel(x, Tokens.Value.UserId));
            Users         = Model.Users.ToReadOnlyReactiveCollection(x => new UserViewModel(x));
            Trends        = Model.Trends.ToReadOnlyReactiveCollection(x => new TrendViewModel(x));
            SavedSearches = Model.SavedSearches.ToReadOnlyReactiveCollection(x => new SearchQueryViewModel(x));

            Notice = Notice.Instance;
        }
Ejemplo n.º 39
0
 public HasScoreComponent()
 {
     Score = new IntReactiveProperty(0);
 }
Ejemplo n.º 40
0
 public EnemyModel(EnemyData enemyData, Vector2 initialPos)
 {
     this.position  = new ReactiveProperty <Vector2>();
     this.enemyData = new ReactiveProperty <EnemyData>(enemyData);
     position.Value = initialPos;
 }
Ejemplo n.º 41
0
        public UserMylistPageViewModel(
            Services.PageManager pageManager,
            Services.DialogService dialogService,
            NiconicoSession niconicoSession,
            UserProvider userProvider,
            LoginUserMylistProvider loginUserMylistProvider,
            OtherOwneredMylistManager otherOwneredMylistManager,
            UserMylistManager userMylistManager,
            LocalMylistManager localMylistManager,
            HohoemaPlaylist hohoemaPlaylist
            )
        {
            PageManager               = pageManager;
            DialogService             = dialogService;
            NiconicoSession           = niconicoSession;
            UserProvider              = userProvider;
            LoginUserMylistProvider   = loginUserMylistProvider;
            OtherOwneredMylistManager = otherOwneredMylistManager;
            UserMylistManager         = userMylistManager;
            LocalMylistManager        = localMylistManager;
            HohoemaPlaylist           = hohoemaPlaylist;
            IsLoginUserMylist         = new ReactiveProperty <bool>(false);

            OpenMylistCommand = new ReactiveCommand <Interfaces.IMylist>();

            OpenMylistCommand.Subscribe(listItem =>
            {
                PageManager.OpenPage(HohoemaPageType.Mylist, $"id={listItem.Id}&origin={listItem.ToMylistOrigin().ToString()}");
            });

            AddMylistGroupCommand = new DelegateCommand(async() =>
            {
                MylistGroupEditData data = new MylistGroupEditData()
                {
                    Name              = "新しいマイリスト",
                    Description       = "",
                    IsPublic          = false,
                    MylistDefaultSort = MylistDefaultSort.Latest,
                    IconType          = IconType.Default,
                };

                // 成功するかキャンセルが押されるまで繰り返す
                while (true)
                {
                    if (true == await DialogService.ShowCreateMylistGroupDialogAsync(data))
                    {
                        var result = await UserMylistManager.AddMylist(
                            data.Name,
                            data.Description,
                            data.IsPublic,
                            data.MylistDefaultSort,
                            data.IconType
                            );

                        if (result == Mntone.Nico2.ContentManageResult.Success)
                        {
                            await ResetList();
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
                                                        , () => UserMylistManager.Mylists.Count < UserMylistManager.MaxMylistGroupCountCurrentUser
                                                        );

            RemoveMylistGroupCommand = new DelegateCommand <Interfaces.IMylist>(async(item) =>
            {
                var mylistOrigin = item.ToMylistOrigin();
                if (mylistOrigin == PlaylistOrigin.Local)
                {
                    if (item.Id == HohoemaPlaylist.WatchAfterPlaylistId)
                    {
                        return;
                    }
                }
                else if (mylistOrigin == PlaylistOrigin.LoginUser)
                {
                    if (item.Id == "0")
                    {
                        return;
                    }
                }

                // 確認ダイアログ
                var originText     = mylistOrigin == PlaylistOrigin.Local ? "ローカルマイリスト" : "マイリスト";
                var contentMessage = $"{item.Label} を削除してもよろしいですか?(変更は元に戻せません)";

                var dialog = new MessageDialog(contentMessage, $"{originText}削除の確認");
                dialog.Commands.Add(new UICommand("削除", async(i) =>
                {
                    if (mylistOrigin == PlaylistOrigin.Local)
                    {
                        LocalMylistManager.RemoveCommand.Execute(item as LocalMylistGroup);
                    }
                    else if (mylistOrigin == PlaylistOrigin.LoginUser)
                    {
                        await UserMylistManager.RemoveMylist(item.Id);
                        //                        await UpdateUserMylist();
                    }
                }));

                dialog.Commands.Add(new UICommand("キャンセル"));
                dialog.CancelCommandIndex  = 1;
                dialog.DefaultCommandIndex = 1;

                await dialog.ShowAsync();
            });


            EditMylistGroupCommand = new DelegateCommand <Interfaces.IMylist>(async item =>
            {
                var mylistOrigin = item.ToMylistOrigin();
                if (mylistOrigin == PlaylistOrigin.Local)
                {
                    if (item.Id == HohoemaPlaylist.WatchAfterPlaylistId)
                    {
                        return;
                    }
                }
                else if (mylistOrigin == PlaylistOrigin.LoginUser)
                {
                    if (item.Id == "0")
                    {
                        return;
                    }
                }

                if (mylistOrigin == PlaylistOrigin.Local)
                {
                    var localMylist = item as LocalMylistGroup;
                    var resultText  = await DialogService.GetTextAsync("プレイリスト名を変更",
                                                                       localMylist.Label,
                                                                       localMylist.Label,
                                                                       (tempName) => !string.IsNullOrWhiteSpace(tempName)
                                                                       );

                    if (!string.IsNullOrWhiteSpace(resultText))
                    {
                        localMylist.Label = resultText;
                    }
                }


                if (mylistOrigin == PlaylistOrigin.LoginUser)
                {
                    var mylistGroupListItem   = item as UserOwnedMylist;
                    var selectedMylistGroupId = mylistGroupListItem.Id;

                    if (selectedMylistGroupId == null)
                    {
                        return;
                    }

                    var mylistGroup          = UserMylistManager.GetMylistGroup(selectedMylistGroupId);
                    MylistGroupEditData data = new MylistGroupEditData()
                    {
                        Name              = mylistGroup.Label,
                        Description       = mylistGroup.Description,
                        IsPublic          = mylistGroup.IsPublic,
                        MylistDefaultSort = mylistGroup.Sort,
                        IconType          = mylistGroup.IconType,
                    };

                    // 成功するかキャンセルが押されるまで繰り返す
                    while (true)
                    {
                        if (true == await DialogService.ShowCreateMylistGroupDialogAsync(data))
                        {
                            mylistGroup.Label       = data.Name;
                            mylistGroup.Description = data.Description;
                            mylistGroup.IsPublic    = data.IsPublic;
                            mylistGroup.Sort        = data.MylistDefaultSort;
                            mylistGroup.IconType    = data.IconType;
                            var result = await LoginUserMylistProvider.UpdateMylist(mylistGroup);

                            if (result == Mntone.Nico2.ContentManageResult.Success)
                            {
                                // TODO: UI上のマイリスト表示を更新する
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            });

            PlayAllCommand = new DelegateCommand <Interfaces.IMylist>((mylist) =>
            {
                if (mylist.ItemCount == 0)
                {
                    return;
                }

                HohoemaPlaylist.Play(mylist);
            });



            AddLocalMylistCommand = new DelegateCommand(async() =>
            {
                var name = await DialogService.GetTextAsync("新しいローカルマイリスト名を入力", "ローカルマイリスト名", "",
                                                            (s) =>
                {
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        return(false);
                    }

                    if (LocalMylistManager.Mylists.Any(x => x.Label == s))
                    {
                        return(false);
                    }

                    return(true);
                });

                if (name != null)
                {
                    LocalMylistManager.Mylists.Add(new LocalMylistGroup(Guid.NewGuid().ToString(), name));
                }
            });
        }
Ejemplo n.º 42
0
        public ItemFromListProviderViewModel(Dictionary <T, SelectOption>?items,
                                             IComparer <CheckableSelectOption <T> > comparer,
                                             Func <T, bool> shouldBeSelected,
                                             bool asFlags,
                                             T?current = default)
        {
            this.asFlags = asFlags;

            this.items = AutoDispose(new SourceList <CheckableSelectOption <T> >());
            ReadOnlyObservableCollection <CheckableSelectOption <T> > outFilteredList;

            currentFilter = AutoDispose(new ReactiveProperty <Func <CheckableSelectOption <T>, bool> >(_ => true,
                                                                                                       Compare.Create <Func <CheckableSelectOption <T>, bool> >((_, _) => false, _ => 0)));
            AutoDispose(this.items.Connect()
                        .Filter(currentFilter)
                        .Sort(comparer)
                        .Bind(out outFilteredList)
                        .Subscribe());
            FilteredItems = outFilteredList;

            if (items != null)
            {
                this.items.Edit(list =>
                {
                    foreach (T key in items.Keys)
                    {
                        bool isSelected = shouldBeSelected(key);
                        var item        = new CheckableSelectOption <T>(key, items[key], isSelected);
                        if (isSelected)
                        {
                            SelectedItem = item;
                        }
                        list.Add(item);
                    }
                });
            }

            Columns = new ObservableCollection <ColumnDescriptor>
            {
                new("Key", "Entry", 80),
                new("Name", "Name", 220),
                new("Description", "Description", 320)
            };

            if (asFlags)
            {
                Columns.Insert(0, new ColumnDescriptor("", "IsChecked", 35, true));
            }

            if (items == null || items.Count == 0)
            {
                SearchText = current != null?current.ToString() ?? "" : "";
            }

            ShowItemsList = items?.Count > 0;
            DesiredHeight = ShowItemsList ? 670 : 130;
            DesiredWidth  = ShowItemsList ? 800 : 400;
            Accept        = new DelegateCommand(() =>
            {
                if (SelectedItem == null && FilteredItems.Count == 1)
                {
                    SelectedItem = FilteredItems[0];
                }
                CloseOk?.Invoke();
            }, () => asFlags || SelectedItem != null || FilteredItems.Count == 1 || int.TryParse(SearchText, out _));
            Cancel = new DelegateCommand(() => CloseCancel?.Invoke());

            FilteredItems.ObserveCollectionChanges().Subscribe(_ => Accept.RaiseCanExecuteChanged());
            this.WhenPropertyChanged(t => t.SearchText).Subscribe(_ => Accept.RaiseCanExecuteChanged());
            this.WhenPropertyChanged(t => t.SelectedItem).Subscribe(_ => Accept.RaiseCanExecuteChanged());
        }
 public StateMapping(object state, ReactiveProperty <StateMapping> callbackState)
 {
     _state        = state;
     _currentState = callbackState;
 }
Ejemplo n.º 44
0
 internal static IDisposable BindToErrorProvider <T>(this ReactiveProperty <T> property, ErrorProvider errorProvider, Control control)
 {
     return(property.ObserveErrorChanged.Subscribe(x => errorProvider.SetError(control, x?.OfType <string>().FirstOrDefault(y => true))));
 }
Ejemplo n.º 45
0
	public VolumeModel() {
		m_bgm = new ReactiveProperty<float>();
		m_sfx = new ReactiveProperty<float>();

		ResetVolume();
	}
Ejemplo n.º 46
0
 public ReactiveStateHolder(FightState state)
 {
     _state          = state;
     ObservableState = new ReactiveProperty <FightState>(state);
 }
Ejemplo n.º 47
0
 private void Awake()
 {
     selected = new ReactiveProperty <AThrowable>();
 }
 public PersonViewModel(string name, int age)
 {
     Name = new ReactiveProperty <string>(name);
     Age  = new ReactiveProperty <int>(age);
 }
 public EmployeeViewModel(Employee model)
 {
     Name = ReactiveProperty.FromObject(model, x => x.Name, ignoreValidationErrorValue: true);
 }
Ejemplo n.º 50
0
 public ShopEffectGroup(ShopEffectGroupEntity entity)
 {
     Id      = entity.Id;
     Name    = new ReactiveProperty <string>(entity.Name);
     Effects = new ReactiveList <ShopEffect>(entity.ShopEffects.Select(x => new ShopEffect(this, x)));
 }
        public CacheManagementPageViewModel(
            CacheSettings cacheSettings,
            VideoCacheManager videoCacheManager,
            CacheSaveFolder cacheSaveFolder,
            NicoVideoProvider nicoVideoProvider,
            PageManager pageManager,
            DialogService dialogService,
            NotificationService notificationService,
            HohoemaPlaylist hohoemaPlaylist
            )
        {
            CacheSettings                  = cacheSettings;
            VideoCacheManager              = videoCacheManager;
            CacheSaveFolder                = cacheSaveFolder;
            NicoVideoProvider              = nicoVideoProvider;
            HohoemaDialogService           = dialogService;
            NotificationService            = notificationService;
            HohoemaPlaylist                = hohoemaPlaylist;
            IsRequireUpdateCacheSaveFolder = new ReactiveProperty <bool>(false);

            IsCacheUserAccepted = CacheSettings.ObserveProperty(x => x.IsUserAcceptedCache)
                                  .ToReadOnlyReactiveProperty();

            RequireEnablingCacheCommand = new DelegateCommand(async() =>
            {
                var result = await HohoemaDialogService.ShowAcceptCacheUsaseDialogAsync();
                if (result)
                {
                    CacheSettings.IsEnableCache               = true;
                    CacheSettings.IsUserAcceptedCache         = true;
                    (App.Current).Resources["IsCacheEnabled"] = true;

                    await RefreshCacheSaveFolderStatus();

                    NotificationService.ShowInAppNotification(
                        InAppNotificationPayload.CreateReadOnlyNotification("キャッシュの保存先フォルダを選択してください。\n保存先が選択されると利用準備が完了します。",
                                                                            showDuration: TimeSpan.FromSeconds(30)
                                                                            ));

                    if (await CacheSaveFolder.ChangeUserDataFolder())
                    {
                        await RefreshCacheSaveFolderStatus();
                        await ResetList();

                        NotificationService.ShowInAppNotification(
                            InAppNotificationPayload.CreateReadOnlyNotification("キャッシュの利用準備が出来ました")
                            );
                    }
                }
            });

            ReadCacheAcceptTextCommand = new DelegateCommand(async() =>
            {
                var result = await HohoemaDialogService.ShowAcceptCacheUsaseDialogAsync(showWithoutConfirmButton: true);
            });



            CacheFolderStateDescription = new ReactiveProperty <string>("");
            CacheSaveFolderPath         = new ReactiveProperty <string>("");

            OpenCurrentCacheFolderCommand = new DelegateCommand(async() =>
            {
                await RefreshCacheSaveFolderStatus();

                var folder = await CacheSaveFolder.GetVideoCacheFolder();
                if (folder != null)
                {
                    await Launcher.LaunchFolderAsync(folder);
                }
            });


            ChangeCacheFolderCommand = new DelegateCommand(async() =>
            {
                var prevPath = CacheSaveFolderPath.Value;

                if (await CacheSaveFolder.ChangeUserDataFolder())
                {
                    NotificationService.ShowInAppNotification(
                        InAppNotificationPayload.CreateReadOnlyNotification($"キャッシュの保存先を {CacheSaveFolderPath.Value} に変更しました")
                        );

                    await RefreshCacheSaveFolderStatus();

                    await VideoCacheManager.OnCacheFolderChanged();

                    await ResetList();
                }
            });
        }
        public NiconicoFollowToggleButtonService(
            IScheduler scheduler,
            FollowManager followManager,
            DialogService dialogService
            )
        {
            FollowManager = followManager;
            DialogService = dialogService;

            _followTarget     = new ReactiveProperty <IFollowable>(scheduler, null).AddTo(disposables);
            _nowProcessFollow = new ReactiveProperty <bool>(scheduler, false).AddTo(disposables);
            _isFollowTarget   = new ReactiveProperty <bool>(scheduler, false).AddTo(disposables);

            CanToggleFollow =
                new []
            {
                _followTarget.ToUnit(),
                    _isFollowTarget.ToUnit()
            }
            .CombineLatest()
            .Select(_ =>
            {
                var isFollow = _isFollowTarget.Value;
                if (_followTarget.Value == null)
                {
                    return(false);
                }

                return(isFollow
                    ? true
                    : FollowManager.CanMoreAddFollow(_followTarget.Value)
                       );
            })
            .ToReadOnlyReactiveProperty(eventScheduler: scheduler)
            .AddTo(disposables);

            ToggleFollowCommand =
                new[]
            {
                _nowProcessFollow.Select(x => !x),
                CanToggleFollow
            }
            .CombineLatestValuesAreAllTrue()
            .ToAsyncReactiveCommand()
            .AddTo(disposables);

            ToggleFollowCommand.Subscribe(async() =>
            {
                _nowProcessFollow.Value = true;

                try
                {
                    var followTarget = _followTarget.Value;
                    if (FollowManager.IsFollowItem(followTarget))
                    {
                        if (await ConfirmRemovingFollow())
                        {
                            var result = await FollowManager.RemoveFollow(followTarget);
                        }
                    }
                    else if (FollowManager.CanMoreAddFollow(followTarget))
                    {
                        await FollowManager.AddFollow(followTarget);
                    }

                    _isFollowTarget.Value = FollowManager.IsFollowItem(FollowTarget.Value);
                }
                finally
                {
                    _nowProcessFollow.Value = false;
                }

                // トグルボタンの押したらとりあえず切り替わる仕様に対応するためのコード
                // 現在のフォロー状態に応じたトグル状態を確実化する
                await Task.Delay(500);

                RaisePropertyChanged(nameof(IsFollowTarget));
            })
            .AddTo(disposables);
        }
Ejemplo n.º 53
0
        public KeyboardWindowViewModel(IWindowService windowService, KeyboardWindowModel model) : base(windowService, model)
        {
            this._model = model;

            #region Initialize Properties

            model.Label.CollectionChanged += (sender, args) =>
            {
                void ChangeValue(IList objectList, string value = null)
                {
                    if (objectList.Count <= 0)
                    {
                        return;
                    }

                    var newItem = objectList[0];

                    if (!(newItem is KeyValuePair <OriginalKey, string> pair))
                    {
                        return;
                    }

                    var name = pair.Key.ToString();

                    if (Label.Value.ContainsKey(name))
                    {
                        Label.Value[name] = value ?? pair.Value;
                    }
                    else
                    {
                        Label.Value.Add(name, value ?? pair.Value);
                    }
                }

                if (args.NewItems == null)
                {
                    ChangeValue(args.OldItems, "");
                    return;
                }

                ChangeValue(args.NewItems);
            };

            Label = new ReactiveProperty <ObservableDictionary <string, string> >
            {
                Value = new ObservableDictionary <string, string>(
                    model.Label.ToDictionary(key => key.Key.ToString(), pair => pair.Value))
            };
            KeyboardIsEnabled       = model.ToReactivePropertyAsSynchronized(m => m.KeyboardIsEnabled).AddTo(_compositeDisposable);
            SettingWindowVisibility = model.ToReactivePropertyAsSynchronized(m => m.SettingWindowVisibility).AddTo(_compositeDisposable);
            SourceKeyText           = model.ToReactivePropertyAsSynchronized(m => m.SourceKeyText).AddTo(_compositeDisposable);
            DestKeyText             = model.ToReactivePropertyAsSynchronized(m => m.DestKeyText).AddTo(_compositeDisposable);
            #endregion

            #region Initialize Events
            KeyboardBtClicked         = new DelegateCommand <OriginalKey?>(KeyboardBt_Clicked);
            DestroyInputButtonClicked = new DelegateCommand(DestroyInputButton_Clicked);
            OkPopupBtClicked          = new DelegateCommand(OkPopupBt_Clicked);
            ClosePopupBtClicked       = new DelegateCommand(ClosePopupBt_Clicked);
            #endregion
        }
 private void Awake()
 {
     _bodySource = GetComponent <BodySourceManager>();
     _skeleton   = new ReactiveProperty <KinectSkeletonData>();
 }
Ejemplo n.º 55
0
 public EnemyModel(long initialHP)
 {
     HP     = new ReactiveProperty <long>(initialHP);
     IsDead = HP.Select(hp => hp <= 0).ToReactiveProperty();
 }
Ejemplo n.º 56
0
        public ChoiceArtifactViewModel()
        {
            // Show/Hide Blob
            ShowHideBlobSectionCommand.Subscribe(_ =>
            {
                ShowHideBlobSectionButtonLabel.Value = ShowBlobSectionVisibility.Value == Visibility.Collapsed
                    ? ExpandButtonLabel
                    : CollapseButtonLabel;
                ShowBlobSectionVisibility.Value = ShowBlobSectionVisibility.Value == Visibility.Collapsed
                    ? Visibility.Visible
                    : Visibility.Collapsed;
            })
            .AddTo(disposable);

            // Storage Credential Input
            StorageConnectionInput = new ReactiveProperty <string>(blobConnectionUseCase.Read <string>("blob_connection_string"));
            StorageConnectionInput.Subscribe(x => blobConnectionUseCase.Save("blob_connection_string", x)).AddTo(disposable);
            StorageContainerInput = new ReactiveProperty <string>(blobConnectionUseCase.Read <string>("container"));
            StorageContainerInput.Subscribe(x => blobConnectionUseCase.Save("container", x)).AddTo(disposable);

            // Copy Button
            CopyButtonContent  = new ReactiveProperty <string>("Copy SasUrl");
            CopyButtonEnabled  = ArtifactUrl.Select(x => !string.IsNullOrWhiteSpace(x)).ToReactiveProperty();
            OnClickCopyCommand = CopyButtonEnabled.ToReactiveCommand();
            OnClickCopyCommand
            .Do(_ => blobSasUrlUseCase.CopySasUrl(ArtifactUrl.Value, StorageConnectionInput.Value, StorageContainerInput.Value, SelectedArtifact.Value.Name))
            .SelectMany(x => TemporaryDisableCopyButtonAsObservable(TimeSpan.FromMilliseconds(500), "Copy SasUrl"))
            .Subscribe()
            .AddTo(disposable);

            // Download Button
            blobArtifactUsecase.DownloadStatus.Subscribe(x => DownloadStatus.Value = x).AddTo(disposable);
            OnClickDownloadCommand = CopyButtonEnabled.ToAsyncReactiveCommand();
            OnClickDownloadCommand
            .Subscribe(async _ => await blobArtifactUsecase.DownloadHoloLensPackagesAsync(StorageConnectionInput.Value, StorageContainerInput.Value, SelectedArtifact.Value.Name, SelectedArtifact.Value.Size, SelectedArtifact.Value.FileName))
            .AddTo(disposable);

            // OpenFolder Button
            OnClickOpenDownloadFolderCommand.Subscribe(_ => blobArtifactUsecase.OpenFolderAsync()).AddTo(disposable);
            OnClickOpenDownloadBlobFolderCommand.Subscribe(_ => blobArtifactUsecase.OpenDownloadFolderAsync()).AddTo(disposable);

            // Initialize by obtain artifact informations
            blobArtifactUsecase.Artifacts
            .Where(x => x != null)
            .Do(x =>
            {
                Projects.Add(x);
                BlobResult.Value = $"Found {Projects.Count} projects.";
            })
            .Subscribe()
            .AddTo(disposable);
            blobArtifactUsecase.RequestFailedMessage
            .Do(x => BlobResult.Value = x)
            .Subscribe()
            .AddTo(disposable);

            // Blob Download
            ComboBoxEnabled         = Projects.CollectionChangedAsObservable().Any().ToReactiveProperty();
            IsEnableCheckBlobButton = StorageConnectionInput
                                      .CombineLatest(StorageContainerInput, (r, l) => !string.IsNullOrWhiteSpace(r) && !string.IsNullOrWhiteSpace(l))
                                      .ToReadOnlyReactiveProperty();
            OnClickCheckBlobCommand = IsEnableCheckBlobButton.ToAsyncReactiveCommand();
            OnClickCheckBlobCommand.Subscribe(async _ =>
            {
                var task             = blobArtifactUsecase.RequestHoloLensPackagesAsync(StorageConnectionInput.Value, StorageContainerInput.Value);
                IsBlobChecking.Value = true;
                Projects.Clear();
                Branches?.Clear();
                Artifacts?.Clear();
                BlobResult.Value = "Trying obtain project infomations.";
                await task;
                IsBlobChecking.Value = false;
            })
            .AddTo(disposable);
            OnClickCancelBlobCommand = IsBlobChecking.Select(x => x).ToReactiveCommand();
            OnClickCancelBlobCommand
            .Do(_ => Projects.Clear())
            .Subscribe(_ => blobArtifactUsecase.CancelRequest())
            .AddTo(disposable);

            // Update Collection with Clear existing collection when selected.
            Branches = SelectedProject.Where(x => x != null)
                       .Do(_ => Branches?.Clear())
                       .Do(_ => Artifacts?.Clear())
                       .SelectMany(x => blobArtifactUsecase.GetArtifactCache(x.Project))
                       .ToReactiveCollection();
            Artifacts = SelectedBranch.Where(x => x != null)
                        .Do(x => Artifacts?.Clear())
                        .SelectMany(x => blobArtifactUsecase.GetArtifactCache(SelectedProject.Value?.Project, x.Branch))
                        .ToReactiveCollection();
            SelectedArtifact
            .Where(x => x != null)
            .Do(x =>
            {
                ArtifactName.Value    = x.Name;
                ArtifactCaption.Value = $"(Size: {x.Size}, MD5: {x.MD5}, LeaseState: {x.LeaseState})";
                ArtifactUrl.Value     = x.Uri.AbsoluteUri;
            })
            .ToReactiveProperty();
        }
Ejemplo n.º 57
0
        public EnquetePageViewModel(INavigationService navigationService,
                                    IOpenWebPageService webService,
                                    IAnalyticsService analyticsService,
                                    ILocalConfigService configService,
                                    IConstUrls constUrls)
        {
            _navigationService = navigationService;
            _webService        = webService;
            _analyticsService  = analyticsService;
            _configService     = configService;

            Ages       = AGE.Keys.ToList();
            Members    = MEMBER.Keys.ToList();
            Residences = RESIDENCE.Keys.ToList();
            Wheres     = WHERE.Keys.ToList();
            Accesses   = ACCESS.Keys.ToList();

            AgeValidation       = AgeSelected.SetValidateNotifyError((val) => string.IsNullOrEmpty(val) ? "年齢が選択されていません" : null).AddTo(this.Disposable);
            MemberValidation    = MemberSelected.SetValidateNotifyError((val) => string.IsNullOrEmpty(val) ? "所属が選択されていません" : null).AddTo(this.Disposable);
            ResidenceValidation = ResidenceSelected.SetValidateNotifyError((val) => string.IsNullOrEmpty(val) ? "居住地が選択されていません" : null).AddTo(this.Disposable);
            WhereValidation     = WhereSelected.SetValidateNotifyError((val) => string.IsNullOrEmpty(val) ? "どこで知ったのかが選択されていません" : null).AddTo(this.Disposable);
            AccessValidation    = AccessSelected.SetValidateNotifyError((val) => string.IsNullOrEmpty(val) ? "どのように来たのかが選択されていません" : null).AddTo(this.Disposable);

            AgeSelected.AddTo(this.Disposable);
            MemberSelected.AddTo(this.Disposable);
            ResidenceSelected.AddTo(this.Disposable);
            WhereSelected.AddTo(this.Disposable);
            AccessSelected.AddTo(this.Disposable);

            SubmitCommand = new[]
            {
                AgeValidation.ObserveHasErrors,
                MemberValidation.ObserveHasErrors,
                ResidenceValidation.ObserveHasErrors,
                WhereValidation.ObserveHasErrors,
                AccessValidation.ObserveHasErrors,
            }
            .CombineLatestValuesAreAllFalse()
            .ToReactiveCommand()
            .AddTo(this.Disposable);

            SubmitCommand.Subscribe(async() =>
            {
                await Submit();
                await SaveUserProfile();
                await _navigationService.NavigateAsync("/AppNavigationRootPage/NavigationPage/HomePage");
            }).AddTo(this.Disposable);

            SkipCommand = new DelegateCommand(async() =>
            {
                SetValueSecret();
                await Submit();
                await SaveUserProfile();
                await _navigationService.NavigateAsync("/AppNavigationRootPage/NavigationPage/HomePage");
            });

            TermsOfUseCommand = new DelegateCommand(async() =>
            {
                await _webService.OpenUri(constUrls.TermsOfUseUrl);
            });
        }
Ejemplo n.º 58
0
    public ReactiveProperty <int> color;   // 3 黑桃; 2 红桃; 1 梅花; 0 方块

    public PokerData(int _num, int _color)
    {
        num     = new ReactiveProperty <int>(_num);
        realNum = new ReactiveProperty <int>(_num > 10 ? 0 : _num);
        color   = new ReactiveProperty <int>(_color);
    }
Ejemplo n.º 59
0
        /// <summary>
        /// コンストラクタ。
        /// </summary>
        /// <param name="canModify">
        /// 再生や音声保存に関わる設定値の変更可否状態値。
        /// </param>
        /// <param name="charaStyle">ExoCharaStyle 値。</param>
        /// <param name="uiConfig">UI設定値。</param>
        /// <param name="lastStatus">直近のアプリ状態値の設定先。</param>
        /// <param name="openFileDialogService">ファイル選択ダイアログサービス。</param>
        public ExoCharaStyleViewModel(
            IReadOnlyReactiveProperty <bool> canModify,
            IReadOnlyReactiveProperty <ExoCharaStyle> charaStyle,
            IReadOnlyReactiveProperty <UIConfig> uiConfig,
            IReactiveProperty <IAppStatus> lastStatus,
            IOpenFileDialogService openFileDialogService)
            : base(canModify, charaStyle)
        {
            ValidateArgumentNull(uiConfig, nameof(uiConfig));
            ValidateArgumentNull(lastStatus, nameof(lastStatus));
            ValidateArgumentNull(openFileDialogService, nameof(openFileDialogService));

            this.LastStatus            = lastStatus;
            this.OpenFileDialogService = openFileDialogService;

            // 各プロパティ値
            this.Render         = this.MakeConfigProperty(c => c.Render);
            this.Text           = this.MakeConfigProperty(c => c.Text);
            this.IsTextClipping = this.MakeConfigProperty(c => c.IsTextClipping);
            this.Play           = this.MakeConfigProperty(c => c.Play);

            // 内包 ViewModel のセットアップ
            this.SetupViewModels();

            // テキストスタイル雛形コレクション
            this.Templates =
                new ReactiveProperty <ReadOnlyCollection <ExoTextStyleTemplate> >(
                    new List <ExoTextStyleTemplate>().AsReadOnly())
                .AddTo(this.CompositeDisposable);

            // 選択中テキストスタイル雛形インデックス
            this.SelectedTemplateIndex =
                new ReactiveProperty <int>(-1).AddTo(this.CompositeDisposable);

            // 直近のテキストスタイル雛形ファイルパス
            this.LastTemplateFilePath =
                new ReactiveProperty <string>().AddTo(this.CompositeDisposable);

            // テキストスタイル雛形保持フラグ
            this.HasTemplate =
                this.Templates
                .Select(temps => temps.Count > 0)
                .ToReadOnlyReactiveProperty(false)
                .AddTo(this.CompositeDisposable);

            // コレクションが空でなくなったらアイテム選択
            var tempIndexNotifier =
                Observable
                .CombineLatest(
                    this.HasTemplate,
                    this.SelectedTemplateIndex,
                    (hasTemp, index) => new { hasTemp, index })
                .DistinctUntilChanged();

            Observable
            .Zip(tempIndexNotifier, tempIndexNotifier.Skip(1))
            .Where(v => !v[0].hasTemp && v[1].hasTemp && v[1].index < 0)
            .Subscribe(_ => this.SelectedTemplateIndex.Value = 0)
            .AddTo(this.CompositeDisposable);

            // UI開閉設定
            this.IsTextUIExpanded =
                this.MakeInnerPropertyOf(uiConfig, c => c.IsExoCharaTextExpanded);
            this.IsAudioUIExpanded =
                this.MakeInnerPropertyOf(uiConfig, c => c.IsExoCharaAudioExpanded);
            this.IsTextImportUIExpanded =
                this.MakeInnerPropertyOf(uiConfig, c => c.IsExoCharaTextImportExpanded);

            // テキストスタイル雛形用ファイルのロード可能状態
            var templateLoadable = new ReactiveProperty <bool>(true);

            // テキストスタイル雛形ロード中フラグ
            this.IsTemplateLoading =
                templateLoadable
                .Inverse()
                .ToReadOnlyReactiveProperty()
                .AddTo(this.CompositeDisposable);

            // テキストスタイル雛形用ファイル選択コマンド
            // 実施中はファイルロード不可にする
            this.SelectTemplateFileCommand =
                this.MakeSharedAsyncCommand(
                    templateLoadable,
                    this.ExecuteSelectTemplateFileCommand);

            // テキストスタイル雛形用ファイルドラッグオーバーコマンド
            this.DragOverTemplateFileCommand =
                this.MakeCommand <DragEventArgs>(
                    this.ExecuteDragOverTemplateFileCommand,
                    templateLoadable);

            // テキストスタイル雛形用ファイルドロップコマンド
            // 実施中はファイルロード不可にする
            this.DropTemplateFileCommand =
                this.MakeSharedAsyncCommand <DragEventArgs>(
                    templateLoadable,
                    this.ExecuteDropTemplateFileCommand);

            // テキストスタイル雛形適用コマンド
            this.ApplyTemplateCommand =
                this.MakeCommand(
                    this.ExecuteApplyTemplateCommand,
                    this.CanModify,
                    this.HasTemplate,
                    this.SelectedTemplateIndex
                    .Select(i => i >= 0 && i < this.Templates.Value.Count),
                    templateLoadable);
        }
Ejemplo n.º 60
0
 void Awake()
 {
     id = new ReactiveProperty <int>(-1);
 }