Exemplo n.º 1
0
        public static IDisposable BindTwoWayTo <TSource, TTarget>(this IReactiveProperty <TSource> This, IReactiveProperty <TTarget> target)
        {
            if (This == null || target == null)
            {
                return(Disposable.Empty);
            }

            bool isUpdating = false;

            return(new CompositeDisposable(
                       This
                       .Where(_ => !isUpdating)
                       .Subscribe(x =>
            {
                isUpdating = true;
                target.Value = (TTarget)(object)x;
                isUpdating = false;
            }),
                       target
                       .Where(_ => !isUpdating)
                       .Subscribe(x =>
            {
                isUpdating = true;
                This.Value = (TSource)(object)x;
                isUpdating = false;
            })));
        }
Exemplo n.º 2
0
        public SelectRectangleViewModel()
        {
            MouseLeftDownPoint       = new ReactivePropertySlim <RoixBorderPoint>(mode: ReactivePropertyMode.None);
            MouseLeftUpPoint         = new ReactivePropertySlim <RoixBorderPoint>(mode: ReactivePropertyMode.None);
            MouseMovePoint           = new ReactivePropertySlim <RoixBorderPoint>();
            ViewBorderSize           = new ReactivePropertySlim <RoixSize>(mode: ReactivePropertyMode.DistinctUntilChanged);
            SelectedRectangleToModel = new ReactivePropertySlim <RoixIntRect>();

            var imageSourceSize = MyImage.ToRoixIntSize();

            // 画像座標系の選択枠(これを基準に管理する) マウス操作中に枠を更新 + 操作完了時に枠位置を通知する
            var selectedRectangleOnImage = MouseMovePoint
                                           .Select(latestPoint => (startPoint: MouseLeftDownPoint.Value, latestPoint))
                                           .Where(x => x.startPoint != x.latestPoint)
                                           .SkipUntil(MouseLeftDownPoint.ToUnit())
                                           .TakeUntil(MouseLeftUpPoint.ToUnit())
                                           .Finally(() =>
            {
                var(startPoint, latestPoint) = (MouseLeftDownPoint.Value, MouseLeftUpPoint.Value);
                if (startPoint == default || latestPoint == default || startPoint == latestPoint)
                {
                    return;
                }

                SelectedRectangleToModel.Value = RoixBorderIntRect.Create(startPoint, latestPoint, imageSourceSize).Roi;
            })
                                           .Repeat()
                                           .Select(x => RoixBorderIntRect.Create(x.startPoint, x.latestPoint, imageSourceSize))
                                           .ToReadOnlyReactivePropertySlim();

            // View座標系の選択枠
            SelectedRectangle = selectedRectangleOnImage
                                .CombineLatest(ViewBorderSize, (rect, border) => rect.ConvertToNewBorder(border).Roi)
                                .ToReadOnlyReactivePropertySlim();
        }
 public GameRoundStatisticsModel()
 {
     _friends     = new ReactiveProperty <int>().AddTo(Disposer);
     _enemies     = new ReactiveProperty <int>().AddTo(Disposer);
     _neutral     = new ReactiveProperty <int>().AddTo(Disposer);
     _friendsLost = new ReactiveProperty <int>().AddTo(Disposer);
 }
Exemplo n.º 4
0
        public void Serialize(ref MessagePackWriter writer, IReactiveProperty <T> value, MessagePackSerializerOptions options)
        {
            var rxProp = value as ReactiveProperty <T>;

            if (rxProp != null)
            {
                ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactiveProperty <T> >().Serialize(ref writer, rxProp, options);
                return;
            }

            var slimProp = value as ReactivePropertySlim <T>;

            if (slimProp != null)
            {
                ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactivePropertySlim <T> >().Serialize(ref writer, slimProp, options);
                return;
            }

            if (value == null)
            {
                writer.WriteNil();
            }
            else
            {
                throw new InvalidOperationException("Serializer only supports ReactiveProperty<T> or ReactivePropertySlim<T>. If serialize is ReadOnlyReactiveProperty, should mark [Ignore] and restore on IMessagePackSerializationCallbackReceiver.OnAfterDeserialize. Type:" + value.GetType().Name);
            }
        }
