Ejemplo n.º 1
0
        /// <summary>
        /// Forces content to scroll until the coordinate space of a System.Windows.Media.Visual object is visible.
        /// This is optimized for horizontal scrolling only
        /// </summary>
        /// <param name="visual">A System.Windows.Media.Visual that becomes visible.</param>
        /// <param name="rectangle">A bounding rectangle that identifies the coordinate space to make visible.</param>
        /// <returns>A System.Windows.Rect that is visible.</returns>
        public Rect MakeVisible(Visual visual, Rect rectangle)
        {
            // We can only work on visuals that are us or children.
            // An empty rect has no size or position.  We can't meaningfully use it.
            if (rectangle.IsEmpty ||
                visual == null ||
                visual == (Visual)this ||
                !this.IsAncestorOf(visual))
            {
                return(Rect.Empty);
            }

            // Compute the child's rect relative to (0,0) in our coordinate space.
            GeneralTransform childTransform = visual.TransformToAncestor(this);

            rectangle = childTransform.TransformBounds(rectangle);

            // Initialize the viewport
            Rect viewport = new Rect(HorizontalOffset, rectangle.Top, ViewportWidth, rectangle.Height);

            rectangle.X += viewport.X;

            // Compute the offsets required to minimally scroll the child maximally into view.
            double minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right);

            // We have computed the scrolling offsets; scroll to them.
            SetHorizontalOffset(minX);

            // Compute the visible rectangle of the child relative to the viewport.
            viewport.X = minX;
            rectangle.Intersect(viewport);

            rectangle.X -= viewport.X;

            // Return the rectangle
            return(rectangle);
        }
        // Token: 0x06006FD8 RID: 28632 RVA: 0x002026EC File Offset: 0x002008EC
        internal static Rect CalculateVisibleRect(Rect visibleRect, Visual originalVisual)
        {
            Visual visual = VisualTreeHelper.GetParent(originalVisual) as Visual;

            while (visual != null && visibleRect != Rect.Empty)
            {
                if (VisualTreeHelper.GetClip(visual) != null)
                {
                    GeneralTransform inverse = originalVisual.TransformToAncestor(visual).Inverse;
                    if (inverse != null)
                    {
                        Rect rect = VisualTreeHelper.GetClip(visual).Bounds;
                        rect = inverse.TransformBounds(rect);
                        visibleRect.Intersect(rect);
                    }
                    else
                    {
                        visibleRect = Rect.Empty;
                    }
                }
                visual = (VisualTreeHelper.GetParent(visual) as Visual);
            }
            return(visibleRect);
        }
Ejemplo n.º 3
0
        /* /trazar una ruta entre dos puntos
         * private async void ShowRouteOnMap()
         * {
         *  // Start at Microsoft in Redmond, Washington.                       4.456561               -75.181589
         *  BasicGeoposition startLocation = new BasicGeoposition() { Latitude = 4.456561, Longitude = -75.181589 };
         *
         *  // End at the city of Seattle, Washington.                         4.448132              -75.179071
         *  BasicGeoposition endLocation = new BasicGeoposition() { Latitude = 4.411145, Longitude = -75.264982 };
         *
         *
         *  // Get the route between the points.
         *  MapRouteFinderResult routeResult =
         *        await MapRouteFinder.GetDrivingRouteAsync(
         *        new Geopoint(startLocation),
         *        new Geopoint(endLocation),
         *        MapRouteOptimization.Time,
         *        MapRouteRestrictions.None);
         *
         *  if (routeResult.Status == MapRouteFinderStatus.Success)
         *  {
         *      // Use the route to initialize a MapRouteView.
         *      MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
         *      viewOfRoute.RouteColor = Colors.Yellow;
         *      viewOfRoute.OutlineColor = Colors.Black;
         *
         *      // Add the new MapRouteView to the Routes collection
         *      // of the MapControl.
         *      myMap.Routes.Add(viewOfRoute);
         *
         *      // Fit the MapControl to the route.
         *      await myMap.TrySetViewBoundsAsync(
         *            routeResult.Route.BoundingBox,
         *            null,
         *            Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None);
         *  }
         * } */

        //Ubicaicon de Punto / Ventana emergente a Bing Maps
        private void SpaceNeedle_Click(object sender, RoutedEventArgs e)
        {
            Geopoint spaceNeedlePoint = new Geopoint
                                            (new BasicGeoposition {
                Latitude = 4.457118, Longitude = -75.181588
            });

            PlaceInfoCreateOptions options = new PlaceInfoCreateOptions();

            options.DisplayAddress = "400 Broad St, Seattle, WA 98109";
            options.DisplayName    = "Seattle Space Needle";

            PlaceInfo spaceNeedlePlace = PlaceInfo.Create(spaceNeedlePoint, options);

            FrameworkElement targetElement = (FrameworkElement)sender;

            GeneralTransform generalTransform =
                targetElement.TransformToVisual((FrameworkElement)targetElement.Parent);

            Rect rectangle = generalTransform.TransformBounds(new Rect(new Point
                                                                           (targetElement.Margin.Left, targetElement.Margin.Top), targetElement.RenderSize));

            spaceNeedlePlace.Show(rectangle, Windows.UI.Popups.Placement.Below);
        }
Ejemplo n.º 4
0
        bool IsCrush()
        {
            bool temp = false;

            foreach (var el in Cnvs.Children)
            {
                if (el is Ellipse)
                {
                    if ((el as Ellipse).Tag == "Meteor")
                    {
                        try
                        {
                            Ellipse          my_eliplse = (Ellipse)el;
                            GeneralTransform t1         = my_eliplse.TransformToVisual(this);
                            GeneralTransform t2         = earth.TransformToVisual(this);
                            Rect             r1         = t1.TransformBounds(new Rect()
                            {
                                X = 0, Y = 0, Width = my_eliplse.ActualWidth, Height = my_eliplse.ActualHeight
                            });
                            Rect r2 = t2.TransformBounds(new Rect()
                            {
                                X = 0, Y = 0, Width = earth.ActualWidth, Height = earth.ActualHeight
                            });
                            bool result = r1.IntersectsWith(r2);
                            if (result)
                            {
                                return(true);
                            }
                        }

                        catch { }
                    }
                }
            }
            return(temp);
        }
Ejemplo n.º 5
0
        private static LabelSizeInfo GetLabelSize(FrameworkElement visual)
        {
            RadSize       visualSize = GetVisualDesiredSize(visual);
            LabelSizeInfo sizeInfo   = new LabelSizeInfo()
            {
                UntransformedSize = visualSize
            };

            GeneralTransform transform = visual.RenderTransform;

            if (transform != null)
            {
                Rect labelRect = new Rect(0, 0, visualSize.Width, visualSize.Height);
                labelRect = transform.TransformBounds(labelRect);
                sizeInfo.TransformOffset = new RadPoint(labelRect.X, labelRect.Y);
                sizeInfo.Size            = new RadSize(labelRect.Width, labelRect.Height);
            }
            else
            {
                sizeInfo.Size = visualSize;
            }

            return(sizeInfo);
        }
Ejemplo n.º 6
0
        //Festlegen der Standorte und setzen der PlaceNeedles auf der Map mittls Langitude und Longitude
        //Festlegen des zu Übergebenden Textes
        private void Ansbach_Click(object sender, RoutedEventArgs e)
        {
            MapService.ServiceToken = "abcdef-abcdefghijklmno";
            Bestellung4.Text        = "- Ansbach \r\n";

            Geopoint seattlePoint = new Geopoint
                                        (new BasicGeoposition
            {
                Latitude  = 49.3007,
                Longitude = 10.5692
            });

            PlaceInfo spaceNeedlePlace = PlaceInfo.Create(seattlePoint);

            FrameworkElement targetElement = (FrameworkElement)sender;

            GeneralTransform generalTransform =
                targetElement.TransformToVisual((FrameworkElement)targetElement.Parent);

            Rect rectangle = generalTransform.TransformBounds(new Rect(new Point
                                                                           (targetElement.Margin.Bottom, targetElement.Margin.Top), targetElement.RenderSize));

            spaceNeedlePlace.Show(rectangle, Windows.UI.Popups.Placement.Below);
        }
Ejemplo n.º 7
0
        private Rect BoundsRelativeTo(FrameworkElement element, Visual relativeTo)
        {
            GeneralTransform gt = element.TransformToAncestor(relativeTo);

            return(gt.TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight)));
        }
