예제 #1
0
        internal void Unapply()
        {
            object sourceObject;

            if (_weakSource != null && _weakSource.TryGetTarget(out sourceObject))
            {
                for (var i = 0; i < _parts.Count - 1; i++)
                {
                    BindingExpressionPart part = _parts[i];

                    if (!part.IsSelf)
                    {
                        part.TryGetValue(sourceObject, out sourceObject);
                    }

                    part.Unsubscribe();
                }
            }

            if (_trackingTemplatedParent)
            {
                BindableObject target = null;
                if (_weakTarget?.TryGetTarget(out target) == true && target is Element elem)
                {
                    elem.TemplatedParentChanged -= OnTargetTemplatedParentChanged;
                }
            }

            _weakSource = null;
            _weakTarget = null;

            ClearAncestryChangeSubscriptions();
        }
예제 #2
0
        void OnElementBindingContextChanged(object sender, EventArgs e)
        {
            if (!(sender is Element elem) ||
                !(this.Binding is Binding binding))
            {
                return;
            }

            BindableObject target = null;

            if (_weakTarget?.TryGetTarget(out target) != true)
            {
                return;
            }

            object currentSource = null;

            if (_weakSource?.TryGetTarget(out currentSource) == true)
            {
                // make sure that this isn't just a repeat notice
                // from someone else in the chain about our already-resolved
                // binding source
                if (object.ReferenceEquals(currentSource, elem.BindingContext))
                {
                    return;
                }
            }

            binding.Unapply();
            binding.Apply(null, target, _targetProperty);
        }
예제 #3
0
        private protected override void OnLoaded()
        {
            base.OnLoaded();

            // TODO: Find a proper way to decide whether a CommandBar exists on canvas (within Page), or is mapped to the UINavigationController's NavigationBar.

            CommandBar?commandBar = null;

            _commandBar?.TryGetTarget(out commandBar);

            if (_commandBar == null)
            {
                commandBar  = TemplatedParent as CommandBar;
                _commandBar = new WeakReference <CommandBar?>(commandBar);

                _navigationBar = commandBar?.GetRenderer(RendererFactory).Native;
            }
            else
            {
                _navigationBar = commandBar?.ResetRenderer(RendererFactory).Native;
            }

            if (_navigationBar == null)
            {
                throw new InvalidOperationException("No NavigationBar from renderer");
            }

            _navigationBar.SetNeedsLayout();

            var navigationBarSuperview = _navigationBar?.Superview;

            // Allows the UINavigationController's NavigationBar instance to be moved to the Page. This feature
            // is used in the context of the sample application to test NavigationBars outside of a NativeFramePresenter for
            // UI Testing. In general cases, this should not happen as the bar may be moved back to to this presenter while
            // another page is already visible, making this bar overlay on top of another.
            if (FeatureConfiguration.CommandBar.AllowNativePresenterContent && (navigationBarSuperview == null || navigationBarSuperview is NativeCommandBarPresenter))
            {
                Content = _navigationBar;
            }

            var statusBar = StatusBar.GetForCurrentView();

            statusBar.Showing += OnStatusBarChanged;
            statusBar.Hiding  += OnStatusBarChanged;

            _statusBarSubscription.Disposable = Disposable.Create(() =>
            {
                statusBar.Showing -= OnStatusBarChanged;
                statusBar.Hiding  -= OnStatusBarChanged;
            });

            // iOS doesn't automatically update the navigation bar position when the status bar visibility changes.
            void OnStatusBarChanged(StatusBar sender, object args)
            {
                _navigationBar !.SetNeedsLayout();
                _navigationBar !.Superview.SetNeedsLayout();
            }
        }
예제 #4
0
            private void SetupCollectionChanged(INotifyCollectionChanged?collection)
            {
                INotifyCollectionChanged?oldCollection = null;

                _collectionReference?.TryGetTarget(out oldCollection);
                if (oldCollection != null)
                {
                    oldCollection.CollectionChanged -= OnItemsSourceCollectionChanged;
                }
                if (collection != null)
                {
                    collection.CollectionChanged += OnItemsSourceCollectionChanged;
                    _collectionReference          = new WeakReference <INotifyCollectionChanged>(collection);
                }
            }
예제 #5
0
        public void WriteExpression(TextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            TextWriter       w       = null;
            TypeScriptWriter visitor = null;

            _CachedTextWriter?.TryGetTarget(out w);

            if (w == writer && _CachedTypeScriptWriter?.TryGetTarget(out visitor) == true)
            {
                Accept(visitor);
            }
            else
            {
                visitor                 = new TypeScriptWriter(writer);
                _CachedTextWriter       = new WeakReference <TextWriter>(writer);
                _CachedTypeScriptWriter = new WeakReference <TypeScriptWriter>(visitor);

                Accept(visitor);
            }
        }