Exemplo n.º 5
0
        public CollectiblesViewModel(CollectiblesList list, TagsList tags)
        {
            SearchText = new ReactiveProperty <string>("");

            AllItems = list.Collectibles.Select(item => new CollectibleViewModel(item, SearchText, tags.Tags)).ToReactiveCollection();

            Func <CollectibleViewModel, CollectibleViewModel, int> sortByTitle = (a, b) => String.Compare(a.OriginalTitle, b.OriginalTitle);

            Func <CollectibleViewModel, bool> filter = vm =>
            {
                if (string.IsNullOrEmpty(SearchText.Value))
                {
                    return(true);
                }

                if (SearchText.Value.StartsWith("t:"))
                {
                    var tag = SearchText.Value.Substring(2).ToLower();

                    return(vm.Tags.Any(t => t.Name.ToLower().Contains(tag)));
                }

                if (vm.OriginalTitle.ToLower().Contains(SearchText.Value.ToLower()))
                {
                    return(true);
                }

                return(false);
            };

            Items = AllItems.WhereMany(filter, t => t.Tags.ObserveCountChanged().AsUnitObservable(), SearchText.AsUnitObservable()).Sort(sortByTitle, null);

            SelectedItems = Items.WhereMany(vm => vm.IsSelected.Value, vm => vm.IsSelected.AsUnitObservable()).Sort(sortByTitle, null);
        }
Exemplo n.º 6
0
        public int Serialize(ref byte[] bytes, int offset, IReactiveProperty <T> value, IFormatterResolver formatterResolver)
        {
            var rxProp = value as ReactiveProperty <T>;

            if (rxProp != null)
            {
                return(ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactiveProperty <T> >().Serialize(ref bytes, offset, rxProp, formatterResolver));
            }

            var slimProp = value as ReactivePropertySlim <T>;

            if (slimProp != null)
            {
                return(ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactivePropertySlim <T> >().Serialize(ref bytes, offset, slimProp, formatterResolver));
            }

            if (value == null)
            {
                return(MessagePackBinary.WriteNil(ref bytes, offset));
            }
            else
            {
                throw new InvalidOperationException("Serializer only supports ReactiveProperty<T> or ReactivePropertySlim<T>. If serialize is ReadOnlyReactiveProperty, should mark [Ignore] and restore on IMessagePackSerializationCallbackReceiver.OnAfterDeserialize. Type:" + value.GetType().Name);
            }
        }
Exemplo n.º 7
0
 public static IDisposable Bind <T>(IReactiveProperty <T> propertyA, IReadOnlyReactiveProperty <T> propertyB, params IFilter <T>[] filters)
 {
     return(propertyB
            .ApplyInputFilters(filters)
            .DistinctUntilChanged()
            .Subscribe(x => propertyA.Value = x));
 }
    /// <summary>
    /// Data binding method.
    /// </summary>
    /// <typeparam name="TView">View type</typeparam>
    /// <typeparam name="TProperty">Property type</typeparam>
    /// <param name="self">View</param>
    /// <param name="propertySelector">Target property selector</param>
    /// <param name="source">Source property</param>
    /// <param name="updateSourceTrigger">Update source trigger</param>
    /// <returns>Data binding token</returns>
    public static IDisposable SetBinding <TView, TProperty>(
        this TView self,
        Expression <Func <TView, TProperty> > propertySelector,
        IReactiveProperty <TProperty> source, Func <TView, IObservable <Unit> > updateSourceTrigger = null)
        where TView : View
    {
        var d = new CompositeDisposable();

        var isUpdating = false;
        var setter     = AccessorCache <TView> .LookupSet(propertySelector, out var propertyName);

        source
        .Where(_ => !isUpdating)
        .Subscribe(x => setter(self, x))
        .AddTo(d);
        if (updateSourceTrigger != null)
        {
            var getter = AccessorCache <TView> .LookupGet(propertySelector, out propertyName);

            updateSourceTrigger(self).Subscribe(_ =>
            {
                isUpdating = true;
                try
                {
                    source.Value = getter(self);
                }
                finally
                {
                    isUpdating = false;
                }
            }).AddTo(d);
        }

        return(d);
    }
