IntersectsWith() public method

public IntersectsWith ( Rect rect ) : bool
rect Rect
return bool
Example #1
0
        public ObservableCollection<GameObject> Collision(List<GameObject> attackers, List<GameObject> defenders,
            ObservableCollection<GameObject> gameObjects, int canvasHeight, out int numberOfCollisions)
        {
            var collisions = 0;

            foreach (var attacker in attackers)
            {
                var attackerRectangle = new Rect(attacker.Left, attacker.Top,
                    attacker.ImageWidth, attacker.ImageHeight);

                foreach (var defender in defenders)
                {
                    var defenderRectangle = new Rect(defender.Left, defender.Top,
                        defender.ImageWidth, defender.ImageHeight);

                    var collisionDetected = attackerRectangle.IntersectsWith(defenderRectangle);
                    if (collisionDetected)
                    {
                        gameObjects.Remove(attacker);
                        if (defender.Type != GameObjectType.Player)
                        {
                            gameObjects.Remove(defender);
                        }


                        collisions += 1;
                        break;
                    }
                }
            }


            numberOfCollisions = collisions;
            return gameObjects;
        }
 internal static Rect GetOnScreenPosition(Rect floatRect)
 {
     Rect rect1 = floatRect;
     floatRect = floatRect.LogicalToDeviceUnits();
     Rect rect2;
     Rect rect3;
     Screen.FindMaximumSingleMonitorRectangle(floatRect, out rect2, out rect3);
     if (floatRect.IntersectsWith(rect3))
         return rect1;
     Screen.FindMonitorRectsFromPoint(NativeMethods.NativeMethods.GetCursorPos(), out rect2, out rect3);
     var rect4 = rect3.DeviceToLogicalUnits();
     if (rect1.Width > rect4.Width)
         rect1.Width = rect4.Width;
     if (rect1.Height > rect4.Height)
         rect1.Height = rect4.Height;
     if (rect4.Right <= rect1.X)
         rect1.X = rect4.Right - rect1.Width;
     if (rect4.Left > rect1.X + rect1.Width)
         rect1.X = rect4.Left;
     if (rect4.Bottom <= rect1.Y)
         rect1.Y = rect4.Bottom - rect1.Height;
     if (rect4.Top > rect1.Y + rect1.Height)
         rect1.Y = rect4.Top;
     return rect1;
 }
 public void Check_Collision()
 {
     for (int i = 0; i < _lstVM.Count; i++)
     {
         Elipse el1 = _lstVM[i].El;
         var x1 = el1.Left;
         var y1 = el1.Top;
         Rect r1 = new Rect(x1 + 3, y1 + 3, el1.Width - 3, el1.Height - 3);
         for (int j = i + 1; j < _lstVM.Count; j++)
         {
             Elipse el2 = _lstVM[j].El;
             var x2 = el2.Left;
             var y2 = el2.Top;
             Rect r2 = new Rect(x2 + 3, y2 + 3, el2.Width - 3, el2.Height - 3);
             if (r1.IntersectsWith(r2))
             {
                 MessageBox.Show("Game Over:\nCant Elim: "+ _cantElim.ToString());
                 game_timer.Stop();
                 list_timer.Stop();
                 var mainWindow = (Application.Current.MainWindow as Window1);
                 mainWindow.Close();
                 return;
                 //int a = 1;
             }
         }
     }
 }
Example #4
0
		/// <summary>
		/// Applies the specified old data rect.
		/// </summary>
		/// <param name="oldDataRect">The old data rect.</param>
		/// <param name="newDataRect">The new data rect.</param>
		/// <param name="viewport">The viewport.</param>
		/// <returns></returns>
        /// 
		public override Rect Apply(Rect oldDataRect, Rect newDataRect, Viewport2D viewport)
		{
			DataRect res = domain;
			if (domain.IsEmpty)
			{
				res = newDataRect;
			}
			else if (newDataRect.IntersectsWith(domain))
			{
				res = newDataRect;
                if (newDataRect.Size == oldDataRect.Size)
                {
                    if (res.XMin < domain.XMin) res.XMin = domain.XMin;
                    if (res.YMin < domain.YMin) res.YMin = domain.YMin;
                    if (res.XMax > domain.XMax) res.XMin += domain.XMax - res.XMax;
                    if (res.YMax > domain.YMax) res.YMin += domain.YMax - res.YMax;
                }
                else
                {
                    newDataRect.Intersect(domain);
                    res = newDataRect;
                }
			}

			return res;
		}
        protected override void OnScrollChanged(ScrollChangedEventArgs e)
        {
            base.OnScrollChanged(e);

            var panel = Content as Panel;
            if (panel == null)
            {
                return;
            }

            var viewport = new Rect(new Point(0, 0), RenderSize);

            foreach (UIElement child in panel.Children)
            {
                if (!child.IsVisible)
                {
                    SetIsInViewport(child, false);
                    continue;
                }

                var transform = child.TransformToAncestor(this);
                var childBounds = transform.TransformBounds(new Rect(new Point(0, 0), child.RenderSize));
                SetIsInViewport(child, viewport.IntersectsWith(childBounds));
            }
        }