Ejemplo n.º 8
0
        private Rect GetElementRect(FrameworkElement element)
        {
            GeneralTransform buttonTransform = element.TransformToVisual(null);

            return(buttonTransform.TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight)));
        }
        void ScrollPages_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            // Weirdly, ScrollChanged is a bubbling event - not a callback on the very object
            // So you can receive a scroll event from ANY of your children?!!?!!!!!
            // Inside the reading page, there are scrollbars in the annotation popups, which cause this to fire.  So ignore those...
            if (e.Source != ScrollPages)
            {
                return;
            }

            if (DateTime.MaxValue == first_scroll_timestamp)
            {
                first_scroll_timestamp = DateTime.UtcNow;

                if (remember_last_read_page)
                {
                    if (0 < pdf_renderer_control_stats.pdf_document.PageLastRead)
                    {
                        //Logging.Info("**********************************Restoring page to page " + pdf_renderer_control_stats.pdf_document.PageLastRead);
                        PDFRendererPageControl page_control = (PDFRendererPageControl)ObjPagesPanel.Children[pdf_renderer_control_stats.pdf_document.PageLastRead - 1];
                        page_control.BringIntoView();
                    }
                }
            }

            /*
             *  Logging.Info(
             *      "\n----------------------------------------------------------" +
             *      "\nExtentHeight={0}," +
             *      "\nExtentHeightChange={1}," +
             *      "\nExtentWidth={2}," +
             *      "\nExtentWidthChange={3}," +
             *      "\nHorizontalChange={4}," +
             *      "\nHorizontalOffset={5}," +
             *      "\nVerticalChange={6}," +
             *      "\nVerticalOffset={7}," +
             *      "\nViewportHeight={8}," +
             *      "\nViewportHeightChange={9}," +
             *      "\nViewportWidth={10}," +
             *      "\nViewportWidthChange={11}," +
             *      "",
             *
             *      e.ExtentHeight,
             *      e.ExtentHeightChange,
             *      e.ExtentWidth,
             *      e.ExtentWidthChange,
             *      e.HorizontalChange,
             *      e.HorizontalOffset,
             *      e.VerticalChange,
             *      e.VerticalOffset,
             *      e.ViewportHeight,
             *      e.ViewportHeightChange,
             *      e.ViewportWidth,
             *      e.ViewportWidthChange
             *      );
             */

            // Lets see which pages are in view
            PDFRendererPageControl        first_page_in_view = null;
            List <PDFRendererPageControl> pages_in_view      = new List <PDFRendererPageControl>();
            List <PDFRendererPageControl> pages_not_in_view  = new List <PDFRendererPageControl>();

            foreach (PDFRendererPageControl page in ObjPagesPanel.Children.OfType <PDFRendererPageControl>().Reverse())
            {
                GeneralTransform childTransform = page.TransformToAncestor(ScrollPages);
                Rect             rectangle      = childTransform.TransformBounds(new Rect(new Point(0, 0), page.RenderSize));
                Rect             result         = Rect.Intersect(new Rect(new Point(0, 0), ScrollPages.RenderSize), rectangle);

                if (result != Rect.Empty)
                {
                    if (null == first_page_in_view)
                    {
                        first_page_in_view = page;
                    }

                    pages_in_view.Add(page);
                }
                else
                {
                    pages_not_in_view.Add(page);
                }
            }

            // Check if the selected page has gone off screen.  If so, select the next page.
            if (null != SelectedPage)
            {
                if (!pages_in_view.Contains(SelectedPage))
                {
                    // IF this is the first time the selected page has gone off screen, record the moment
                    if (DateTime.MaxValue == selected_page_first_offscreen_timestamp)
                    {
                        selected_page_first_offscreen_timestamp = DateTime.UtcNow;
                    }

                    // We wait for a few moments after it has gone off the screen...2 is arbitrary, but large enough that we can zoom without changing the selected page before the zoom gets time to move thesleected page back onto the screen...
                    if (DateTime.UtcNow.Subtract(selected_page_first_offscreen_timestamp).TotalSeconds > 1)
                    {
                        if (null != first_page_in_view)
                        {
                            SelectedPage = first_page_in_view;
                            selected_page_first_offscreen_timestamp = DateTime.MaxValue;
                        }
                    }
                }
                else
                {
                    selected_page_first_offscreen_timestamp = DateTime.MaxValue;
                }
            }


            bool SKIP = false;

            if (SKIP)
            {
                // Lets pretend the pages just before and after the pages in view are in view - that way we dont have to wait for the render
                int min_page = Int32.MaxValue;
                int max_page = Int32.MinValue;
                foreach (PDFRendererPageControl page in pages_in_view)
                {
                    min_page = Math.Min(min_page, page.PageNumber - 1);
                    max_page = Math.Max(max_page, page.PageNumber + 1);
                }
                foreach (PDFRendererPageControl page in pages_not_in_view)
                {
                    if (min_page == page.PageNumber || max_page == page.PageNumber)
                    {
                        pages_in_view.Add(page);
                    }
                }
                foreach (PDFRendererPageControl page in pages_in_view)
                {
                    pages_not_in_view.Remove(page);
                }
            }

            // Clear down the pages NOT in view
            foreach (PDFRendererPageControl page in pages_not_in_view)
            {
                page.SetPageNotInView();
            }

            // Notify the new pages that are in view
            foreach (PDFRendererPageControl page in pages_in_view)
            {
                //Logging.Info("Page {0} is in view!!!!!!!!!!!!!!", page.PageNumber);
                page.SetPageInView();
            }

            // If the page has been resized or rescaled, try keep the scrollbars in the same place...
            if (0 != e.ExtentHeightChange)
            {
                double prev_extent_height    = e.ExtentHeight - e.ExtentHeightChange;
                double vertical_offset_ratio = e.VerticalOffset / prev_extent_height;
                double new_vertical_offset   = vertical_offset_ratio * e.ExtentHeight;

                if (!Double.IsNaN(new_vertical_offset))
                {
                    //Logging.Info("Forcing vertical offset from {0} to {1}", e.VerticalOffset, new_vertical_offset);
                    ScrollPages.ScrollToVerticalOffset(new_vertical_offset);
                    return;
                }
                else
                {
                }
            }


            // Store the last seen page - but not right at the start
            if (DateTime.UtcNow.Subtract(first_scroll_timestamp).TotalSeconds > 1)
            {
                if (remember_last_read_page)
                {
                    if (0 < pages_in_view.Count)
                    {
                        PDFRendererPageControl page = pages_in_view[0];

                        // Set the last read page
                        pdf_renderer_control_stats.pdf_document.PageLastRead = page.Page;
                        // Dont notify this now as it causes many writes of the metadata to be done, which is slow for large highlightlists
                        //pdf_renderer_control_stats.pdf_document.Bindable.NotifyPropertyChanged(() => pdf_renderer_control_stats.pdf_document.PageLastRead);
                    }
                }
            }
        }
Ejemplo n.º 10
0
        //-------------------------------------------------------------------
        //
        //  Internal Methods
        //
        //-------------------------------------------------------------------

        #region Internal Methods

        /// <summary>
        /// ScrollContentPresenter implementation of <seealso cref="IScrollInfo.MakeVisible" />.
        /// </summary>
        /// <param name="visual">The Visual that should become visible</param>
        /// <param name="rectangle">A rectangle representing in the visual's coordinate space to make visible.</param>
        /// <param name="throwOnError">If true the method throws an exception when an error is encountered, otherwise the method returns Rect.Empty when an error is encountered</param>
        /// <returns>
        /// A rectangle in the IScrollInfo's coordinate space that has been made visible.
        /// Other ancestors to in turn make this new rectangle visible.
        /// The rectangle should generally be a transformed version of the input rectangle.  In some cases, like
        /// when the input rectangle cannot entirely fit in the viewport, the return value might be smaller.
        /// </returns>
        internal Rect MakeVisible(Visual visual, Rect rectangle, bool throwOnError)
        {
            // (ScrollContentPresenter.MakeVisible can cause an exception when encountering an empty rectangle)
            // This method exists to keep ScrollContentPresenter.MakeVisible v1 behavior
            // while allowing callers of IScrollInfo.MakeVisible in the platform work around a bug
            // in the v1 behavior.
            // If this bug is fixed look for callers of IScrollInfo.MakeVisible with workarounds.
            // They should be updated remove the workarounds.

            //
            // Note: This code presently assumes we/children are layout clean.  See work item 22269 for more detail.
            //

            // We can only work on visuals that are us or children.
            // An empty rect has no size or position.  We can't meaningfully use it.
            if (rectangle.IsEmpty ||
                visual == null ||
                visual == (Visual)this ||
                !this.IsAncestorOf(visual))
            {
                return(Rect.Empty);
            }

            // This is a false positive by PreSharp. visual cannot be null because of the 'if' check above
#pragma warning disable 1634, 1691
#pragma warning disable 56506
            // Compute the child's rect relative to (0,0) in our coordinate space.
            GeneralTransform childTransform = visual.TransformToAncestor(this);
#pragma warning restore 56506
#pragma warning restore 1634, 1691

            rectangle = childTransform.TransformBounds(rectangle);

            if (!IsScrollClient || (!throwOnError && rectangle.IsEmpty))
            {
                return(rectangle);
            }

            // Initialize the viewport
            Rect viewport = new Rect(HorizontalOffset, VerticalOffset, ViewportWidth, ViewportHeight);
            rectangle.X += viewport.X;
            rectangle.Y += viewport.Y;

            // Compute the offsets required to minimally scroll the child maximally into view.
            double minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right);
            double minY = ComputeScrollOffsetWithMinimalScroll(viewport.Top, viewport.Bottom, rectangle.Top, rectangle.Bottom);

            // We have computed the scrolling offsets; scroll to them.
            SetHorizontalOffset(minX);
            SetVerticalOffset(minY);

            // Compute the visible rectangle of the child relative to the viewport.
            viewport.X = minX;
            viewport.Y = minY;
            rectangle.Intersect(viewport);

            if (throwOnError)
            {
                // (ScrollContentPresenter.MakeVisible can cause an exception when encountering an empty rectangle)
                // Old behavior for app compat
                rectangle.X -= viewport.X;
                rectangle.Y -= viewport.Y;
            }
            else
            {
                // (ScrollContentPresenter.MakeVisible can cause an exception when encountering an empty rectangle)
                // New correct behavior
                if (!rectangle.IsEmpty)
                {
                    rectangle.X -= viewport.X;
                    rectangle.Y -= viewport.Y;
                }
            }

            // Return the rectangle
            return(rectangle);
        }