예제 #6
0
        private async void CalculateColor()
        {
            // HACK: yield control to avoid a race condition where things might not be initialized yet, resulting in no color being applied
            await ThreadingTask.Delay(1);
            View view = null;
            T item;
            if (RealmCollection != null && 
                _view?.TryGetTarget(out view) == true &&
                (item = view.BindingContext as T) != null)
            {
                try
                {
                    Color backgroundColor;
                    if (item.IsCompleted)
                    {
                        backgroundColor = CompletedColor;
                    }
                    else
                    {
                        var index = RealmCollection.IndexOf(item);
                        var fraction = index / (double)Math.Max(13, RealmCollection.Count);
                        backgroundColor = GradientColorAtFraction(fraction);
                    }

                    view.BackgroundColor = backgroundColor;
                }
                catch
                {
                    // Let's not crash because of a coloring fail :)
                }
            }
        }
예제 #7
0
        public static T Value <T>(this WeakReference <T> item) where T : class
        {
            T v = null;

            item?.TryGetTarget(out v);
            return(v);
        }
        private Regex GetServiceNameRegex(String category, string key)
        {
            ConcurrentDictionary <String, Regex> GetRegexCache()
            {
                ConcurrentDictionary <string, Regex> cache = null;

                if (_regexCache?.TryGetTarget(out cache) ?? false)
                {
                    return(cache);
                }
                cache       = new ConcurrentDictionary <string, Regex>();
                _regexCache = new WeakReference <ConcurrentDictionary <String, Regex> >(cache);
                return(cache);
            }

            return(GetRegexCache().GetOrAdd($"{category}:{key}", k =>
            {
                StringBuilder servicePattern = new StringBuilder("^");

                foreach (String c in key.Select(c => c.ToString()))
                {
                    String charString = c.Equals("*") ? "\\S" : Regex.Escape(c);
                    servicePattern.Append(charString);
                }
                Regex rg = new Regex(servicePattern.ToString(), RegexOptions.Compiled, TimeSpan.FromSeconds(10));
                return rg;
            }));
        }
예제 #9
0
        /// <summary>
        /// 【参考実装】Subscribe 時じゃなくて、IObservable に対して細工する版。
        ///
        /// <paramref name="observable"/> をラップして、Subscribe が全部弱イベント購読になる <see cref="IObservable{T}"/> を作る。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="observable"></param>
        /// <returns></returns>
        public static IObservable <T> AsWeakObservable <T>(this IObservable <T> observable)
        {
            return(Observable.Create((IObserver <T> observer) =>
            {
                WeakReference <IDisposable>?weakSubscription = null;
                IDisposable?subscription = null;

                subscription = observable.Subscribe(x =>
                {
                    IDisposable d;
                    if (!(weakSubscription?.TryGetTarget(out d) ?? false))
                    {
                        subscription?.Dispose();
                        return;
                    }
                    observer.OnNext(x);
                });

                var s = new SingleAssignmentDisposable();
                s.Disposable = subscription;

                weakSubscription = new WeakReference <IDisposable>(s);
                return s;
            }));
        }
예제 #10
0
        /// <summary>
        /// Gets the alive object in this <see cref="WeakReference{T}"/> or the <paramref name="defaultValue"/> if not alive.
        /// </summary>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <param name="self">The weak reference.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns></returns>
        public static T GetOrDefault <T>(this WeakReference <T> self, T defaultValue = default(T)) where T : class
        {
            T value = defaultValue;

            self?.TryGetTarget(out value);
            return(value);
        }
        /// <summary>
        /// @return The current {@link CustomTabsSession} object.
        /// </summary>
        /// <returns>The current session.</returns>
        public static CustomTabsSession GetCurrentSession()
        {
            CustomTabsSession customTabsSession = null;

            sCurrentSession?.TryGetTarget(out customTabsSession);
            return(customTabsSession);
        }
        /// <summary>
        /// 弱イベント購読。
        /// 戻り値の <see cref="IDisposable"/> が誰からも参照されなくなったら自動的にイベント購読解除する。
        /// </summary>
        /// <typeparam name="T">イベント引数の型。</typeparam>
        /// <param name="observable">イベント発生側。</param>
        /// <param name="onNext">イベント受取側。</param>
        /// <returns>イベント購読解除用の disposable。</returns>
        /// <remarks>
        /// 弱参照の性質上、<see cref="GC"/> がかかって初めて「誰も使ってない」判定を受ける。
        /// それまではイベント購読解除されず、イベントが届き続ける。
        /// GC タイミングに左右されるコードは推奨できないんで、可能な限り、
        /// 戻り値の <see cref="IDisposable.Dispose"/> を明示的に呼ぶべき。
        /// </remarks>
        public static IDisposable WeakSubscribe <T>(this IObservable <T> observable, Action <T> onNext)
        {
            WeakReference <IDisposable>?weakSubscription = null;
            IDisposable?subscription = null;

            subscription = observable.Subscribe(x =>
            {
                IDisposable d;
                if (!(weakSubscription?.TryGetTarget(out d) ?? false))
                {
                    // 弱参照のターゲットが消えてたらイベント購読解除。
                    subscription?.Dispose();
                    return;
                }
                onNext(x);
            });

            // subscription は↑のラムダ式が参照を持っちゃうことになるので、
            // 別の IDisposable を作ってラップ。
            var s = new SingleAssignmentDisposable();

            s.Disposable = subscription;

            // 作った、外から呼ぶ用 IDisposable の弱参照を作る。
            weakSubscription = new WeakReference <IDisposable>(s);
            return(s);
        }