Example #6
0
 public static double GetLinkLengthBetweenRectangles(Rect rectangle1, Rect rectangle2)
 {
     if (rectangle1.IntersectsWith(rectangle2)) {
         return 0;
     }
     Point linkStart, linkEnd;
     ComputeLinkBetweenRectangles(rectangle1, rectangle2, 0, out linkStart, out linkEnd);
     Vector link = linkEnd - linkStart;
     return link.Length;
 }
        private void textBox_TextChanged(object sender,TextChangedEventArgs e) {
            story.SelectAll();
            if(textBox.MaxLength == textBox.Text.Length && textBox.Text == story.Selection.Text.Replace("\r", "").Replace("\n", "")) {
                ExportData();
                Application.Current.Shutdown();
            }

            foreach(TextChange i in e.Changes) {
                if (textBox.Text.Substring(i.Offset, i.AddedLength) == " ")
                {
                    mCurrentChar = -1;
                    int index = story.Selection.Text.Substring(i.Offset + 1).IndexOf(' ');
                    if (index > -1)
                    {
                        Int32 length = story.Selection.Text.Substring(i.Offset + 1, index).Length;
                        mTriggerChar = mRandom.Next(0, length);
                        mData.Add(mTimer.ElapsedMilliseconds);
                        mTimer.Restart();
                    }
                }
            }

            story.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty,Brushes.Black);
            string textToPos = textBox.Text;
            string textToRetypeToPos = story.Selection.Text.Substring(0,textToPos.Length);
            story.Selection.Select(story.Selection.Start,story.Selection.Start.GetPositionAtOffset(textToPos.Length));
            if(textToPos == textToRetypeToPos) story.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty,Brushes.Green);
            else story.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty,Brushes.Red);

            if(mCurrentChar == mTriggerChar) {
                popup_image.Source = (BitmapImage)Resources[mRandom.Next(1,6).ToString()];
                Rect rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex,true);
                Point coords = textBox.TransformToAncestor(this).Transform(rect.Location);
                popup_image.Height = popup_image.Width = mRandom.Next(100,351);
                Rect image;
                do {
                    Int32 x = mRandom.Next(0,1281);
                    Int32 y = mRandom.Next(0,721);

                    popup.Margin = new Thickness(-popup_image.Width / 2 + x,-popup_image.Height / 2 + textBox.FontSize / 2 + y,0,0);
                    rect = new Rect(new Point(coords.X - popup_image.Width / 2,coords.Y - popup_image.Height / 2),new Point(coords.X + popup_image.Width / 2,coords.Y + textBox.FontSize + popup_image.Height / 2));
                    image = new Rect(new Point(popup.Margin.Left,popup.Margin.Top),popup_image.DesiredSize);
                } while(popup.Margin.Left + popup_image.Width / 2 < 0 || popup.Margin.Left + popup_image.Width / 2 > 640
                    || popup.Margin.Top + popup_image.Height / 2 < 0 || popup.Margin.Top + popup_image.Height / 2 > 480 || rect.IntersectsWith(image));

                popup.Visibility = Visibility.Visible;
            }
            ++mCurrentChar;
        }
Example #8
0
        public void Start()
        {
            var upSpeed = App.Random.Next(25000, 60000) / 10000.0;
            this.timer = new DispatcherTimer(DispatcherPriority.Render, App.Current.Dispatcher);
            this.timer.Interval = TimeSpan.FromTicks(10000000 / 60); // 60 loop per sec
            this.timer.Tick += (_, __) =>
            {
                this.right += 10;
                this.UI.SetValue(Canvas.RightProperty, this.right);

                this.bottom += upSpeed;
                this.UI.SetValue(Canvas.BottomProperty, this.bottom);
                upSpeed -= 0.1;

                var myPoint = this.GetPoint();
                var myRect = new Rect(myPoint.X, myPoint.Y, this.UI.ActualWidth, this.UI.ActualHeight);
                var match = this.field.Walls.Cast<WithHitPoints>()
                    .Concat(new WithHitPoints[] { this.field.Castle })
                    .Where(x => x != null)
                    .FirstOrDefault(x =>
                    {
                        var point = x.GetPoint();
                        return myRect.IntersectsWith(new Rect(point.X, point.Y, x.UI.ActualWidth, x.UI.ActualHeight));
                    });
                if (match != null)
                {
                    this.timer.Stop();
                    match.MakeDamage(this.Power);
                    this.UI = new UnitViews.Explosion();
                    this.UI.SetValue(Canvas.RightProperty, this.right);
                    this.UI.SetValue(Canvas.BottomProperty, this.bottom);
                    if (this.UIChanged != null)
                        this.UIChanged(this, EventArgs.Empty);
                    DispatcherAsync.Delay(TimeSpan.FromSeconds(0.5), () =>
                    {
                        if (this.Disappeared != null)
                            this.Disappeared(this, EventArgs.Empty);
                    });
                }
                else if (this.right > (this.UI.Parent as FrameworkElement).ActualWidth)
                {
                    this.timer.Stop();
                    if (this.Disappeared != null)
                        this.Disappeared(this, EventArgs.Empty);
                }
            };
            this.timer.Start();
        }
Example #9
0
		public virtual IEnumerable<int> FindInArea(Rect area)
		{
			for (var i = 0; i < Count; i++)
			{
				var x = XValues[i];
				var y = YValues[i];
				var w = WidthValues[i];
				var h = HeightValues[i];

				var rect = new Rect(x, y, w, h);
				if (area.IntersectsWith(rect))
				{
					yield return i;
				}
			}
		}
Example #10
0
        bool IsFree(MyObject obj, int x, int y)
        {
            Rect myRectangleObj = new Rect();
            myRectangleObj.Location = new Point(x, y);
            myRectangleObj.Size = new Size(obj.Width, obj.Height);

            foreach (var item in area.LMyObject)
            {
                Rect myRectangle = new Rect();
                myRectangle.Location = new Point(item.X, item.Y);
                myRectangle.Height = item.Height;
                myRectangle.Width = item.Width;

                if (myRectangle.IntersectsWith(myRectangleObj))
                    return false;
            }
            return true;
        }
