/// <summary>
 /// Corresponds to a gain of focus
 /// </summary>
 public override void EditingStarted(UITextView textView)
 {
     if (_textBox.GetTarget() is TextBox textBox && textBox.FocusState == FocusState.Unfocused)
     {
         textBox.Focus(FocusState.Pointer);
     }
 }
Ejemplo n.º 2
0
        public void When_Disposable_with_finalizer_is_collected_Then_only_unmanaged_resources_are_disposed()
        {
            var disposable = new WeakReference <WithFinalizer>(new WithFinalizer());

            Assert.That(disposable.GetTarget().IsDisposed, Is.False);
            Assert.DoesNotThrow(() => disposable.GetTarget().CallEnsureNotDisposed());
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.That(disposable.GetTarget(), Is.Null);
            Assert.That(WithoutFinalizer.DisposeOverrideCalled, Is.True);
            Assert.That(WithoutFinalizer.BothManagedAndUnmanagedWereDisposed, Is.False);
        }
Ejemplo n.º 3
0
        public void UpdateFont()
        {
            var textBox = _textBox.GetTarget();

            if (textBox != null)
            {
                var newFont = UIFontHelper.TryGetFont((float)textBox.FontSize, textBox.FontWeight, textBox.FontStyle, textBox.FontFamily);

                if (newFont != null)
                {
                    base.Font = newFont;
                    this.InvalidateMeasure();
                }
            }
        }
Ejemplo n.º 4
0
        public static IDisposable SetDisposableBinding(this DependencyObject target, DependencyProperty dependencyProperty, Binding binding,
                                                       bool restoreValue = false)
        {
            var localValue = target.ReadLocalValue(dependencyProperty);
            var weakRef    = new WeakReference(target);

            BindingOperations.SetBinding(target, dependencyProperty, binding);

            return(DelegateDisposable.Create(delegate
            {
                var reference = weakRef.GetTarget <DependencyObject>();

                if (reference == null)
                {
                    return;
                }

                if (reference.ReadLocalBinding(dependencyProperty) != binding)
                {
                    return;
                }

                if (restoreValue == false)
                {
                    reference.ClearValue(dependencyProperty);
                }
                else
                {
                    reference.RestoreLocalValue(dependencyProperty, localValue);
                }
            }));
        }
Ejemplo n.º 5
0
        public static string SafeToString <T>(this WeakReference <T> z)
            where T : class
        {
            T a = z.GetTarget();

            return((a == null) ? "〿" : a.ToString());
        }
Ejemplo n.º 6
0
 public void ReleaseStrong(WeakReference <object> key)
 {
     if (!_items.Remove(key.GetTarget() ?? throw new NullReferenceException("Key was collected")))
     {
         throw new ArgumentOutOfRangeException(nameof(key));
     }
 }
Ejemplo n.º 7
0
        internal void ScrollToCursor()
        {
            var window = _window.GetTarget();

            if (window == null)
            {
                // TextBox may not yet have been attached to window when it was templated
                window  = _textBox.GetTarget().FindFirstParent <Uno.UI.Controls.Window>();
                _window = new WeakReference <Uno.UI.Controls.Window>(window);
            }

            if (this.IsFirstResponder)
            {
                window.MakeVisible(this, BringIntoViewMode.BottomRightOfViewPort);
            }
        }
Ejemplo n.º 8
0
        private void InitializeProperties()
        {
            OnTextChanged(CreateInitialValueChangerEventArgs(TextProperty, null, Text));
            OnInputScopeChanged(CreateInitialValueChangerEventArgs(InputScopeProperty, null, InputScope));
            OnMaxLengthChanged(CreateInitialValueChangerEventArgs(MaxLengthProperty, null, MaxLength));
            OnAcceptsReturnChanged(CreateInitialValueChangerEventArgs(AcceptsReturnProperty, null, AcceptsReturn));
            OnIsEnabledChanged(false, IsEnabled);
            OnForegroundColorChanged(null, Foreground);
            UpdateFontPartial(this);
            OnHeaderChanged();
            OnIsTextPredictionEnabledChanged(CreateInitialValueChangerEventArgs(IsTextPredictionEnabledProperty, IsTextPredictionEnabledProperty.GetMetadata(GetType()).DefaultValue, IsTextPredictionEnabled));
            OnIsSpellCheckEnabledChanged(CreateInitialValueChangerEventArgs(IsSpellCheckEnabledProperty, IsSpellCheckEnabledProperty.GetMetadata(GetType()).DefaultValue, IsSpellCheckEnabled));
            OnTextAlignmentChanged(CreateInitialValueChangerEventArgs(TextAlignmentProperty, TextAlignmentProperty.GetMetadata(GetType()).DefaultValue, TextAlignment));
            OnTextWrappingChanged(CreateInitialValueChangerEventArgs(TextWrappingProperty, TextWrappingProperty.GetMetadata(GetType()).DefaultValue, TextWrapping));
            OnFocusStateChanged((FocusState)FocusStateProperty.GetMetadata(GetType()).DefaultValue, FocusState);

            var buttonRef = _deleteButton?.GetTarget();

            if (buttonRef != null)
            {
                buttonRef.Command = new DelegateCommand(DeleteText);
            }

            InitializePropertiesPartial();
        }