Exemplo n.º 9
0
        protected ManagedObject()
        {
            _initialized = new ReactiveProperty <bool>();
            _disposed    = new ReactiveProperty <bool>();

            Disposables = new CompositeDisposable();
        }
        public ClosableViewMediator(ILogger logger)
        {
            _logger          = logger;
            _registeredViews = new Dictionary <Type, IClosableViewController>();

            _isAnyPanelOpen = new ReactiveProperty <bool>().AddTo(Disposer);
        }
Exemplo n.º 11
0
        public NewTootBoxViewModel(IReactiveProperty <Status> inReplyTo, IMastodonClient client)
        {
            this.inReplyTo = inReplyTo;
            this.client    = client;
            InReplyTo      = inReplyTo.ToReadOnlyReactiveProperty();

            TootCommand = Text.Select(t => t.Length > 0)
                          .ToAsyncReactiveCommand()
                          .WithSubscribe(executeTootCommand);
            CancelReplyCommand = this.inReplyTo
                                 .Select(svm => svm != null)
                                 .ToReactiveCommand()
                                 .WithSubscribe(() => this.inReplyTo.Value = null);

            this.inReplyTo.Subscribe(status =>
            {
                if (status == null)
                {
                    InReplyToText.Value = null;
                }
                else
                {
                    Status OriginalStatus = status.Reblog ?? status;
                    InReplyToText.Value   = $"To: {OriginalStatus.Account.UserName}: {OriginalStatus.Content}";
                    Text.Value            = $"@{OriginalStatus.Account.AccountName} {Text.Value}";
                }
            });
        }
        /// <summary>
        /// Find the "Label" attribute value in a property's attribute metadata.
        /// </summary>
        /// <param name="prop">Property.</param>
        /// <param name="vm">View model of the property.</param>
        /// <returns>Label attribute value or empty string if not found.</returns>
        private static string GetLabelAttribute(this IReactiveProperty prop, IReactiveProperties vm)
        {
            var labelKey = nameof(TextFieldAttribute.Label);
            var attrs    = prop.GetAttributes(vm);

            return(attrs?.ContainsKey(labelKey) == true ? attrs[labelKey]?.ToString().TrimEnd(':') : string.Empty);
        }
Exemplo n.º 13
0
        // one shot

        /// <summary>
        /// Waits the until value changed asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public static async Task <T> WaitUntilValueChangedAsync <T>(this IReactiveProperty <T> source, CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var handler = GetAsyncHandler <T>(source, cancellationToken))
            {
                return(await handler);
            }
        }
        public BoardPreparationUnitPool(int maxUnits)
        {
            _maxUnits = maxUnits;

            Units        = new List <IPreparationUnitModel>();
            _isBoardFull = new ReactiveProperty <bool>();
        }
Exemplo n.º 15
0
 public ViewModel(ReactiveProperty <int> x, IReactiveProperty <int> y, IReadOnlyReactiveProperty <int> z)
 {
     Prop1 = x;
     Prop2 = y;
     Prop3 = z;
     OnAfterDeserialize();
 }
Exemplo n.º 16
0
        public void Ctor(IReactiveProperty <EnumCharacterWindow> charWindow, ListOfCharactersController listCharactersManager)
        {
            base.Ctor();
            _listCharactersManager = listCharactersManager;
            _charWindow            = charWindow;

            _listClasses = new GameObjectLinkedList <CharacterClass>(new[]
            {
                new LinkedListItem <CharacterClass>(CharacterClass.Warrior, _warriorIcon),
                new LinkedListItem <CharacterClass>(CharacterClass.Rogue, _rogueIcon),
                new LinkedListItem <CharacterClass>(CharacterClass.Hunter, _hunterIcon),
                new LinkedListItem <CharacterClass>(CharacterClass.Mage, _mageIcon)
            });

            // //prev class
            // _prevClassButton.OnPointerClickAsObservable().Subscribe(_ =>
            // {
            //     if (_listClasses.MovePrev())
            //         _listCharactersManager.PrototypePlayer.CharacterClass.Value = _listClasses.Current.Key;
            // }).AddTo(_subscriptions);
            // //next class
            // _nextClassButton.OnPointerClickAsObservable().Subscribe(_ =>
            // {
            //     if (_listClasses.MoveNext())
            //         _listCharactersManager.PrototypePlayer.CharacterClass.Value = _listClasses.Current.Key;
            // }).AddTo(_subscriptions);

            //goto settings
            _gotoSettingChar.OnPointerClickAsObservable().Subscribe(_ =>
            {
                _charWindow.Value = EnumCharacterWindow.NewSettingsCharacter;
            }).AddTo(_subscriptions);
        }
