예제 #1
0
        internal static double GetFontHeight(this FrameworkElement source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            var textProperties = new TextProperties(
                TextOptions.GetTextFormattingMode(source),
                TextElement.GetFontFamily(source),
                TextElement.GetFontStyle(source),
                TextElement.GetFontWeight(source),
                TextElement.GetFontStretch(source),
                TextElement.GetFontSize(source));

            lock ((( ICollection )s_fontHeight).SyncRoot)
            {
                double fontHeight;

                if (!s_fontHeight.TryGetValue(textProperties, out fontHeight))
                {
                    var formatter               = TextFormatter.Create(textProperties.FormattingMode);
                    var typeface                = new Typeface(textProperties.FontFamily, textProperties.FontStyle, textProperties.FontWeight, textProperties.FontStretch);
                    var textSource              = new EmptyTextSource();
                    var textRunProperties       = new EmptyTextRunProperties(typeface, textProperties.FontSize);
                    var textParagraphProperties = new EmptyTextParagraphProperties(textRunProperties);
                    var textLine                = formatter.FormatLine(textSource, 0, 0d, textParagraphProperties, null);

                    fontHeight = textLine.Height;
                    s_fontHeight.Add(textProperties, fontHeight);
                }

                return(fontHeight);
            }
        }
 /// <summary>
 /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
 /// </summary>
 public static TextFormatter Create(DependencyObject owner)
 {
     if (owner == null)
     {
         throw new ArgumentNullException("owner");
     }
                 #if DOTNET4
     return(TextFormatter.Create(TextOptions.GetTextFormattingMode(owner)));
                 #else
     if (TextFormattingModeProperty != null)
     {
         object formattingMode = owner.GetValue(TextFormattingModeProperty);
         return((TextFormatter)typeof(TextFormatter).InvokeMember(
                    "Create",
                    BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
                    null, null,
                    new object[] { formattingMode },
                    CultureInfo.InvariantCulture));
     }
     else
     {
         return(TextFormatter.Create());
     }
                 #endif
 }
예제 #3
0
        /// <summary>
        /// Creates formatted text.
        /// </summary>
        /// <param name="element">The owner element. The text formatter setting are read from this element.</param>
        /// <param name="text">The text.</param>
        /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param>
        /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
        /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
        /// <returns>A FormattedText object using the specified settings.</returns>
        public static FormattedText CreateFormattedText(FrameworkElement element, string text, Typeface typeface, double?emSize, Brush foreground)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            if (typeface == null)
            {
                typeface = element.CreateTypeface();
            }
            if (emSize == null)
            {
                emSize = TextBlock.GetFontSize(element);
            }
            if (foreground == null)
            {
                foreground = TextBlock.GetForeground(element);
            }

#pragma warning disable CS0618
            return(new FormattedText(
                       text,
                       CultureInfo.CurrentCulture,
                       FlowDirection.LeftToRight,
                       typeface,
                       emSize.Value,
                       foreground,
                       null,
                       TextOptions.GetTextFormattingMode(element)
                       ));
        }
예제 #4
0
 private FormattedText CreateFormattedText(string text, Typeface typeface, double?emSize, Brush foreground)
 {
     if (text == null)
     {
         throw new ArgumentNullException("text");
     }
     if (typeface == null)
     {
         typeface = CreateTypeface();
     }
     if (emSize == null)
     {
         emSize = TextBlock.GetFontSize(this);
     }
     if (foreground == null)
     {
         foreground = TextBlock.GetForeground(this);
     }
     return(new FormattedText(
                text,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                typeface,
                emSize.Value,
                foreground,
                null,
                TextOptions.GetTextFormattingMode(this)
                ));
 }