Ejemplo n.º 9
0
        public static string SafeToString <T>(this WeakReference <T> z, Converter <T, string> conversion)
            where T : class
        {
            T a = z.GetTarget();

            return((a == null) ? "〿" : conversion(a));
        }
Ejemplo n.º 10
0
        private void InitializeProperties()
        {
            UpdatePlaceholderVisibility();
            UpdateButtonStates();
            OnInputScopeChanged(CreateInitialValueChangerEventArgs(InputScopeProperty, null, InputScope));
            OnMaxLengthChanged(CreateInitialValueChangerEventArgs(MaxLengthProperty, null, MaxLength));
            OnAcceptsReturnChanged(CreateInitialValueChangerEventArgs(AcceptsReturnProperty, null, AcceptsReturn));
            OnIsReadonlyChanged(CreateInitialValueChangerEventArgs(IsReadOnlyProperty, null, IsReadOnly));
            OnForegroundColorChanged(null, Foreground);
            UpdateFontPartial();
            OnHeaderChanged();
            OnIsTextPredictionEnabledChanged(CreateInitialValueChangerEventArgs(IsTextPredictionEnabledProperty, IsTextPredictionEnabledProperty.GetMetadata(GetType()).DefaultValue, IsTextPredictionEnabled));
            OnIsSpellCheckEnabledChanged(CreateInitialValueChangerEventArgs(IsSpellCheckEnabledProperty, IsSpellCheckEnabledProperty.GetMetadata(GetType()).DefaultValue, IsSpellCheckEnabled));
            OnTextAlignmentChanged(CreateInitialValueChangerEventArgs(TextAlignmentProperty, TextAlignmentProperty.GetMetadata(GetType()).DefaultValue, TextAlignment));
            OnTextWrappingChanged(CreateInitialValueChangerEventArgs(TextWrappingProperty, TextWrappingProperty.GetMetadata(GetType()).DefaultValue, TextWrapping));
            OnFocusStateChanged((FocusState)FocusStateProperty.GetMetadata(GetType()).DefaultValue, FocusState, initial: true);
            OnVerticalContentAlignmentChanged(VerticalAlignment.Top, VerticalContentAlignment);
            OnTextCharacterCasingChanged(CreateInitialValueChangerEventArgs(CharacterCasingProperty, CharacterCasingProperty.GetMetadata(GetType()).DefaultValue, CharacterCasing));

            var buttonRef = _deleteButton?.GetTarget();

            if (buttonRef != null)
            {
                var thisRef = (this as IWeakReferenceProvider).WeakReference;
                buttonRef.Command = new DelegateCommand(() => (thisRef.Target as TextBox)?.DeleteButtonClick());
            }

            InitializePropertiesPartial();
        }
Ejemplo n.º 11
0
 internal override void OnLoading()
 {
     if (_parentOverride?.GetTarget() is { } parentOverride&& !(this.GetParent() is DependencyObject))
     {
         this.SetParent(parentOverride);
     }
     base.OnLoading();
 }
Ejemplo n.º 12
0
 public async Task <StorageItemThumbnail> GetAlbumCoverSource()
 {
     return(await _albumCoverSource.GetTarget(async() =>
     {
         var file = GetFile();
         return await file.GetThumbnailAsync(ThumbnailMode.MusicView);
     }));
 }
Ejemplo n.º 13
0
        public void Test_MemoryLeak_WeakEvent()
        {
            // 1. Normal Event will hold the strong reference which prevent the GC collect.
            var view      = new TestView();
            var viewModel = new TestViewModel();
            var reference = new WeakReference(view);

            viewModel.TestViewModelEvent += view.OnEventOccured;
            viewModel.RaiseTestViewModelEvent();
            Assert.AreEqual(1, view.EventCount);
            Assert.AreEqual(1, viewModel.GetTestViewModelEventInvocationCount());

            view = null;
            GC.Collect();
            Assert.IsTrue(reference.IsAlive); // Still live

            viewModel.TestViewModelEvent -= reference.GetTarget <TestView>().OnEventOccured;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            Assert.IsFalse(reference.IsAlive);

            reference = null;
            Assert.IsNull(reference.GetTarget <TestView>());

            // 2. WeakEvent hold the weak reference which will not prevent GC collect.
            var view2      = new TestView();
            var viewModel2 = new TestViewModel();
            var reference2 = new WeakReference(view2);

            var weakEvent = new WeakEvent(view2);

            weakEvent.AttachEvent(viewModel2, null, "TestViewModelEvent", "OnEventOccured");
            viewModel2.RaiseTestViewModelEvent();


            Assert.AreEqual(1, view2.EventCount);

            view2 = null;
            GC.Collect();
            Assert.IsFalse(reference2.IsAlive);

            viewModel2.RaiseTestViewModelEvent();
            Assert.AreEqual(0, viewModel2.GetTestViewModelEventInvocationCount());
        }
