// ----------------------------------------------------------------------- // // Copyright 2015 MIT Licence. See licence.md for more information. // // ----------------------------------------------------------------------- namespace Perspex.VisualTree { using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; /// /// Tracks the bounds of a control. /// /// /// This class is used by Adorners to track the control that the adorner is attached to. /// public class BoundsTracker { /// /// Starts tracking the specified visual. /// /// The visual. /// An observable that returns the tracked bounds. public IObservable Track(Visual visual) { return this.Track(visual, (Visual)visual.GetVisualRoot()); } /// /// Starts tracking the specified visual relative to another control. /// /// The visual. /// The control that the tracking should be relative to. /// An observable that returns the tracked bounds. public IObservable Track(Visual visual, Visual relativeTo) { var visuals = visual.GetSelfAndVisualAncestors() .TakeWhile(x => x != relativeTo) .Reverse(); var boundsSubscriptions = new List>(); foreach (var v in visuals.Cast()) { boundsSubscriptions.Add(v.GetObservable(Visual.BoundsProperty)); } var bounds = Observable.CombineLatest(boundsSubscriptions).Select(ExtractBounds); // TODO: Track transform and clip rectangle. return Observable.Select(bounds, x => new TransformedBounds((Rect)x, (Rect)new Rect(), (Matrix)Matrix.Identity)); } /// /// Sums a collection of rectangles. /// /// The collection of rectangles. /// The summed rectangle. private static Rect ExtractBounds(IList rects) { var position = rects.Select(x => x.Position).Aggregate((a, b) => a + b); return new Rect(position, rects.Last().Size); } } }