예제 #5
0
        void CreateFormattedLineSource(double viewportWidthOverride)
        {
            lastFormattedLineSourceViewportWidth = viewportWidthOverride;
            var    wordWrapStyle  = Options.WordWrapStyle();
            bool   isWordWrap     = (wordWrapStyle & WordWrapStyles.WordWrap) != 0;
            bool   isAutoIndent   = isWordWrap && (wordWrapStyle & WordWrapStyles.AutoIndent) != 0;
            double wordWrapWidth  = isWordWrap ? viewportWidthOverride : 0;
            var    maxAutoIndent  = isAutoIndent ? viewportWidthOverride / 4 : 0;
            bool   useDisplayMode = TextOptions.GetTextFormattingMode(this) == TextFormattingMode.Display;
            var    classifier     = Options.IsColorizationEnabled() ? aggregateClassifier : NullClassifier.Instance;

            int tabSize = Options.GetTabSize();

            tabSize = Math.Max(1, tabSize);
            tabSize = Math.Min(60, tabSize);

            // This value is what VS uses, see: https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.text.formatting.iformattedlinesource.baseindentation.aspx
            //	"This is generally a small value like 2.0, so that some characters (such as an italic
            //	 slash) will not be clipped by the left edge of the view."
            const double baseIndent = 2.0;

            (FormattedLineSource as IDisposable)?.Dispose();
            FormattedLineSource = formattedTextSourceFactoryService.Create(
                TextSnapshot,
                VisualSnapshot,
                tabSize,
                baseIndent,
                wordWrapWidth,
                maxAutoIndent,
                useDisplayMode,
                classifier,
                textAndAdornmentSequencer,
                classificationFormatMap,
                (wordWrapStyle & (WordWrapStyles.WordWrap | WordWrapStyles.VisibleGlyphs)) == (WordWrapStyles.WordWrap | WordWrapStyles.VisibleGlyphs));
        }
예제 #6
0
        /// <summary>
        /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public static ITextFormatter Create(DependencyObject owner, TextFormatterProvider provider)
        {
            if (owner == null)
            {
                throw new ArgumentNullException("owner");
            }
#if DOTNET4
            switch (provider)
            {
            case TextFormatterProvider.BuiltIn:
                return(new WpfTextFormatter(TextOptions.GetTextFormattingMode(owner)));

            case TextFormatterProvider.GlyphRunFormatter:
                return(new GlyphRunFormatter(TextOptions.GetTextFormattingMode(owner)));
            }
            return(null);
#else
            object formattingMode = null;
            if (TextFormattingModeProperty != null)
            {
                formattingMode = owner.GetValue(TextFormattingModeProperty);
            }

            switch (provider)
            {
            case TextFormatterProvider.BuiltIn:
                return(new WpfTextFormatter(formattingMode));

            case TextFormatterProvider.GlyphRunFormatter:
                return(new Rendering.GlyphRunFormatter(formattingMode));
            }
#endif
        }
예제 #7
0
        int CacheHash()
        {
            int hash = 17;

            hash = hash * 23 + H(GetValue(TextProperty));
            hash = hash * 23 + H(GetValue(FontFamilyProperty));
            hash = hash * 23 + H(GetValue(FontStyleProperty));
            hash = hash * 23 + H(GetValue(FontWeightProperty));
            hash = hash * 23 + H(GetValue(FontStretchProperty));
            hash = hash * 23 + H(GetValue(FontSizeProperty));
            hash = hash * 23 + H(GetValue(ForegroundProperty));
            hash = hash * 23 + H(GetValue(BackgroundProperty));
            hash = hash * 23 + H(FlowDirection);
            hash = hash * 23 + H(CultureInfo.CurrentUICulture);

            var newMode = TextOptions.GetTextFormattingMode(this);

            hash = hash * 23 + (int)newMode;

            if (textFormattingMode != newMode)
            {
                textFormattingMode = newMode;
                fmt = null;
                Debug.Assert(hash != cache);
            }

            return(hash);
        }