Ejemplo n.º 14
0
        internal void ScrollToCursor()
        {
            var window = _window.GetTarget();

            if (this.IsFirstResponder)
            {
                window.MakeVisible(this, BringIntoViewMode.BottomRightOfViewPort);
            }
        }
Ejemplo n.º 15
0
        public override CGSize SizeThatFits(CGSize size)
        {
            var textBox = _textBox.GetTarget();

            if (textBox != null)
            {
                //bug in base.SizeThatFits(size) where we get stuck and size is never return for value NaN
                if (nfloat.IsNaN(size.Width))
                {
                    size = new CGSize(nfloat.PositiveInfinity, nfloat.PositiveInfinity);
                }

                //at this point size returned represent all the space available
                //to have the same behavior of Windows, we need to call UIView.SizeThatFits() to return a size that best fits
                var expectedSize = base.SizeThatFits(size);

                //Disable the scroll if you are given enough space. Else framework will use the scrollview to move text up
                ScrollEnabled = expectedSize.Height >= size.Height;

                var canTakeAllSpace = expectedSize.Height < size.Height && !nfloat.IsInfinity(size.Height) && size.Height != textBox.MaxHeight;
                // if textBox.Height is set, size.Height will be the same
                var shouldTakeAllSpace = !double.IsNaN(textBox.Height) || textBox.VerticalAlignment == VerticalAlignment.Stretch;
                if (canTakeAllSpace && shouldTakeAllSpace)
                {
                    expectedSize.Height = size.Height;                    //Take all the space given
                }

                canTakeAllSpace = expectedSize.Width < size.Width && !nfloat.IsInfinity(size.Width) && size.Width != textBox.MaxWidth;
                // if textBox.Width is set, size.Width will be the same
                shouldTakeAllSpace = !double.IsNaN(textBox.Width) || textBox.HorizontalAlignment == HorizontalAlignment.Stretch;
                if (canTakeAllSpace && shouldTakeAllSpace)
                {
                    expectedSize.Width = size.Width;                    //Take all the space given
                }

                var result = IFrameworkElementHelper.SizeThatFits(this, expectedSize);                //Adjust for NaN and MaxHeight..

                return(result);
            }
            else
            {
                return(CGSize.Empty);
            }
        }
Ejemplo n.º 16
0
        internal void UpdateTextFromNative(string newText)
        {
            var textBox = _textBox?.GetTarget();

            if (textBox != null)
            {
                var text = textBox.ProcessTextInput(newText);
                SetTextNative(text);
            }
        }
Ejemplo n.º 17
0
 public async Task <BitmapImage> GetAlbumCover()
 {
     return(await _albumCover.GetTarget(async() =>
     {
         var cover = await GetAlbumCoverSource();
         var image = new BitmapImage();
         image.SetSource(cover);
         return image;
     }));
 }
Ejemplo n.º 18
0
        private void OnTextChanged()
        {
            var textBox = _textBox?.GetTarget();

            if (textBox != null)
            {
                var text = textBox.ProcessTextInput(Text);
                SetTextNative(text);
            }
        }
Ejemplo n.º 19
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            _isDisposed = true;

            _target.GetTarget <DependencyObject>()?.RestoreLocalValue(_property, Value);
        }
Ejemplo n.º 20
0
            internal override string OnTryToString(WeakReference <ConfigurationClusterer> x)
            {
                var xx = x.GetTarget();

                if (xx == null)
                {
                    return("(Missing)");
                }

                return(xx.DisplayName);
            }
Ejemplo n.º 21
0
        private static string ElementToString <T>(WeakReference <T> arg)
            where T : Visualisable
        {
            var arga = arg.GetTarget();

            if (arga == null)
            {
                return("(missing)");
            }

            return(arga.DisplayName);
        }
Ejemplo n.º 22
0
        private static string GetDisplayName(WeakReference <ConfigurationStatistic> a)
        {
            ConfigurationStatistic b = a.GetTarget();

            if (b == null)
            {
                return("[MISSING STATISTIC]");
            }
            else
            {
                return(b.ToString());
            }
        }
Ejemplo n.º 23
0
            protected override void OnPropertyChanged(DependencyObject depObj, DependencyProperty dependencyProperty, object oldValue, object newValue)
            {
                _cacheStore.Value = newValue;

                var interactivityObject = _interactivityObjectWeak.GetTarget <InteractivityObject>();

                if (interactivityObject != null)
                {
                    _property.OnChanged(interactivityObject, oldValue, newValue);
                }
                else
                {
                    Dispose();
                }
            }