Exemplo n.º 17
0
        public void Ctor(IReactiveProperty <EnumMainWindow> activeWindow,
                         IReactiveProperty <EnumCharacterWindow> activeCharWindow, ListOfCharactersController listCharactersManager)
        {
            base.Ctor();
            _activeWindow          = activeWindow;
            _listCharactersManager = listCharactersManager;
            _activeCharWindow      = activeCharWindow;

            //создать нового персонажа
            _createCharacterButton.OnPointerClickAsObservable().Subscribe(_ =>
            {
                _activeCharWindow.Value = EnumCharacterWindow.NewSelectClass;
            }).AddTo(_subscriptions);

            //выбор персонажа и переход
            _selectingCharacterButton.OnPointerClickAsObservable().Subscribe(_ =>
            {
                _activeWindow.Value = EnumMainWindow.Battle;
            }).AddTo(_subscriptions);

            //листаем список персонажей
            _prevCharButton.OnPointerClickAsObservable().Subscribe(_ => { _listCharactersManager.MovePrev(); })
            .AddTo(_subscriptions);
            _nextCharButton.OnPointerClickAsObservable().Subscribe(_ => { _listCharactersManager.MoveNext(); })
            .AddTo(_subscriptions);

            //подписываемся на изменение персонажа
            _listCharactersManager.CurrentCharacter.Subscribe(view => { _info.text = view.Description.Value; });
        }
Exemplo n.º 18
0
 public GameSettingsViewModelStub()
 {
     soundEnabled = new ReactiveProperty <bool>(true);
     musicEnabled = new ReactiveProperty <bool>(true);
     musicLevel   = new ReactiveProperty <float>(0.5f);
     soundLevel   = new ReactiveProperty <float>(0.5f);
 }
Exemplo n.º 19
0
 protected TweenToShiftingTargetCompletableBase(IReactiveProperty <T> property, IObservable <T> target, float duration, IEaser easer = null)
 {
     _property = property;
     _target   = target;
     _duration = duration;
     _easer    = easer;
 }
Exemplo n.º 20
0
 public void RegistTurnReactiveProperty(IReactiveProperty <bool> _isMyTurn)
 {
     _isMyTurn.Subscribe(isMyTurn =>
     {
         returnLocalInput = isMyTurn;
     });
 }
Exemplo n.º 21
0
        public void Ctor(IReactiveProperty <EnumBattleWindow> battleState)
        {
            base.Ctor();
            LevelGeneratorPanel.Ctor();
            FightPanel.Ctor();
            VictoryPanel.Ctor();
            PausePanel.Ctor();
            FailPanel.Ctor();

            _battleState = battleState;

            _battleState.Subscribe(_ =>
            {
                if (!enabled)
                {
                    return;
                }
                if (_battleState.Value == EnumBattleWindow.DungeonGenerator)
                {
                    LevelGeneratorPanel.Show();
                }
                else
                {
                    LevelGeneratorPanel.Hide();
                }
                if (_battleState.Value == EnumBattleWindow.Fight)
                {
                    FightPanel.Show();
                }
                else
                {
                    FightPanel.Hide();
                }
                if (_battleState.Value == EnumBattleWindow.Victory)
                {
                    VictoryPanel.Show();
                }
                else
                {
                    VictoryPanel.Hide();
                }
                if (_battleState.Value == EnumBattleWindow.Fail)
                {
                    FailPanel.Show();
                }
                else
                {
                    FailPanel.Hide();
                }
                if (_battleState.Value == EnumBattleWindow.Pause)
                {
                    PausePanel.Show();
                }
                else
                {
                    PausePanel.Hide();
                }
            }).AddTo(_subscriptions);
        }