예제 #8
0
 public static ITextFormatter GetTextFormatter(DependencyObject owner, bool useNewFormatter)
 {
     if (useNewFormatter)
     {
         return(TextOptions.GetTextFormattingMode(owner) == TextFormattingMode.Ideal ? GlyphRunFormatter_Ideal : GlyphRunFormatter_Display);
     }
     return(TextOptions.GetTextFormattingMode(owner) == TextFormattingMode.Ideal ? WpfTextFormatter_Ideal : WpfTextFormatter_Display);
 }
예제 #9
0
 public static ITextFormatter Create(DependencyObject owner, bool useNewFormatter)
 {
     if (useNewFormatter)
     {
         return(new GlyphRunFormatter(TextOptions.GetTextFormattingMode(owner)));
     }
     return(new WpfTextFormatter(TextOptions.GetTextFormattingMode(owner)));
 }
예제 #10
0
 /// <summary>
 /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
 /// </summary>
 public static TextFormatter Create(DependencyObject owner)
 {
     if (owner == null)
     {
         throw new ArgumentNullException("owner");
     }
     return(TextFormatter.Create(TextOptions.GetTextFormattingMode(owner)));
 }
 /// <summary>
 /// Ensures the PtsContext exists.
 /// </summary>
 private void EnsurePtsContext()
 {
     if (_ptsContext == null)
     {
         TextFormattingMode textFormattingMode = TextOptions.GetTextFormattingMode(this.PropertyOwner);
         _ptsContext        = new PtsContext(true, textFormattingMode);
         _textFormatterHost = new TextFormatterHost(_ptsContext.TextFormatter, textFormattingMode);
         _section           = new MS.Internal.PtsHost.Section(this);
     }
 }
예제 #12
0
 // Token: 0x06006A7B RID: 27259 RVA: 0x001E4664 File Offset: 0x001E2864
 private void EnsurePtsContext()
 {
     if (this._ptsContext == null)
     {
         TextFormattingMode textFormattingMode = TextOptions.GetTextFormattingMode(this.PropertyOwner);
         this._ptsContext        = new PtsContext(true, textFormattingMode);
         this._textFormatterHost = new TextFormatterHost(this._ptsContext.TextFormatter, textFormattingMode, this._owner.PixelsPerDip);
         this._section           = new Section(this);
     }
 }
예제 #13
0
        public static bool IsTextTrimmed(this TextBlock textBlock)
        {
            if (textBlock.TextTrimming == TextTrimming.None)
            {
                return(false);
            }
            var textFormattingMode = TextOptions.GetTextFormattingMode(textBlock);
            var typeface           = new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch);
            var formattedText      = new FormattedText(textBlock.Text, CultureInfo.CurrentCulture, textBlock.FlowDirection, typeface, textBlock.FontSize, textBlock.Foreground, new NumberSubstitution(), textFormattingMode, VisualTreeHelper.GetDpi(textBlock).PixelsPerDip);

            return(textBlock.SnapsToDevicePixels || textBlock.UseLayoutRounding || textFormattingMode == TextFormattingMode.Display ? (int)textBlock.ActualWidth < (int)formattedText.Width : textBlock.ActualWidth.LessThan(formattedText.Width));
        }