예제 #13
0
        protected override void OnCompletedCore()
        {
            Action oncomplete = null;

            if (_onCompleted?.TryGetTarget(out oncomplete) == true)
            {
                oncomplete();
            }
        }
예제 #14
0
        protected override void OnErrorCore(Exception error)
        {
            Action <Exception> onerror = null;

            if (_onError?.TryGetTarget(out onerror) == true)
            {
                onerror(error);
            }
        }
예제 #15
0
        protected override void OnNextCore(T value)
        {
            Action <T> onnext = null;

            if (_onNext?.TryGetTarget(out onnext) == true)
            {
                onnext(value);
            }
        }
예제 #16
0
        public void Execute(object parameter)
        {
            object executeTarget = null;

            if (ExecuteTargetReference?.TryGetTarget(out executeTarget) ?? false)
            {
                ExecuteCallbackInfo.Invoke(executeTarget, new[] { parameter });
            }
        }
예제 #17
0
        /// <summary>
        /// Статичная цель всегда будет считаться полной.
        /// </summary>
        public bool IsEmpty()
        {
            if (_isStaticTarget)
            {
                return(false);
            }

            return(!(_target?.TryGetTarget(out _) ?? true));
        }
예제 #18
0
    internal static bool TryGet <T>(this WeakReference <T>?weakRef, [NotNullWhen(true)] out T?value) where T : class
    {
        if (weakRef?.TryGetTarget(out value) ?? false)
        {
            return(true);
        }

        value = null;
        return(false);
    }
예제 #19
0
        internal NavigationView GetNavigationViewParent()
        {
            var result = default(NavigationView);

            if (m_navigationView?.TryGetTarget(out result) ?? false)
            {
                return(result);
            }

            return(null);
        }
예제 #20
0
        internal SyntaxNode GetWeakRedElement(ref WeakReference <SyntaxNode> slot, int index)
        {
            SyntaxNode value = null;

            if (slot?.TryGetTarget(out value) == true)
            {
                return(value);
            }

            return(CreateWeakItem(ref slot, index));
        }
예제 #21
0
        /// <summary>
        /// Detaches from the subscribed event.
        /// </summary>
        public void Detach()
        {
            var source = _source;

            if (source == null)
            {
                _weakSource?.TryGetTarget(out source);
            }
            if (source == null)
            {
                return;
            }

            _onDetachAction(this, source);
        }
예제 #22
0
        /// <summary>
        /// Updates an existing gradient layer's parameters, if found, from the provided <see cref="T:XFGloss.Gradient"/>
        /// instance.
        /// </summary>
        /// <param name="gradient">Gradient.</param>
        void UpdateGradientLayerParams(Gradient gradient)
        {
            // If a layer currently exists but the gradient is being set to null...
            if (gradient == null)
            {
                UIView view = null;
                if ((bool)_gradientView?.TryGetTarget(out view) && view != null)
                {
                    RemoveGradientLayer(view);
                }
                return;
            }

            UpdateRotation(gradient.Rotation);
            UpdateSteps(gradient.Steps);
        }