Example #11
0
		public override Rect Apply(Rect oldDataRect, Rect newDataRect, Viewport2D viewport)
		{
			Rect res = oldDataRect;
			if (newDataRect.IntersectsWith(border))
			{
				res = newDataRect;
				if (newDataRect.Size == oldDataRect.Size)
				{
					if (res.X < border.X) res.X = border.X;
					if (res.Y < border.Y) res.Y = border.Y;
					if (res.Right > border.Right) res.X += border.Right - res.Right;
					if (res.Bottom > border.Bottom) res.Y += border.Bottom - res.Bottom;
				}
				else
				{
					res = Rect.Intersect(newDataRect, border);
				}
			}
			return res;
		}
        private static void OnSetIsUserVisibleBehaviourChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
        {
            FrameworkElement frameworkElement = dependencyObject as FrameworkElement;

            if (frameworkElement == null)
                return;

            if (!(eventArgs.NewValue is bool))
                return;

            if ((bool)eventArgs.NewValue)
            {
                frameworkElement.LayoutUpdated += (sender, layoutUpdateEventArgs) =>
                {
                    if (frameworkElement != null)
                    {
                        //HACK: AJ: This uses a hard coded container type.
                        FrameworkElement containerFrameworkElement = frameworkElement.FindAncestor<System.Windows.Controls.ListView>();

                        bool isUserVisible = false;

                        if (frameworkElement.IsVisible)
                        {
                            Rect containerBounds = frameworkElement.TransformToAncestor(containerFrameworkElement).TransformBounds(new Rect(0.0, 0.0, frameworkElement.ActualWidth, frameworkElement.ActualHeight));
                            Rect frameworkElementBounds = new Rect(0.0, 0.0, containerFrameworkElement.ActualWidth, containerFrameworkElement.ActualHeight);

                            isUserVisible = frameworkElementBounds.IntersectsWith(containerBounds);
                        }

                        if (GetIsUserVisible(frameworkElement) != isUserVisible)
                            frameworkElement.SetValue(IsUserVisibleProperty, isUserVisible);
                    }
                };

                frameworkElement.Unloaded += (sender, routedEventArgs) =>
                {
                    frameworkElement.SetValue(IsUserVisibleProperty, false);
                };
            }
        }
 protected bool IsFullyOrPartiallyVisible(FrameworkElement child, FrameworkElement scrollViewer)
 {
     var childTransform = child.TransformToAncestor(scrollViewer);
     var childRectangle = childTransform.TransformBounds(
                               new Rect(new Point(0, 0), child.RenderSize));
     var ownerRectangle = new Rect(new Point(0, 0), scrollViewer.RenderSize);
     return ownerRectangle.IntersectsWith(childRectangle);
 }
		public void IntersectsWith ()
		{
			Rect r = new Rect (0, 0, 50, 50);

			// fully contained
			Assert.IsTrue (r.IntersectsWith (new Rect (10, 10, 10, 10)));

			// crosses top side
			Assert.IsTrue (r.IntersectsWith (new Rect (5, -5, 10, 10)));

			// crosses right side
			Assert.IsTrue (r.IntersectsWith (new Rect (5, 5, 50, 10)));

			// crosses bottom side
			Assert.IsTrue (r.IntersectsWith (new Rect (5, 5, 10, 50)));

			// crosses left side
			Assert.IsTrue (r.IntersectsWith (new Rect (-5, 5, 10, 10)));

			// completely outside (top)
			Assert.IsFalse (r.IntersectsWith (new Rect (5, -5, 1, 1)));

			// completely outside (right)
			Assert.IsFalse (r.IntersectsWith (new Rect (75, 5, 1, 1)));

			// completely outside (bottom)
			Assert.IsFalse (r.IntersectsWith (new Rect (5, 75, 1, 1)));

			// completely outside (left)
			Assert.IsFalse (r.IntersectsWith (new Rect (-25, 5, 1, 1)));
		}
Example #15
0
        /// <summary>
        /// Checks for shape overlap of bounding boxes (collision detection).
        /// </summary>
        /// <param name="shape1">
        /// The first shape name.
        /// </param>
        /// <param name="shape2">
        /// The second shape name.
        /// </param>
        /// <returns>
        /// "True" or "False".
        /// </returns>
        public static Primitive OverlapBox(Primitive shape1, Primitive shape2)
        {
            UIElement obj1, obj2;

            try
            {
                if (!_objectsMap.TryGetValue((string)shape1, out obj1))
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shape1);
                    return "False";
                }
                if (!_objectsMap.TryGetValue((string)shape2, out obj2))
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shape2);
                    return "False";
                }

                Rect rect1 = new Rect(obj1.RenderSize);
                Rect rect2 = new Rect(obj2.RenderSize);
                rect1.Offset(VisualTreeHelper.GetOffset(obj1));
                rect2.Offset(VisualTreeHelper.GetOffset(obj2));
                return rect1.IntersectsWith(rect2) ? "True" : "False";
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "False";
            }
        }
Example #16
0
 private static bool RectangleIntersectsLine(Rect rect, Point startPoint, Point endPoint)
 {
     rect.Inflate(-1, -1);
     return rect.IntersectsWith(new Rect(startPoint, endPoint));
 }
Example #17
0
        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            Canvas canvas = sender as Canvas;

            if (movingNodeOrigins.Count > 0)
            {
                Point mousePosition = e.GetPosition(canvas);
                mousePosition = new Point(mousePosition.X - PanX, mousePosition.Y - PanY);

                foreach (NodeControl nodeControl in movingNodeOrigins.Keys)
                {
                    ContentPresenter contentPresenter = VisualTreeHelper.GetParent(nodeControl) as ContentPresenter;
                    Point nodeControlPosition = new Point(mousePosition.X / Scale - movingNodeOffsets[nodeControl].Value.X, mousePosition.Y / Scale - movingNodeOffsets[nodeControl].Value.Y);

                    nodeControlPosition.X = Math.Round(nodeControlPosition.X / 4) * 4;
                    nodeControlPosition.Y = Math.Round(nodeControlPosition.Y / 4) * 4;

                    contentPresenter.SetValue(Canvas.LeftProperty, nodeControlPosition.X);
                    contentPresenter.SetValue(Canvas.TopProperty, nodeControlPosition.Y);
                }
            }

            if (creatingNewLink)
            {
                DependencyObject overElement = e.OriginalSource as DependencyObject;
                while (overElement != null && !(overElement is NodeControl))
                    overElement = VisualTreeHelper.GetParent(overElement);

                NodeControl nodeControl = overElement as NodeControl;
                if (nodeControl != null)
                {
                    DestinationAnchorBinder.Anchor = nodeControl.NodeAnchor;
                }
                else
                {
                    Point mousePosition = e.GetPosition(canvas);

                    DestinationAnchorBinder.Anchor = DestinationAnchor;
                    DestinationAnchorBinder.Anchor.SetValue(Canvas.LeftProperty, mousePosition.X / Scale - PanX);
                    DestinationAnchorBinder.Anchor.SetValue(Canvas.TopProperty, mousePosition.Y / Scale - PanY);
                }

                NotifyPropertyChanged(nameof(DestinationAnchorBinder));
            }

            if (Panning)
            {
                Point panningPosition = e.GetPosition(EditorScroller);

                PanX += (panningPosition.X - panningStart.X) / Scale;
                PanY += (panningPosition.Y - panningStart.Y) / Scale;

                panningStart = panningPosition;
            }

            if (Selecting)
            {
                Point mousePosition = e.GetPosition(EditorCanvas);

                SelectionEnd = new Point(mousePosition.X + PanX, mousePosition.Y + PanY);
                SelectedNodes.Clear();

                Rect selectionRect = new Rect(SelectionStart, SelectionEnd);

                foreach (var pair in nodeControls)
                {
                    Rect nodeRect = new Rect(pair.Key.X + PanX, pair.Key.Y + PanY, pair.Value.ActualWidth, pair.Value.ActualHeight);

                    if (selectionRect.IntersectsWith(nodeRect))
                        SelectedNodes.Add(pair.Key);
                }

                UpdateThumbnail();
            }
        }