예제 #14
0
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            base.OnPreviewKeyDown(e);
            if (!e.Handled && e.Key == Key.D && e.KeyboardDevice.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt))
            {
                enableFocusDebugOutput = !enableFocusDebugOutput;

                StringWriter output = new StringWriter();
                output.WriteLine("Keyboard.FocusedElement = " + GetElementName(Keyboard.FocusedElement));
                output.WriteLine("ActiveContent = " + GetElementName(this.ActiveContent));
                output.WriteLine("ActiveViewContent = " + GetElementName(this.ActiveViewContent));
                output.WriteLine("ActiveWorkbenchWindow = " + GetElementName(this.ActiveWorkbenchWindow));
                ((AvalonDockLayout)workbenchLayout).WriteState(output);
                LoggingService.Debug(output.ToString());
                e.Handled = true;
            }
            if (!e.Handled && e.Key == Key.F && e.KeyboardDevice.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt))
            {
                if (TextOptions.GetTextFormattingMode(this) == TextFormattingMode.Display)
                {
                    TextOptions.SetTextFormattingMode(this, TextFormattingMode.Ideal);
                }
                else
                {
                    TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);
                }
                this.StatusBar.SetMessage("TextFormattingMode=" + TextOptions.GetTextFormattingMode(this));
            }
            if (!e.Handled && e.Key == Key.R && e.KeyboardDevice.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt))
            {
                switch (TextOptions.GetTextRenderingMode(this))
                {
                case TextRenderingMode.Auto:
                case TextRenderingMode.ClearType:
                    TextOptions.SetTextRenderingMode(this, TextRenderingMode.Grayscale);
                    break;

                case TextRenderingMode.Grayscale:
                    TextOptions.SetTextRenderingMode(this, TextRenderingMode.Aliased);
                    break;

                default:
                    TextOptions.SetTextRenderingMode(this, TextRenderingMode.ClearType);
                    break;
                }
                this.StatusBar.SetMessage("TextRenderingMode=" + TextOptions.GetTextRenderingMode(this));
            }
            if (!e.Handled && e.Key == Key.G && e.KeyboardDevice.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt))
            {
                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                this.StatusBar.SetMessage("Total memory = " + (GC.GetTotalMemory(true) / 1024 / 1024f).ToString("f1") + " MB");
            }
        }
예제 #15
0
 private void btnFontSize_Click(object sender, RoutedEventArgs e)
 {
     Debug.WriteLine("Before change size, mode=" + TextOptions.GetTextFormattingMode(txtFontTest));
     if (txtFontTest.FontSize == 12)
     {
         txtFontTest.FontSize = 30;
     }
     else
     {
         txtFontTest.FontSize = 12;
     }
     Debug.WriteLine("After change size, mode=" + TextOptions.GetTextFormattingMode(txtFontTest));
 }
예제 #16
0
 /// <summary>
 /// Copied from source code of AvalonEdit in order to use in custom implemenation.
 /// </summary>
 /// <param name="element">Current framework element</param>
 /// <param name="text">Current text</param>
 /// <param name="typeface">Current typeface</param>
 /// <param name="emSize">Requested size</param>
 /// <param name="foreground">Current foreground brush</param>
 /// <returns>FormattedText for framework element</returns>
 /// <history>
 /// [Curtis_Beard]		04/08/2015	ADD: update RichTextBox to AvalonEdit
 /// </history>
 private FormattedText CreateFormattedText(FrameworkElement element, string text, Typeface typeface, double?emSize, Brush foreground)
 {
     return(new FormattedText(
                text,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                typeface,
                emSize.Value,
                foreground,
                null,
                TextOptions.GetTextFormattingMode(element)
                ));
 }
예제 #17
0
		/// <summary>
		/// Creates formatted text.
		/// </summary>
		/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
		/// <param name="text">The text.</param>
		/// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param>
		/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
		/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
		/// <returns>A FormattedText object using the specified settings.</returns>
		public static FormattedText CreateFormattedText(FrameworkElement element, string text, Typeface typeface, double? emSize, Brush foreground)
		{
			if (element == null)
				throw new ArgumentNullException("element");
			if (text == null)
				throw new ArgumentNullException("text");
			if (typeface == null)
				typeface = element.CreateTypeface();
			if (emSize == null)
				emSize = TextBlock.GetFontSize(element);
			if (foreground == null)
				foreground = TextBlock.GetForeground(element);

			return new FormattedText(
				text,
				CultureInfo.CurrentCulture,
				FlowDirection.LeftToRight,
				typeface,
				emSize.Value,
				foreground,
				null,
				TextOptions.GetTextFormattingMode(element)
			);
			#else
			if (TextFormattingModeProperty != null) {
				object formattingMode = element.GetValue(TextFormattingModeProperty);
				return (FormattedText)Activator.CreateInstance(
					typeof(FormattedText),
					text,
					CultureInfo.CurrentCulture,
					FlowDirection.LeftToRight,
					typeface,
					emSize,
					foreground,
					null,
					formattingMode
				);
			} else {
				return new FormattedText(
					text,
					CultureInfo.CurrentCulture,
					FlowDirection.LeftToRight,
					typeface,
					emSize.Value,
					foreground
				);
			}

		}
