public static void SetTextProperties(this DependencyObject dependencyObject, TextFormattingRunProperties textProperties) { dependencyObject.SetValue(TextElement.FontFamilyProperty, textProperties.Typeface.FontFamily); dependencyObject.SetValue(TextElement.FontSizeProperty , textProperties.FontRenderingEmSize); dependencyObject.SetValue(TextElement.FontStyleProperty , textProperties.Italic ? FontStyles.Italic : FontStyles.Normal); dependencyObject.SetValue(TextElement.FontWeightProperty, textProperties.Bold ? FontWeights.Bold : FontWeights.Normal); dependencyObject.SetValue(TextElement.BackgroundProperty, textProperties.BackgroundBrush); dependencyObject.SetValue(TextElement.ForegroundProperty, textProperties.ForegroundBrush); }
Info GetInfo(TextFormattingRunProperties props) { Info info; if (dict.TryGetValue(props, out info)) return info; var ft = new FormattedText("Xg ", props.CultureInfo, FlowDirection.LeftToRight, props.Typeface, props.FontRenderingEmSize, props.ForegroundBrush, null, textFormattingMode); info = new Info(ft); dict.Add(props, info); return info; }
void WriteCss(TextFormattingRunProperties props) { cssWriter.Clear(); if (!props.ForegroundBrushEmpty) WriteCssColor("color", props.ForegroundBrush); if (!props.BoldEmpty && props.Bold) cssWriter.Append($"font-weight: bold; "); if (!props.ItalicEmpty && props.Italic) cssWriter.Append($"font-style: italic; "); }
public PowerShellTextFormattingParagraphProperties( TextFormattingRunProperties textProperties, IFormattedLineSource formattedLineSource, IServiceProvider serviceProvider) : base(textProperties) { ServiceProvider = serviceProvider; ColumnWidth = formattedLineSource.ColumnWidth; var dte = (DTE) ServiceProvider.GetService( typeof (DTE) ); UpdateProperties( formattedLineSource, dte ); }
private void TestTheme(TextFormattingRunProperties textProperties, Theme? expectedTheme) { var classificationFormatMapService=new StubIClassificationFormatMapService(); classificationFormatMapService.GetClassificationFormatMapString = category => { return new StubIClassificationFormatMap { DefaultTextPropertiesGet = () => textProperties }; }; var environmentService = Utils.CreateEnvironmentService(classificationFormatMapService); var theme = environmentService.GetTheme(); Assert.AreEqual(expectedTheme, theme); }
/// <summary> /// Creates a <see cref = "T:System.Windows.Media.TextFormatting.TextParagraphProperties" /> for the provided configuration. /// </summary> /// <param name = "formattedLineSource">The <see cref = "T:Microsoft.VisualStudio.Text.Formatting.IFormattedLineSource" /> that's performing the formatting of the line. You can access useful properties about the ongoing formatting operation from this object.</param> /// <param name = "textProperties">The <see cref = "T:Microsoft.VisualStudio.Text.Formatting.TextFormattingRunProperties" /> of the line for which <see cref = "T:System.Windows.Media.TextFormatting.TextParagraphProperties" /> are to be provided. This paramter can be used to obtain formatting information about the textual contents of the line.</param> /// <param name = "line">The <see cref = "T:Microsoft.VisualStudio.Text.IMappingSpan" /> corresponding to the line that's being formatted/rendered.</param> /// <param name = "lineStart">The <see cref = "T:Microsoft.VisualStudio.Text.IMappingPoint" /> corresponding to the beginning of the line segment that's being formatted. This paramter is relevant for word-wrap scenarios where a single <see cref = "T:Microsoft.VisualStudio.Text.ITextSnapshotLine" /> results in multiple formatted/rendered lines on the view.</param> /// <param name = "lineSegment">The segment number of the line segment that's been currently formatted. This is a zero-based index and is applicable to word-wrapped lines. If a line is word-wrapped into 4 segments, you will receive 4 calls for the line with lineSegments of 0, 1, 2, and 3.</param> /// <returns> /// A <see cref = "T:System.Windows.Media.TextFormatting.TextParagraphProperties" /> to be used when the line is being formatted. /// </returns> /// <remarks> /// Please note that you can return a <see cref = "T:Microsoft.VisualStudio.Text.Formatting.TextFormattingParagraphProperties" /> which has a convenient set of basic properties defined. /// </remarks> public TextParagraphProperties Create( IFormattedLineSource formattedLineSource, TextFormattingRunProperties textProperties, IMappingSpan line, IMappingPoint lineStart, int lineSegment) { if (_TextParagraphProperties == null) { _TextParagraphProperties = new PowerShellTextFormattingParagraphProperties( textProperties, formattedLineSource, ServiceProvider ); } return TextParagraphProperties; }
/// <summary> /// Create an ITextViewHost instance for the active ITextBuffer /// </summary> internal IWpfTextViewHost CreateTextViewHost(IWpfTextView textView) { textView.Options.SetOptionValue(DefaultTextViewOptions.UseVisibleWhitespaceId, true); var textViewHost = _vimComponentHost.TextEditorFactoryService.CreateTextViewHost(textView, setFocus: true); var classificationFormatMap = _classificationFormatMapService.GetClassificationFormatMap(textViewHost.TextView); classificationFormatMap.DefaultTextProperties = TextFormattingRunProperties.CreateTextFormattingRunProperties( new Typeface(Constants.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal), Constants.FontSize, Colors.Black); return(textViewHost); }
/// <summary> /// Use clear type if we are in an en-us environment and the <see cref="TextFormattingRunProperties"/>' /// font is under the Consolas family. /// </summary> /// <param name="textProperties">The properties that contain the font information.</param> private void SetClearTypeHint(TextFormattingRunProperties textProperties) { string familyName; if (!textProperties.TypefaceEmpty && textProperties.Typeface.FontFamily.FamilyNames.TryGetValue(EnUsLanguage, out familyName) && string.Compare(familyName, "Consolas", StringComparison.OrdinalIgnoreCase) == 0) { TextOptions.SetTextRenderingMode(this, TextRenderingMode.ClearType); } else { TextOptions.SetTextRenderingMode(this, TextRenderingMode.Auto); } }
private IEnumerable <(SnapshotSpan Span, TextFormattingRunProperties Formatting)> GetTextSpansWithFormatting(ITextBuffer textBuffer) { var wholeBufferSpan = new SnapshotSpan(textBuffer.CurrentSnapshot, 0, textBuffer.CurrentSnapshot.Length); var tags = _classificationAggregator.GetTags(wholeBufferSpan); foreach (var tag in tags) { TextFormattingRunProperties formattingProperties = _classificationFormatMap.GetTextProperties(tag.Tag.ClassificationType); int startPoint = tag.Span.Start.GetPoint(textBuffer, PositionAffinity.Successor).Value.Position; Span textSpan = new Span( startPoint, tag.Span.End.GetPoint(textBuffer, PositionAffinity.Predecessor).Value.Position - startPoint); yield return(new SnapshotSpan(textBuffer.CurrentSnapshot, textSpan), formattingProperties); } }
private void TestTheme(TextFormattingRunProperties textProperties, Theme?expectedTheme) { var classificationFormatMapService = new StubIClassificationFormatMapService(); classificationFormatMapService.GetClassificationFormatMapString = category => { return(new StubIClassificationFormatMap { DefaultTextPropertiesGet = () => textProperties }); }; var environmentService = Utils.CreateEnvironmentService(classificationFormatMapService); var theme = environmentService.GetTheme(); Assert.AreEqual(expectedTheme, theme); }
private void CreateDrawingObjects() { // this gets the color settings configured by the // user in Fonts and Colors (or the default in out // classification type). TextFormattingRunProperties format = formatMap.GetTextProperties(formatType); fillBrush = format.BackgroundBrush; Brush penBrush = format.ForegroundBrush; borderPen = new Pen(penBrush, 0.5); borderPen.Freeze(); RedrawAdornments(); }
/// <summary> /// Returns the relevant font style name for <paramref name="formatting"/> if it exists or the fallback name /// </summary> public static string GetFontStyleName(this TextFormattingRunProperties formatting) { if (formatting.Italic) { return(FontStyleService.Italic); } if (formatting.TypefaceEmpty) { return(FontStyleService.Normal); } var styleName = formatting.Typeface.Style.ToString(); return(FontStyleService.SupportedStyleByNames.ContainsKey(styleName) ? styleName : FontStyleService.Normal); }
/// <summary> /// Apply <see cref="Typeface"/> that build from <paramref name="classification"/> using /// <paramref name="defaultFormatting"/> as fallback values /// </summary> private static TextFormattingRunProperties ApplyTypeFace( TextFormattingRunProperties formatting, Classification classification, TextFormattingRunProperties defaultFormatting) { TextFormattingRunProperties ApplyTypeFace(TypeFaces mask, Typeface fallbackFace) { if (mask.Is(TypeFaces.Style) && !formatting.ItalicEmpty) { formatting = formatting.ClearItalic(); } return(formatting.SetTypeface(new Typeface( mask.Is(TypeFaces.Family) ? FontFamilyService.SupportedFamilies[classification.FontFamily] : fallbackFace.FontFamily, mask.Is(TypeFaces.Style) ? FontStyleService.SupportedStyleByNames[classification.FontStyle] : fallbackFace.Style, fallbackFace.Weight, mask.Is(TypeFaces.Stretch) ? FontStretchService.SupportedStretches[classification.FontStretch] : fallbackFace.Stretch))); } if (formatting.TypefaceEmpty) { var faces = TypeFaces.Family | TypeFaces.Stretch; switch (classification.FontStyle) { case FontStyleService.Italic when !formatting.Italic: formatting = formatting.SetItalic(true); break; case FontStyleService.Normal when formatting.Italic: formatting = formatting.SetItalic(false); break; default: faces |= TypeFaces.Style; break; } formatting = ApplyTypeFace(faces, defaultFormatting.Typeface); } else { var typeFace = formatting.Typeface; if (!typeFace.Style.Equals(FontStyleService.SupportedStyleByNames[classification.FontStyle]) || !typeFace.FontFamily.Source.Equals(classification.FontFamily) || typeFace.Stretch.ToOpenTypeStretch() != classification.FontStretch) { formatting = ApplyTypeFace(TypeFaces.All, typeFace); } } return(formatting); }
private static Color GetColor([NotNull] TextFormattingRunProperties properties) { if (properties.ForegroundBrushEmpty) { return(Color.Empty); } var solidColorBrush = properties.ForegroundBrush as SolidColorBrush; if (solidColorBrush == null) { return(Color.Empty); } return(solidColorBrush.Color.ToWinForms()); }
private void UpdateFormat() { var lineNumberType = _classificationTypeRegistry.GetClassificationType("line number"); _formatting = _classificationFormatMap.GetTextProperties(lineNumberType); Background = _formatting.BackgroundBrush; _textFormatter = _formattedLineSource.UseDisplayMode ? TextFormatter.Create(TextFormattingMode.Display) : TextFormatter.Create(TextFormattingMode.Ideal); NumberWidth = Enumerable.Range(0, 10).Max(x => MakeTextLine(x).Width); _formatChanged = true; }
private void UpdateColors() { var theme = themeEngine.GetCurrentTheme(); // Did theme change? if (theme != currentTheme) { currentTheme = theme; var colors = themeColors[theme]; var formatMap = classificationFormatMapService.GetClassificationFormatMap(ClassificationCategory); // TODO: It seems this approach doesn't update Fonts & Colors settings try { formatMap.BeginBatchUpdate(); foreach (var pair in colors) { string type = pair.Key; var color = pair.Value; var classificationType = classificationTypeRegistry.GetClassificationType(type); var oldProp = formatMap.GetTextProperties(classificationType); var foregroundBrush = color.ForegroundColor == null ? null : new SolidColorBrush(color.ForegroundColor.Value); var backgroundBrush = color.BackgroundColor == null ? null : new SolidColorBrush(color.BackgroundColor.Value); var newProp = TextFormattingRunProperties.CreateTextFormattingRunProperties( foregroundBrush, backgroundBrush, oldProp.Typeface, null, null, oldProp.TextDecorations, oldProp.TextEffects, oldProp.CultureInfo); formatMap.SetTextProperties(classificationType, newProp); } } finally { formatMap.EndBatchUpdate(); } } }
internal void UpdateColors(IEnumerable <CategoryItemDecorationSettings> changedItems) { if (_classificationFormatMapService == null || _registryService == null) { SatisfyImports(); } if (_classificationFormatMap == null) { _classificationFormatMap = _classificationFormatMapService.GetClassificationFormatMap(_textView); } if (_T4Types == null) { _T4Types = _classificationFormatMap.CurrentPriorityOrder.Where(x => x?.Classification.Contains("T4") == true).ToList(); } try { if (_classificationFormatMap.IsInBatchUpdate) { return; } _classificationFormatMap.BeginBatchUpdate(); foreach (CategoryItemDecorationSettings changedItem in changedItems) { string classificationKey = changedItem.DisplayName; IClassificationType classificationType = _T4Types.FirstOrDefault(x => x.Classification.Contains(classificationKey)); if (classificationType == null) { continue; } TextFormattingRunProperties textProperties = CreateTextProperties(changedItem); _classificationFormatMap.SetExplicitTextProperties(classificationType, textProperties); } } catch (Exception) { //TO-DO: Log exception } finally { _classificationFormatMap.EndBatchUpdate(); } }
private void TestTheme(TextFormattingRunProperties textProperties, Theme?expectedTheme) { var classificationFormatMap = Substitute.For <IClassificationFormatMap>(); classificationFormatMap.DefaultTextProperties .Returns(textProperties); var classificationFormatMapService = Substitute.For <IClassificationFormatMapService>(); classificationFormatMapService.GetClassificationFormatMap(Arg.Any <string>()) .Returns(classificationFormatMap); var environmentService = Utils.CreateEnvironmentService(classificationFormatMapService); var actualTheme = environmentService.GetTheme(); actualTheme.Should().Be(expectedTheme); }
protected virtual void Create(params string[] lines) { _textView = CreateTextView(lines); _textBuffer = _textView.TextBuffer; _controlCharUtil = new ControlCharUtil(); _classificationFormatMap = new Mock <IClassificationFormatMap>(MockBehavior.Strict); var typeface = SystemFonts.CaptionFontFamily.GetTypefaces().First(); var textFormattingProperties = TextFormattingRunProperties.CreateTextFormattingRunProperties(typeface, 10.0, Colors.Black); _classificationFormatMap.SetupGet(x => x.DefaultTextProperties).Returns(textFormattingProperties); _source = new CharDisplayTaggerSource( _textView, new Mock <IEditorFormatMap>(MockBehavior.Loose).Object, _controlCharUtil, _classificationFormatMap.Object); _basicTaggerSource = _source; }
public void UpdateColors() { var newTheme = _themeManager.GetCurrentTheme(); if (newTheme != VisualStudioTheme.Unknown && newTheme != _currentTheme) { _currentTheme = newTheme; var colors = newTheme == VisualStudioTheme.Dark ? DarkColors : LightAndBlueColors; var formatMap = _classificationFormatMapService.GetClassificationFormatMap(category: "text"); try { formatMap.BeginBatchUpdate(); foreach (var pair in colors) { string type = pair.Key; FontColor color = pair.Value; var classificationType = _classificationTypeRegistry.GetClassificationType(type); var oldProp = formatMap.GetTextProperties(classificationType); var foregroundBrush = color.Foreground == null ? null : new SolidColorBrush(color.Foreground.Value); var backgroundBrush = color.Background == null ? null : new SolidColorBrush(color.Background.Value); var newProp = TextFormattingRunProperties.CreateTextFormattingRunProperties( foregroundBrush, backgroundBrush, oldProp.Typeface, null, null, oldProp.TextDecorations, oldProp.TextEffects, oldProp.CultureInfo); formatMap.SetTextProperties(classificationType, newProp); } } finally { formatMap.EndBatchUpdate(); } } }
/// <summary> /// Returns the relevant font family name for <paramref name="formatting"/> if if exists or the fallback name /// </summary> public static string GetFontFamily(this TextFormattingRunProperties formatting) { string source; if (!formatting.TypefaceEmpty) { source = formatting.Typeface.FontFamily.Source; if (FontFamilyService.SupportedFamilies.ContainsKey(source)) { return(source); } } source = "Consolas"; return(FontFamilyService.SupportedFamilies.ContainsKey(source) ? source : FontFamilyService.SupportedFamilies.Keys.First()); }
void WriteCss(TextFormattingRunProperties props) { cssWriter.Clear(); if (!props.ForegroundBrushEmpty) { WriteCssColor("color", props.ForegroundBrush); } if (!props.BoldEmpty && props.Bold) { cssWriter.Append($"font-weight: bold; "); } if (!props.ItalicEmpty && props.Italic) { cssWriter.Append($"font-style: italic; "); } }
static DOC.Run CreateRun(string text, TextFormattingRunProperties defaultProperties, TextFormattingRunProperties properties, Flags flags) { var run = new DOC.Run(text); if (properties == null) { return(run); } if (!properties.BackgroundBrushEmpty) { run.Background = properties.BackgroundBrush; } if (!properties.ForegroundBrushEmpty) { run.Foreground = properties.ForegroundBrush; } if (!properties.BoldEmpty) { run.FontWeight = properties.Bold ? FontWeights.Bold : FontWeights.Normal; } if (!properties.ItalicEmpty) { run.FontStyle = properties.Italic ? FontStyles.Italic : FontStyles.Normal; } if (!properties.FontRenderingEmSizeEmpty && (flags & Flags.DisableFontSize) == 0) { run.FontSize = properties.FontRenderingEmSize; } if (!properties.TextDecorationsEmpty) { run.TextDecorations = properties.TextDecorations; } if (!properties.TextEffectsEmpty) { run.TextEffects = properties.TextEffects; } if (!properties.TypefaceEmpty && !IsSameTypeFace(defaultProperties, properties)) { run.FontFamily = properties.Typeface.FontFamily; } return(run); }
private void FillLookupDictionary() { _lookupDictionary["comment"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Times New Roman"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal), 14, Colors.Gray); _lookupDictionary["identifier"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Colors.Black); _lookupDictionary["keyword"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Color.FromRgb(0, 0x80, 0xff)); _lookupDictionary["whitespace"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Colors.Black); _lookupDictionary["operator"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Colors.Teal); _lookupDictionary["literal"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Colors.Brown); _lookupDictionary["String"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Color.FromRgb(0xff, 0x40, 0)); _lookupDictionary["other"] = new TextFormattingRunProperties(new Typeface("Lucida Console"), 12, Colors.Black); _lookupDictionary["bold_comment"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Times New Roman"), FontStyles.Italic, FontWeights.Bold, FontStretches.Normal), 14, Colors.Gray); _lookupDictionary["bold_identifier"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Colors.Black); _lookupDictionary["bold_keyword"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Color.FromRgb(0, 0xa8, 0xff)); _lookupDictionary["bold_whitespace"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Colors.Black); _lookupDictionary["bold_operator"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Colors.Teal); _lookupDictionary["bold_literal"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Colors.Brown); _lookupDictionary["bold_string"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Color.FromRgb(0xff, 0x40, 0)); _lookupDictionary["bold_other"] = new TextFormattingRunProperties(new Typeface(new FontFamily("Lucida Console"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 12, Colors.Black); }
public void SetFont(TextFormattingRunProperties formatting) { var backgroundBrush = formatting.BackgroundBrush; if (backgroundBrush.Opacity != 1.0) { backgroundBrush = backgroundBrush.Clone(); backgroundBrush.Opacity = 1.0; backgroundBrush.Freeze(); } Background = backgroundBrush; m_child.Foreground = formatting.ForegroundBrush; m_child.FontSize = formatting.FontRenderingEmSize; m_child.FontFamily = formatting.Typeface.FontFamily; m_child.FontStretch = formatting.Typeface.Stretch; m_child.FontStyle = formatting.Typeface.Style; m_child.FontWeight = formatting.Typeface.Weight; }
public TextFormattingRunProperties GetExplicitTextProperties(IClassificationType classificationType) { if (classificationType is null) { throw new ArgumentNullException(nameof(classificationType)); } var info = TryGetClassificationInfo(classificationType, canCreate: false); if (info is null) { return(TextFormattingRunProperties.CreateTextFormattingRunProperties()); } if (info.ExplicitTextProperties is null) { CreateExplicitTextProperties(info); } Debug.Assert(!(info.ExplicitTextProperties is null)); return(info.ExplicitTextProperties); }
/// <summary> /// Try to add or remove <paramref name="decoration"/> to the <paramref name="formatting"/> using <paramref name="needToAddDecoration"/> /// </summary> /// <param name="formatting"></param> /// <param name="needToAddDecoration">Determines when the input <paramref name="decoration"/> should be added or removed</param> private static TextFormattingRunProperties ApplyDecoration( TextFormattingRunProperties formatting, bool needToAddDecoration, TextDecoration decoration) { if (formatting.TextDecorations.Contains(decoration) ^ needToAddDecoration) { // NOTE: directly creates a new instance from existing collection to correctly determines // in the future that items are contained or not var clone = new TextDecorationCollection(formatting.TextDecorations); if (needToAddDecoration) { clone.Add(decoration); } else { clone.Remove(decoration); } return(formatting.SetTextDecorations(clone)); } return(formatting); }
/// <summary> /// Creates the default classification from <paramref name="formatting"/> /// which doesn't set the default values for properties that can be reset /// </summary> public static ClassificationSettings ToDefaultSettings( this TextFormattingRunProperties formatting, string classificationName) { var defaultOption = ClassificationService.GetDefaultOption(classificationName); return(new ClassificationSettings { Name = classificationName, FontFamily = formatting.GetFontFamily(), IsBold = formatting.Bold, FontStyle = formatting.GetFontStyleName(), IsOverline = formatting.TextDecorations.Contains(TextDecorations.OverLine[0]), IsUnderline = formatting.TextDecorations.Contains(TextDecorations.Underline[0]), IsStrikethrough = formatting.TextDecorations.Contains(TextDecorations.Strikethrough[0]), IsBaseline = formatting.TextDecorations.Contains(TextDecorations.Baseline[0]), IsDisabled = defaultOption.IsDisabled, IsDisabledInXml = defaultOption.IsDisabledInXml, IsDisabledInEditor = defaultOption.IsDisabledInEditor, IsDisabledInQuickInfo = defaultOption.IsDisabledInQuickInfo, }); }
private Theme? GetThemeFromTextProperties(TextFormattingRunProperties properties) { if (!properties.BackgroundBrushEmpty) { var solidColorBrush = properties.BackgroundBrush as SolidColorBrush; if (solidColorBrush != null) { if (solidColorBrush.Color.GetLightness() < 0.5) { return Theme.Dark; } return Theme.Light; } } if (!properties.ForegroundBrushEmpty) { var solidColorBrush = properties.ForegroundBrush as SolidColorBrush; if (solidColorBrush != null) { if (solidColorBrush.Color.GetLightness() < 0.5) { return Theme.Light; } return Theme.Dark; } } return null; }
private void UpdateClassificationColors(IClassificationFormatMap formatMap) { try { formatMap.BeginBatchUpdate(); foreach (var pair in ThemeColors.Colors) { var type = pair.Key; var color = pair.Value; var classificationType = _classificationTypeRegistry.GetClassificationType(type); if (classificationType == null) { Error.LogError($"Cannot find classification type related to {type}", Module); continue; } var oldProp = formatMap.GetTextProperties(classificationType); var foregroundBrush = color.Foreground == null ? null : new SolidColorBrush(color.Foreground.Value); var backgroundBrush = color.Background == null ? null : new SolidColorBrush(color.Background.Value); var newProp = TextFormattingRunProperties.CreateTextFormattingRunProperties( foregroundBrush, backgroundBrush, oldProp.Typeface, null, null, oldProp.TextDecorations, oldProp.TextEffects, oldProp.CultureInfo); formatMap.SetTextProperties(classificationType, newProp); } } finally { formatMap.EndBatchUpdate(); } }
public void UpdateColors() { var currentTheme = _themeManager.GetCurrentTheme(); if (currentTheme == VisualStudioTheme.Unknown || currentTheme == _lastTheme) { return; } _lastTheme = currentTheme; var colors = _themeColors[currentTheme]; var formatMap = _classificationFormatMapService.GetClassificationFormatMap(category: "text"); try { formatMap.BeginBatchUpdate(); foreach (var pair in colors) { var type = pair.Key; var color = pair.Value; var classificationType = _classificationTypeRegistryService.GetClassificationType(type); var oldProp = formatMap.GetTextProperties(classificationType); var brush = new SolidColorBrush(color); var newProp = TextFormattingRunProperties.CreateTextFormattingRunProperties( brush, null, oldProp.Typeface, null, null, oldProp.TextDecorations, oldProp.TextEffects, oldProp.CultureInfo); formatMap.SetTextProperties(classificationType, newProp); } } finally { formatMap.EndBatchUpdate(); } }
/// <summary> /// Initializes a new instance of the <see cref="TestsAdornment"/> class. /// </summary> /// <param name="view">Text view to create the adornment for</param> /// <param name="classifier"></param> /// <param name="classificationRegistry"></param> /// <param name="formatMap"></param> public TestsAdornment(IWpfTextView view, IClassifier classifier, IClassificationTypeRegistryService classificationRegistry, IClassificationFormatMapService formatMap) { if (view == null) { throw new ArgumentNullException(nameof(view)); } IClassificationType missClassificationType = classificationRegistry.GetClassificationType(CodeCoverageClassifierType.Miss); IClassificationFormatMap missFormat = formatMap.GetClassificationFormatMap(view); TextFormattingRunProperties missText = missFormat.GetTextProperties(missClassificationType); MissedBackground = missText.BackgroundBrush; IClassificationType hitClassificationType = classificationRegistry.GetClassificationType(CodeCoverageClassifierType.Hit); IClassificationFormatMap hitFormat = formatMap.GetClassificationFormatMap(view); TextFormattingRunProperties hitText = hitFormat.GetTextProperties(hitClassificationType); HitBackground = hitText.BackgroundBrush; IClassificationType notRunClassificationType = classificationRegistry.GetClassificationType(CodeCoverageClassifierType.NotRun); IClassificationFormatMap notRunFormat = formatMap.GetClassificationFormatMap(view); TextFormattingRunProperties notRunText = notRunFormat.GetTextProperties(notRunClassificationType); NotRunBackground = notRunText.BackgroundBrush; _layer = view.GetAdornmentLayer("TestsAdornment"); _view = view; _classifier = classifier; _view.LayoutChanged += OnLayoutChanged; _tests = PowershellService.Current.Tests; _tests.ModelChanged += ShowHitsModelChanged; _tests.ShowLinesModelChanged += ShowHitsModelChanged; }
static void UpdateFormatCache(object sender, EventArgs args) { var defaultFormat = DefaultClassificationFormatMap.DefaultTextProperties; if (_DefaultFormatting == null) { _DefaultFormatting = defaultFormat; } else if (_DefaultFormatting.ForegroundBrushSame(defaultFormat.ForegroundBrush) == false) { Debug.WriteLine("DefaultFormatting Changed"); // theme changed lock (_syncRoot) { var formattings = new Dictionary <IClassificationType, TextFormattingRunProperties>(_BackupFormattings.Count); LoadFormattings(formattings); _BackupFormattings = formattings; _DefaultFormatting = defaultFormat; } } lock (_syncRoot) { UpdateIdentifySymbolSource(_SyntaxStyleCache); } }
static DOC.Run CreateRun(string text, TextFormattingRunProperties defaultProperties, TextFormattingRunProperties properties, Flags flags) { var run = new DOC.Run(text); if (properties == null) return run; if (!properties.BackgroundBrushEmpty) run.Background = properties.BackgroundBrush; if (!properties.ForegroundBrushEmpty) run.Foreground = properties.ForegroundBrush; if (!properties.BoldEmpty) run.FontWeight = properties.Bold ? FontWeights.Bold : FontWeights.Normal; if (!properties.ItalicEmpty) run.FontStyle = properties.Italic ? FontStyles.Italic : FontStyles.Normal; if (!properties.FontRenderingEmSizeEmpty && (flags & Flags.DisableFontSize) == 0) run.FontSize = properties.FontRenderingEmSize; if (!properties.TextDecorationsEmpty) run.TextDecorations = properties.TextDecorations; if (!properties.TextEffectsEmpty) run.TextEffects = properties.TextEffects; if (!properties.TypefaceEmpty && !IsSameTypeFace(defaultProperties, properties)) run.FontFamily = properties.Typeface.FontFamily; return run; }
static bool IsSameTypeFace(TextFormattingRunProperties a, TextFormattingRunProperties b) { if (a.TypefaceEmpty != b.TypefaceEmpty) return false; if (a.Typeface == b.Typeface) return true; return GetFontName(a) == GetFontName(b); }
static string GetFontName(TextFormattingRunProperties props) { if (props.TypefaceEmpty) return string.Empty; string name; if (!props.Typeface.FontFamily.FamilyNames.TryGetValue(language, out name)) name = null; return name ?? string.Empty; }
public void OnInvisible() { replLineNumberInput1TextFormattingRunProperties = null; replLineNumberInput2TextFormattingRunProperties = null; replLineNumberOutputTextFormattingRunProperties = null; }
public double GetLineHeight(TextFormattingRunProperties props) => GetInfo(props).LineHeight;
protected override void OnTextPropertiesChangedCore() => lineNumberTextFormattingRunProperties = classificationFormatMap.GetTextProperties(lineNumberClassificationType);
public MultipleTooltipContentPresenter([NotNull] TextFormattingRunProperties formatting) { _formatting = formatting; }
public void SetExplicitTextProperties(IClassificationType classificationType, TextFormattingRunProperties properties) { throw new NotImplementedException(); }
public double GetTextHeightBelowBaseline(TextFormattingRunProperties props) => GetInfo(props).TextHeightBelowBaseline;
public double GetColumnWidth(TextFormattingRunProperties props) => GetInfo(props).ColumnWidth;
public void OnTextPropertiesChanged(IClassificationFormatMap classificationFormatMap) { replLineNumberInput1TextFormattingRunProperties = classificationFormatMap.GetTextProperties(replLineNumberInput1ClassificationType); replLineNumberInput2TextFormattingRunProperties = classificationFormatMap.GetTextProperties(replLineNumberInput2ClassificationType); replLineNumberOutputTextFormattingRunProperties = classificationFormatMap.GetTextProperties(replLineNumberOutputClassificationType); }
protected override void UnregisterEventsCore() => lineNumberTextFormattingRunProperties = null;
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); }
/// <summary> /// Creates a <see cref="TextBlock"/> /// </summary> /// <param name="text">Full text</param> /// <param name="defaultProperties">Default text run properties</param> /// <param name="orderedPropsAndSpans">Ordered enumerable of spans and text run properties</param> /// <param name="flags">Flags</param> /// <returns></returns> public static TextBlock Create(string text, TextFormattingRunProperties defaultProperties, IEnumerable<TextRunPropertiesAndSpan> orderedPropsAndSpans, Flags flags = Flags.None) { if (text == null) throw new ArgumentNullException(nameof(text)); if (defaultProperties == null) throw new ArgumentNullException(nameof(defaultProperties)); if (orderedPropsAndSpans == null) throw new ArgumentNullException(nameof(orderedPropsAndSpans)); var textBlock = new TextBlock(); int textOffset = 0; bool filterOutNewlines = (flags & Flags.FilterOutNewlines) != 0; foreach (var tag in orderedPropsAndSpans) { if (textOffset < tag.Span.Start) textBlock.Inlines.Add(CreateRun(ToString(text.Substring(textOffset, tag.Span.Start - textOffset), filterOutNewlines), defaultProperties, null, flags)); textBlock.Inlines.Add(CreateRun(ToString(text.Substring(tag.Span.Start, tag.Span.Length), filterOutNewlines), defaultProperties, tag.Properties, flags)); textOffset = tag.Span.End; } if (textOffset < text.Length) textBlock.Inlines.Add(CreateRun(ToString(text.Substring(textOffset), filterOutNewlines), defaultProperties, null, flags)); if (!defaultProperties.BackgroundBrushEmpty) textBlock.Background = defaultProperties.BackgroundBrush; if (!defaultProperties.ForegroundBrushEmpty) textBlock.Foreground = defaultProperties.ForegroundBrush; if (!defaultProperties.BoldEmpty) textBlock.FontWeight = defaultProperties.Bold ? FontWeights.Bold : FontWeights.Normal; if (!defaultProperties.ItalicEmpty) textBlock.FontStyle = defaultProperties.Italic ? FontStyles.Italic : FontStyles.Normal; if (!defaultProperties.FontRenderingEmSizeEmpty && (flags & Flags.DisableFontSize) == 0) textBlock.FontSize = defaultProperties.FontRenderingEmSize; if (!defaultProperties.TextDecorationsEmpty) textBlock.TextDecorations = defaultProperties.TextDecorations; if (!defaultProperties.TextEffectsEmpty) textBlock.TextEffects = defaultProperties.TextEffects; if ((flags & Flags.DisableSetTextBlockFontFamily) == 0 && !defaultProperties.TypefaceEmpty) textBlock.FontFamily = defaultProperties.Typeface.FontFamily; if ((flags & Flags.DisableWordWrap) == 0) textBlock.TextWrapping = TextWrapping.Wrap; return textBlock; }
/// <summary> /// Constructor /// </summary> /// <param name="span">Span</param> /// <param name="properties">Text properties</param> public TextRunPropertiesAndSpan(Span span, TextFormattingRunProperties properties) { if (properties == null) throw new System.ArgumentNullException(nameof(properties)); Span = span; Properties = properties; }
private static void SetTextProperties(DependencyObject dependencyObject, TextFormattingRunProperties properties, bool setFontFamily) { if (setFontFamily) { dependencyObject.SetValue(TextElement.FontFamilyProperty, properties.Typeface.FontFamily); dependencyObject.SetValue(TextElement.FontSizeProperty, properties.FontRenderingEmSize); } dependencyObject.SetValue(TextElement.FontStyleProperty, properties.Italic ? FontStyles.Italic : FontStyles.Normal); dependencyObject.SetValue(TextElement.FontWeightProperty, properties.Bold ? FontWeights.Bold : FontWeights.Normal); dependencyObject.SetValue(TextElement.ForegroundProperty, properties.ForegroundBrush); dependencyObject.SetValue(TextElement.BackgroundProperty, properties.BackgroundBrush); dependencyObject.SetValue(TextElement.TextEffectsProperty, properties.TextEffects); }