Example #18
0
        /*
        void circuitInkCanvas_StylusMove(object sender, StylusEventArgs e)
        {
            if (IsReadOnly)
                return;

            TimeSpan ts = _stopWatch.Elapsed;
            if (ts.TotalSeconds - _lastElapsedSecs> 2)
            {
                _stopWatch.Stop();
                _stopWatch = Stopwatch.StartNew();
                MessageBox.Show("Popup");
            }

            Point mp2 = e.GetPosition(circuitInkCanvas);

            circuitInkCanvas.BringIntoView(new Rect(new Point(mp2.X - 10, mp2.Y - 10),
                new Point(mp2.X + 10, mp2.Y + 10)));

            switch (dragging)
            {
                case DragState.CONNECT_FROM:
                    dragWire.Destination = mp2;
                    break;
                case DragState.CONNECT_TO:
                    dragWire.Origin = mp2;
                    break;
                case DragState.MOVE:
                    #region DragState is Move
                    foreach (Gate g in selected)
                    {
                        //g.RenderTransform = new TranslateTransform(mp2.X, mp2.Y);
                        //Direct Move
                        
                            double dx = mp2.X - mp.X;
                            double dy = mp2.Y - mp.Y;
                            ((GateLocation)g.Tag).x = ((GateLocation)g.Tag).x + dx;
                            ((GateLocation)g.Tag).y = ((GateLocation)g.Tag).y + dy;
                            double cx = ((GateLocation)g.Tag).x % GRID_SIZE;
                            double cy = ((GateLocation)g.Tag).y % GRID_SIZE;

                            Point op = new Point(g.Margin.Left, g.Margin.Top);

                            if ((Math.Abs(cx) < DELTA_SNAP || Math.Abs(GRID_SIZE - cx) < DELTA_SNAP) &&
                                (Math.Abs(cy) < DELTA_SNAP || Math.Abs(GRID_SIZE - cy) < DELTA_SNAP))
                            {
                                g.Margin = new Thickness(Math.Round(g.Margin.Left / GRID_SIZE) * GRID_SIZE,
                                    Math.Round(g.Margin.Top / GRID_SIZE) * GRID_SIZE, 0, 0);

                            }
                            else
                            {
                                g.Margin = new Thickness(((GateLocation)g.Tag).x, ((GateLocation)g.Tag).y, 0, 0);
                            }

                            Point np = new Point(g.Margin.Left, g.Margin.Top);
                            if (op != np)
                                moves.Add(new UndoRedo.MoveGate(g, this, op, np));

                            SizeCanvas();
                            g.BringIntoView(); // still needed because gate larger than 20px block

                    }

                    UpdateWireConnections();
                    break;
                    #endregion
                case DragState.NONE:
                    #region Drag State is None
                    // not dragging
                    // creating a selection rectangle
                    if (ReadyToSelect)
                    {
                        double x1 = Math.Min(mp2.X, sp.X);
                        double width = Math.Abs(mp2.X - sp.X);

                        double y1 = Math.Min(mp2.Y, sp.Y);
                        double height = Math.Abs(mp2.Y - sp.Y);

                        dragSelect.Margin = new Thickness(x1, y1, 0, 0);
                        dragSelect.Width = width;
                        dragSelect.Height = height;
                        dragSelect.Visibility = Visibility.Visible;

                        // select any gates inside the rectangle
                        Rect select = new Rect(x1, y1, width, height);
                        foreach (Gate g in gates.Values)
                        {
                            Rect grect = new Rect(g.Margin.Left, g.Margin.Top, g.Width, g.Height);
                            if (select.IntersectsWith(grect) && !g.Selected)
                            {
                                g.Selected = true;
                                selected.Add(g);
                            }

                            // this is not the same as just "not" or else the above
                            if (!select.IntersectsWith(grect) && g.Selected)
                            {
                                g.Selected = false;
                                selected.Remove(g);
                            }
                        }
                    }
                    break;
                    #endregion
            }
            mp = mp2;
        }
         * 
         * */
        
        /*
        void circuitInkCanvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsReadOnly)
                return;

            TimeSpan ts = _stopWatch.Elapsed;
            if (ts.TotalSeconds - _lastElapsedSecs > 2)
            {
                MessageBox.Show("Popup");
            }

            Point mp2 = e.GetPosition(circuitInkCanvas);

            circuitInkCanvas.BringIntoView(new Rect(new Point(mp2.X - 10, mp2.Y - 10),
                new Point(mp2.X + 10, mp2.Y + 10)));

            switch (dragging)
            {
                case DragState.CONNECT_FROM:
                    dragWire.Destination = mp2;
                    break;
                case DragState.CONNECT_TO:
                    dragWire.Origin = mp2;
                    break;
                case DragState.MOVE:
                    #region DragState is Move
                    foreach (Gate g in selected)
                    {
                        //g.RenderTransform = new TranslateTransform(mp2.X, mp2.Y);
                        //Direct Move
                        if (e.LeftButton == MouseButtonState.Pressed)
                        {
                            double dx = mp2.X - mp.X;
                            double dy = mp2.Y - mp.Y;
                            ((GateLocation)g.Tag).x = ((GateLocation)g.Tag).x + dx;
                            ((GateLocation)g.Tag).y = ((GateLocation)g.Tag).y + dy;
                            double cx = ((GateLocation)g.Tag).x % GRID_SIZE;
                            double cy = ((GateLocation)g.Tag).y % GRID_SIZE;

                            Point op = new Point(g.Margin.Left, g.Margin.Top);

                            if ((Math.Abs(cx) < DELTA_SNAP || Math.Abs(GRID_SIZE - cx) < DELTA_SNAP) &&
                                (Math.Abs(cy) < DELTA_SNAP || Math.Abs(GRID_SIZE - cy) < DELTA_SNAP))
                            {
                                g.Margin = new Thickness(Math.Round(g.Margin.Left / GRID_SIZE) * GRID_SIZE,
                                    Math.Round(g.Margin.Top / GRID_SIZE) * GRID_SIZE, 0, 0);

                            }
                            else
                            {
                                g.Margin = new Thickness(((GateLocation)g.Tag).x, ((GateLocation)g.Tag).y, 0, 0);
                            }

                            Point np = new Point(g.Margin.Left, g.Margin.Top);
                            if (op != np)
                                moves.Add(new UndoRedo.MoveGate(g, this, op, np));

                            SizeCanvas();
                            g.BringIntoView(); // still needed because gate larger than 20px block

                        }
                                               
                    }

                    UpdateWireConnections();
                    break;
                    #endregion
                case DragState.NONE:
                    #region Drag State is None
                        // not dragging
                        // creating a selection rectangle
                        if (ReadyToSelect)
                        {
                            double x1 = Math.Min(mp2.X, sp.X);
                            double width = Math.Abs(mp2.X - sp.X);

                            double y1 = Math.Min(mp2.Y, sp.Y);
                            double height = Math.Abs(mp2.Y - sp.Y);

                            dragSelect.Margin = new Thickness(x1, y1, 0, 0);
                            dragSelect.Width = width;
                            dragSelect.Height = height;
                            dragSelect.Visibility = Visibility.Visible;

                            // select any gates inside the rectangle
                            Rect select = new Rect(x1, y1, width, height);
                            foreach (Gate g in gates.Values)
                            {
                                Rect grect = new Rect(g.Margin.Left, g.Margin.Top, g.Width, g.Height);
                                if (select.IntersectsWith(grect) && !g.Selected)
                                {
                                    g.Selected = true;
                                    selected.Add(g);
                                }

                                // this is not the same as just "not" or else the above
                                if (!select.IntersectsWith(grect) && g.Selected)
                                {
                                    g.Selected = false;
                                    selected.Remove(g);
                                }
                            }
                        }
                        break;
                        #endregion 
            }
            mp = mp2;
        }
         * */

        /*
       void circuitInkCanvas_PreviewStylusDown(object sender, StylusDownEventArgs e)
       {
           if (EditingMode.currentEditingMode != EditingMode.EditingModeType.SketchLogicGate)
           {
               MessageBox.Show("Please Check Sketch Logic Diagram Radio Button", "TIP");
               return;
           }

           _lastElapsedSecs = _stopWatch.Elapsed.TotalSeconds;

           // only come here if the uigate doesn't handle it
           ClearSelection();

           Point mp2 = e.GetPosition(circuitInkCanvas);

           sp = new Point(mp2.X, mp2.Y);

           ReadyToSelect = true;

           onGateStroke = false;

           foreach (UIElement gate in circuitInkCanvas.Children)
           {
               if (gate is Gate)
               {
                   Gate g = gate as Gate;
                   Rect grect = new Rect(g.Margin.Left, g.Margin.Top, g.Width, g.Height);
                   if (mp2.X >= grect.Left && mp2.X <= grect.Right
                       && mp2.Y >= grect.Top && mp2.Y <= grect.Bottom)
                   {
                       onGateStroke = true;
                       uigate_MouseDown(g, e);

                       if (dragging == DragState.MOVE)
                       {
                           if (g is UIGates.UserInput)
                           {
                               UIGates.UserInput temp = g as UIGates.UserInput;
                               temp.r_MouseDown(this, e);
                           }
                       }
                       break;
                   }
               }
           }

           e.Handled = true;
       }
       */


        #endregion

        public void circuitInkCanvas_PreviewStylusMove(object sender, StylusEventArgs e)
        {
            if (IsReadOnly)
                return;

            Point mp2 = e.GetPosition(circuitInkCanvas);

            if (sender is ConnectedWire)
            {
                #region connectedWire Object

                onWireMoveStroke = true;

                ConnectedWire myWire = sender as ConnectedWire;

                Gate.TerminalID tid = myWire.OriginTerminalID;

                // ok, so are we connecting to or from
                // is this an input or output?
                if (tid.isInput)
                {
                    // can only connect from an input
                    // if there is no other connection here
                    //if (wires.ContainsKey(new Gates.Terminal(tid.ID, tid.abgate)))

                    dragging = DragState.CONNECT_TO;
                    dragWire.Value = false;

                    // highlight all terminals which provide output
                    foreach (Gates.AbstractGate ag in gates.Keys)
                    {
                        for (int i = 0; i < ag.Output.Length; i++)
                        {
                            gates[ag].FindTerminal(false, i).t.Highlight = true;
                        }
                    }
                }
                else
                {
                    dragging = DragState.CONNECT_FROM;
                    // TODO: if the value of the output changes
                    // while being dragged, this won't update
                    dragWire.Value = tid.abgate.Output[tid.ID];


                    // highlight all terminals which accept input
                    // note this is all inputs NOT already connected
                    foreach (Gates.AbstractGate ag in gates.Keys)
                    {
                        for (int i = 0; i < ag.NumberOfInputs; i++)
                        {
                            if (c.GetSource(new Gates.Terminal(i, ag)) == null)
                                gates[ag].FindTerminal(true, i).t.Highlight = true;
                        }
                    }
                }
                beginTID = tid;

                dragWire.Destination = tid.t.TranslatePoint(new Point(5, 5), circuitInkCanvas);
                dragWire.Origin = tid.t.TranslatePoint(new Point(5, 5), circuitInkCanvas);

                //if (dragging == DragState.MOVE)
                //{
                //    if (g is UIGates.UserInput)
                //    {
                //        UIGates.UserInput temp = g as UIGates.UserInput;
                //        temp.r_MouseDown(this, e);
                //    }
                //}
                //break;

                return;

                #endregion
            }

            circuitInkCanvas.BringIntoView(new Rect(new Point(mp2.X - 10, mp2.Y - 10),
                new Point(mp2.X + 10, mp2.Y + 10)));

            switch (dragging)
            {
                case DragState.CONNECT_FROM:

                    foreach (UIElement gate in circuitInkCanvas.Children)
                    {
                        if (gate is Gate)
                        {
                            Gate g = gate as Gate;
                            foreach (Gate.TerminalID tid in g)
                            {
                                tid.t.Background = Brushes.Transparent;
                            }
                         }
                    }
                   
                    // gate termination indication
                    foreach (UIElement gate in circuitInkCanvas.Children)
                    {
                        if (gate is Gate)
                        {
                            Gate g = gate as Gate;
                            Rect grect = new Rect(g.Margin.Left - 10, g.Margin.Top - 10, g.Width + 10, g.Height + 10);

                            bool condition = false;
                            condition = grect.Contains(mp2);
                            if (condition)
                            {
                                Rect gRect = new Rect(g.Margin.Left, g.Margin.Top, g.Width, g.Height);

                                foreach (Gate.TerminalID tid in g)
                                {
                                    Rect tRect = GetTerminalBounds(g, grect, tid);
                                    condition = tRect.Contains(mp2);
                                    if (condition)
                                    {
                                        tid.t.Background = Brushes.Yellow;
                                    }else
                                    {
                                        tid.t.Background = Brushes.Transparent;
                                    }
                                }
                            }
                        }
                    }
                    dragWire.Destination = mp2;
                    break;
                case DragState.CONNECT_TO:
                     foreach (UIElement gate in circuitInkCanvas.Children)
                    {
                        if (gate is Gate)
                        {
                            Gate g = gate as Gate;
                            foreach (Gate.TerminalID tid in g)
                            {
                                tid.t.Background = Brushes.Transparent;
                            }
                         }
                    }
                   
                    // gate termination indication
                    foreach (UIElement gate in circuitInkCanvas.Children)
                    {
                        if (gate is Gate)
                        {
                            Gate g = gate as Gate;
                            Rect grect = new Rect(g.Margin.Left - 10, g.Margin.Top - 10, g.Width + 10, g.Height + 10);

                            bool condition = false;
                            condition = grect.Contains(mp2);
                            if (condition)
                            {
                                Rect gRect = new Rect(g.Margin.Left, g.Margin.Top, g.Width, g.Height);

                                foreach (Gate.TerminalID tid in g)
                                {
                                    Rect tRect = GetTerminalBounds(g, grect, tid);
                                    condition = tRect.Contains(mp2);
                                    if (condition)
                                    {
                                        tid.t.Background = Brushes.Yellow;
                                    }else
                                    {
                                        tid.t.Background = Brushes.Transparent;
                                    }
                                }
                            }
                        }
                    }
                    dragWire.Origin = mp2;
                    break;
                case DragState.MOVE:
                    #region DragState is Move

                    foreach (Gate g in selected)
                    {
                        //g.RenderTransform = new TranslateTransform(mp2.X, mp2.Y);
                        //Direct Move

                        double dx = mp2.X - mp.X;
                        double dy = mp2.Y - mp.Y;
                        ((GateLocation)g.Tag).x = ((GateLocation)g.Tag).x + dx;
                        ((GateLocation)g.Tag).y = ((GateLocation)g.Tag).y + dy;
                        double cx = ((GateLocation)g.Tag).x % GRID_SIZE;
                        double cy = ((GateLocation)g.Tag).y % GRID_SIZE;

                        Point op = new Point(g.Margin.Left, g.Margin.Top);

                        if ((Math.Abs(cx) < DELTA_SNAP || Math.Abs(GRID_SIZE - cx) < DELTA_SNAP) &&
                            (Math.Abs(cy) < DELTA_SNAP || Math.Abs(GRID_SIZE - cy) < DELTA_SNAP))
                        {
                            g.Margin = new Thickness(Math.Round(g.Margin.Left / GRID_SIZE) * GRID_SIZE,
                                Math.Round(g.Margin.Top / GRID_SIZE) * GRID_SIZE, 0, 0);

                        }
                        else
                        {
                            g.Margin = new Thickness(((GateLocation)g.Tag).x, ((GateLocation)g.Tag).y, 0, 0);
                        }

                        Point np = new Point(g.Margin.Left, g.Margin.Top);
                        if (op != np)
                            moves.Add(new UndoRedo.MoveGate(g, this, op, np));

                        SizeCanvas();
                        g.BringIntoView(); // still needed because gate larger than 20px block

                    }

                    UpdateWireConnections();
                    break;
                    #endregion
                case DragState.NONE:
                    #region Drag State is None
                    // not dragging
                    // creating a selection rectangle
                    if (ReadyToSelect)
                    {
                        double x1 = Math.Min(mp2.X, sp.X);
                        double width = Math.Abs(mp2.X - sp.X);

                        double y1 = Math.Min(mp2.Y, sp.Y);
                        double height = Math.Abs(mp2.Y - sp.Y);

                        //dragSelect.Margin = new Thickness(x1, y1, 0, 0);
                        //dragSelect.Width = width;
                        //dragSelect.Height = height;
                        //dragSelect.Visibility = Visibility.Visible;

                        // select any gates inside the rectangle
                        Rect select = new Rect(x1, y1, width, height);
                        foreach (Gate g in gates.Values)
                        {
                            Rect grect = new Rect(g.Margin.Left, g.Margin.Top, g.Width, g.Height);
                            if (select.IntersectsWith(grect) && !g.Selected)
                            {
                                g.Selected = true;
                                selected.Add(g);
                            }

                            // this is not the same as just "not" or else the above
                            if (!select.IntersectsWith(grect) && g.Selected)
                            {
                                g.Selected = false;
                                selected.Remove(g);
                            }
                        }
                    }
                    break;
                    #endregion
            }

            mp = mp2;
        }
        /// <summary>
        ///     Helper method to nudge the keytip into the
        ///     boundary of the adorner layer.
        /// </summary>
        internal void NudgeIntoAdornerLayerBoundary(AdornerLayer adornerLayer)
        {
            if (_keyTipControl != null && _keyTipControl.IsLoaded)
            {
                Point adornerOrigin = this.TranslatePoint(new Point(), adornerLayer);
                Rect adornerLayerRect = new Rect(0, 0, adornerLayer.ActualWidth, adornerLayer.ActualHeight);
                Rect keyTipControlRect = new Rect(adornerOrigin.X + _keyTipTransform.X,
                    adornerOrigin.Y + _keyTipTransform.Y,
                    _keyTipControl.ActualWidth,
                    _keyTipControl.ActualHeight);
                if (adornerLayerRect.IntersectsWith(keyTipControlRect) &&
                    !adornerLayerRect.Contains(keyTipControlRect))
                {
                    double deltaX = 0;
                    double deltaY = 0;

                    // Nudge the keytip control horizontally if its left or right
                    // edge falls outside the adornerlayer.
                    if (DoubleUtil.LessThan(keyTipControlRect.Left, adornerLayerRect.Left))
                    {
                        deltaX = adornerLayerRect.Left - keyTipControlRect.Left;
                    }
                    else if (DoubleUtil.GreaterThan(keyTipControlRect.Right, adornerLayerRect.Right))
                    {
                        deltaX = adornerLayerRect.Right - keyTipControlRect.Right;
                    }

                    // Nudge the keytip control vertically if its top or bottom
                    // edge falls outside the adornerlayer.
                    if (DoubleUtil.LessThan(keyTipControlRect.Top, adornerLayerRect.Top))
                    {
                        deltaY = adornerLayerRect.Top - keyTipControlRect.Top;
                    }
                    else if (DoubleUtil.GreaterThan(keyTipControlRect.Bottom, adornerLayerRect.Bottom))
                    {
                        deltaY = adornerLayerRect.Bottom - keyTipControlRect.Bottom;
                    }

                    _keyTipTransform.X += deltaX;
                    _keyTipTransform.Y += deltaY;
                }
            }
        }
        void ApplyRegion(Rect wndRect)
        {
            if (!this.CanTransform())
                return;

            wndRect = new Rect(
                this.TransformFromDeviceDPI(wndRect.TopLeft),
                this.TransformFromDeviceDPI(wndRect.Size));

            _lastApplyRect = wndRect;

            if (PresentationSource.FromVisual(this) == null)
                return;


            if (_dockingManager != null)
            {
                List<Rect> otherRects = new List<Rect>();

                foreach (Window fl in Window.GetWindow(_dockingManager).OwnedWindows)
                {
                    //not with myself!
                    if (fl == this)
                        continue;

                    if (!fl.IsVisible)
                        continue;

                    Rect flRect = new Rect(
                        PointFromScreen(new Point(fl.Left, fl.Top)), 
                        PointFromScreen(new Point(fl.Left + fl.Width, fl.Top + fl.Height)));

                    if (flRect.IntersectsWith(wndRect))
                        otherRects.Add(Rect.Intersect(flRect, wndRect));
                }

                IntPtr hDestRegn = CreateRectRgn(
                        (int)wndRect.Left,
                        (int)wndRect.Top,
                        (int)wndRect.Right,
                        (int)wndRect.Bottom);

                foreach (Rect otherRect in otherRects)
                {
                    IntPtr otherWin32Rect = CreateRectRgn(
                        (int)otherRect.Left,
                        (int)otherRect.Top,
                        (int)otherRect.Right,
                        (int)otherRect.Bottom);

                    CombineRgn(hDestRegn, hDestRegn, otherWin32Rect, (int)CombineRgnStyles.RGN_DIFF);
                }


                SetWindowRgn(new WindowInteropHelper(this).Handle, hDestRegn, true);
            }        
        }