예제 #18
0
        private static FrameworkElement CreateElement(string text, IWpfTextView textView, TextFormattingRunProperties format)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a font size 1/4 smaller than the font size of the rest of the editor
            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = format.FontRenderingEmSize - (0.25 * format.FontRenderingEmSize),
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,

                // Adds a little bit of padding to the left of the text relative to the border
                // to make the text seem more balanced in the border
                Padding           = new Thickness(left: 1, top: 0, right: 0, bottom: 0),
                Text              = text + ":",
                VerticalAlignment = VerticalAlignment.Center,
            };

            // Encapsulates the textblock within a border. Sets the height of the border to be 3/4 of the original
            // height. Gets foreground/background colors from the options menu. The margin is the distance from the
            // adornment to the text and pushing the adornment upwards to create a separation when on a specific line
            var border = new Border
            {
                Background          = format.BackgroundBrush,
                Child               = block,
                CornerRadius        = new CornerRadius(2),
                Height              = textView.LineHeight - (0.25 * textView.LineHeight),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin              = new Thickness(left: 0, top: -0.20 * textView.LineHeight, right: 5, bottom: 0),
                Padding             = new Thickness(1),

                // Need to set SnapsToDevicePixels and UseLayoutRounding to avoid unnecessary reformatting
                SnapsToDevicePixels = textView.VisualElement.SnapsToDevicePixels,
                UseLayoutRounding   = textView.VisualElement.UseLayoutRounding,
                VerticalAlignment   = VerticalAlignment.Center
            };

            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(border, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(border, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(border, TextOptions.GetTextRenderingMode(textView.VisualElement));

            border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            return(border);
        }
예제 #19
0
        protected override Size MeasureOverride(Size availableSize)
        {
            // always call the base class, it creates the typeface and enSize
            var size = base.MeasureOverride(availableSize);

            if (LineNumbers.Count > 0)
            {
                double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
                int    digits       = (int)Math.Floor(Math.Log10(LineNumbers.Max()) + 1);

                FormattedText text = new FormattedText(
                    new string('9', digits), CultureInfo.CurrentCulture, TextView.FlowDirection,
                    typeface, emSize, Brushes.Black, null,
                    TextOptions.GetTextFormattingMode(this), pixelsPerDip);
                return(new Size(text.Width, 0));
            }
            else
            {
                return(size);
            }
        }
예제 #20
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (LineNumbers.Count > 0)
            {
                TextView textView   = TextView;
                Size     renderSize = RenderSize;
                if (textView != null && textView.VisualLinesValid)
                {
                    var    foreground   = (Brush)GetValue(Control.ForegroundProperty);
                    double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;

                    foreach (VisualLine line in textView.VisualLines)
                    {
                        int lineIndex = line.FirstDocumentLine.LineNumber - 1;

                        if (lineIndex >= 0 && lineIndex < LineNumbers.Count)
                        {
                            FormattedText text = new FormattedText(
                                LineNumbers[lineIndex].ToString(),
                                CultureInfo.CurrentCulture,
                                FlowDirection.LeftToRight,
                                typeface,
                                emSize,
                                foreground,
                                null,
                                TextOptions.GetTextFormattingMode(this),
                                pixelsPerDip);
                            double y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
                            drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
                        }
                    }
                }
            }
            else
            {
                base.OnRender(drawingContext);
            }
        }
