private void AddBranchAdornment(ITextViewLine line, SnapshotSpan span, LineCoverage coverage, bool isUpToDate) { var diameter = _textView.LineHeight / _branchCoverageSpotHeightDivider; var spacing = _branchCoverageSpotGap + diameter; var top = (line.Height - diameter) / 2d; var brush = _brushesAndPens[coverage.BranchCoverageState].Brush; var pen = _brushesAndPens[coverage.BranchCoverageState].Pen; var groupIndex = 0; var index = 0; var left = _sequenceCoverageLineWidth * 1.5d; foreach (var branchPoint in coverage.BranchesVisited) { foreach (var branch in branchPoint) { var rect = new Rect(left, line.Top + top, diameter, diameter); var geometry = new EllipseGeometry(rect); geometry.Freeze(); var brushOverride = brush; var penOverride = pen; if (branch && coverage.BranchVisitors[groupIndex][index].Any(p => SelectedTests.Contains(p))) { brushOverride = _selectedBrushAndPen.Brush; penOverride = _selectedBrushAndPen.Pen; } var drawing = new GeometryDrawing(branch ? brushOverride : null, penOverride, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image() { Source = drawingImage, Opacity = isUpToDate ? 1d : _modifiedOpacity }; var testMethod = coverage.BranchVisitors[groupIndex][index].FirstOrDefault(); if (testMethod != null) { image.MouseLeftButtonDown += (o, e) => e.Handled = true; image.MouseLeftButtonUp += (o, e) => _selectTestCommand.Execute(testMethod); image.Cursor = Cursors.Hand; image.Tag = coverage.BranchVisitors[groupIndex][index].ToArray(); image.MouseRightButtonDown += (o, e) => e.Handled = true; image.MouseRightButtonUp += OnTestItemRightButtonUp; SharedDictionaryManager.InitializeDictionaries(image.Resources.MergedDictionaries); } Canvas.SetLeft(image, geometry.Bounds.Left); Canvas.SetTop(image, geometry.Bounds.Top); _adornmentLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); left += spacing; index++; } groupIndex++; index = 0; left += spacing; } }
private void AddResultAnchorAdornment(ITextViewLine line, SnapshotSpan span, LineResult[] lineResults, bool isUpToDate) { if (lineResults.Length > 0) { var geometry = Geometry.Parse("F1M9.4141,8L12.4141,11 11.0001,12.414 8.0001,9.414 5.0001,12.414 3.5861,11 6.5861,8 3.5861,5 5.0001,3.586 8.0001,6.586 11.0001,3.586 12.4141,5z"); geometry.Freeze(); var drawing = new GeometryDrawing(lineResults.Any(p => p.IsPrimary) ? _exceptionOriginBrushAndPen.Brush : _exceptionTraceBrushAndPen.Brush, null, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var toolTip = new StackPanel() { MaxWidth = 600 }; foreach (var group in lineResults.GroupBy(p => p.ErrorMessage)) { var header = new TextBlock() { Text = string.Join(Environment.NewLine, group.Select(p => p.TestMethod.ShortName).Distinct()), TextWrapping = TextWrapping.Wrap }; var description = new TextBlock() { Text = group.Key, TextWrapping = TextWrapping.Wrap, Opacity = 0.7d, Margin = new Thickness(0, 0, 0, 10) }; toolTip.Children.Add(header); toolTip.Children.Add(description); } toolTip.Children.OfType <TextBlock>().Last().Margin = new Thickness(); var viewBox = new Viewbox() { Width = _textView.LineHeight, Height = _textView.LineHeight, Stretch = Stretch.Uniform }; var button = new ActionButton() { Icon = drawingImage, CommandParameter = lineResults.FirstOrDefault().TestMethod, Command = _selectTestCommand, ToolTip = toolTip, Cursor = Cursors.Hand, Tag = new AnchorData() { Targets = lineResults.Select(p => p.TestMethod).ToArray(), Type = AnchorType.Error }, Opacity = isUpToDate ? 1 : _modifiedOpacity }; button.MouseRightButtonDown += (o, e) => e.Handled = true; button.MouseRightButtonUp += OnTestItemRightButtonUp; viewBox.Child = button; Canvas.SetLeft(viewBox, _sequenceCoverageLineWidth); Canvas.SetTop(viewBox, line.Top); _adornmentLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, viewBox, null); } }
private void HighlightCoverage(CoverageState[] coverdata, ProfileVector profiledata, ITextViewLine line) { if (view == null || profiledata == null || line == null || view.TextSnapshot == null) { return; } IWpfTextViewLineCollection textViewLines = view.TextViewLines; if (textViewLines == null || line.Extent == null) { return; } int lineno = 1 + view.TextSnapshot.GetLineNumberFromPosition(line.Extent.Start); CoverageState covered = lineno < coverdata.Length ? coverdata[lineno] : CoverageState.Irrelevant; if (covered != CoverageState.Irrelevant) { SnapshotSpan span = new SnapshotSpan(view.TextSnapshot, Span.FromBounds(line.Start, line.End)); Geometry g = textViewLines.GetMarkerGeometry(span); if (g != null) { g = new RectangleGeometry(new Rect(g.Bounds.X, g.Bounds.Y, view.ViewportWidth, g.Bounds.Height)); GeometryDrawing drawing = (covered == CoverageState.Covered) ? new GeometryDrawing(coveredBrush, coveredPen, g) : new GeometryDrawing(uncoveredBrush, uncoveredPen, g); drawing.Freeze(); DrawingImage drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); Image image = new Image(); image.Source = drawingImage; //Align the image with the top of the bounds of the text geometry Canvas.SetLeft(image, g.Bounds.Left); Canvas.SetTop(image, g.Bounds.Top); layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); } } var profile = profiledata.Get(lineno); if (profile != null && profile.Item1 != 0 || profile.Item2 != 0) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(profile.Item1); sb.Append("%/"); sb.Append(profile.Item2); sb.Append("%"); SnapshotSpan span = new SnapshotSpan(view.TextSnapshot, Span.FromBounds(line.Start, line.End)); Geometry g = textViewLines.GetMarkerGeometry(span); if (g != null) // Yes, this apparently happens... { double x = g.Bounds.X + g.Bounds.Width + 20; if (x < view.ViewportWidth / 2) { x = view.ViewportWidth / 2; } g = new RectangleGeometry(new Rect(x, g.Bounds.Y, 30, g.Bounds.Height)); Label lbl = new Label(); lbl.FontSize = 7; lbl.Foreground = Brushes.Black; lbl.Background = Brushes.Transparent; lbl.FontFamily = new FontFamily("Verdana"); lbl.Content = sb.ToString(); Canvas.SetLeft(lbl, g.Bounds.Left); Canvas.SetTop(lbl, g.Bounds.Top); layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, lbl, null); } } }
private void AddSequenceAdornment(ITextViewLine line, SnapshotSpan span, LineCoverage coverage, bool isUpToDate) { var rect = new Rect(0d, line.Top, _sequenceCoverageLineWidth, line.Height); var geometry = new RectangleGeometry(rect); geometry.Freeze(); var brush = _brushesAndPens[coverage.SequenceCoverageState].Brush; if (coverage.SequenceCoverageState == CoverageState.Covered && coverage.LineVisitors.Any(p => SelectedTests.Contains(p))) { brush = _selectedBrushAndPen.Brush; } var drawing = new GeometryDrawing(brush, null, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var toolTip = new StackPanel(); var header = new TextBlock() { Text = string.Format(Resources.VisitorCount, coverage.VisitCount), TextWrapping = TextWrapping.Wrap }; toolTip.Children.Add(header); var image = new Image() { Source = drawingImage, ToolTip = toolTip, Opacity = isUpToDate ? 1d : _modifiedOpacity }; Canvas.SetLeft(image, geometry.Bounds.Left); Canvas.SetTop(image, geometry.Bounds.Top); SharedDictionaryManager.InitializeDictionaries(image.Resources.MergedDictionaries); if (coverage.LineVisitors.Count > 0) { var description = new TextBlock() { Text = string.Join("\r\n", coverage.LineVisitors.Select(p => p.ShortName)), TextWrapping = TextWrapping.Wrap, Opacity = 0.7d }; toolTip.Children.Add(description); image.Tag = coverage.LineVisitors.ToArray(); image.MouseRightButtonDown += (o, e) => e.Handled = true; image.MouseRightButtonUp += OnTestItemRightButtonUp; image.MouseLeftButtonDown += (o, e) => e.Handled = true; image.MouseLeftButtonUp += (o, e) => _selectTestCommand.Execute(coverage.LineVisitors.First()); image.Cursor = Cursors.Hand; } _adornmentLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); }
private void DrawCaret(Selection selection) { SnapshotSpan span; Geometry geometry; // EOF edge case fix if (selection.Caret.GetPosition(Snapshot) == Snapshot.Length) { span = new SnapshotSpan(selection.Caret.GetPoint(Snapshot).Subtract(1), 1); var textView = view.TextViewLines[view.TextViewLines.Count - 1]; var rect = new Rect( textView.Right, textView.Bottom - view.FormattedLineSource.LineHeight, view.FormattedLineSource.ColumnWidth, view.FormattedLineSource.LineHeight); geometry = new RectangleGeometry(rect); } else { span = new SnapshotSpan(selection.Caret.GetPoint(Snapshot), 1); geometry = view.TextViewLines.GetMarkerGeometry(span); } UIElement element = null; double virtualSpace = 0; if (geometry != null) { if (view.Caret.OverwriteMode && !selection.IsSelection()) { var drawing = new GeometryDrawing(insertionBrush, new Pen(), geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); element = new Image { Source = drawingImage }; } else { element = new Rectangle { Fill = caretBrush, Width = view.FormattedLineSource.ColumnWidth / 6, Height = view.FormattedLineSource.LineHeight, Margin = new Thickness(0, 0, 0, 0), }; virtualSpace = selection.VirtualSpaces * view.TextViewLines[0].VirtualSpaceWidth; } } if (element != null) { Canvas.SetLeft(element, geometry.Bounds.Left + virtualSpace); Canvas.SetTop(element, geometry.Bounds.Top); layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, Vsix.Name, element, null); } }
public TileModeExample() { Background = Brushes.White; Margin = new Thickness(20); StackPanel mainPanel = new StackPanel(); mainPanel.HorizontalAlignment = HorizontalAlignment.Left; // // Create a Drawing. This will be the DrawingBrushes' content. // PolyLineSegment triangleLinesSegment = new PolyLineSegment(); triangleLinesSegment.Points.Add(new Point(50, 0)); triangleLinesSegment.Points.Add(new Point(0, 50)); PathFigure triangleFigure = new PathFigure(); triangleFigure.IsClosed = true; triangleFigure.StartPoint = new Point(0, 0); triangleFigure.Segments.Add(triangleLinesSegment); PathGeometry triangleGeometry = new PathGeometry(); triangleGeometry.Figures.Add(triangleFigure); GeometryDrawing triangleDrawing = new GeometryDrawing(); triangleDrawing.Geometry = triangleGeometry; triangleDrawing.Brush = new SolidColorBrush(Color.FromArgb(255, 204, 204, 255)); Pen trianglePen = new Pen(Brushes.Black, 2); triangleDrawing.Pen = trianglePen; trianglePen.MiterLimit = 0; triangleDrawing.Freeze(); // // Create the first TileBrush. Its content is not tiled. // DrawingBrush tileBrushWithoutTiling = new DrawingBrush(); tileBrushWithoutTiling.Drawing = triangleDrawing; tileBrushWithoutTiling.TileMode = TileMode.None; // Create a rectangle and paint it with the DrawingBrush. Rectangle noTileExampleRectangle = createExampleRectangle(); noTileExampleRectangle.Fill = tileBrushWithoutTiling; // Add a header and the rectangle to the main panel. mainPanel.Children.Add(createExampleHeader("None")); mainPanel.Children.Add(noTileExampleRectangle); // // Create another TileBrush, this time with tiling. // DrawingBrush tileBrushWithTiling = new DrawingBrush(); tileBrushWithTiling.Drawing = triangleDrawing; tileBrushWithTiling.TileMode = TileMode.Tile; // Specify the brush's Viewport. Otherwise, // a single tile will be produced that fills // the entire output area and its TileMode will // have no effect. // This setting uses realtive values to // creates four tiles. tileBrushWithTiling.Viewport = new Rect(0, 0, 0.5, 0.5); // Create a rectangle and paint it with the DrawingBrush. Rectangle tilingExampleRectangle = createExampleRectangle(); tilingExampleRectangle.Fill = tileBrushWithTiling; mainPanel.Children.Add(createExampleHeader("Tile")); mainPanel.Children.Add(tilingExampleRectangle); // // Create a TileBrush with FlipX tiling. // The brush's content is flipped horizontally as it is // tiled in this example // DrawingBrush tileBrushWithFlipXTiling = new DrawingBrush(); tileBrushWithFlipXTiling.Drawing = triangleDrawing; tileBrushWithFlipXTiling.TileMode = TileMode.FlipX; // Specify the brush's Viewport. tileBrushWithFlipXTiling.Viewport = new Rect(0, 0, 0.5, 0.5); // Create a rectangle and paint it with the DrawingBrush. Rectangle flipXTilingExampleRectangle = createExampleRectangle(); flipXTilingExampleRectangle.Fill = tileBrushWithFlipXTiling; mainPanel.Children.Add(createExampleHeader("FlipX")); mainPanel.Children.Add(flipXTilingExampleRectangle); // // Create a TileBrush with FlipY tiling. // The brush's content is flipped vertically as it is // tiled in this example // DrawingBrush tileBrushWithFlipYTiling = new DrawingBrush(); tileBrushWithFlipYTiling.Drawing = triangleDrawing; tileBrushWithFlipYTiling.TileMode = TileMode.FlipY; // Specify the brush's Viewport. tileBrushWithFlipYTiling.Viewport = new Rect(0, 0, 0.5, 0.5); // Create a rectangle and paint it with the DrawingBrush. Rectangle flipYTilingExampleRectangle = createExampleRectangle(); flipYTilingExampleRectangle.Fill = tileBrushWithFlipYTiling; mainPanel.Children.Add(createExampleHeader("FlipY")); mainPanel.Children.Add(flipYTilingExampleRectangle); // // Create a TileBrush with FlipXY tiling. // The brush's content is flipped vertically as it is // tiled in this example // DrawingBrush tileBrushWithFlipXYTiling = new DrawingBrush(); tileBrushWithFlipXYTiling.Drawing = triangleDrawing; tileBrushWithFlipXYTiling.TileMode = TileMode.FlipXY; // Specify the brush's Viewport. tileBrushWithFlipXYTiling.Viewport = new Rect(0, 0, 0.5, 0.5); // Create a rectangle and paint it with the DrawingBrush. Rectangle flipXYTilingExampleRectangle = createExampleRectangle(); flipXYTilingExampleRectangle.Fill = tileBrushWithFlipXYTiling; mainPanel.Children.Add(createExampleHeader("FlipXY")); mainPanel.Children.Add(flipXYTilingExampleRectangle); Content = mainPanel; }
private void CreateVisual(CaretAdornmentData nodeData, int caretLineOffset, int caretOffset, IUserIdentity userIdentity) { if (RepoDocument != null && nodeData.RelativeToServerSource) { var remoteFileText = SourceControlRepo.GetRemoteFileLines(View.TextBuffer.GetTextDocumentFilePath()); if (remoteFileText != null) { string localFileText = View.TextSnapshot.GetText(); caretLineOffset = LineNumberTranslator.GetLineNumber(localFileText.Split(new[] { "\r\n" }, StringSplitOptions.None), remoteFileText, caretLineOffset, FileNumberBasis.Local); } } var caretLineNumber = View.TextSnapshot.GetLineNumberFromPosition(nodeData.SpanStart) + caretLineOffset; var caretPosition = View.TextSnapshot.GetLineFromLineNumber(Math.Min(caretLineNumber, View.TextSnapshot.LineCount - 1)).Start.Position + caretOffset; if (caretPosition < nodeData.NonWhiteSpaceStart) { caretPosition = nodeData.NonWhiteSpaceStart; } else if (caretPosition > nodeData.SpanEnd) { caretPosition = nodeData.SpanEnd; } var atEnd = caretPosition >= View.TextSnapshot.Length; var remoteCaretSpan = new SnapshotSpan(View.TextSnapshot, atEnd ? View.TextSnapshot.Length - 1 : caretPosition, 1); var onSameLineAsEnd = remoteCaretSpan.Start.GetContainingLine().LineNumber == View.TextSnapshot.GetLineNumberFromPosition(View.TextSnapshot.Length); Geometry characterGeometry = View.TextViewLines.GetMarkerGeometry(remoteCaretSpan); if (characterGeometry != null) { var caretGeometry = new LineGeometry(atEnd && onSameLineAsEnd ? characterGeometry.Bounds.TopRight : characterGeometry.Bounds.TopLeft, atEnd && onSameLineAsEnd ? characterGeometry.Bounds.BottomRight : characterGeometry.Bounds.BottomLeft); var drawing = new GeometryDrawing(null, UserColours.GetUserPen(userIdentity), caretGeometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image { Source = drawingImage, }; // Align the image with the top of the bounds of the text geometry var bounds = caretGeometry.Bounds; Canvas.SetLeft(image, bounds.Left); Canvas.SetTop(image, bounds.Top); Layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, remoteCaretSpan, null, image, null); FrameworkElement userControl = null; if (UserAvatars.ContainsKey(userIdentity.Id) && UserAvatars[userIdentity.Id].Count != 0) { userControl = UserAvatars[userIdentity.Id].Dequeue(); } if (TeamCodingPackage.Current.Settings.UserSettings.UserCodeDisplay == Options.UserSettings.UserDisplaySetting.Colour) { if (userControl == null) { userControl = new Border() { Tag = userIdentity.Id, Background = UserColours.GetUserBrush(userIdentity), CornerRadius = new CornerRadius(bounds.Height / 2 / 2) }; } userControl.Width = bounds.Height / 2; userControl.Height = bounds.Height / 2; Canvas.SetTop(userControl, bounds.Top - (userControl.Height * 0.75)); } else { if (userControl == null) { userControl = TeamCodingPackage.Current.UserImages.CreateUserIdentityControl(userIdentity); } userControl.Width = bounds.Height / 1.25f; userControl.Height = bounds.Height / 1.25f; Canvas.SetTop(userControl, bounds.Top - userControl.Height); } userControl.ToolTip = userIdentity.DisplayName ?? userIdentity.Id; Canvas.SetLeft(userControl, bounds.Left - userControl.Width / 2); Layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, remoteCaretSpan, null, userControl, AdornmentRemoved); } }
public async System.Threading.Tasks.Task Explode() { if (ParticleCount > MaxParticleCount) { return; } ParticleCount++; // TODO: rewrite this part for better design & performance // store service & package as static member. var service = ServiceProvider.GlobalProvider.GetService(typeof(SPowerMode)); var pm_service = service as IPowerMode; var package = pm_service.Package; var page = package.General; ExplosionParticle.Color = page.Color; ExplosionParticle.AlphaRemoveAmount = page.AlphaRemoveAmount; ExplosionParticle.bGetColorFromEnvironment = bGetColorFromEnvironment; ExplosionParticle.RandomColor = page.RandomColor; ExplosionParticle.FrameDelay = page.FrameDelay; ExplosionParticle.Gravity = page.Gravity; ExplosionParticle.MaxParticleCount = page.MaxParticleCount; ExplosionParticle.MaxSideVelocity = page.MaxSideVelocity; ExplosionParticle.MaxUpVelocity = page.MaxUpVelocity; //ExplosionParticle.ParticlesEnabled = page.ParticlesEnabled; //ExplosionParticle.ShakeEnabled = page.ShakeEnabled; ExplosionParticle.StartAlpha = page.StartAlpha; // End of TODO. var alpha = StartAlpha; var upVelocity = Random.NextDouble() * MaxUpVelocity; var leftVelocity = Random.NextDouble() * MaxSideVelocity * Random.NextSignSwap(); SolidColorBrush brush = null; if (bGetColorFromEnvironment) { var svc = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SVsUIShell)) as Microsoft.VisualStudio.Shell.Interop.IVsUIShell5; brush = new SolidColorBrush(Microsoft.VisualStudio.Shell.VsColors.GetThemedWPFColor(svc, Microsoft.VisualStudio.PlatformUI.EnvironmentColors.PanelTextColorKey)); } else if (RandomColor) { brush = new SolidColorBrush(Random.NextColor()); } else { brush = new SolidColorBrush(Color); } brush.Freeze(); var drawing = new GeometryDrawing(brush, null, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image { Source = drawingImage, }; while (alpha >= AlphaRemoveAmount) { _left -= leftVelocity; _top -= upVelocity; upVelocity -= Gravity; alpha -= AlphaRemoveAmount; image.Opacity = alpha; Canvas.SetLeft(image, _left); Canvas.SetTop(image, _top); try { // Add the image to the adornment layer and make it relative to the viewport adornmentLayer.AddAdornment(AdornmentPositioningBehavior.ViewportRelative, null, null, image, null); await System.Threading.Tasks.Task.Delay(FrameDelay); adornmentLayer.RemoveAdornment(image); } catch { break; } } try { adornmentLayer.RemoveAdornment(image); } catch { //Ignore all errors, not critical } ParticleCount--; }
public static DrawingImage CreateImage(PointPattern[] pointPatterns, Size size, Color color) { if (pointPatterns == null) { return(null); } DrawingGroup drawingGroup = new DrawingGroup(); for (int i = 0; i < pointPatterns.Length; i++) { PathGeometry pathGeometry = new PathGeometry(); color.A = (byte)(0xFF - i * 0x55); SolidColorBrush brush = new SolidColorBrush(color); Pen drawingPen = new Pen(brush, 3 + i * 2) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }; if (pointPatterns[i].Points == null) { return(null); } for (int j = 0; j < pointPatterns[i].Points.Count; j++) { if (pointPatterns[i].Points[j].Count == 1) { Geometry ellipse = new EllipseGeometry(new Point(size.Width * j + size.Width / 2, size.Height / 2), drawingPen.Thickness / 2, drawingPen.Thickness / 2); pathGeometry.AddGeometry(ellipse); continue; } StreamGeometry sg = new StreamGeometry { FillRule = FillRule.EvenOdd }; using (StreamGeometryContext sgc = sg.Open()) { // Create new size object accounting for pen width Size szeAdjusted = new Size(size.Width - drawingPen.Thickness - 1, (size.Height - drawingPen.Thickness - 1)); Size scaledSize; Point[] scaledPoints = ScaleGesture(pointPatterns[i].Points[j], szeAdjusted.Width - 10, szeAdjusted.Height - 10, out scaledSize); // Define size that will mark the offset to center the gesture double iLeftOffset = (size.Width / 2) - (scaledSize.Width / 2); double iTopOffset = (size.Height / 2) - (scaledSize.Height / 2); Vector sizOffset = new Vector(iLeftOffset + j * size.Width, iTopOffset); sgc.BeginFigure(Point.Add(scaledPoints[0], sizOffset), false, false); foreach (Point p in scaledPoints) { sgc.LineTo(Point.Add(p, sizOffset), true, true); } DrawArrow(sgc, scaledPoints, sizOffset, drawingPen.Thickness); } sg.Freeze(); pathGeometry.AddGeometry(sg); } pathGeometry.Freeze(); GeometryDrawing drawing = new GeometryDrawing(null, drawingPen, pathGeometry); drawing.Freeze(); drawingGroup.Children.Add(drawing); } // myPath.Data = sg; drawingGroup.Freeze(); DrawingImage drawingImage = new DrawingImage(drawingGroup); drawingImage.Freeze(); return(drawingImage); }
/// <summary> /// Adds the scarlet box behind the 'a' characters within the given line /// </summary> /// <param name="line">Line to add the adornments</param> private void CreateVisuals(SnapshotSpan leftItem, SnapshotSpan rightItem) { if (VSPackage.Options != null) { this.layer.RemoveAllAdornments(); var swapColor = (Color)ColorConverter.ConvertFromString(VSPackage.Options.ArrowColor); var swapPenBrush = new SolidColorBrush(swapColor); swapPenBrush.Freeze(); var swapPen = new Pen(swapPenBrush, 2); swapPen.Freeze(); var textViewLines = this.view.TextViewLines; renderAdorner(leftItem, false); renderAdorner(rightItem, true); void renderAdorner(SnapshotSpan snapshotSpan, bool isRight) { var geometry = textViewLines.GetMarkerGeometry(snapshotSpan); if (geometry != null) { var swapRect = new Rect(geometry.Bounds.Location, geometry.Bounds.Size); swapRect.Inflate(4, 4); var swapLine = new GeometryGroup(); switch (VSPackage.Options.AdornmentType) { case 1: swapLine = MakeSwapArrow(swapRect); break; case 2: swapLine = MakeSwapBracket(swapRect); break; case 3: swapLine = MakeSwapBadge(swapRect); break; } var drawing = new GeometryDrawing(new SolidColorBrush(swapColor), swapPen, swapLine); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var swapImage = new Image { Source = drawingImage, }; if (isRight) { Canvas.SetLeft(swapImage, swapRect.Right - drawing.Bounds.Width); Canvas.SetTop(swapImage, swapRect.Top); swapImage.RenderTransformOrigin = new Point(0.5, 0.5); var flipTrans = new ScaleTransform(-1, 1); swapImage.RenderTransform = flipTrans; } else { Canvas.SetLeft(swapImage, swapRect.Left); Canvas.SetTop(swapImage, swapRect.Top); } this.layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, snapshotSpan, null, swapImage, null); } } } }
protected override void OnRefresh() { RotarySwitch rotarySwitch = Visual as RotarySwitch; if (rotarySwitch != null) { _imageRect.Width = rotarySwitch.Width; _imageRect.Height = rotarySwitch.Height; _image = ConfigManager.ImageManager.LoadImage(rotarySwitch.KnobImage); _imageBrush = new ImageBrush(_image); _center = new Point(rotarySwitch.Width / 2d, rotarySwitch.Height / 2d); _lines = new GeometryDrawing(); _lines.Pen = new Pen(new SolidColorBrush(rotarySwitch.LineColor), rotarySwitch.LineThickness); _labels.Clear(); Vector v1 = new Point(_center.X, 0) - _center; double lineLength = v1.Length * rotarySwitch.LineLength; double labelDistance = v1.Length * rotarySwitch.LabelDistance; v1.Normalize(); GeometryGroup lineGroup = new GeometryGroup(); Brush labelBrush = new SolidColorBrush(rotarySwitch.LabelColor); foreach (RotarySwitchPosition position in rotarySwitch.Positions) { Matrix m1 = new Matrix(); m1.Rotate(position.Rotation); if (rotarySwitch.DrawLines) { Vector v2 = v1 * m1; Point startPoint = _center; Point endPoint = startPoint + (v2 * lineLength); lineGroup.Children.Add(new LineGeometry(startPoint, endPoint)); } if (rotarySwitch.DrawLabels) { FormattedText labelText = rotarySwitch.LabelFormat.GetFormattedText(labelBrush, position.Name); labelText.TextAlignment = TextAlignment.Center; labelText.MaxTextWidth = rotarySwitch.Width; labelText.MaxTextHeight = rotarySwitch.Height; if (rotarySwitch.MaxLabelHeight > 0d && rotarySwitch.MaxLabelHeight < rotarySwitch.Height) { labelText.MaxTextHeight = rotarySwitch.MaxLabelHeight; } if (rotarySwitch.MaxLabelWidth > 0d && rotarySwitch.MaxLabelWidth < rotarySwitch.Width) { labelText.MaxTextWidth = rotarySwitch.MaxLabelWidth; } Point location = _center + (v1 * m1 * labelDistance); if (position.Rotation <= 10d || position.Rotation >= 350d) { location.X -= labelText.MaxTextWidth / 2d; location.Y -= labelText.Height; } else if (position.Rotation < 170d) { location.X -= (labelText.MaxTextWidth - labelText.Width) / 2d; location.Y -= labelText.Height / 2d; } else if (position.Rotation <= 190d) { location.X -= labelText.MaxTextWidth / 2d; } else { location.X -= (labelText.MaxTextWidth + labelText.Width) / 2d; location.Y -= labelText.Height / 2d; } _labels.Add(new SwitchPositionLabel(labelText, location)); } } _lines.Geometry = lineGroup; _lines.Freeze(); } else { _image = null; _imageBrush = null; _lines = null; _labels.Clear(); } }
/// <summary> /// When hit Ctrl+D /// </summary> internal void SelectNextOcurrence() { string selectedText; // Se já tem algo selecionado if (_selectionList.Count <= 0 && !_view.Selection.IsEmpty) { selectedText = _view.Selection.StreamSelectionSpan.GetText(); // Coloca o cursor na própria palavra já selecionada _lastIndex = (_lastIndex == 0) ? _view.Selection.ActivePoint.Position.Position - selectedText.Length : _lastIndex; } else if (_selectionList.Count > 0) { var itemSelecionado = _selectionList[0]; selectedText = _view.TextViewLines.FormattedSpan.GetText().Substring(itemSelecionado.Start, itemSelecionado.End - itemSelecionado.Start); // Coloca o cursor na própria palavra já selecionada _lastIndex = (_lastIndex == 0) ? itemSelecionado.End - selectedText.Length : _lastIndex; } else { // Se não tinha nada selecionado então retorno pois agora o filtro é este, o comando sempre vem para cá return; } _view.Selection.IsActive = false; _view.Selection.Clear(); _view.Caret.IsHidden = true; // Expressão para buscar todas as palavras que forem iguais ao texto selecionado Regex todoLineRegex = new Regex(selectedText + @"\b"); // Executa a expressão buscando as palavras MatchCollection matches = todoLineRegex.Matches(_view.TextViewLines.FormattedSpan.GetText()); // Se encontrou algo igual ao selecionado if (matches.Count > 0) { // Último match que foi encontrado Match ultimoMatch = matches[matches.Count - 1]; // Próximo match depois do último selecionado Match match = todoLineRegex.Match(_view.TextViewLines.FormattedSpan.GetText(), _lastIndex); // Se selecionou a próxima e é depois da última if (match.Success && (_trackPointList.Count < matches.Count)) { if (match.Index == ultimoMatch.Index) { _lastIndex = 1; } else { _lastIndex = match.Index + match.Length; } SnapshotSpan span = new SnapshotSpan(_view.TextSnapshot, Span.FromBounds(match.Index, match.Index + match.Length)); Geometry geometry = _view.TextViewLines.GetMarkerGeometry(span); if (geometry != null) { Brush brush = new SolidColorBrush(Color.FromArgb(0x20, 0x00, 0x00, 0xff)); brush.Freeze(); SolidColorBrush penBrush = new SolidColorBrush(Colors.Red); penBrush.Freeze(); Pen pen = new Pen(penBrush, 0.5); pen.Freeze(); GeometryDrawing drawing = new GeometryDrawing(brush, pen, geometry); drawing.Freeze(); DrawingImage drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); Image image = new Image { Source = drawingImage, }; // Align the image with the top of the bounds of the text geometry Canvas.SetLeft(image, geometry.Bounds.Left); Canvas.SetTop(image, geometry.Bounds.Top); // Adiciona o adornment, mas ao fazer o RedrawScreen ele é perdido _layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); // Cria o novo ponto do cursor, neste caso estou colocando ele na frente da palavra, ou seja na direita da palavra ITrackingPoint cursorTrackingPoint = _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, match.Index + match.Length), PointTrackingMode.Positive); _trackPointList.Add(cursorTrackingPoint); _selectionList.Add(new TextSelection( new Tuple <ITrackingPoint, ITrackingPoint> ( _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, match.Index), PointTrackingMode.Positive), _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, match.Index + match.Length), PointTrackingMode.Positive) ), _view)); RedrawScreen(); } } Selecting = true; // Diz que está editando Editing = true; } }
private void UpdateUIRepresentation() { if (isUpdating) { return; } if (plotter == null) { return; } IPointDataSource dataSource = DataSource; if (dataSource == null) { return; } visibleWhileUpdate = plotter.Viewport.Visible; isUpdating = true; panel.Children.Clear(); DependencyObject dependencyDataSource = dataSource as DependencyObject; if (dependencyDataSource != null) { DataSource2dContext.SetVisibleRect(dependencyDataSource, plotter.Viewport.Visible); DataSource2dContext.SetScreenRect(dependencyDataSource, plotter.Viewport.Output); } IEnumerable <Point> viewportPoints = dataSource; var transform = plotter.Viewport.Transform; if (!(transform.DataTransform is IdentityTransform)) { viewportPoints = dataSource.DataToViewport(transform.DataTransform); } var screenPoints = viewportPoints.ViewportToScreen(transform); var filteredPoints = filters.Filter(screenPoints, plotter.Viewport); DataRect bounds = DataRect.Empty; double strokeThickness = 3; bool first = true; Point lastPointOfPrevLine = new Point(); int overallCount = 0; panel.BeginBatchAdd(); const int ptsInPolyline = 500; foreach (var pointGroup in filteredPoints.Split(ptsInPolyline)) { int ptsCount = ptsInPolyline; if (!first) { ptsCount++; } PointCollection pointCollection = new PointCollection(ptsCount); if (!first) { pointCollection.Add(lastPointOfPrevLine); } else { first = false; } pointCollection.AddMany(pointGroup); overallCount += pointCollection.Count - 1; if (pointCollection.Count == 0) { break; } lastPointOfPrevLine = pointCollection[pointCollection.Count - 1]; pointCollection.Freeze(); DataRect ithBounds = BoundsHelper.GetViewportBounds(pointCollection.ScreenToViewport(transform)); #if geom UIElement line = null; StreamGeometry geometry = new StreamGeometry(); using (var dc = geometry.Open()) { dc.BeginFigure(pointCollection[0], false, false); dc.PolyLineTo(pointCollection, true, false); } geometry.Freeze(); GeometryDrawing drawing = new GeometryDrawing { Geometry = geometry, Pen = new Pen(Brushes.Blue, 1) }; drawing.Freeze(); DrawingBrush brush = new DrawingBrush { Drawing = drawing }; brush.Freeze(); var rectangle = new Rectangle { Fill = brush, IsHitTestVisible = false }; Rect ithScreenBounds = ithBounds.ViewportToScreen(transform); if (true || ithScreenBounds.Width > 2000 || ithScreenBounds.Height > 2000 || ithScreenBounds.Width < 1 || ithScreenBounds.Height < 1) { line = rectangle; } else { Size intSize = new Size((int)ithScreenBounds.Width, (int)ithScreenBounds.Height); rectangle.Measure(intSize); rectangle.Arrange(new Rect(intSize)); RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)ithScreenBounds.Width, (int)ithScreenBounds.Height, 96, 96, PixelFormats.Pbgra32); renderBitmap.Render(rectangle); renderBitmap.Freeze(); line = new Image { Source = renderBitmap }; } #else var line = CreateLine(); line.Points = pointCollection; #endif bounds.Union(ithBounds); ViewportRectPanel.SetViewportBounds(line, ithBounds); #if !geom ViewportMarginPanel.SetScreenMargin(line, new Size(strokeThickness / 2, strokeThickness / 2)); #endif panel.Children.Add(line); isUpdating = false; } panel.EndBatchAdd(); Debug.WriteLine("OverallCount = " + (overallCount + 1)); Viewport2D.SetContentBounds(this, bounds); isUpdating = false; }