Example #21
0
        private static bool IsInRegion(Rect region, ILocatable locatable, bool fullyEnclosed)
        {
            double x0 = locatable.X;
            double y0 = locatable.Y;

            if (false == fullyEnclosed) // Cross selection.
            {
                var test = new Rect(x0, y0, locatable.Width, locatable.Height);
                return region.IntersectsWith(test);
            }

            double x1 = x0 + locatable.Width;
            double y1 = y0 + locatable.Height;
            return (region.Contains(x0, y0) && region.Contains(x1, y1));
        }
    public void AddDraggedColumnGhost( UIElement element )
    {
      if( ( element == null ) || m_elementToDraggedElementAdorner.ContainsKey( element ) )
        return;

      // Get the Rect for the DataGridControl
      DataGridControl dataGridControl = this.DraggedDataGridContext.DataGridControl;

      Rect dataGridControlRect = new Rect( 0, 0, dataGridControl.ActualWidth, dataGridControl.ActualHeight );

      Point elementToDataGridControl = element.TranslatePoint( ColumnReorderingDragSourceManager.EmptyPoint, dataGridControl );

      // Get the Rect for the element that request a ghost
      Rect elementRect = new Rect( elementToDataGridControl, element.RenderSize );

      // This is a special case with the current Element that is always layouted, but can be out of view
      if( !elementRect.IntersectsWith( dataGridControlRect ) )
        return;

      AnimatedDraggedElementAdorner adorner = new AnimatedDraggedElementAdorner( element, this.AdornerLayerInsideDragContainer, true );

      this.ApplyContainerClip( adorner );

      this.AdornerLayerInsideDragContainer.Add( adorner );

      m_elementToDraggedElementAdorner.Add( element, adorner );
    }
 public static bool CheckCollision(TextBlock e1, TextBlock e2)
 {
     var r1 = new Rect(e1.Margin.Left, e1.Margin.Top, e1.ActualWidth, e1.ActualHeight);
     return r1.IntersectsWith(new Rect(e2.Margin.Left, e2.Margin.Top, e2.Width, e2.Height));
 }
    private void SetPopupDragAdorner( ColumnManagerCell columnManagerCell )
    {
      if( columnManagerCell == null )
        return;

      if( m_popupDraggedElementAdorner != null )
      {
        this.AdornerLayerInsideDragContainer.Remove( m_popupDraggedElementAdorner );
        m_popupDraggedElementAdorner = null;
      }

      // Get the Rect for the DataGridControl
      DataGridControl dataGridControl = this.DraggedDataGridContext.DataGridControl;

      Rect dataGridControlRect = new Rect( 0d, 0d, dataGridControl.ActualWidth, dataGridControl.ActualHeight );

      Point elementToDataGridControl = columnManagerCell.TranslatePoint( ColumnReorderingDragSourceManager.EmptyPoint, dataGridControl );

      // Get the Rect for the element that request a ghost
      Rect elementRect = new Rect( elementToDataGridControl, columnManagerCell.RenderSize );

      // This is a special case with the current Element that is always be layouted, but can be out of view
      if( !elementRect.IntersectsWith( dataGridControlRect ) )
        return;

      AnimatedDraggedElementAdorner adorner = new AnimatedDraggedElementAdorner( columnManagerCell, this.AdornerLayerInsideDragContainer, true );

      adorner.AdornedElementImage.Opacity = 0d;

      this.ApplyContainerClip( adorner );

      this.AdornerLayerInsideDragContainer.Add( adorner );

      m_popupDraggedElementAdorner = adorner;
    }