예제 #21
0
        private static FrameworkElement CreateElement(
            ImmutableArray <TaggedText> taggedTexts,
            IWpfTextView textView,
            TextFormattingRunProperties format,
            IClassificationFormatMap formatMap,
            ClassificationTypeMap typeMap,
            bool classify)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a font size 1/4 smaller than the font size of the rest of the editor
            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = format.FontRenderingEmSize - (0.25 * format.FontRenderingEmSize),
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,

                // Adds a little bit of padding to the left of the text relative to the border
                // to make the text seem more balanced in the border
                Padding           = new Thickness(left: 1, top: 0, right: 1, bottom: 0),
                VerticalAlignment = VerticalAlignment.Center,
            };

            var(trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts);

            foreach (var taggedText in trimmedTexts)
            {
                var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true));

                if (classify && taggedText.Tag != TextTags.Text)
                {
                    var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName()));
                    var brush      = properties.ForegroundBrush.Clone();
                    run.Foreground = brush;
                }

                block.Inlines.Add(run);
            }

            // Encapsulates the textblock within a border. Sets the height of the border to be 3/4 of the original
            // height. Gets foreground/background colors from the options menu. The margin is the distance from the
            // adornment to the text and pushing the adornment upwards to create a separation when on a specific line

            // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte
            // left or right side.
            var left  = leftPadding * 5;
            var right = rightPadding * 5;

            var border = new Border
            {
                Background          = format.BackgroundBrush,
                Child               = block,
                CornerRadius        = new CornerRadius(2),
                Height              = textView.LineHeight - (0.25 * textView.LineHeight),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin              = new Thickness(left, top: -0.20 * textView.LineHeight, right, bottom: 0),
                Padding             = new Thickness(1),

                // Need to set SnapsToDevicePixels and UseLayoutRounding to avoid unnecessary reformatting
                SnapsToDevicePixels = textView.VisualElement.SnapsToDevicePixels,
                UseLayoutRounding   = textView.VisualElement.UseLayoutRounding,
                VerticalAlignment   = VerticalAlignment.Center
            };

            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(border, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(border, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(border, TextOptions.GetTextRenderingMode(textView.VisualElement));

            border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            return(border);
        }
예제 #22
0
        /// <summary>
        /// Creates formatted text.
        /// </summary>
        /// <param name="element">The owner element. The text formatter setting are read from this element.</param>
        /// <param name="text">The text.</param>
        /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param>
        /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
        /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
        /// <returns>A FormattedText object using the specified settings.</returns>
        public static FormattedText CreateFormattedText(FrameworkElement element, string text, Typeface typeface, double?emSize, Brush foreground)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            if (typeface == null)
            {
                typeface = element.CreateTypeface();
            }
            if (emSize == null)
            {
                emSize = TextBlock.GetFontSize(element);
            }
            if (foreground == null)
            {
                foreground = TextBlock.GetForeground(element);
            }
#if DOTNET4
#pragma warning disable CS0618 // Type or member is obsolete
            return(new FormattedText(
                       text,
                       CultureInfo.CurrentCulture,
                       FlowDirection.LeftToRight,
                       typeface,
                       emSize.Value,
                       foreground,
                       null,
                       TextOptions.GetTextFormattingMode(element)
                       ));

#pragma warning restore CS0618 // Type or member is obsolete
#else
            if (TextFormattingModeProperty != null)
            {
                object formattingMode = element.GetValue(TextFormattingModeProperty);
                return((FormattedText)Activator.CreateInstance(
                           typeof(FormattedText),
                           text,
                           CultureInfo.CurrentCulture,
                           FlowDirection.LeftToRight,
                           typeface,
                           emSize,
                           foreground,
                           null,
                           formattingMode
                           ));
            }
            else
            {
                return(new FormattedText(
                           text,
                           CultureInfo.CurrentCulture,
                           FlowDirection.LeftToRight,
                           typeface,
                           emSize.Value,
                           foreground
                           ));
            }
#endif
        }