Exemplo n.º 22
0
 public static void Subscribe <T>(this IReactiveProperty <T> target, Action <T> onValueChanged, bool setInstant = false)
 {
     target.OnValueChanged += onValueChanged;
     if (setInstant)
     {
         onValueChanged(target.Value);
     }
 }
Exemplo n.º 23
0
        public MoveRectangleModel()
        {
            var imageSourceSize = MyImage.ToRoixIntSize();
            var initialRect     = new RoixIntRect(1, 2, 2, 2).ToRoixBorder(imageSourceSize);

            Rect = new ReactivePropertySlim <RoixBorderIntRect>(initialValue: initialRect);
            //Rect.Subscribe(x => Debug.WriteLine($"Model Rect: {x}"));
        }
Exemplo n.º 24
0
 public ReactivePropertyObserverBridgeStringReplace(IReactiveProperty <string> reactiveProperty)
     : base(
         reactiveProperty,
         new OnNextStrategyReplace <string>(),
         new OnErrorStrategyIgnore <string>(),
         new OnCompleteStrategyIgnore <string>())
 {
 }
Exemplo n.º 25
0
        protected EventTracker(T component)
        {
            Assert.IsNotNull(component, "component != null");

            _state = new ReactiveProperty <bool>();

            Component = component;
        }
Exemplo n.º 26
0
 /// <summary>
 /// コンストラクタ。
 /// </summary>
 /// <param name="sharedCanExecute">
 /// コマンド実施可否状態を共有する ReactiveProperty 。
 /// </param>
 /// <param name="executer">コマンド処理デリゲート。</param>
 /// <param name="parameterConverter">
 /// コマンドパラメータ変換デリゲート。 null ならば変換しない。
 /// </param>
 public AsyncCommandHolder(
     IReactiveProperty <bool> sharedCanExecute,
     Func <TParameter, Task <TResult> > executer,
     Func <TParameter, TParameter> parameterConverter = null)
     : base(sharedCanExecute)
 {
     this.Construct(executer, parameterConverter);
 }
Exemplo n.º 27
0
        public UIContext()
        {
            _style           = new UIStyleReactiveProperty();
            _activeComponent = new ReactiveProperty <IInteractableComponent>();

            _defaultCursor = CursorNames.Default;
            _cursorState   = CursorState.Vislbe;
        }
 public ReactivePropertyObserverBridgeStringAdd(IReactiveProperty <string> reactiveProperty)
     : base(
         reactiveProperty,
         new OnNextStrategyConcatenateStrigns(string.Empty, Environment.NewLine),
         new OnErrorStrategyIgnore <string>(),
         new OnCompleteStrategyIgnore <string>())
 {
 }
        public TutorialSavegame(TutorialSavegameData savegameData)
        {
            _savegameData = savegameData;

            State = CreateBoundProperty(
                savegameData.State,
                value => savegameData.State = value);
        }
Exemplo n.º 30
0
    public CharacterStatus( StatExpressionsInfo expressionsInfo )
    {
        strength = new IntReactiveProperty( 0 );
        agility = new IntReactiveProperty( 0 );

        maxHealth = CreateCalculator( expressionsInfo.healthExpression ).Select( _ => (int)_ ).ToReactiveProperty();
        moveSpeed = CreateCalculator( expressionsInfo.moveSpeedExpression ).Select( _ => (float)_ ).ToReactiveProperty();
    }
Exemplo n.º 31
0
 public DamageCalcVm(PokemonData pokemonData)
 {
     Model       = pokemonData;
     EV          = new ReactivePropertySlim <int>(252);
     Name        = new ReactivePropertySlim <string>("エースバーン");
     Personarity = new ReactivePropertySlim <string>("ようき");
     IsDefence   = new ReactivePropertySlim <int>(0);
 }
Exemplo n.º 32
0
    private ReactiveCalculator CreateCalculator( IReactiveProperty<string> expression )
    {
        var result = new ReactiveCalculator( expression );

        result.SubscribeProperty( "strength", strength );
        result.SubscribeProperty( "agility", agility );

        return result;
    }
 public Enemy(int initialHp)
 {
     // Declarative Property
     CurrentHp = new ReactiveProperty<long>(initialHp);
     IsDead = CurrentHp.Select(x => x <= 0).ToReactiveProperty();
 }