Example #25
0
        private void UpdateSelection()
        {
            designerCanvas.SelectionService.ClearSelection();

            Rect rubberBand = new Rect(startPoint.Value, endPoint.Value);
            foreach (Control item in designerCanvas.Children)
            {
                Rect itemRect = VisualTreeHelper.GetDescendantBounds(item);
                Rect itemBounds = item.TransformToAncestor(designerCanvas).TransformBounds(itemRect);

                //rubberBand.Contains
                if (rubberBand.IntersectsWith(itemBounds))
                {
                    if (item is Connection)
                        designerCanvas.SelectionService.AddToSelection(item as ISelectable);
                    else
                    {
                        DesignerItem di = item as DesignerItem;
                        if (di.ParentID == null)
                        {
                            designerCanvas.SelectionService.AddToSelection(di);
                            DiagramControl.CanExpandAndCollapseSelectedItem = true;
                        }
                    }
                }
            }
        }
    private static bool TryHitTestCell( ColumnManagerCell cell, Point point, UIElement dragContainer )
    {
      Row parentRow = cell.ParentRow;

      if( parentRow == null )
        return true;

      FixedCellPanel fixedCellPanel = parentRow.CellsHostPanel as FixedCellPanel;

      if( fixedCellPanel == null )
        return true;

      Decorator scrollingCellsDecorator = fixedCellPanel.ScrollingCellsDecorator;

      if( !scrollingCellsDecorator.IsAncestorOf( cell ) )
        return true;

      Point cellPoint = cell.TranslatePoint( ColumnReorderingDragSourceManager.EmptyPoint, dragContainer );

      Rect cellRect = new Rect( cellPoint.X, cellPoint.Y, cell.ActualWidth, cell.ActualHeight );

      Point scrollingCellsDecoratorPoint = scrollingCellsDecorator.TranslatePoint( ColumnReorderingDragSourceManager.EmptyPoint, dragContainer );

      Rect scrollingCellsDecoratorRect = new Rect( scrollingCellsDecoratorPoint.X, scrollingCellsDecoratorPoint.Y, scrollingCellsDecorator.ActualWidth, scrollingCellsDecorator.ActualHeight );

      if( !cellRect.IntersectsWith( scrollingCellsDecoratorRect ) )
      {
        return false;
      }
      else if( !scrollingCellsDecoratorRect.Contains( point ) )
      {
        return false;
      }

      return true;
    }
        private void UpdateTargetLocation(ImageAdornment imageAdornment)
        {
            imageAdornment.RenderTrackingPoint = null;

            foreach (ITextViewLine line in View.TextViewLines)
            {
                var lineArea = new Rect(line.Left, line.Top, line.Width, line.Height);
                Rect imageAdornmentArea = imageAdornment.VisualElement.Area;
                // Use the height half to be able to move the image up and down
                imageAdornmentArea.Height = imageAdornmentArea.Height/2;

                if (line.Length > 0 && lineArea.IntersectsWith(imageAdornmentArea))
                {
                    imageAdornment.RenderTrackingPoint = View.TextSnapshot.CreateTrackingPoint(line.Start.Position,
                                                                                               PointTrackingMode.Negative);
                    imageAdornment.UpdateTrackingSpan(line);

                    return;
                }
            }
        }