예제 #23
0
        private static FrameworkElement CreateElement(
            ImmutableArray <TaggedText> taggedTexts,
            IWpfTextView textView,
            TextFormattingRunProperties format,
            IClassificationFormatMap formatMap,
            ClassificationTypeMap typeMap,
            bool classify)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a inline tag that will be 3/4s the size of a normal line. This shrink size tends to work
            // well with VS at any zoom level or font size.
            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = 0.75 * format.FontRenderingEmSize,
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,
                // Adds a little bit of padding to the left of the text relative to the border to make the text seem
                // more balanced in the border
                Padding = new Thickness(left: 2, top: 0, right: 2, bottom: 0)
            };

            var(trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts);

            foreach (var taggedText in trimmedTexts)
            {
                var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true));

                if (classify && taggedText.Tag != TextTags.Text)
                {
                    var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName()));
                    var brush      = properties.ForegroundBrush.Clone();
                    run.Foreground = brush;
                }

                block.Inlines.Add(run);
            }

            block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            // Encapsulates the textblock within a border. Gets foreground/background colors from the options menu.
            // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte
            // left or right side.
            var left  = leftPadding * 5;
            var right = rightPadding * 5;

            var border = new Border
            {
                Background        = format.BackgroundBrush,
                Child             = block,
                CornerRadius      = new CornerRadius(2),
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin            = new Thickness(left, top: 0, right, bottom: 0),
            };

            // gets pixel distance of baseline to top of the font height
            var dockPanelHeight = format.Typeface.FontFamily.Baseline * format.FontRenderingEmSize;
            var dockPanel       = new DockPanel
            {
                Height        = dockPanelHeight,
                LastChildFill = false,
                // VerticalAlignment is set to Top because it will rest to the top relative to the stackpanel
                VerticalAlignment = VerticalAlignment.Top
            };

            dockPanel.Children.Add(border);
            DockPanel.SetDock(border, Dock.Bottom);

            var stackPanel = new StackPanel
            {
                // Height set to align the baseline of the text within the TextBlock with the baseline of text in the editor
                Height      = dockPanelHeight + (block.DesiredSize.Height - (block.FontFamily.Baseline * block.FontSize)),
                Orientation = Orientation.Vertical
            };

            stackPanel.Children.Add(dockPanel);
            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(stackPanel, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(stackPanel, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(stackPanel, TextOptions.GetTextRenderingMode(textView.VisualElement));

            return(stackPanel);
        }
예제 #24
0
 public static Size MeasureText(string text, Control control)
 {
     return(MeasureText(text, control.FontFamily, control.FontSize,
                        control.FontStyle, control.FontWeight, control.FontStretch,
                        TextOptions.GetTextFormattingMode(control)));
 }
 void UpdateViewLayoutOptionsCache(FrameworkElement view)
 {
     m_textRenderingMode  = TextOptions.GetTextRenderingMode(view);
     m_textHintingMode    = TextOptions.GetTextHintingMode(view);
     m_textFormattingMode = TextOptions.GetTextFormattingMode(view);
 }
 Boolean AreViewLayoutOptionsChanged(FrameworkElement view)
 {
     return((TextOptions.GetTextRenderingMode(view) != m_textRenderingMode) ||
            (TextOptions.GetTextHintingMode(view) != m_textHintingMode) ||
            (TextOptions.GetTextFormattingMode(view) != m_textFormattingMode));
 }
예제 #27
0
        /// <summary>
        /// Determines whether or not the text in <paramref name="textBlock"/> is currently being trimmed due to width or height constraints.
        /// </summary>
        /// <param name="textBlock">The <see cref="TextBlock"/> to evaluate.</param>
        /// <returns><c>true</c> if the text is currently being trimmed; otherwise <c>false</c></returns>
        private static bool EvaluateIsTextTrimmed([NotNull] TextBlock textBlock)
        {
            var fontFamily = textBlock.FontFamily;
            var text       = textBlock.Text;

            if ((fontFamily == null) || (text == null))
            {
                return(false);
            }

            var typeface           = new Typeface(fontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch);
            var numberSubstitution = new NumberSubstitution(NumberSubstitution.GetCultureSource(textBlock), NumberSubstitution.GetCultureOverride(textBlock), NumberSubstitution.GetSubstitution(textBlock));

#if NET45
            var formattedText = new FormattedText(text, CultureInfo.CurrentCulture, textBlock.FlowDirection, typeface, textBlock.FontSize, textBlock.Foreground, numberSubstitution, TextOptions.GetTextFormattingMode(textBlock));
#else
            var pixelsPerDip  = textBlock.GetPhysicalPixelSize().Height;
            var formattedText = new FormattedText(text, CultureInfo.CurrentCulture, textBlock.FlowDirection, typeface, textBlock.FontSize, textBlock.Foreground, numberSubstitution, TextOptions.GetTextFormattingMode(textBlock), pixelsPerDip);
#endif

            var padding      = textBlock.Padding;
            var actualWidth  = textBlock.ActualWidth - padding.Left - padding.Right;
            var actualHeight = textBlock.ActualHeight - padding.Top - padding.Bottom;

            if (textBlock.TextWrapping != TextWrapping.NoWrap)
            {
                formattedText.MaxTextWidth = actualWidth;
            }

            var isTextTrimmed = ((Math.Floor(formattedText.Height) - actualHeight) > 0.0001) || (Math.Floor(formattedText.Width) - actualWidth > 0.0001);

            return(isTextTrimmed);
        }
예제 #28
0
        private static FrameworkElement CreateElement(
            ImmutableArray <TaggedText> taggedTexts,
            IWpfTextView textView,
            TextFormattingRunProperties format,
            IClassificationFormatMap formatMap,
            ClassificationTypeMap typeMap,
            bool classify)
        {
            // Constructs the hint block which gets assigned parameter name and fontstyles according to the options
            // page. Calculates a inline tag that will be 3/4s the size of a normal line. This shrink size tends to work
            // well with VS at any zoom level or font size.

            var block = new TextBlock
            {
                FontFamily = format.Typeface.FontFamily,
                FontSize   = 0.75 * format.FontRenderingEmSize,
                FontStyle  = FontStyles.Normal,
                Foreground = format.ForegroundBrush,

                // Adds a little bit of padding to the left of the text relative to the border
                // to make the text seem more balanced in the border
                Padding           = new Thickness(left: 1, top: 0, right: 1, bottom: 0),
                VerticalAlignment = VerticalAlignment.Center,
            };

            var(trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts);

            foreach (var taggedText in trimmedTexts)
            {
                var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true));

                if (classify && taggedText.Tag != TextTags.Text)
                {
                    var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName()));
                    var brush      = properties.ForegroundBrush.Clone();
                    run.Foreground = brush;
                }

                block.Inlines.Add(run);
            }

            // Encapsulates the textblock within a border. Gets foreground/background colors from the options menu.

            // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte
            // left or right side.
            var left  = leftPadding * 5;
            var right = rightPadding * 5;

            var border = new Border
            {
                Background   = format.BackgroundBrush,
                Child        = block,
                CornerRadius = new CornerRadius(2),

                // Place 3 pixels above/below the border object.  This works well as the highlighting lines are 2px
                // each, giving us 1 px of space on both side of the inline tag and them.  This gives the inline tag
                // an appropriate floating-halfway feeling on the line.
                Margin = new Thickness(left, top: 3, right, bottom: 3),
            };

            // Need to set these properties to avoid unnecessary reformatting because some dependancy properties
            // affect layout
            TextOptions.SetTextFormattingMode(border, TextOptions.GetTextFormattingMode(textView.VisualElement));
            TextOptions.SetTextHintingMode(border, TextOptions.GetTextHintingMode(textView.VisualElement));
            TextOptions.SetTextRenderingMode(border, TextOptions.GetTextRenderingMode(textView.VisualElement));

            border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            return(border);
        }