예제 #23
0
        public void IGenericSharedAPI_ClearOrRemove_ReferenceRemovedFromCollection(bool useRemove)
        {
            if (typeof(T).IsValueType || IsReadOnly)
            {
                return;
            }

            IEnumerable <T> collection = GenericIEnumerableFactory();

            WeakReference <object> wr = PopulateAndRemove(collection, useRemove);

            Assert.True(SpinWait.SpinUntil(() =>
            {
                GC.Collect();
                return(!wr.TryGetTarget(out _));
            }, 30_000));
            GC.KeepAlive(collection);
예제 #24
0
            public override void HandleMessage(Message msg)
            {
                MusicService service;

                weakReference.TryGetTarget(out service);
                if (service != null && service.playback != null)
                {
                    if (service.playback.IsPlaying)
                    {
                        LogHelper.Debug(Tag, "Ignoring delayed stop since the media player is in use.");
                        return;
                    }
                    LogHelper.Debug(Tag, "Stopping service with delay handler.");
                    service.StopSelf();
                    service.serviceStarted = false;
                }
            }
예제 #25
0
 internal static CounterGroup GetCounterGroup(EventSource eventSource)
 {
     lock (s_counterGroupsLock)
     {
         int eventSourceIndex = EventListener.EventSourceIndex(eventSource);
         EnsureEventSourceIndexAvailable(eventSourceIndex);
         Debug.Assert(s_counterGroups != null);
         WeakReference <CounterGroup> weakRef = CounterGroup.s_counterGroups[eventSourceIndex];
         CounterGroup?ret = null;
         if (weakRef == null || !weakRef.TryGetTarget(out ret))
         {
             ret = new CounterGroup(eventSource);
             CounterGroup.s_counterGroups[eventSourceIndex] = new WeakReference <CounterGroup>(ret);
         }
         return(ret);
     }
 }
예제 #26
0
파일: ListProxy.cs 프로젝트: zhamppx97/maui
            void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                ListProxy proxy;

                if (!_weakProxy.TryGetTarget(out proxy))
                {
                    INotifyCollectionChanged collection;
                    if (_weakCollection.TryGetTarget(out collection))
                    {
                        collection.CollectionChanged -= OnCollectionChanged;
                    }

                    return;
                }

                proxy.OnCollectionChanged(sender, e);
            }
예제 #27
0
 // Returns -1 if the member is not in the chain or the
 // chain is no longer valid.
 int FindAncestryIndex(Element elem)
 {
     for (int i = 0; i < _ancestryChain.Count; i++)
     {
         WeakReference <Element> weak = _ancestryChain[i];
         Element chainMember          = null;
         if (!weak.TryGetTarget(out chainMember))
         {
             return(-1);
         }
         else if (object.Equals(elem, chainMember))
         {
             return(i);
         }
     }
     return(-1);
 }
        public static SharedResources GetSharedResources(ICanvasResourceCreator resourceCreator)
        {
            var             device = resourceCreator.Device;
            SharedResources sharedResources;

            if (currentSharedResources.TryGetTarget(out sharedResources))
            {
                if (sharedResources.Device == device)
                {
                    return(sharedResources);
                }
            }

            sharedResources = new SharedResources(device);
            currentSharedResources.SetTarget(sharedResources);
            return(sharedResources);
        }
예제 #29
0
        public bool ContainsData(string dataName)
        {
            if (dataName == null)
            {
                return(false);
            }

            if (!dataDic.ContainsKey(dataName))
            {
                return(false);
            }

            WeakReference <object> wr = dataDic[dataName];
            object o = null;

            return(wr.TryGetTarget(out o));
        }
            public override void HandleMessage(Android.OS.Message msg)
            {
                switch (msg.What)
                {
                case MESSAGE_RETRY_CONNECTION:

                    FullWalletConfirmationButtonFragment fragment = null;
                    mWeakReference.TryGetTarget(out fragment);

                    if (fragment != null)
                    {
                        fragment.mGoogleApiClient.Connect();
                    }

                    break;
                }
            }
예제 #31
0
    public static void GetValueTest()
    {
        ConditionalWeakTable<object, object> cwt = new ConditionalWeakTable<object, object>();
        object key = new object();
        object obj = null;

        object value = cwt.GetValue(key, k => new object());

        Assert.True(cwt.TryGetValue(key, out value));
        Assert.Equal(value, cwt.GetOrCreateValue(key));

        WeakReference<object> wrValue = new WeakReference<object>(value, false);
        WeakReference<object> wrkey = new WeakReference<object>(key, false);
        key = null;
        value = null;

        GC.Collect();

        // key and value must be collected
        Assert.False(wrValue.TryGetTarget(out obj));
        Assert.False(wrkey.TryGetTarget(out obj));
    }
        [OuterLoop] // finalizer/GC interactions
        public void TestNullTarget_CompletionNoCaching()
        {
            // Make sure that the Completion task returned by a NullTarget
            // is not cached across all NullTargets.  Since it'll never complete,
            // that would be a potentially huge memory leak.

            var state = new object();
            var wro = new WeakReference<object>(state);
            DataflowBlock.NullTarget<int>().Completion.ContinueWith(delegate { }, state);
            state = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Assert.False(wro.TryGetTarget(out state));
        }
        public void AllowFinalization()
        {
            // Explicitly do not dispose, to allow finalization to happen, just to try to verify
            // that nothing fails when it does.
            MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
            MemoryMappedViewStream s = mmf.CreateViewStream();

            var mmfWeak = new WeakReference<MemoryMappedFile>(mmf);
            var sWeak = new WeakReference<MemoryMappedViewStream>(s);

            mmf = null;
            s = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Assert.False(mmfWeak.TryGetTarget(out mmf));
            Assert.False(sWeak.TryGetTarget(out s));
        }