Ejemplo n.º 11
0
        private void UpdateGroupHeaders()
        {
            var firstVisibleItemIndex = this.GetFirstVisibleIndex();

            foreach (var item in visibleGroupHeaders)
            {
                //top header
                if (item.Key.FirstIndex <= firstVisibleItemIndex && (firstVisibleItemIndex <= item.Key.LastIndex || item.Key.LastIndex == -1))
                {
                    item.Value.Visibility = Visibility.Visible;
                    item.Value.Margin     = new Thickness(0);
                    item.Value.Clip       = null;
                    currentTopGroupHeader = item.Value;
                }
                else
                {
                    ListViewItem listViewItem = ContainerFromIndex(item.Key.FirstIndex) as ListViewItem;

                    if (listViewItem == null && item.Key.LastIndex != -1)
                    {
                        listViewItem = ContainerFromIndex(item.Key.LastIndex) as ListViewItem;
                    }
                    if (listViewItem != null)
                    {
                        //handle moving header
                        {
                            //unloaded
                            if (listViewItem.ActualHeight == 0 || listViewItem.ActualWidth == 0)
                            {
                                listViewItem.Loaded += ListViewItem_Loaded;
                            }
                            else
                            {
                                GeneralTransform gt = listViewItem.TransformToVisual(this);
                                var rect            = gt.TransformBounds(new Rect(0, 0, listViewItem.ActualWidth, listViewItem.ActualHeight));
                                groupHeaderDelta = item.Key.Height;
                                //add delta,so that it does not look like suddenly
                                if (rect.Bottom + groupHeaderDelta < 0 || rect.Top > this.ActualHeight + groupHeaderDelta)
                                {
                                    item.Value.Visibility = Visibility.Collapsed;
                                    item.Value.Margin     = new Thickness(0);
                                    item.Value.Clip       = null;
                                }
                                //in view port
                                else
                                {
                                    item.Value.Visibility = Visibility.Visible;
                                    item.Value.Margin     = new Thickness(0, rect.Top - groupHeaderDelta - defaultListViewItemMargin.Top, 0, 0);
                                    if (item.Value.Margin.Top < 0)
                                    {
                                        var clipHeight = groupHeaderDelta + item.Value.Margin.Top;
                                        //moving header has part in viewport
                                        if (clipHeight > 0)
                                        {
                                            item.Value.Clip = new RectangleGeometry()
                                            {
                                                Rect = new Rect(0, -item.Value.Margin.Top, this.ActualWidth, clipHeight)
                                            };
                                        }
                                        //moving header not in viewport
                                        else
                                        {
                                            item.Value.Visibility = Visibility.Collapsed;
                                            item.Value.Clip       = null;
                                        }
                                    }
                                    else if (item.Value.Margin.Top + groupHeaderDelta > this.ActualHeight)
                                    {
                                        var clipHeight = groupHeaderDelta - (groupHeaderDelta + item.Value.Margin.Top - this.ActualHeight);
                                        //moving header has part in viewport
                                        if (clipHeight > 0)
                                        {
                                            item.Value.Clip = new RectangleGeometry()
                                            {
                                                Rect = new Rect(0, 0, this.ActualWidth, clipHeight)
                                            };
                                        }
                                        //moving header not in viewport
                                        else
                                        {
                                            item.Value.Visibility = Visibility.Collapsed;
                                            item.Value.Clip       = null;
                                        }
                                    }
                                    //moving header all in viewport
                                    else
                                    {
                                        item.Value.Clip = null;
                                    }

                                    if (currentTopGroupHeader != null)
                                    {
                                        var delta = currentTopGroupHeader.ActualHeight - (item.Value.Margin.Top);
                                        if (delta > 0)
                                        {
                                            currentTopGroupHeader.Margin = new Thickness(0, -delta, 0, 0);
                                            currentTopGroupHeader.Clip   = new RectangleGeometry()
                                            {
                                                Rect = new Rect(0, delta, currentTopGroupHeader.ActualWidth, currentTopGroupHeader.ActualHeight)
                                            };
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (item.Value != currentTopGroupHeader)
                        {
                            item.Value.Visibility = Visibility.Collapsed;
                            item.Value.Margin     = new Thickness(0);
                            item.Value.Clip       = null;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Draws a mouse cursor on the adorened element
        /// </summary>
        /// <param name="drawingContext"></param>
        protected override void OnRender(DrawingContext drawingContext)
        {
            GeneralTransform inverse = elementTransform.Inverse;

            if (inverse == null)
            {
                return;
            }

            Brush blackBrush = new SolidColorBrush(Colors.Black);

            float radius = 15;

            if (locked)
            {
                // Draw the little circle around the lock point

                Point point = elementTransform.Transform(lockPoint);
                drawingContext.DrawEllipse(null, new Pen(blackBrush, 3), point, 2.5, 2.5);
                drawingContext.DrawEllipse(null, new Pen(new SolidColorBrush(Colors.White), 2), point, 2.5, 2.5);

                // Draw the big yellow circle

                var yellowPen = new Pen(new SolidColorBrush(Colors.Yellow), 2);
                var blackPen  = new Pen(blackBrush, 3);
                drawingContext.DrawEllipse(null, blackPen, mousePoint, radius, radius);
                drawingContext.DrawEllipse(null, yellowPen, mousePoint, radius, radius);
            }
            else
            {
                // Draw the target symbol

                var blackPen = new Pen(blackBrush, .7);
                drawingContext.DrawEllipse(null, blackPen, mousePoint, radius, radius);
                drawingContext.DrawLine(blackPen, new Point(mousePoint.X - radius * 1.6, mousePoint.Y),
                                        new Point(mousePoint.X - 2, mousePoint.Y));
                drawingContext.DrawLine(blackPen, new Point(mousePoint.X + radius * 1.6, mousePoint.Y),
                                        new Point(mousePoint.X + 2, mousePoint.Y));
                drawingContext.DrawLine(blackPen, new Point(mousePoint.X, mousePoint.Y - radius * 1.6),
                                        new Point(mousePoint.X, mousePoint.Y - 2));
                drawingContext.DrawLine(blackPen, new Point(mousePoint.X, mousePoint.Y + radius * 1.6),
                                        new Point(mousePoint.X, mousePoint.Y + 2));
            }

            // Draw the coordinate text

            // Works out the number of decimal places required to show the difference between
            // 2 pixels. E.g if pixels are .1 apart then use 2 places etc
            Rect rect = inverse.TransformBounds(new Rect(0, 0, 1, 1));

            int xFigures = Math.Max(1, (int)(Math.Ceiling(-Math.Log10(rect.Width)) + .1));
            int yFigures = Math.Max(1, (int)(Math.Ceiling(-Math.Log10(rect.Height)) + .1));

            // Number of significant figures for the x coordinate
            string xFormat = "#0." + new string('#', xFigures);
            /// Number of significant figures for the y coordinate
            string yFormat = "#0." + new string('#', yFigures);

            Point coordinate = locked ? lockPoint : inverse.Transform(mousePoint);

            string coordinateText = coordinate.X.ToString(xFormat) + "," + coordinate.Y.ToString(yFormat);

            if (flipYAxis)
            {
                drawingContext.PushTransform(new ScaleTransform(1, 1));
            }
            else
            {
                drawingContext.PushTransform(new ScaleTransform(1, -1));
            }

            var formattedText = new FormattedText(coordinateText, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                                  new Typeface("Arial"), 10, blackBrush);
            var textBoxPen = new Pen(new SolidColorBrush(Color.FromArgb(127, 255, 255, 255)), 1);

            Rect textBoxRect = flipYAxis
                                   ?
                               new Rect(new Point(mousePoint.X + radius * .7, mousePoint.Y + radius * .7),
                                        new Size(formattedText.Width, formattedText.Height))
                                   :
                               new Rect(new Point(mousePoint.X + radius * .7, -mousePoint.Y + radius * .7),
                                        new Size(formattedText.Width, formattedText.Height));

            double diff = textBoxRect.Right + 3 - ((FrameworkElement)AdornedElement).ActualWidth;

            if (diff > 0)
            {
                textBoxRect.Location = new Point(textBoxRect.Left - diff, textBoxRect.Top);
            }

            drawingContext.DrawRectangle(textBoxPen.Brush, textBoxPen, textBoxRect);
            drawingContext.DrawText(formattedText, textBoxRect.Location);
            drawingContext.Pop();
        }
Ejemplo n.º 13
0
        internal void RenderFixedNode(DrawingContext dc)
        {
            //
            //Iterate through fix node to draw red dotted line
            //
            CultureInfo EnglishCulture = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;

            int lineCount = _lineResults.Length;

            if (lineCount == 0)
            {
                return;
            }

            FixedNode fixedStartPage = _lineResults[0].Start;
            FixedNode fixedEndPage   = _lineResults[lineCount - 1].End;

            FixedNode[]   fixedNodes = _fixedTextBuilder.FixedFlowMap.FixedOrderGetRangeNodes(fixedStartPage, fixedEndPage);
            FixedPage     fp         = _fixedTextBuilder.FixedTextContainer.FixedDocument.GetFixedPage(PageIndex);
            FormattedText ft;
            Point         prevTextPoint = new Point(0, 0);
            DpiScale      dpi           = fp.GetDpi();

            foreach (FixedNode currentFixedNode in fixedNodes)
            {
                if (currentFixedNode.Page == FixedFlowMap.FixedOrderStartPage)
                {
                    prevTextPoint.X = prevTextPoint.Y = 0;
                    ft = new FormattedText("FixedOrderStartPage",
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkViolet,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);
                    continue;
                }
                if (currentFixedNode.Page == FixedFlowMap.FixedOrderEndPage)
                {
                    prevTextPoint.X = fp.Width - 100;
                    prevTextPoint.Y = fp.Height - 10;
                    ft = new FormattedText("FixedOrderEndPage",
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkViolet,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);
                    continue;
                }
                if (currentFixedNode[1] == FixedFlowMap.FixedOrderStartVisual ||
                    currentFixedNode[1] == FixedFlowMap.FixedOrderEndVisual)
                {
                    prevTextPoint.X = 2;
                    prevTextPoint.Y = prevTextPoint.Y + 10;
                    String outputString = currentFixedNode[1] == FixedFlowMap.FixedOrderStartVisual ?
                                          "FixedOrderStartVisual" : "FixedOrderEndVisual";
                    ft = new FormattedText(outputString,
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkViolet,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);
                    continue;
                }

                DependencyObject dependencyObject = fp.GetElement(currentFixedNode);

                Image image = dependencyObject as Image;
                if (image != null)
                {
                    GeneralTransform transform = image.TransformToAncestor(fp);
                    // You can't use GetContentBounds inside OnRender
                    Rect boundingRect = new Rect(0, 0, image.Width, image.Height);
                    Rect imageRect    = transform.TransformBounds(boundingRect);

                    if (!imageRect.IsEmpty)
                    {
                        // Image might overlap, inflate the box.
                        imageRect.Inflate(1, 1);

                        Pen pen = new Pen(Brushes.DarkMagenta, 1.5);
                        DrawRectOutline(dc, pen, imageRect);

                        prevTextPoint.X = imageRect.Right;
                        prevTextPoint.Y = imageRect.Bottom - 10;
                    }
                    else
                    {
                        prevTextPoint.X = 2;
                        prevTextPoint.Y = prevTextPoint.Y + 10;
                    }
                    ft = new FormattedText(currentFixedNode.ToString(),
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkViolet,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);
                    continue;
                }
                Path path = dependencyObject as Path;
                if (path != null)
                {
                    GeneralTransform transform = path.TransformToAncestor(fp);
                    // You can't use GetContentBounds inside OnRender
                    Rect boundingRect = path.Data.Bounds;
                    Rect imageRect    = transform.TransformBounds(boundingRect);

                    if (!imageRect.IsEmpty)
                    {
                        // Image might overlap, inflate the box.
                        imageRect.Inflate(1, 1);

                        Pen pen = new Pen(Brushes.DarkMagenta, 1.5);
                        DrawRectOutline(dc, pen, imageRect);

                        prevTextPoint.X = imageRect.Right;
                        prevTextPoint.Y = imageRect.Bottom - 10;
                    }
                    else
                    {
                        prevTextPoint.X = 2;
                        prevTextPoint.Y = prevTextPoint.Y + 10;
                    }
                    ft = new FormattedText(currentFixedNode.ToString(),
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkViolet,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);
                    continue;
                }
                Glyphs glyphs = dependencyObject as Glyphs;
                if (glyphs != null)
                {
                    GlyphRun run = glyphs.ToGlyphRun();
                    if (run != null)
                    {
                        Rect glyphBox = run.ComputeAlignmentBox();
                        glyphBox.Offset(glyphs.OriginX, glyphs.OriginY);
                        GeneralTransform transform = glyphs.TransformToAncestor(fp);
                        //
                        // Draw it using the dotted red line
                        //
                        Pen       pen = new Pen(Brushes.Red, 0.5);
                        Transform t   = transform.AffineTransform;
                        if (t != null)
                        {
                            dc.PushTransform(t);
                        }
                        else
                        {
                            dc.PushTransform(Transform.Identity);
                        }
                        DrawRectOutline(dc, pen, glyphBox);

                        prevTextPoint.X = glyphBox.Right;
                        prevTextPoint.Y = glyphBox.Bottom;
                        transform.TryTransform(prevTextPoint, out prevTextPoint);
                        dc.Pop(); // transform
                    }
                    else
                    {
                        prevTextPoint.X = 2;
                        prevTextPoint.Y = prevTextPoint.Y + 10;
                    }

                    ft = new FormattedText(currentFixedNode.ToString(),
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkViolet,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);
                    continue;
                }

                //
                // For anything else, there is this code to draw ...
                //
                prevTextPoint.X = 2;
                prevTextPoint.Y = prevTextPoint.Y + 10;
                ft = new FormattedText(currentFixedNode.ToString(),
                                       EnglishCulture,
                                       FlowDirection.LeftToRight,
                                       new Typeface("Courier New"),
                                       8,
                                       Brushes.DarkViolet,
                                       dpi.PixelsPerDip);
                dc.DrawText(ft, prevTextPoint);
            }
        }
Ejemplo n.º 14
0
        private Drawing PerformHitTest(Rect rect, IntersectionDetail detail)
        {
            if (_svgDrawing == null)
            {
                return(null);
            }

            var rectDisplay = _displayTransform.TransformBounds(rect);
            var geomDisplay = new RectangleGeometry(rectDisplay);

            DrawingGroup    groupDrawing    = null;
            GlyphRunDrawing glyRunDrawing   = null;
            GeometryDrawing geometryDrawing = null;

            Drawing foundDrawing = null;

            DrawingCollection drawings = _svgDrawing.Children;

            for (int i = drawings.Count - 1; i >= 0; i--)
            {
                Drawing drawing = drawings[i];
                if (TryCast.Cast(drawing, out geometryDrawing))
                {
                    if (HitTestDrawing(geometryDrawing, geomDisplay, detail))
                    {
                        string uniqueId = SvgObject.GetUniqueId(drawing);
                        if (!string.IsNullOrWhiteSpace(uniqueId))
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out groupDrawing))
                {
                    if (SvgObject.GetType(groupDrawing) == SvgObjectType.Text)
                    {
                        var textBounds = new RectangleGeometry(groupDrawing.Bounds);
                        if (textBounds.FillContainsWithDetail(geomDisplay) == detail)
                        {
                            string uniqueId = SvgObject.GetUniqueId(drawing);
                            if (!string.IsNullOrWhiteSpace(uniqueId))
                            {
                                foundDrawing = drawing;
                                break;
                            }
                        }
                    }
                    if (HitTestDrawing(groupDrawing, geomDisplay, out foundDrawing, detail))
                    {
                        string uniqueId = SvgObject.GetUniqueId(drawing);
                        if (!string.IsNullOrWhiteSpace(uniqueId))
                        {
                            foundDrawing = drawing;
                            break;
                        }
                    }
                }
                else if (TryCast.Cast(drawing, out glyRunDrawing))
                {
                    if (HitTestDrawing(glyRunDrawing, geomDisplay, detail))
                    {
                        foundDrawing = drawing;
                        break;
                    }
                }
            }

            return(foundDrawing);
        }
Ejemplo n.º 15
0
        public static Rect GetRelativeElementRect(UIElement element, UIElement parent)
        {
            GeneralTransform transform = element.TransformToVisual(parent);

            return(transform.TransformBounds(new Rect(new Point(), element.RenderSize)));
        }
Ejemplo n.º 16
0
        private System.Windows.Rect GetChildRectangle(UIElement uieChild)
        {
            GeneralTransform generalTransform = uieChild.TransformToAncestor(this.ScrollOwner);

            return(generalTransform.TransformBounds(new System.Windows.Rect(new System.Windows.Point(0.0, 0.0), uieChild.RenderSize)));
        }
Ejemplo n.º 17
0
        private void _outerScrollViewer_ViewChanging(object sender, ScrollViewerViewChangingEventArgs e)
        {
            GeneralTransform gt = this.TransformToVisual(OuterScrollViewer);
            var rect            = gt.TransformBounds(new Rect(0, 0, this.ActualWidth, this.ActualHeight));

            //add delta,so that it does not look like suddenly
            if (rect.Bottom < 0 || rect.Top > OuterScrollViewer.ActualHeight)
            {
                //r.Row = Rows.GetItemAt(fy - scrollPosition.Y);
                //r.Row2 = Math.Min(Rows.GetItemAt(sz.Height - scrollPosition.Y), Rows.Count - 1);
            }
            //in view port
            else
            {
                var update = false;
                if (preview != null)
                {
                    if (OuterScrollViewerVerticalScrollEnable && OuterScrollViewerHorizontalScrollEnable)
                    {
                        update = (preview.VerticalOffset != e.NextView.VerticalOffset || preview.HorizontalOffset != e.NextView.HorizontalOffset);
                    }
                    else if (OuterScrollViewerVerticalScrollEnable)
                    {
                        update = preview.VerticalOffset != e.NextView.VerticalOffset;
                    }
                    else if (OuterScrollViewerHorizontalScrollEnable)
                    {
                        update = preview.HorizontalOffset != e.NextView.HorizontalOffset;
                    }

                    if (update)
                    {
                        var sz = _cellPanel.DesiredSize;
                        // find top/bottom rows
                        var r = new CellRange(Rows.Frozen, Columns.Frozen);
                        if (OuterScrollViewerVerticalScrollEnable)
                        {
                            sz.Height = OuterScrollViewer.ActualHeight * 1.5;
                            var y = HeaderActualHeight - OuterScrollViewer.VerticalOffset;
                            y     += topToOuterScrollViewer;
                            r.Row  = Rows.GetItemAt(-y - OuterScrollViewer.ActualHeight);
                            r.Row2 = Math.Min(Rows.GetItemAt(sz.Height - y), Rows.Count - 1);
                        }

                        if (OuterScrollViewerHorizontalScrollEnable)
                        {
                            sz.Width = OuterScrollViewer.ActualWidth * 1.5;
                            var x = -OuterScrollViewer.HorizontalOffset;
                            r.Column  = Columns.GetItemAt(-x - OuterScrollViewer.ActualWidth);
                            r.Column2 = Math.Min(Columns.GetItemAt(sz.Width - x), Columns.Count - 1);
                        }


                        if (_cellPanel.ViewRange != r)
                        {
                            _cellPanel.UpdateViewRange(r);
                        }
                        if (_columnHeaderPanel.ViewRange.Column != r.Column || _columnHeaderPanel.ViewRange.Column2 != r.Column2)
                        {
                            _columnHeaderPanel.UpdateViewRange(r);
                        }
                    }
                }
                preview = e.NextView;
            }
        }
Ejemplo n.º 18
0
        private void _UpdateHighlightBackground(DrawingContext dc, ArrayList highlights)
        {
            Debug.Assert(highlights != null);

            PathGeometry highlightGeometry = null;
            Brush        highlightBrush    = null;

            Rect combinedRect = Rect.Empty;

            foreach (FixedHighlight fh in highlights)
            {
                Brush bg = null;

                if (fh.HighlightType == FixedHighlightType.None)
                {
#if NEVER
                    // use this code if you want to see unrecognized highlights
                    bg = Brushes.Yellow;
#else
                    continue;
#endif
                }

                Rect backgroundRect = fh.ComputeDesignRect();

                if (backgroundRect == Rect.Empty)
                {
                    continue;
                }

                GeneralTransform transform = fh.Element.TransformToAncestor(_page);
                // This is a workaround. We should really look into changing
                Transform t = transform.AffineTransform;
                if (t == null)
                {
                    t = Transform.Identity;
                }

                // Inflate by 1 pixel on each side to have a better selection visual for continuous lines
                // backgroundRect.Inflate(1,1);

                Glyphs g = fh.Glyphs;

                if (fh.HighlightType == FixedHighlightType.TextSelection)
                {
                    bg = (g == null) ? SelectionHighlightInfo.ObjectMaskBrush : SelectionHighlightInfo.BackgroundBrush;
                }
                else if (fh.HighlightType == FixedHighlightType.AnnotationHighlight)
                {
                    bg = fh.BackgroundBrush;
                }



                // can add cases for new types of highlights
                if (fh.Element.Clip != null)
                {
                    Rect clipRect = fh.Element.Clip.Bounds;
                    backgroundRect.Intersect(clipRect);
                    //thisGeometry = Geometry.Combine(thisGeometry, fh.Element.Clip, GeometryCombineMode.Intersect, t);
                }

                Geometry thisGeometry = new RectangleGeometry(backgroundRect);
                thisGeometry.Transform = t;

                backgroundRect = transform.TransformBounds(backgroundRect);


                // used to cut down on calls to Geometry.Combine for complex geometries
                // involving multiple non-intersecting paths

                Debug.Assert(bg != null);
                if (bg != highlightBrush || backgroundRect.Top > combinedRect.Bottom + .1 || backgroundRect.Bottom + .1 < combinedRect.Top ||
                    backgroundRect.Left > combinedRect.Right + .1 || backgroundRect.Right + .1 < combinedRect.Left)
                {
                    if (highlightBrush != null)
                    {
                        Debug.Assert(highlightGeometry != null);
                        highlightGeometry.FillRule = FillRule.Nonzero;
                        dc.DrawGeometry(highlightBrush, null, highlightGeometry);
                    }
                    highlightBrush    = bg;
                    highlightGeometry = new PathGeometry();
                    highlightGeometry.AddGeometry(thisGeometry);
                    combinedRect = backgroundRect;
                }
                else
                {
                    highlightGeometry.AddGeometry(thisGeometry);
                    combinedRect.Union(backgroundRect);
                }
            }

            if (highlightBrush != null)
            {
                Debug.Assert(highlightGeometry != null);
                highlightGeometry.FillRule = FillRule.Nonzero;
                dc.DrawGeometry(highlightBrush, null, highlightGeometry);
            }
        }
Ejemplo n.º 19
0
        protected void BringCardIntoView(Card card)
        {
            // Get the current target viewport (bypass animations in progress)
            GeneralTransform transform     = TransformToDescendant(cardsView);
            Rect             visibleBounds = transform.TransformBounds(new Rect(0, 0, ActualWidth, ActualHeight));

            var cardRect = new Rect(card.X, card.Y, Program.GameEngine.Definition.CardWidth,
                                    Program.GameEngine.Definition.CardHeight);

            if (visibleBounds.Contains(cardRect))
            {
                return;                                   // okay, already completely into view
            }
            // Compute the new table bounds
            Rect newBounds = visibleBounds;

            if (cardRect.Left < visibleBounds.Left)
            {
                newBounds.X = cardRect.Left;
            }
            newBounds.Width = Math.Max(visibleBounds.Right, cardRect.Right) - newBounds.Left;
            if (cardRect.Top < visibleBounds.Top)
            {
                newBounds.Y = cardRect.Top;
            }
            newBounds.Height = Math.Max(visibleBounds.Bottom, cardRect.Bottom) - newBounds.Top;

            if (Player.LocalPlayer.InvertedTable)
            {
                // Transform the viewport so that it will fit correctly after the invert transform is applied
                newBounds.X = -newBounds.Right;
                newBounds.Y = -newBounds.Bottom;
            }

            // Compute the zoom and offset corresponding to the new view
            double newZoom = Math.Min(
                (Program.GameEngine.Table.Definition.Width + 2 * _stretchMargins.Width) / newBounds.Width,
                (Program.GameEngine.Table.Definition.Height + 2 * _stretchMargins.Height) / newBounds.Height);
            var newOffset = new Vector(
                -_stretchMargins.Width - newBounds.X * newZoom,
                -_stretchMargins.Height - newBounds.Y * newZoom);

            // Combine new values with the current ones
            // (bypassing animations, e.g. when moving several cards outside the bounds at the same time
            var realZoom = (double)GetAnimationBaseValue(ZoomProperty);

            //var realOffset = (Vector)GetAnimationBaseValue(OffsetProperty);
            if (newZoom > realZoom)
            {
                newZoom = realZoom;
            }
            //if (newOffset.X < realOffset.X) newOffset.X = realOffset.X;
            //if (newOffset.Y < realOffset.Y) newOffset.Y = realOffset.Y;

            double oldZoom   = Zoom;
            Vector oldOffset = Offset;

            Zoom   = newZoom;
            Offset = newOffset;
            // Animate the table with the result
            AnimationTimeline anim = new DoubleAnimation
            {
                From         = oldZoom,
                To           = newZoom,
                Duration     = TimeSpan.FromMilliseconds(150),
                FillBehavior = FillBehavior.Stop
            };

            BeginAnimation(ZoomProperty, anim);
            anim = new VectorAnimation
            {
                From         = oldOffset,
                To           = newOffset,
                Duration     = TimeSpan.FromMilliseconds(150),
                FillBehavior = FillBehavior.Stop
            };
            BeginAnimation(OffsetProperty, anim);

            // Note: the new visibleBounds may end up bigger than newBounds,
            // because the window aspect ratio may be different
        }
Ejemplo n.º 20
0
        //------------------------------------------------------
        //
        //  Protected Methods
        //
        //------------------------------------------------------

        #region Protected Methods

        /// <summary>
        /// Render override to render the composition adorner here.
        /// </summary>
        protected override void OnRender(DrawingContext drawingContext)
        {
            // Get the matrix from AdornedElement to the visual parent to get the transformed
            // start/end point
            Visual parent2d = VisualTreeHelper.GetParent(this.AdornedElement) as Visual;

            if (parent2d == null)
            {
                return;
            }

            GeneralTransform transform = AdornedElement.TransformToAncestor(parent2d);

            if (transform == null)
            {
                return;
            }

            // Please note that we do the highlight adornment for the CONVERTED text only
            // for Simplified Chinese IMEs. Doing this uniformly across all IMEs wasnt possible
            // because it was noted that some of them (viz. Japanese) werent being consistent
            // about this attribute.

            bool isChinesePinyin = chinesePinyin.Equals(InputLanguageManager.Current.CurrentInputLanguage.IetfLanguageTag);

            // Render the each of the composition string attribute from the attribute ranges.
            for (int i = 0; i < _attributeRanges.Count; i++)
            {
                DoubleCollection dashArray;

                // Get the composition attribute range from the attribute range lists
                AttributeRange attributeRange = (AttributeRange)_attributeRanges[i];

                // Skip the rendering composition lines if the composition line doesn't exist.
                if (attributeRange.CompositionLines.Count == 0)
                {
                    continue;
                }

                // Set the line bold and squiggle
                bool lineBold            = attributeRange.TextServicesDisplayAttribute.IsBoldLine ? true : false;
                bool squiggle            = false;
                bool hasVirtualSelection = (attributeRange.TextServicesDisplayAttribute.AttrInfo & UnsafeNativeMethods.TF_DA_ATTR_INFO.TF_ATTR_TARGET_CONVERTED) != 0;

                Brush  selectionBrush   = null;
                double selectionOpacity = -1;
                Pen    selectionPen     = null;

                if (isChinesePinyin && hasVirtualSelection)
                {
                    DependencyObject owner = _textView.TextContainer.Parent;
                    selectionBrush   = (Brush)owner.GetValue(TextBoxBase.SelectionBrushProperty);
                    selectionOpacity = (double)owner.GetValue(TextBoxBase.SelectionOpacityProperty);
                }

                // Set the line height and cluse gap value that base on the ratio of text height
                double height     = attributeRange.Height;
                double lineHeight = height * (lineBold ? BoldLineHeightRatio : NormalLineHeightRatio);
                double clauseGap  = height * ClauseGapRatio;

                // Create Pen for drawing the composition lines with the specified line color
                Pen pen = new Pen(new SolidColorBrush(Colors.Black), lineHeight);

                // Set the pen style that based on IME's composition line style
                switch (attributeRange.TextServicesDisplayAttribute.LineStyle)
                {
                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DOT:
                    // Add the dot length and specify the start/end line cap as the round
                    dashArray = new DoubleCollection();
                    dashArray.Add(DotLength);
                    dashArray.Add(DotLength);

                    pen.DashStyle    = new DashStyle(dashArray, 0);
                    pen.DashCap      = System.Windows.Media.PenLineCap.Round;
                    pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
                    pen.EndLineCap   = System.Windows.Media.PenLineCap.Round;

                    // Update the line height for the dot line. Dot line will be more thickness than
                    // other line to show it clearly.
                    lineHeight = height * (lineBold ? BoldDotLineHeightRatio : NormalDotLineHeightRatio);

                    break;

                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DASH:
                    double dashLength    = height * (lineBold ? BoldDashRatio : NormalDashRatio);
                    double dashGapLength = height * (lineBold ? BoldDashGapRatio : NormalDashGapRatio);

                    // Add the dash and dash gap legth
                    dashArray = new DoubleCollection();
                    dashArray.Add(dashLength);
                    dashArray.Add(dashGapLength);

                    pen.DashStyle    = new DashStyle(dashArray, 0);
                    pen.DashCap      = System.Windows.Media.PenLineCap.Round;
                    pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
                    pen.EndLineCap   = System.Windows.Media.PenLineCap.Round;

                    break;

                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SOLID:
                    pen.StartLineCap = System.Windows.Media.PenLineCap.Round;
                    pen.EndLineCap   = System.Windows.Media.PenLineCap.Round;

                    break;

                case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SQUIGGLE:
                    squiggle = true;
                    break;
                }

                double halfLineHeight = lineHeight / 2;

                // Draw the each of the composition line
                for (int j = 0; j < attributeRange.CompositionLines.Count; j++)
                {
                    CompositionLine compositionLine = (CompositionLine)attributeRange.CompositionLines[j];

                    // Get the start/end point for composition adorner.
                    // Currently Text doesn't aware of the spaceroom for the drawing of the composition
                    // adorner(like as normal/bold dot/line/squggle), so we should draw the composition adorners
                    // to the closest area of the bottom text.
                    Point startPoint = new Point(compositionLine.StartPoint.X + clauseGap, compositionLine.StartPoint.Y - halfLineHeight);
                    Point endPoint   = new Point(compositionLine.EndPoint.X - clauseGap, compositionLine.EndPoint.Y - halfLineHeight);

                    // Apply composition line color which is actually the foreground of text as well
                    pen.Brush = new SolidColorBrush(compositionLine.LineColor);

                    // Apply matrix to start/end point
                    //
                    transform.TryTransform(startPoint, out startPoint);
                    transform.TryTransform(endPoint, out endPoint);

                    if (isChinesePinyin && hasVirtualSelection)
                    {
                        Rect rect = Rect.Union(compositionLine.StartRect, compositionLine.EndRect);
                        rect = transform.TransformBounds(rect);

                        drawingContext.PushOpacity(selectionOpacity);

                        drawingContext.DrawRectangle(selectionBrush, selectionPen, rect);

                        drawingContext.Pop();
                    }

                    if (squiggle)
                    {
                        // Draw the squiggle line with using of the PathFigure and DrawGemetry.
                        // We may revisit this logic to render the smooth squiggle line.
                        Point pathPoint = new Point(startPoint.X, startPoint.Y - halfLineHeight);

                        double squiggleGap = halfLineHeight;

                        PathFigure pathFigure = new PathFigure();
                        pathFigure.StartPoint = pathPoint;

                        int indexPoint = 0;

                        while (indexPoint < ((endPoint.X - startPoint.X) / (squiggleGap)))
                        {
                            if (indexPoint % 4 == 0 || indexPoint % 4 == 3)
                            {
                                pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y + halfLineHeight);
                                pathFigure.Segments.Add(new LineSegment(pathPoint, true));
                            }
                            else if (indexPoint % 4 == 1 || indexPoint % 4 == 2)
                            {
                                pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y - halfLineHeight);
                                pathFigure.Segments.Add(new LineSegment(pathPoint, true));
                            }

                            indexPoint++;
                        }

                        PathGeometry pathGeometry = new PathGeometry();
                        pathGeometry.Figures.Add(pathFigure);

                        // Draw the composition line with the squiggle
                        drawingContext.DrawGeometry(null, pen, pathGeometry);
                    }
                    else
                    {
                        drawingContext.DrawLine(pen, startPoint, endPoint);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public Rect GetBounds(FrameworkElement childElement, FrameworkElement parentElement)
        {
            GeneralTransform transform = childElement.TransformToVisual(parentElement);

            return(transform.TransformBounds(new Rect(0, 0, childElement.ActualWidth, childElement.ActualHeight)));
        }
        public void BuildStoryboardForElement(Storyboard storyboard, UIElement element)
        {
            storyboard.Duration = transitionDuration;

            List <UIElement> elements = new List <UIElement>();

            ItemTurnstileHelper.GetTurnstileElements(element, XMode, ref elements);

            for (int i = 0; i < elements.Count; i++)
            {
                UIElement child = elements[i];

                if (child.Projection == null)
                {
                    child.Projection = new PlaneProjection();
                }

                GeneralTransform childTransform = child.TransformToVisual(element);
                Point            point          = childTransform.Transform(new Point(0, 0));
                Rect             rectangle      = childTransform.TransformBounds(new Rect(new Point(0, 0), child.RenderSize));

                //Check if the elements Rect intersects with that of the scrollviewer's
                rectangle.Intersect(new Rect(new Point(0, 0), element.RenderSize));

                //if result is Empty then the element is not in view
                if (rectangle == Rect.Empty)
                {
                    continue;
                }
                else
                {
                    TimeSpan animationStart = TimeSpan.Zero;
                    TimeSpan animationEnd   = TimeSpan.Zero;

                    switch (XMode)
                    {
                    case ItemTurnstileXMode.BackwardIn:
                    case ItemTurnstileXMode.ForwardIn:
                        animationEnd   = GetAnimationStart(element, elements[i], point.Y, point.X);
                        animationStart = animationEnd.Subtract(individualTransitionDuration) < TimeSpan.Zero ? TimeSpan.Zero : animationEnd.Subtract(individualTransitionDuration);
                        break;

                    case ItemTurnstileXMode.BackwardOut:
                    case ItemTurnstileXMode.ForwardOut:
                        animationStart = GetAnimationStart(element, elements[i], point.Y, point.X);
                        animationEnd   = animationStart.Add(individualTransitionDuration);
                        break;
                    }

                    var rotationY = GetRotationY(animationStart, animationEnd);
                    Storyboard.SetTarget(rotationY, child);
                    storyboard.Children.Add(rotationY);

                    var rotationZ = GetRotationZ(animationStart, animationEnd);
                    Storyboard.SetTarget(rotationZ, child);
                    storyboard.Children.Add(rotationZ);

                    var fade = GetFade(animationStart, animationEnd);
                    Storyboard.SetTarget(fade, child);
                    storyboard.Children.Add(fade);

                    var centerX = GetCenterX(child, point);
                    Storyboard.SetTarget(centerX, child);
                    storyboard.Children.Add(centerX);
                }
            }
        }
Ejemplo n.º 23
0
        internal void RenderFlowNode(DrawingContext dc)
        {
            FormattedText ft;
            FixedNode     fixedNode;

            FixedSOMElement[] somElements;
            String            ouptputString;
            FixedElement      fixedElement;
            Random            random = new Random();

            CultureInfo EnglishCulture = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;

            FixedPage fp = _fixedTextBuilder.FixedTextContainer.FixedDocument.GetFixedPage(PageIndex);
            //
            //Iterate through flow node to draw Transparent Rect and draw its index
            //
            Point    prevTextPoint = new Point(0, 0);
            DpiScale dpi           = fp.GetDpi();

            for (int i = FlowStart.Fp; i <= FlowEnd.Fp; i++)
            {
                FlowNode fn = _fixedTextBuilder.FixedFlowMap[i];
                switch (fn.Type)
                {
                case FlowNodeType.Boundary:
                case FlowNodeType.Virtual:
                    // this two cases won't happen.
                    Debug.Assert(false);
                    break;

                case FlowNodeType.Start:
                case FlowNodeType.End:
                {
                    fixedElement = fn.Cookie as FixedElement;
                    String typeString = fixedElement.Type.ToString();
                    int    indexofDot = typeString.LastIndexOf('.');
                    ouptputString = String.Format("{0}-{1}",
                                                  fn.ToString(),
                                                  typeString.Substring(indexofDot + 1));

                    ft = new FormattedText(ouptputString,
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkGreen,
                                           dpi.PixelsPerDip);
                    // Ideally, for FlowNodeType.Start, this should find next FlowNode with physical location,
                    // and draw it around the physical location.
                    prevTextPoint = CreateFromLastTextPoint(prevTextPoint);

                    dc.DrawText(ft, prevTextPoint);
                    break;
                }

                case FlowNodeType.Noop:
                    ft = new FormattedText(fn.ToString(),
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkGreen,
                                           dpi.PixelsPerDip);
                    prevTextPoint = CreateFromLastTextPoint(prevTextPoint);
                    dc.DrawText(ft, prevTextPoint);
                    break;

                case FlowNodeType.Run:
                    //
                    // Paint the region. The rect is the union of child glyphs.
                    //

                    Glyphs glyphs;
                    Rect   flowRunBox = Rect.Empty;
                    Rect   glyphBox;
                    somElements = _fixedTextBuilder.FixedFlowMap.FlowNodes[fn.Fp].FixedSOMElements;

                    foreach (FixedSOMElement currentSomeElement in somElements)
                    {
                        FixedNode currentFixedNode = currentSomeElement.FixedNode;
                        int       startIndex       = currentSomeElement.StartIndex;
                        int       endIndex         = currentSomeElement.EndIndex;

                        // same as (_IsBoundaryFixedNode(currentFixedNode))
                        if (currentFixedNode.Page == FixedFlowMap.FixedOrderStartPage ||
                            currentFixedNode.Page == FixedFlowMap.FixedOrderEndPage ||
                            currentFixedNode[1] == FixedFlowMap.FixedOrderStartVisual ||
                            currentFixedNode[1] == FixedFlowMap.FixedOrderEndVisual)
                        {
                            continue;
                        }

                        glyphs = fp.GetGlyphsElement(currentFixedNode);
                        Debug.Assert(glyphs != null);

                        glyphBox = FixedTextView._GetGlyphRunDesignRect(glyphs, startIndex, endIndex);
                        if (!glyphBox.IsEmpty)
                        {
                            GeneralTransform g = glyphs.TransformToAncestor(fp);

                            glyphBox = g.TransformBounds(glyphBox);
                        }

                        flowRunBox.Union(glyphBox);
                    }

                    if (flowRunBox.IsEmpty)
                    {
                        Debug.Assert(false);
                    }
                    prevTextPoint.X = flowRunBox.Right;
                    prevTextPoint.Y = flowRunBox.Bottom - random.Next(15);

                    // Draw something the upper left corner of region.
                    ft = new FormattedText(fn.ToString() + "-" + Convert.ToString((int)(fn.Cookie)) +
                                           "-" + Convert.ToString(somElements.Length),
                                           EnglishCulture,
                                           FlowDirection.LeftToRight,
                                           new Typeface("Courier New"),
                                           8,
                                           Brushes.DarkBlue,
                                           dpi.PixelsPerDip);
                    dc.DrawText(ft, prevTextPoint);

                    Pen pen = new Pen(Brushes.Blue, 2);
                    flowRunBox.Inflate(random.Next(3), random.Next(3));
                    DrawRectOutline(dc, pen, flowRunBox);
                    break;

                case FlowNodeType.Object:
                    //
                    // Find the mapping fixed node
                    //
                    somElements = _fixedTextBuilder.FixedFlowMap.FlowNodes[fn.Fp].FixedSOMElements;

                    foreach (FixedSOMElement currentSomeElement in somElements)
                    {
                        fixedNode = currentSomeElement.FixedNode;

                        DependencyObject dependencyObject = fp.GetElement(fixedNode);

                        Image image = dependencyObject as Image;
                        Path  path  = dependencyObject as Path;

                        if (image != null || path != null)
                        {
                            Rect imageRect, boundingRect = Rect.Empty;
                            //
                            // Get Image bounding box.
                            //
                            GeneralTransform transform = ((Visual)dependencyObject).TransformToAncestor(fp);
                            // You can't use GetContentBounds inside OnRender
                            if (image != null)
                            {
                                boundingRect = new Rect(0, 0, image.Width, image.Height);
                            }
                            else
                            {
                                boundingRect = path.Data.Bounds;
                            }

                            if (!boundingRect.IsEmpty)
                            {
                                imageRect = transform.TransformBounds(boundingRect);

                                // Image might overlap, inflate the box.
                                imageRect.Inflate(3, 3);
                                dc.DrawRectangle(Brushes.CadetBlue, null, imageRect);

                                prevTextPoint.X = imageRect.Right;
                                prevTextPoint.Y = imageRect.Top;
                            }
                        }
                        else
                        {
                            //
                            // If the object is the Image type(that is not likey).
                            // Use the last Point to infer a comment area!
                            //
                            Debug.Assert(false);
                        }

                        fixedElement = fn.Cookie as FixedElement;
                        ft           = new FormattedText(fn.ToString(),
                                                         EnglishCulture,
                                                         FlowDirection.LeftToRight,
                                                         new Typeface("Courier New"),
                                                         8,
                                                         Brushes.DarkGreen,
                                                         dpi.PixelsPerDip);
                        dc.DrawText(ft, prevTextPoint);
                    }

                    break;

                default:
                    Debug.Assert(false);
                    break;
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This helper method is used by TextRangeAdaptor to bring the range into view
        /// through multiple nested scroll providers.
        /// </summary>
        internal void ScrollIntoView(ITextPointer start, ITextPointer end, bool alignToTop)
        {
            // Calculate the bounding rectangle for the range
            Rect rangeBounds = Rect.Empty;

            Rect[] lineBounds = GetBoundingRectangles(start, end, false, false);
            foreach (Rect rect in lineBounds)
            {
                rangeBounds.Union(rect);
            }

            ITextView textView = GetUpdatedTextView();

            if (textView != null && !rangeBounds.IsEmpty)
            {
                // Find out the visible portion of the range.
                Rect visibleRect        = GetVisibleRectangle(textView);
                Rect rangeVisibleBounds = Rect.Intersect(rangeBounds, visibleRect);
                if (rangeVisibleBounds == rangeBounds)
                {
                    // The range is already in the view. It's probably not aligned as requested,
                    // but who cares since it's entirely visible anyway.
                    return;
                }

                // Ensure the visibility of the range.
                // BringIntoView will do most of the magic except the very first scroll
                // in order to satisfy the requested alignment.
                UIElement renderScope = textView.RenderScope;
                Visual    visual      = renderScope;
                while (visual != null)
                {
                    IScrollInfo isi = visual as IScrollInfo;
                    if (isi != null)
                    {
                        // Transform the bounding rectangle into the IScrollInfo coordinates.
                        if (visual != renderScope)
                        {
                            GeneralTransform childToParent = renderScope.TransformToAncestor(visual);
                            rangeBounds = childToParent.TransformBounds(rangeBounds);
                        }

                        if (isi.CanHorizontallyScroll)
                        {
                            isi.SetHorizontalOffset(alignToTop ? rangeBounds.Left : (rangeBounds.Right - isi.ViewportWidth));
                        }
                        if (isi.CanVerticallyScroll)
                        {
                            isi.SetVerticalOffset(alignToTop ? rangeBounds.Top : (rangeBounds.Bottom - isi.ViewportHeight));
                        }
                        break;
                    }
                    visual = VisualTreeHelper.GetParent(visual) as Visual;
                }

                FrameworkElement fe = renderScope as FrameworkElement;
                if (fe != null)
                {
                    fe.BringIntoView(rangeVisibleBounds);
                }
            }
            else
            {
                // If failed to retrive range bounds, try to Bring into view closes element.
                ITextPointer pointer = alignToTop ? start.CreatePointer() : end.CreatePointer();
                pointer.MoveToElementEdge(alignToTop ? ElementEdge.AfterStart : ElementEdge.AfterEnd);
                FrameworkContentElement element = pointer.GetAdjacentElement(LogicalDirection.Backward) as FrameworkContentElement;
                if (element != null)
                {
                    element.BringIntoView();
                }
            }
        }
Ejemplo n.º 25
0
        //--------------------------------------------------------------------
        //
        // Constructors
        //
        //---------------------------------------------------------------------

        #region Constructors

        private FixedSOMTextRun(Rect boundingRect, GeneralTransform trans, FixedNode fixedNode, int startIndex, int endIndex) : base(fixedNode, startIndex, endIndex, trans)
        {
            _boundingRect = trans.TransformBounds(boundingRect);
        }
Ejemplo n.º 26
0
        private void UpdateGroupHeaders()
        {
            if (groupCollection != null)
            {
                var firstVisibleItemIndex = this.GetFirstVisibleIndex();
                if (firstVisibleItemIndex < 0)
                {
                    return;
                }
                foreach (var item in groupCollection.GroupHeaders)
                {
                    if (item.FirstIndex == -1)
                    {
                        continue;
                    }
                    if (item.FirstIndex <= firstVisibleItemIndex && (firstVisibleItemIndex <= item.LastIndex || item.LastIndex == -1))
                    {
                        currentTopGroupHeader.Visibility  = Visibility.Visible;
                        currentTopGroupHeader.Margin      = new Thickness(0);
                        currentTopGroupHeader.Clip        = null;
                        currentTopGroupHeader.DataContext = item;
                    }
                    else
                    {
                        ListViewItem listViewItem = ContainerFromIndex(item.FirstIndex) as ListViewItem;

                        if (listViewItem == null && item.LastIndex != -1)
                        {
                            listViewItem = ContainerFromIndex(item.LastIndex) as ListViewItem;
                        }
                        if (listViewItem != null)
                        {
                            //handle moving header
                            {
                                //unloaded
                                if (listViewItem.ActualHeight == 0 || listViewItem.ActualWidth == 0)
                                {
                                    listViewItem.Loaded += ListViewItem_Loaded;
                                }
                                else
                                {
                                    GeneralTransform gt = listViewItem.TransformToVisual(this);
                                    var rect            = gt.TransformBounds(new Rect(0, 0, listViewItem.ActualWidth, listViewItem.ActualHeight));
                                    //add delta,so that it does not look like suddenly
                                    if (rect.Bottom < 0 || rect.Top > this.ActualHeight)
                                    {
                                    }
                                    //in view port
                                    else
                                    {
                                        if (currentTopGroupHeader != null)
                                        {
                                            var delta = currentTopGroupHeader.ActualHeight - (rect.Top);
                                            if (delta > 0)
                                            {
                                                currentTopGroupHeader.Margin = new Thickness(0, -delta, 0, 0);
                                                currentTopGroupHeader.Clip   = new RectangleGeometry()
                                                {
                                                    Rect = new Rect(0, delta, currentTopGroupHeader.ActualWidth, currentTopGroupHeader.ActualHeight)
                                                };
                                                if (delta >= currentTopGroupHeader.ActualHeight)
                                                {
                                                    currentTopGroupHeader.Visibility  = Visibility.Visible;
                                                    currentTopGroupHeader.Margin      = new Thickness(0);
                                                    currentTopGroupHeader.Clip        = null;
                                                    currentTopGroupHeader.DataContext = item;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// UpdateElementBounds:
        ///     Called by   InkCanvasSelection.UpdateElementBounds
        ///                 ClipboardProcessor.CopySelectionInXAML
        /// </summary>
        /// <param name="originalElement"></param>
        /// <param name="updatedElement"></param>
        /// <param name="transform"></param>
        internal void UpdateElementBounds(UIElement originalElement, UIElement updatedElement, Matrix transform)
        {
            if (originalElement.DependencyObjectType.Id == updatedElement.DependencyObjectType.Id)
            {
                // Get the transform from element to Canvas
                GeneralTransform elementToCanvas = originalElement.TransformToAncestor(_inkCanvas.InnerCanvas);

                //cast to a FrameworkElement, nothing inherits from UIElement besides it right now
                FrameworkElement frameworkElement = originalElement as FrameworkElement;
                Size             size;
                Thickness        thickness = new Thickness();
                if (frameworkElement == null)
                {
                    // Get the element's render size.
                    size = originalElement.RenderSize;
                }
                else
                {
                    size      = new Size(frameworkElement.ActualWidth, frameworkElement.ActualHeight);
                    thickness = frameworkElement.Margin;
                }

                Rect elementBounds = new Rect(0, 0, size.Width, size.Height);   // Rect in element space
                elementBounds = elementToCanvas.TransformBounds(elementBounds); // Rect in Canvas space

                // Now apply the matrix to the element bounds
                Rect newBounds = Rect.Transform(elementBounds, transform);

                if (!DoubleUtil.AreClose(elementBounds.Width, newBounds.Width))
                {
                    if (frameworkElement == null)
                    {
                        Size newSize = originalElement.RenderSize;
                        newSize.Width             = newBounds.Width;
                        updatedElement.RenderSize = newSize;
                    }
                    else
                    {
                        ((FrameworkElement)updatedElement).Width = newBounds.Width;
                    }
                }

                if (!DoubleUtil.AreClose(elementBounds.Height, newBounds.Height))
                {
                    if (frameworkElement == null)
                    {
                        Size newSize = originalElement.RenderSize;
                        newSize.Height            = newBounds.Height;
                        updatedElement.RenderSize = newSize;
                    }
                    else
                    {
                        ((FrameworkElement)updatedElement).Height = newBounds.Height;
                    }
                }

                double left   = InkCanvas.GetLeft(originalElement);
                double top    = InkCanvas.GetTop(originalElement);
                double right  = InkCanvas.GetRight(originalElement);
                double bottom = InkCanvas.GetBottom(originalElement);

                Point originalPosition = new Point(); // Default as (0, 0)
                if (!double.IsNaN(left))
                {
                    originalPosition.X = left;
                }
                else if (!double.IsNaN(right))
                {
                    originalPosition.X = right;
                }

                if (!double.IsNaN(top))
                {
                    originalPosition.Y = top;
                }
                else if (!double.IsNaN(bottom))
                {
                    originalPosition.Y = bottom;
                }

                Point newPosition = originalPosition * transform;

                if (!double.IsNaN(left))
                {
                    InkCanvas.SetLeft(updatedElement, newPosition.X - thickness.Left);           // Left wasn't auto
                }
                else if (!double.IsNaN(right))
                {
                    // NOTICE-2005/05/05-WAYNEZEN
                    // Canvas.RightProperty means the distance between element right side and its parent Canvas
                    // right side. The same definition is applied to Canvas.BottomProperty
                    InkCanvas.SetRight(updatedElement, (right - (newPosition.X - originalPosition.X)));     // Right wasn't not auto
                }
                else
                {
                    InkCanvas.SetLeft(updatedElement, newPosition.X - thickness.Left);           // Both Left and Right were aut. Modify Left by default.
                }

                if (!double.IsNaN(top))
                {
                    InkCanvas.SetTop(updatedElement, newPosition.Y - thickness.Top);           // Top wasn't auto
                }
                else if (!double.IsNaN(bottom))
                {
                    InkCanvas.SetBottom(updatedElement, (bottom - (newPosition.Y - originalPosition.Y)));          // Bottom wasn't not auto
                }
                else
                {
                    InkCanvas.SetTop(updatedElement, newPosition.Y - thickness.Top);           // Both Top and Bottom were aut. Modify Left by default.
                }
            }
            else
            {
                Debug.Assert(false, "The updatedElement has to be the same type as the originalElement.");
            }
        }
Ejemplo n.º 28
0
        public async Task GoToGroupAsync(int groupIndex, ScrollIntoViewAlignment scrollIntoViewAlignment = ScrollIntoViewAlignment.Leading)
        {
            if (groupCollection != null)
            {
                var gc = groupCollection;
                if (groupIndex < gc.GroupHeaders.Count && groupIndex >= 0 && !isGotoGrouping)
                {
                    isGotoGrouping = true;
                    //load more so that ScrollIntoViewAlignment.Leading can go to top
                    var loadcount = this.GetVisibleItemsCount() + 1;

                    progressRing.IsActive   = true;
                    progressRing.Visibility = Visibility.Visible;
                    //make sure user don't do any other thing at the time.
                    this.IsHitTestVisible = false;
                    //await Task.Delay(3000);
                    while (gc.GroupHeaders[groupIndex].FirstIndex == -1)
                    {
                        if (gc.HasMoreItems)
                        {
                            await gc.LoadMoreItemsAsync(loadcount);
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (gc.GroupHeaders[groupIndex].FirstIndex != -1)
                    {
                        //make sure there are enought items to go ScrollIntoViewAlignment.Leading
                        //this.count > (firstIndex + loadcount)
                        if (scrollIntoViewAlignment == ScrollIntoViewAlignment.Leading)
                        {
                            var more = this.Items.Count - (gc.GroupHeaders[groupIndex].FirstIndex + loadcount);
                            if (gc.HasMoreItems && more < 0)
                            {
                                await gc.LoadMoreItemsAsync((uint)Math.Abs(more));
                            }
                        }
                        progressRing.IsActive   = false;
                        progressRing.Visibility = Visibility.Collapsed;
                        var groupFirstIndex = gc.GroupHeaders[groupIndex].FirstIndex;
                        ScrollIntoView(this.Items[groupFirstIndex], scrollIntoViewAlignment);

                        ListViewItem listViewItem = ContainerFromIndex(groupFirstIndex) as ListViewItem;
                        if (listViewItem != null)
                        {
                            GeneralTransform gt = listViewItem.TransformToVisual(this);
                            var rect            = gt.TransformBounds(new Rect(0, 0, listViewItem.ActualWidth, listViewItem.ActualHeight));
                            //add delta,so that it does not look like suddenly
                            if (rect.Bottom < 0 || rect.Top > this.ActualHeight)
                            {
                            }
                            //already in viewport, maybe it will not change view
                            else
                            {
                                this.IsHitTestVisible = true;
                                isGotoGrouping        = false;
                            }
                        }
                    }
                    else
                    {
                        this.IsHitTestVisible   = true;
                        isGotoGrouping          = false;
                        progressRing.IsActive   = false;
                        progressRing.Visibility = Visibility.Collapsed;
                    }
                }
            }
        }
Ejemplo n.º 29
0
        private Geometry GetClipRegion(RowSelectorDecorator decorator, Rect arrangeRect, FrameworkElement referenceElement)
        {
            if (referenceElement == null)
            {
                return(null);
            }

            var rowSelector = decorator.RowSelector;

            if (rowSelector == null)
            {
                return(null);
            }

            GeneralTransform  referenceElementToRowSelectorPaneTransform = referenceElement.TransformToVisual(this);
            Rect              referenceElementRegion = referenceElementToRowSelectorPaneTransform.TransformBounds(new Rect(0, 0, referenceElement.ActualWidth, referenceElement.ActualHeight));
            RectangleGeometry clipRegion             = null;

            if (this.Orientation == Orientation.Vertical)
            {
                UIElement container = rowSelector.DataContext as UIElement;

                if ((container != null) && (container.Clip != null))
                {
                    Rect containerClipBounds = container.Clip.Bounds;

                    // In this case, we will use the container's clip properties (Top and Bottom).
                    clipRegion = new RectangleGeometry(new Rect(0d, containerClipBounds.Y, arrangeRect.Width, containerClipBounds.Height));
                }
                else if ((arrangeRect.Top < referenceElementRegion.Top) || (arrangeRect.Bottom > referenceElementRegion.Bottom))
                {
                    double x = 0d;
                    double y = Math.Max(referenceElementRegion.Top - arrangeRect.Top, 0);

                    double width  = arrangeRect.Width;
                    double height = Math.Max(0, arrangeRect.Height - y - Math.Max(0, arrangeRect.Bottom - referenceElementRegion.Bottom));

                    clipRegion = new RectangleGeometry(new Rect(x, y, width, height));
                }
            }
            else
            {
                UIElement container = rowSelector.DataContext as UIElement;

                if ((container != null) && (container.Clip != null))
                {
                    Rect containerClipBounds = container.Clip.Bounds;

                    // In this case, we will use the container's clip properties (Left and Right).
                    clipRegion = new RectangleGeometry(new Rect(containerClipBounds.X, 0d, containerClipBounds.Width, arrangeRect.Height));
                }
                else if ((arrangeRect.Left < referenceElementRegion.Left) || (arrangeRect.Right > referenceElementRegion.Right))
                {
                    double x = Math.Max(referenceElementRegion.Left - arrangeRect.Left, 0);
                    double y = 0d;

                    double width  = arrangeRect.Width - x - Math.Max(0, arrangeRect.Right - referenceElementRegion.Right);
                    double height = arrangeRect.Height;

                    clipRegion = new RectangleGeometry(new Rect(x, y, width, height));
                }
            }

            return(clipRegion);
        }
Ejemplo n.º 30
0
        private Rect GetRectangleControlRelativeBounds()
        {
            GeneralTransform transform = _rectangleControl.TransformToAncestor(_rubberbandControl);

            return(transform.TransformBounds(new Rect(0, 0, _rubberbandControl.Width, _rubberbandControl.Height)));
        }