Ejemplo n.º 24
0
        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _measureCountTextBlock = GetTemplateChild("MeasureCountTextBlock") as TextBlock;
            _arrangeCountTextBlock = GetTemplateChild("ArrangeCountTextBlock") as TextBlock;
            _stateTextBlock        = GetTemplateChild("StateTextBlock") as TextBlock;
            var inner = GetTemplateChild("MeasureDetectorInner") as MeasureDetectorInner;

            var wr = new WeakReference <MeasureDetectorControl>(this);

            inner.WasMeasured += async() =>
            {
                var that = wr.GetTarget();
                that._measureCount++;
                await that.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    that._measureCountTextBlock.Text = that._measureCount.ToString();
                    that._stateTextBlock.Text        = "Measuring";
                });

                await UpdateState(that);
            };

            inner.WasArranged += async() =>
            {
                var that = wr.GetTarget();
                that._arrangeCount++;
                await that.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    that._arrangeCountTextBlock.Text = that._arrangeCount.ToString();
                    that._stateTextBlock.Text        = "Measuring";
                });

                await UpdateState(that);
            };
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Provides a bi-directional weak event handler management.
        /// </summary>
        /// <param name="list">A list of registrations to manage</param>
        /// <param name="handler">The actual handler to execute.</param>
        /// <param name="raise">The delegate used to raise <paramref name="handler"/> if it has not been collected.</param>
        /// <returns>A disposable that keeps the registration alive.</returns>
        /// <remarks>
        /// The bi-directional relation is defined by the fact that both the
        /// source and the target are weak. The source must be kept alive by
        /// another longer-lived reference, and the target is kept alive by the
        /// return disposable.
        ///
        /// If the returned disposable is collected, the handler will also be
        /// collected. Conversly, if the <paramref name="list"/> is collected
        /// raising the event will produce nothing.
        /// </remarks>
        internal static IDisposable RegisterEvent(IList <GenericEventHandler> list, Delegate handler, EventRaiseHandler raise)
        {
            var wr = new WeakReference(handler);

            GenericEventHandler genericHandler = null;

            // This weak reference ensure that the closure will not link
            // the caller and the callee, in the same way "newValueActionWeak"
            // does not link the callee to the caller.
            var instanceRef = new WeakReference <IList <GenericEventHandler> >(list);

            Action removeHandler = () =>
            {
                var thatList = instanceRef.GetTarget();

                if (thatList != null)
                {
                    thatList.Remove(genericHandler);
                }
            };

            genericHandler = (s, e) =>
            {
                var weakHandler = wr.Target as Delegate;

                if (weakHandler != null)
                {
                    raise(weakHandler, s, e);
                }
                else
                {
                    removeHandler();
                }
            };

            list.Add(genericHandler);

            return(Disposable.Create(() =>
            {
                removeHandler();

                // Force a closure on the callback, to make its lifetime as long
                // as the subscription being held by the callee.
                handler = null;
            }));
        }
Ejemplo n.º 26
0
        internal void OnTextChanged()
        {
            var textBox = _textBox?.GetTarget();

            if (textBox != null)
            {
                var text = textBox.ProcessTextInput(Text);
                SetTextNative(text);
            }

            SetNeedsLayout();
            //We need to schedule the scrolling on the dispatcher so that we wait for the whole UI to be done before scrolling.
            //Because the multiline must have its height set so we can set properly the scrollviewer insets
            CoreDispatcher.Main.RunAsync(
                CoreDispatcherPriority.Normal,
                () => ScrollToCursor()
                );
        }
Ejemplo n.º 27
0
        public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
        {
            var textBoxView = textField as SinglelineTextBoxView;

            if (textBoxView != null)
            {
                if (_textBox.GetTarget()?.OnKey(replacementString.FirstOrDefault()) ?? false)
                {
                    return(false);
                }

                if (_textBox.GetTarget()?.MaxLength > 0)
                {
                    var newLength = textBoxView.Text.Length + replacementString.Length - range.Length;
                    return(newLength <= _textBox.GetTarget()?.MaxLength);
                }
                ;
            }

            return(true);
        }
Ejemplo n.º 28
0
 public ITextBuffer TryFindEditorTextBuffer()
 => _weakEditorBuffer.GetTarget();
Ejemplo n.º 29
0
 public override void Changed(NSNotification notification)
 {
     _securedTextBoxView.GetTarget()?.OnChanged();
 }
Ejemplo n.º 30
0
 public override bool TextShouldBeginEditing(NSControl control, NSText fieldEditor)
 {
     return(!_passwordBox.GetTarget()?.IsReadOnly ?? false);
 }