Example #28
0
        /// <summary> 
        /// Moves the specified rectangle into view, if it isn't already visible.
        /// </summary> 
        /// <param name="r">A rectangle relative to the upper-left corner of the Viewport</param> 
        /// <param name="alwaysCenter">Whether to center the rect at all times or only when necessary.</param>
        private void MakeRectVisible(Rect r, bool alwaysCenter) 
        {
            if (r != Rect.Empty)
            {
                //Calculate the real position of the rectangle in the document. 
                Rect translatedRect = new Rect(HorizontalOffset + r.X, VerticalOffset + r.Y,
                                               r.Width, r.Height); 
 
                Rect viewportRect = new Rect(HorizontalOffset, VerticalOffset,
                                             ViewportWidth, 
                                             ViewportHeight);

                //Unless the alwaysCenter flag is set, if the new position is already
                //visible we don't need to shift the viewport. Otherwise we shift 
                //the offsets so the rect is visible, centering if possible.
                if (alwaysCenter || !translatedRect.IntersectsWith(viewportRect)) 
                { 
                    SetHorizontalOffsetInternal(translatedRect.X - (ViewportWidth / 2.0));
                    SetVerticalOffsetInternal(translatedRect.Y - (ViewportHeight / 2.0)); 
                }
            }
        }
		static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVC, int segmentEndVC)
		{
			TextLine lastTextLine = visualLine.TextLines.Last();
			Vector scrollOffset = textView.ScrollOffset;
			
			for (int i = 0; i < visualLine.TextLines.Count; i++) {
				TextLine line = visualLine.TextLines[i];
				double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop);
				int visualStartCol = visualLine.GetTextLineVisualStartColumn(line);
				int visualEndCol = visualStartCol + line.Length;
				if (line != lastTextLine)
					visualEndCol -= line.TrailingWhitespaceLength;
				
				if (segmentEndVC < visualStartCol)
					break;
				if (lastTextLine != line && segmentStartVC > visualEndCol)
					continue;
				int segmentStartVCInLine = Math.Max(segmentStartVC, visualStartCol);
				int segmentEndVCInLine = Math.Min(segmentEndVC, visualEndCol);
				y -= scrollOffset.Y;
				if (segmentStartVCInLine == segmentEndVCInLine) {
					// GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit
					// We need to return a rectangle to ensure empty lines are still visible
					double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVCInLine);
					pos -= scrollOffset.X;
					// The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active.
					// If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace.
					// Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace.
					if (segmentEndVCInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVC > segmentEndVCInLine && line.TrailingWhitespaceLength == 0)
						continue;
					if (segmentStartVCInLine == visualStartCol && i > 0 && segmentStartVC < segmentStartVCInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0)
						continue;
					yield return new Rect(pos, y, 1, line.Height);
				} else {
					Rect lastRect = Rect.Empty;
					if (segmentStartVCInLine <= visualEndCol) {
						foreach (TextBounds b in line.GetTextBounds(segmentStartVCInLine, segmentEndVCInLine - segmentStartVCInLine)) {
							double left = b.Rectangle.Left - scrollOffset.X;
							double right = b.Rectangle.Right - scrollOffset.X;
							if (!lastRect.IsEmpty)
								yield return lastRect;
							// left>right is possible in RTL languages
							lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
						}
					}
					if (segmentEndVC >= visualLine.VisualLengthWithEndOfLineMarker) {
						double left = (segmentStartVC > visualLine.VisualLengthWithEndOfLineMarker ? visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVC) : line.Width) - scrollOffset.X;
						double right = ((segmentEndVC == int.MaxValue || line != lastTextLine) ? Math.Max(((IScrollInfo)textView).ExtentWidth, ((IScrollInfo)textView).ViewportWidth) : visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVC)) - scrollOffset.X;
						Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
						if (!lastRect.IsEmpty) {
							if (extendSelection.IntersectsWith(lastRect)) {
								lastRect.Union(extendSelection);
								yield return lastRect;
							} else {
								yield return lastRect;
								yield return extendSelection;
							}
						} else
							yield return extendSelection;
					} else
						yield return lastRect;
				}
			}
		}
Example #30
0
		bool Intersects(SnapshotSpan fullSpan, ITextViewLine line, Rect rect) {
			var span = fullSpan.Intersection(line.ExtentIncludingLineBreak);
			if (span == null || span.Value.Length == 0)
				return false;
			var start = line.GetExtendedCharacterBounds(span.Value.Start);
			var end = line.GetExtendedCharacterBounds(span.Value.End - 1);
			double left = Math.Min(start.Left, end.Left) - wpfTextView.ViewportLeft;
			double top = Math.Min(start.Top, end.Top) - wpfTextView.ViewportTop;
			double right = Math.Max(start.Right, end.Right) - wpfTextView.ViewportLeft;
			double bottom = Math.Max(start.Bottom, end.Bottom) - wpfTextView.ViewportTop;
			bool b = left <= right && top <= bottom;
			Debug.Assert(b);
			if (!b)
				return false;
			var r = new Rect(left, top, right - left, bottom - top);
			return r.IntersectsWith(rect);
		}