private static void CheckDefaultColors(ColorableItemInfo[] colorInfos) { ColorableItemInfo item = colorInfos[0]; // If the colors are set to "Default" then that's for the TextEditor category NOT for the target category. // So crBackground might be 0x01000001, which is a White background (as a VS palette color index?). // Since Output and Find Result windows have different default colors (typically different background colors), // we can't just push the color information from the TextEditor category. // // Note: The ColorableItemInfo.crForeground and crBackground fields are documented as returning COLORREF, // which is a uint in the form 0x00BBGGRR. However, VS packages can combine in the __VSCOLORTYPE flags // in the most significant byte, and VS applies those values in ways that don't seem to match the docs. // So we'll just ignore any "color" value that's not a standard Windows COLORREF. const uint ColorTypeMask = 0xFF000000; if (item.bBackgroundValid == 1 && (item.crBackground & ColorTypeMask) != 0) { item.bBackgroundValid = 0; } if (item.bForegroundValid == 1 && (item.crForeground & ColorTypeMask) != 0) { item.bForegroundValid = 0; } colorInfos[0] = item; }
public void Load(params String[] classificationNames) { _classifications.Clear(); Guid category = new Guid(Guids.TextEditorCategory); uint flags = (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | __FCSTORAGEFLAGS.FCSF_READONLY); Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var hr = _colorStorage.Storage.OpenCategory(ref category, flags); ErrorHandler.ThrowOnFailure(hr); try { foreach (var classification in classificationNames) { ColorableItemInfo[] colors = new ColorableItemInfo[1]; hr = _colorStorage.Storage.GetItem(classification, colors); ErrorHandler.ThrowOnFailure(hr); _classifications.Add(classification, colors); } } finally { _colorStorage.Storage.CloseCategory(); } }
private IDictionary <string, ColorableItemInfo[]> ReadTextEditorCategoryFormats() { Dictionary <string, ColorableItemInfo[]> result = null; // Leave out items where the colors are all defaults. using (IDisposable category = this.OpenCategory(DefGuidList.guidTextEditorFontCategory, __FCSTORAGEFLAGS.FCSF_READONLY)) { // If no fonts and colors have been changed from their defaults, then VS won't open the // category for us since we specified FCSF_READONLY without FCSF_LOADDEFAULTS. if (category != null) { result = new Dictionary <string, ColorableItemInfo[]>(); foreach (var pair in this.formatNameToCategoryMap) { string itemName = pair.Key; ColorableItemInfo[] colorInfos = new ColorableItemInfo[1]; // As of VS 2015, GetItem will fail and return REGDB_E_KEYMISSING (0x80040152) // if the item hasn't been customized before and has no associated registry key. if (ErrorHandler.Succeeded(this.storage.GetItem(itemName, colorInfos))) { CheckDefaultColors(colorInfos); result.Add(itemName, colorInfos); } } } } return(result); }
private static bool GetIsDark() { var storage = Package.GetGlobalService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage; if (storage == null) { return(false); } var category = Microsoft.VisualStudio.Editor.DefGuidList.guidTextEditorFontCategory; var success = storage.OpenCategory(ref category, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS)); try { if (success == 0) { var colors = new ColorableItemInfo[1]; var hresult = storage.GetItem("Plain Text", colors); if (hresult == 0) { var dcolor = ColorTranslator.FromOle(Convert.ToInt32(colors[0].crBackground)); var hsp = Math.Sqrt(0.299 * (dcolor.R * dcolor.R) + 0.587 * (dcolor.G * dcolor.G) + 0.114 * (dcolor.B * dcolor.B)); return(hsp < 127.5); } } } finally { storage.CloseCategory(); } return(false); }
public void Set(String classificationName, Color color) { Guid category = new Guid(Guids.TextEditorCategory); uint flags = (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES); Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var hr = _colorStorage.Storage.OpenCategory(ref category, flags); ErrorHandler.ThrowOnFailure(hr); ColorableItemInfo[] colors = new ColorableItemInfo[1]; colors[0].crForeground = (uint)ColorTranslator.ToWin32(color); colors[0].bForegroundValid = 1; _classifications[classificationName] = colors; try { hr = _colorStorage.Storage.SetItem(classificationName, colors); ErrorHandler.ThrowOnFailure(hr); } finally { _colorStorage.Storage.CloseCategory(); } }
public void Load(ColorStorage colorStorage) { ColorableItemInfo[] colors = new ColorableItemInfo[1]; var hr = colorStorage.Storage.GetItem(this.classificationName, colors); ErrorHandler.ThrowOnFailure(hr); this.foregroundChanged = false; if (colors[0].bForegroundValid != 0) { this.foreground = MapColor(colorStorage, colors[0].crForeground); } else { this.foreground = Color.Transparent; } this.backgroundChanged = false; if (colors[0].bBackgroundValid != 0) { this.background = MapColor(colorStorage, colors[0].crBackground); } else { this.background = Color.Transparent; } this.fontFlagsChanged = false; if (colors[0].bFontFlagsValid != 0) { this.fontFlags = MapFontFlags(colors[0].dwFontFlags); } }
public bool GetTextItemInfo( Guid category, string name, out Color foreground, out Color background) { foreground = Colors.Transparent; background = Colors.Transparent; if (fncStorage == null) { return(false); } if (ErrorHandler.Failed(fncStorage.OpenCategory(category, OpenFlags))) { return(false); } try { var itemInfo = new ColorableItemInfo[1]; if (ErrorHandler.Failed(fncStorage.GetItem(name, itemInfo))) { return(false); } DecodePlainTextColors(ref itemInfo[0]); foreground = GetWpfColor(itemInfo[0].crForeground); background = GetWpfColor(itemInfo[0].crBackground); return(true); } finally { fncStorage.CloseCategory(); } }
/// <summary> /// 设置textedit中的颜色 /// </summary> /// <param name="name">例如"String",可以在工具-选项-字体和颜色中查看</param> /// <param name="foreColor">-1采用默认值</param> /// <param name="backColor">-1采用默认值</param> public static void SetTextEditColor(string name, int foreColor, int backColor) { var textEditorGuid = new Guid(textEditGuid); FontColorObject.OpenCategory(ref textEditorGuid, (uint)__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | (uint)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS); try { ColorableItemInfo[] info = new ColorableItemInfo[1]; if (FontColorObject.GetItem(name, info) == VSConstants.S_OK) { if (foreColor != -1) { info[0].crForeground = (uint)foreColor; } if (backColor != -1) { info[0].crBackground = (uint)backColor; } FontColorObject.SetItem(name, info); } } finally { FontColorObject.CloseCategory(); } }
public override Colorizer GetColorizer(IVsTextLines buffer) { // Clear font cache // http://social.msdn.microsoft.com/Forums/office/en-US/54064c52-727d-4015-af70-c72e44d116a7/vs2012-fontandcolors-text-editor-category-for-language-service-colors?forum=vsx IVsFontAndColorStorage storage; Guid textMgrIID = new Guid( //#if VISUALSTUDIO_11_0 "{E0187991-B458-4F7E-8CA9-42C9A573B56C}" /* 'Text Editor Language Services Items' category discovered in the registry. Resetting TextEditor has no effect. */ //#else // FontsAndColorsCategory.TextEditor //#endif ); if (null != (storage = GetService(typeof(IVsFontAndColorStorage)) as IVsFontAndColorStorage) && VSConstants.S_OK == storage.OpenCategory(ref textMgrIID, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS))) { bool missingColor = false; try { ColorableItemInfo[] info = new ColorableItemInfo[1]; for (int i = 0; i < m_colorableItems.Length; ++i) { string colorName; m_colorableItems[i].GetDisplayName(out colorName); if (ErrorHandler.Failed(storage.GetItem(colorName, info))) { missingColor = true; break; } } } finally { storage.CloseCategory(); } if (missingColor) { IOleServiceProvider oleProvider; // The service and interface guids are different, so we need to go to the OLE layer to get the service Guid iid = typeof(IVsFontAndColorCacheManager).GUID; Guid sid = typeof(SVsFontAndColorCacheManager).GUID; IntPtr pCacheManager; if (null != (oleProvider = GetService(typeof(IOleServiceProvider)) as IOleServiceProvider) && VSConstants.S_OK == oleProvider.QueryService(ref sid, ref iid, out pCacheManager) && pCacheManager != IntPtr.Zero) { try { IVsFontAndColorCacheManager cacheManager = (IVsFontAndColorCacheManager)Marshal.GetObjectForIUnknown(pCacheManager); cacheManager.ClearCache(ref textMgrIID); } finally { Marshal.Release(pCacheManager); } } } } return base.GetColorizer(buffer); }
private static bool GetIsDark() { var storage = Package.GetGlobalService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage; if (storage == null) return false; var category = Microsoft.VisualStudio.Editor.DefGuidList.guidTextEditorFontCategory; var success = storage.OpenCategory(ref category, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS)); try { if (success == 0) { var colors = new ColorableItemInfo[1]; var hresult = storage.GetItem("Plain Text", colors); if (hresult == 0) { var dcolor = ColorTranslator.FromOle(Convert.ToInt32(colors[0].crBackground)); var hsp = Math.Sqrt(0.299 * (dcolor.R * dcolor.R) + 0.587 * (dcolor.G * dcolor.G) + 0.114 * (dcolor.B * dcolor.B)); return hsp < 127.5; } } } finally { storage.CloseCategory(); } return false; }
public static ColorableItemInfo[] ToColorableItemInfo(this DrawingColor drawingColor) { ColorableItemInfo[] colorableItemInfo = new ColorableItemInfo[1]; colorableItemInfo[0].crForeground = (uint)ColorTranslator.ToWin32(drawingColor); colorableItemInfo[0].bForegroundValid = 1; return(colorableItemInfo); }
public static Color?GetColorForClassification(ClassifiedSpan classifiedSpan) { if (string.IsNullOrEmpty(classifiedSpan.ClassificationType)) { return(null); } ThreadHelper.ThrowIfNotOnUIThread(); var fontsAndColorStorage = ServiceProvider.GlobalProvider.GetService <SVsFontAndColorStorage, IVsFontAndColorStorage>(); if (fontsAndColorStorage is null) { return(null); } // Open Text Editor category for readonly access. if (fontsAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS)) != VSConstants.S_OK) { // We were unable to access color information. return(null); } try { var colorItems = new ColorableItemInfo[1]; if (fontsAndColorStorage.GetItem(classifiedSpan.ClassificationType, colorItems) != VSConstants.S_OK) { return(null); } var colorItem = colorItems[0]; var fontAndColorUtilities = (IVsFontAndColorUtilities)fontsAndColorStorage; var foregroundColorRef = colorItem.crForeground; if (fontAndColorUtilities.GetColorType(foregroundColorRef, out var foregroundColorType) != VSConstants.S_OK) { // Without being able to check color type, we cannot make a determination. return(null); } // If the color is not CT_RAW then foregroundColorRef doesn't // regpresent the RGB values for the color and we can't interpret them. if (foregroundColorType != (int)__VSCOLORTYPE.CT_RAW) { return(null); } var colorBytes = BitConverter.GetBytes(foregroundColorRef); return(Color.FromRgb(colorBytes[0], colorBytes[1], colorBytes[2])); } finally { fontsAndColorStorage.CloseCategory(); } }
public bool AreForegroundColorsCustomized(SchemeName schemeName, Guid themeId) { AssertIsForeground(); // Ensure we are initialized if (_fontAndColorStorage is null) { _fontAndColorStorage = _serviceProvider.GetService <SVsFontAndColorStorage, IVsFontAndColorStorage>(); _fontAndColorUtilities = (IVsFontAndColorUtilities)_fontAndColorStorage !; } // Make no changes when in high contast mode or in unknown theme. if (SystemParameters.HighContrast || !_colorSchemes.TryGetValue(schemeName, out var colorScheme) || !colorScheme.TryGetValue(themeId, out var colorSchemeTheme)) { return(false); } var coreThemeColors = (themeId == KnownColorThemes.Dark) ? DarkThemeForeground : BlueLightThemeForeground; // Open Text Editor category for readonly access and do not load items if they are defaulted. if (_fontAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK) { // We were unable to access color information. return(false); } try { foreach (var classification in Classifications) { var colorItems = new ColorableItemInfo[1]; if (_fontAndColorStorage.GetItem(classification, colorItems) != VSConstants.S_OK) { // Classifications that are still defaulted will not have entries. continue; } var colorItem = colorItems[0]; if (IsClassificationCustomized(coreThemeColors, colorSchemeTheme, colorItem, classification)) { return(true); } } } finally { _fontAndColorStorage.CloseCategory(); } return(false); }
/// <summary> /// Determines if any Classification foreground colors have been customized in Fonts and Colors. /// </summary> public async Task <bool> AreForegroundColorsCustomizedAsync( ColorSchemeName schemeName, Guid themeId, CancellationToken cancellationToken) { // Make no changes when in high contast mode or in unknown theme. if (SystemParameters.HighContrast || !_colorSchemes.TryGetValue(schemeName, out var colorScheme) || !colorScheme.TryGetValue(themeId, out var colorSchemeTheme)) { return(false); } // Ensure we are initialized if (_fontAndColorStorage is null) { await TaskScheduler.Default; _fontAndColorStorage = await _asyncServiceProvider.GetServiceAsync <SVsFontAndColorStorage, IVsFontAndColorStorage>(_threadingContext.JoinableTaskFactory).ConfigureAwait(false); } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _fontAndColorUtilities ??= (IVsFontAndColorUtilities)_fontAndColorStorage; var coreThemeColors = themeId == KnownColorThemes.Dark ? DarkThemeForeground : BlueLightThemeForeground; // Open Text Editor category for readonly access and do not load items if they are defaulted. if (_fontAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) == VSConstants.S_OK) { try { foreach (var classification in _classifications) { var colorItems = new ColorableItemInfo[1]; if (_fontAndColorStorage.GetItem(classification, colorItems) != VSConstants.S_OK) { // Classifications that are still defaulted will not have entries. continue; } var colorItem = colorItems[0]; if (IsClassificationCustomized(coreThemeColors, colorSchemeTheme, colorItem, classification)) { return(true); } } } finally { _fontAndColorStorage.CloseCategory(); } } return(false); }
private void DecodePlainTextColors(ref ColorableItemInfo info) { if (info.bForegroundValid == 1) { DecodePlainTextColor(ref info.crForeground, COLORINDEX.CI_SYSPLAINTEXT_FG); } if (info.bBackgroundValid == 1) { DecodePlainTextColor(ref info.crBackground, COLORINDEX.CI_SYSPLAINTEXT_BK); } }
private bool IsClassificationCustomized( ImmutableDictionary <string, uint> coreThemeColors, ImmutableDictionary <string, uint> schemeThemeColors, ColorableItemInfo colorItem, string classification) { AssertIsForeground(); Contract.ThrowIfNull(_fontAndColorUtilities); var foregroundColorRef = colorItem.crForeground; if (_fontAndColorUtilities.GetColorType(foregroundColorRef, out var foregroundColorType) != VSConstants.S_OK) { // Without being able to check color type, we cannot make a determination. return(false); } // If the color is defaulted then it isn't customized. if (foregroundColorType == (int)__VSCOLORTYPE.CT_AUTOMATIC) { return(false); } // Since the color type isn't default then it has been customized, we will // perform an additional check for RGB colors to see if the customized color // matches the color scheme color. if (foregroundColorType != (int)__VSCOLORTYPE.CT_RAW) { return(true); } if (coreThemeColors.TryGetValue(classification, out var coreColor)) { return(foregroundColorRef != coreColor); } if (schemeThemeColors.TryGetValue(classification, out var schemeColor)) { return(foregroundColorRef != schemeColor); } // Since Classification inheritance isn't represented in the scheme files, // this switch case will handle the 3 cases we expect. var fallbackColor = classification switch { ClassificationTypeNames.OperatorOverloaded => coreThemeColors[ClassificationTypeNames.Operator], ClassificationTypeNames.ControlKeyword => coreThemeColors[ClassificationTypeNames.Keyword], _ => coreThemeColors[ClassificationTypeNames.Identifier] }; return(foregroundColorRef != fallbackColor); } }
private async Task LoadSystemTextSettingsAsync(CancellationToken cancellationToken) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); try { IVsFontAndColorStorage storage = (IVsFontAndColorStorage)GetGlobalService(typeof(IVsFontAndColorStorage)); var guid = new Guid("A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0"); if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == Microsoft.VisualStudio.VSConstants.S_OK) { #pragma warning disable SA1129 // Do not use default value type constructor LOGFONTW[] fnt = new LOGFONTW[] { new LOGFONTW() }; FontInfo[] info = new FontInfo[] { new FontInfo() }; #pragma warning restore SA1129 // Do not use default value type constructor if (storage.GetFont(fnt, info) == Microsoft.VisualStudio.VSConstants.S_OK) { var fontSize = info[0].wPointSize; if (fontSize > 0) { ResourceAdornmentManager.TextSize = fontSize; } } } if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == Microsoft.VisualStudio.VSConstants.S_OK) { var info = new ColorableItemInfo[1]; // Get the color value configured for regular string display if (storage.GetItem("String", info) == Microsoft.VisualStudio.VSConstants.S_OK) { var win32Color = (int)info[0].crForeground; int r = win32Color & 0x000000FF; int g = (win32Color & 0x0000FF00) >> 8; int b = (win32Color & 0x00FF0000) >> 16; var textColor = Color.FromRgb((byte)r, (byte)g, (byte)b); ResourceAdornmentManager.TextForegroundColor = textColor; } } } catch (Exception exc) { ExceptionHelper.Log(exc, "Error in LoadSystemTextSettingsAsync"); } }
internal static void UpdateClassificationColor(ClassifiedSpan classifiedSpan, Color selectedColor) { if (string.IsNullOrEmpty(classifiedSpan.ClassificationType)) { return; } ThreadHelper.ThrowIfNotOnUIThread(); var fontsAndColorStorage = ServiceProvider.GlobalProvider.GetService <SVsFontAndColorStorage, IVsFontAndColorStorage>(); if (fontsAndColorStorage is null) { return; } // Open Text Editor to make changes. Make sure LOADDEFAULTS is passed so any default // values can be modified as well. if (fontsAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)(__FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) != VSConstants.S_OK) { // We were unable to access color information. return; } try { var colorItems = new ColorableItemInfo[1]; if (fontsAndColorStorage.GetItem(classifiedSpan.ClassificationType, colorItems) != VSConstants.S_OK) { return; } var colorItem = colorItems[0]; colorItem.crForeground = BitConverter.ToUInt32( new byte[] { selectedColor.R, selectedColor.G, selectedColor.B, 0 // Alpha }, 0); if (fontsAndColorStorage.SetItem(classifiedSpan.ClassificationType, new[] { colorItem }) != VSConstants.S_OK) { throw new Exception(); } } finally { fontsAndColorStorage.CloseCategory(); } }
private (Color fg, Color bg, bool bold) GetInfo(string item) { ThreadHelper.ThrowIfNotOnUIThread(); var colorInfo = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(_storage.GetItem(item, colorInfo)); var fg = FontAndColorService.ReadVsColor(colorInfo[0].crForeground); var bg = FontAndColorService.ReadVsColor(colorInfo[0].crBackground); var isBold = ((FONTFLAGS)colorInfo[0].dwFontFlags & FONTFLAGS.FF_BOLD) == FONTFLAGS.FF_BOLD; return(fg, bg, isBold); }
public void Save(ColorStorage colorStorage) { if (this.HasChanged()) { ColorableItemInfo[] colors = new ColorableItemInfo[1]; var hr = colorStorage.Storage.GetItem(this.classificationName, colors); ErrorHandler.ThrowOnFailure(hr); AssignForSave(colorStorage, colors); hr = colorStorage.Storage.SetItem(this.classificationName, colors); ErrorHandler.ThrowOnFailure(hr); } }
void themeEngine_OnThemeChanged(object sender, EventArgs e) { var colorUtilities = Site.GetService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorUtilities; var currentTheme = themeEngine.GetCurrentTheme(); var isDarkTheme = currentTheme == VisualStudioTheme.Dark || currentTheme == VisualStudioTheme.UnknownDark; var store = Package.GetGlobalService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage; if (store == null) { return; } if (store.OpenCategory(DefGuidList.guidTextEditorFontCategory, (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES)) != VSConstants.S_OK) { return; } try { // Update each colorable item foreach (var colorableItem in m_colorableItems) { string canonicalName; var colorInfos = new ColorableItemInfo[1]; if (colorableItem.GetCanonicalName(out canonicalName) == VSConstants.S_OK && store.GetItem(canonicalName, colorInfos) == VSConstants.S_OK) { // Get new color var hiColor = isDarkTheme ? colorableItem.HiForeColorDark : colorableItem.HiForeColorLight; var colorIndex = isDarkTheme ? colorableItem.ForeColorDark : colorableItem.ForeColorLight; if (hiColor != Color.Empty) { colorInfos[0].crForeground = hiColor.R | ((uint)hiColor.G << 8) | ((uint)hiColor.B << 16); } else { colorUtilities.EncodeIndexedColor(colorIndex, out colorInfos[0].crForeground); } // Update color in settings store.SetItem(canonicalName, colorInfos); } } } finally { store.CloseCategory(); } }
public void Load(ColorStorage colorStorage) { ColorableItemInfo[] colors = new ColorableItemInfo[1]; var hr = colorStorage.Storage.GetItem(classificationName, colors); ErrorHandler.ThrowOnFailure(hr); this.foregroundChanged = false; if ( colors[0].bForegroundValid != 0 ) { this.foreground = MapColor(colorStorage, colors[0].crForeground); } this.backgroundChanged = false; if ( colors[0].bBackgroundValid != 0 ) { this.background = MapColor(colorStorage, colors[0].crBackground); } }
void SetColor(string item, Color color, bool isForeground) { var cii = new ColorableItemInfo[1]; uint wincolor = (uint)(color.B << 16) + (uint)(color.R) + (uint)(color.G << 8); if (isForeground) { cii[0].bForegroundValid = 1; cii[0].crForeground = (uint)wincolor; } else { cii[0].bBackgroundValid = 1; cii[0].crBackground = (uint)wincolor; } m_pStorage.SetItem(item, cii); }
private static void SaveColor(IVsFontAndColorStorage vsStorage, ColorKey colorKey, Color color) { var colorableItemInfo = new ColorableItemInfo(); if (colorKey.IsForeground) { colorableItemInfo.bForegroundValid = 1; colorableItemInfo.crForeground = (uint)ColorTranslator.ToWin32(color); } else { colorableItemInfo.bBackgroundValid = 1; colorableItemInfo.crBackground = (uint)ColorTranslator.ToWin32(color); } ErrorHandler.ThrowOnFailure(vsStorage.SetItem(colorKey.Name, new[] { colorableItemInfo })); }
private async Task UpdateColoursFromFontsAndColorsAsync() { var fontAndColorStorage = await lazyIVsFontAndColorStorage.GetValueAsync(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var success = fontAndColorStorage.OpenCategory(ref categoryWithCoverage, storeFlags); var usedFontsAndColors = false; if (success == VSConstants.S_OK) { // https://github.com/microsoft/vs-threading/issues/993 System.Windows.Media.Color GetColor(string displayName) { var touchAreaInfo = new ColorableItemInfo[1]; var getItemSuccess = fontAndColorStorage.GetItem(displayName, touchAreaInfo); if (getItemSuccess == VSConstants.S_OK) { return(ParseColor(touchAreaInfo[0].crBackground)); } throw new NotSupportedException($"{getItemSuccess}"); } try { // https://developercommunity.visualstudio.com/t/fonts-and-colors-coverage-settings-available-in-vs/1683898 var newCoverageTouchedArea = GetColor("Coverage Touched Area"); var newCoverageNotTouchedArea = GetColor("Coverage Not Touched Area"); var newCoveragePartiallyTouchedArea = GetColor("Coverage Partially Touched Area"); SetColors(newCoverageTouchedArea, newCoverageNotTouchedArea, newCoveragePartiallyTouchedArea); usedFontsAndColors = true; }catch (NotSupportedException) { logger.Log("No coverage settings available from Fonts and Colors"); } } fontAndColorStorage.CloseCategory(); if (!usedFontsAndColors) { canUseFontsAndColours = false; UseDefaultColours(); } }
private static void SaveColor(IVsFontAndColorStorage vsStorage, ColorKey colorKey, System.Drawing.Color color) { Debug.WriteLine($"GeneralOptions.SaveColoR keyName={colorKey.Name} color={color}"); ThreadHelper.ThrowIfNotOnUIThread(); ColorableItemInfo[] arr = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(vsStorage.GetItem(colorKey.Name, arr)); if (colorKey.IsForeground) { arr[0].bForegroundValid = 1; arr[0].crForeground = (uint)ColorTranslator.ToWin32(color); } else { arr[0].bBackgroundValid = 1; arr[0].crBackground = (uint)ColorTranslator.ToWin32(color); } ErrorHandler.ThrowOnFailure(vsStorage.SetItem(colorKey.Name, arr)); }
private void UpdateColors() { var theme = themeEngine.GetCurrentTheme(); // Did theme change? if (theme != currentTheme) { currentTheme = theme; var colors = themeColors[theme]; if (fontAndColorStorage != null && fontAndColorUtilities != null) { if (fontAndColorStorage.OpenCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidTextEditorFontCategory, (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES)) == VSConstants.S_OK) { try { foreach (var pair in colors) { var colorInfos = new ColorableItemInfo[1]; if (fontAndColorStorage.GetItem(pair.Key, colorInfos) == VSConstants.S_OK) { if (pair.Value.ForegroundColor != null) { colorInfos[0].crForeground = (uint)(pair.Value.ForegroundColor.Value.R | (pair.Value.ForegroundColor.Value.G << 8) | (pair.Value.ForegroundColor.Value.B << 16)); } if (pair.Value.BackgroundColor != null) { colorInfos[0].crBackground = (uint)(pair.Value.BackgroundColor.Value.R | (pair.Value.BackgroundColor.Value.G << 8) | (pair.Value.BackgroundColor.Value.B << 16)); } fontAndColorStorage.SetItem(pair.Key, colorInfos); } } } finally { fontAndColorStorage.CloseCategory(); } } } } }
private void AcuminatorThemeChangedHandler(object sender, AcuminatorThemeChangedEventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); if (_classificationTypeName == null) { return; } try { Color?foregroundColorForTheme = VSColors.GetThemedColor(_classificationTypeName); if (foregroundColorForTheme == null) { return; } ForegroundColor = foregroundColorForTheme; var classificationType = e.ClassificationTypeRegistry.GetClassificationType(_classificationTypeName); if (classificationType == null) { return; } ColorableItemInfo[] colorInfo = new ColorableItemInfo[1]; if (e.FontAndColorStorage.GetItem(_classificationTypeName, colorInfo) != VSConstants.S_OK) //comment from F# repo: "we don't touch the changes made by the user" { var properties = e.FormatMap.GetTextProperties(classificationType); var newProperties = properties.SetForeground(ForegroundColor.Value); e.FormatMap.SetTextProperties(classificationType, newProperties); } } catch (Exception exception) { AcuminatorVSPackage.Instance?.AcuminatorLogger ?.LogException(exception, logOnlyFromAcuminatorAssemblies: false, Logger.LogMode.Error); } }
/// <summary> /// 获得textedit中的颜色 /// </summary> /// <param name="name"></param> /// <returns></returns> public static Color GetTextEditColor(string name) { Guid textEditorGuid = new Guid(textEditGuid); FontColorObject.OpenCategory(ref textEditorGuid, (uint)__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | (uint)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS); try { ColorableItemInfo[] info = new ColorableItemInfo[1]; if (FontColorObject.GetItem(name, info) == VSConstants.S_OK) { uint c = info[0].crForeground; return(ConvertWindowsRGBToColour((int)c)); } return(Color.Empty); } finally { FontColorObject.CloseCategory(); } }
public void Save(ColorStorage colorStorage) { if ( this.backgroundChanged || this.foregroundChanged ) { ColorableItemInfo[] colors = new ColorableItemInfo[1]; var hr = colorStorage.Storage.GetItem(classificationName, colors); ErrorHandler.ThrowOnFailure(hr); if ( this.foregroundChanged ) { colors[0].crForeground = (uint)ColorTranslator.ToWin32(foreground); colors[0].bForegroundValid = 1; } if ( this.backgroundChanged ) { colors[0].crBackground = (uint)ColorTranslator.ToWin32(background); colors[0].bBackgroundValid = 1; } hr = colorStorage.Storage.SetItem(classificationName, colors); ErrorHandler.ThrowOnFailure(hr); } }
private static System.Drawing.Color LoadColor(IServiceProvider Site, IVsFontAndColorStorage vsStorage, ColorKey colorKey) { ThreadHelper.ThrowIfNotOnUIThread(); var arr = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(vsStorage.GetItem(colorKey.Name, arr)); var isValid = colorKey.IsForeground ? arr[0].bForegroundValid : arr[0].bBackgroundValid; if (isValid == 0) { throw new Exception(); } var colorRef = colorKey.IsForeground ? arr[0].crForeground : arr[0].crBackground; var color = FromColorRef(Site, vsStorage, colorRef); Debug.WriteLine($"GeneralOptions.LoadColoR keyName={colorKey.Name} color={color}"); return(color); }
public HighlightWordFormatDefinition() { // Default the BackgroundColor to a transparent grey BackgroundColor = Color.FromArgb(127, 170, 170, 170); DisplayName = "Highlight Word"; ZOrder = 5; // If possible, set the Background color to match the Highlighted Reference color IVsFontAndColorStorage colorStorage = ServiceProvider.GlobalProvider.GetService(typeof(IVsFontAndColorStorage)) as IVsFontAndColorStorage; ColorableItemInfo[] itemInfoOut = new ColorableItemInfo[1]; if (colorStorage.OpenCategory(ref _textEditorCategory, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == VSConstants.S_OK) { if (colorStorage.GetItem(_itemName, itemInfoOut) == VSConstants.S_OK) { uint hexColor = itemInfoOut[0].crBackground; BackgroundColor = Color.FromArgb(255, (byte)hexColor, (byte)(hexColor >> 8), (byte)(hexColor >> 16)); } colorStorage.CloseCategory(); } }
private Color LoadColor(IVsFontAndColorStorage vsStorage, ColorKey colorKey) { var array = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(vsStorage.GetItem(colorKey.Name, array)); int isValid = colorKey.IsForeground ? array[0].bForegroundValid : array[0].bBackgroundValid; if (isValid == 0) { throw new Exception(); } uint colorRef = colorKey.IsForeground ? array[0].crForeground : array[0].crBackground; return(FromColorRef(vsStorage, colorRef)); }
private static void GetSize() { try { IVsFontAndColorStorage storage = (IVsFontAndColorStorage)EditorExtensionsPackage.GetGlobalService(typeof(IVsFontAndColorStorage)); var guid = new Guid("A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0"); if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == VS.VSConstants.S_OK) { LOGFONTW[] Fnt = new LOGFONTW[] { new LOGFONTW() }; FontInfo[] Info = new FontInfo[] { new FontInfo() }; storage.GetFont(Fnt, Info); _fontSize = (int)Info[0].wPointSize; } if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == VS.VSConstants.S_OK) { var info = new ColorableItemInfo[1]; storage.GetItem("Plain Text", info); _backgroundColor = ConvertFromWin32Color((int)info[0].crBackground); } } catch { } }
private void EnsureUserTextColors() { if (myUserForeColor.IsEmpty) { if (myStorageOpen) { myStorageOpen = false; myStorage.CloseCategory(); // Ignore return } Debug.Assert(myStorage != null); // All paths to this lead through EnsureStore Guid textCategory = TextEditorCategory; ErrorHandler.ThrowOnFailure(myStorage.OpenCategory(ref textCategory, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS))); try { ColorableItemInfo item = new ColorableItemInfo(); myGetItemParam[0] = item; myStorage.GetItem("Plain Text", myGetItemParam); item = myGetItemParam[0]; myUserForeColor = TranslateColorValue(item.crForeground); myUserBackColor = TranslateColorValue(item.crBackground); } finally { myStorage.CloseCategory(); // Ignore return } } }
/// <summary> /// 获得textedit中的颜色 /// </summary> /// <param name="name"></param> /// <returns></returns> public static Color GetTextEditColor(string name) { Guid textEditorGuid = new Guid(textEditGuid); FontColorObject.OpenCategory(ref textEditorGuid, (uint)__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | (uint)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS); try { ColorableItemInfo[] info = new ColorableItemInfo[1]; if (FontColorObject.GetItem(name, info) == VSConstants.S_OK) { uint c = info[0].crForeground; return ConvertWindowsRGBToColour((int)c); } return Color.Empty; } finally { FontColorObject.CloseCategory(); } }
private void GetColors() { try { IVsFontAndColorStorage storage; storage = Package.GetGlobalService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage; var guid = new Guid("A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0"); // text editor if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == 0) { var info = new ColorableItemInfo[1]; storage.GetItem(NoCovColorName, info); _backgroundColor[0] = CoverageMargin.ConvertFromWin32Color(info[0].crBackground); _foregroundColor[0] = CoverageMargin.ConvertFromWin32Color(info[0].crBackground); storage.GetItem(CovColorName, info); _backgroundColor[1] = CoverageMargin.ConvertFromWin32Color(info[0].crBackground); _foregroundColor[1] = CoverageMargin.ConvertFromWin32Color(info[0].crBackground); storage.CloseCategory(); } } catch { } }
/// <summary> /// Initialize a ColorRetriever structure /// </summary> /// <param name="serviceProvider"></param> /// <param name="categoryGuid"></param> /// <param name="indexConverter">Delegate to convert a name into an index</param> public ColorRetriever(IServiceProvider serviceProvider, Guid categoryGuid, NameFromIndex indexConverter) { myServiceProvider = serviceProvider; myShell = null; myStorage = null; myStorageOpen = false; myUserForeColor = Color.Empty; myUserBackColor = Color.Empty; myCategoryGuid = categoryGuid; myGetItemParam = new ColorableItemInfo[1]; myIndexConverter = indexConverter; }
private Color TranslateColorValue(uint colorValue) { if (0 != (colorValue & AllSpecialColorBits)) { uint coreColorValue = colorValue & ~AllSpecialColorBits; switch (colorValue & AllSpecialColorBits) { case StandardPaletteBit: Color knownColor = Color.Empty; switch ((COLORINDEX)coreColorValue) { case COLORINDEX.CI_USERTEXT_FG: EnsureUserTextColors(); knownColor = myUserForeColor; break; case COLORINDEX.CI_USERTEXT_BK: EnsureUserTextColors(); knownColor = myUserBackColor; break; case COLORINDEX.CI_BLACK: knownColor = Color.Black; break; case COLORINDEX.CI_WHITE: knownColor = Color.White; break; case COLORINDEX.CI_MAROON: knownColor = Color.Maroon; break; case COLORINDEX.CI_DARKGREEN: knownColor = Color.DarkGreen; break; case COLORINDEX.CI_BROWN: knownColor = Color.Brown; break; case COLORINDEX.CI_DARKBLUE: knownColor = Color.DarkBlue; break; case COLORINDEX.CI_PURPLE: knownColor = Color.Purple; break; case COLORINDEX.CI_AQUAMARINE: knownColor = Color.Aquamarine; break; case COLORINDEX.CI_LIGHTGRAY: knownColor = Color.LightGray; break; case COLORINDEX.CI_DARKGRAY: knownColor = Color.DarkGray; break; case COLORINDEX.CI_RED: knownColor = Color.Red; break; case COLORINDEX.CI_GREEN: knownColor = Color.Green; break; case COLORINDEX.CI_YELLOW: knownColor = Color.Yellow; break; case COLORINDEX.CI_BLUE: knownColor = Color.Blue; break; case COLORINDEX.CI_MAGENTA: knownColor = Color.Magenta; break; case COLORINDEX.CI_CYAN: knownColor = Color.Cyan; break; case COLORINDEX.CI_SYSSEL_FG: knownColor = SystemColors.HighlightText; break; case COLORINDEX.CI_SYSSEL_BK: knownColor = SystemColors.Highlight; break; case COLORINDEX.CI_SYSINACTSEL_FG: knownColor = SystemColors.InactiveCaptionText; break; case COLORINDEX.CI_SYSINACTSEL_BK: knownColor = SystemColors.InactiveCaption; break; case COLORINDEX.CI_SYSWIDGETMGN_BK: knownColor = SystemColors.ButtonFace; break; case COLORINDEX.CI_SYSPLAINTEXT_FG: knownColor = SystemColors.WindowText; break; case COLORINDEX.CI_SYSPLAINTEXT_BK: knownColor = SystemColors.Window; break; } return knownColor; case SystemColorBit: colorValue = GetSysColor((int)coreColorValue); break; case VsColorBit: if (myShell == null) { myShell = (IVsUIShell2)myServiceProvider.GetService(typeof(IVsUIShell)); } ErrorHandler.ThrowOnFailure(myShell.GetVSSysColorEx((int)coreColorValue, out colorValue)); break; case TrackForegroundColorBit: { ColorableItemInfo[] myGetItemParam = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(myStorage.GetItem(myIndexConverter((int)coreColorValue), myGetItemParam)); return TranslateColorValue(myGetItemParam[0].crForeground); } case TrackBackgroundColorBit: { ColorableItemInfo[] myGetItemParam = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(myStorage.GetItem(myIndexConverter((int)coreColorValue), myGetItemParam)); return TranslateColorValue(myGetItemParam[0].crBackground); } } } return ColorTranslator.FromWin32((int)colorValue); }
static Tuple<Color?, Color?> TryGetItem(IVsFontAndColorStorage storage, string item) { Tuple<Color?, Color?> result = null; // load specific category to prevent our own format classifications being loaded InCategory(storage, Microsoft.VisualStudio.Editor.DefGuidList.guidTextEditorFontCategory, () => { ColorableItemInfo[] colors = new ColorableItemInfo[1]; var hresult = storage.GetItem(item, colors); if (hresult == 0) { result = Tuple.Create<Color?, Color?>(ParseColor(colors[0].crForeground), ParseColor(colors[0].crBackground)); } else { result = Tuple.Create<Color?, Color?>(null, null); } }); return result; }
/// <summary> /// Get the color information for a specific item /// </summary> /// <param name="itemIndex">The index of an item in the category /// used to create the ColorRetriever</param> /// <returns>ColorItem structure</returns> public ColorItem GetColorItem(int itemIndex) { ColorItem retVal = new ColorItem(); EnsureStorage(); ColorableItemInfo item = new ColorableItemInfo(); myGetItemParam[0] = item; ErrorHandler.ThrowOnFailure(myStorage.GetItem(myIndexConverter(itemIndex), myGetItemParam)); item = myGetItemParam[0]; retVal.FontStyle = (item.bFontFlagsValid != 0) ? GetFontStyleFromFontFlags((FONTFLAGS)item.dwFontFlags) : FontStyle.Regular; retVal.ForeColor = (item.bForegroundValid != 0) ? TranslateColorValue(item.crForeground) : Color.Empty; retVal.BackColor = (item.bBackgroundValid != 0) ? TranslateColorValue(item.crBackground) : Color.Empty; return retVal; }
private void SelectedSymbol_PropertyChanged(object sender, PropertyChangedEventArgs e) { fontAndColorStorage.OpenCategory(ref TextEditorFontCategoryGuid, (int) __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES |(int)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS); var symbol = sender as SelectedTextSymbol; symbol.ClassificationMap.BeginBatchUpdate(); var props = symbol.ClassificationMap.GetTextProperties(symbol.ClassificationType); switch(e.PropertyName) { case "Bold": props = props.SetBold(symbol.Bold); symbol.ClassificationMap.SetTextProperties(symbol.ClassificationType,props); var colorInfo = new ColorableItemInfo[1]; fontAndColorStorage.GetItem(symbol.ClassificationName, colorInfo); colorInfo[0].dwFontFlags |= (uint) FONTFLAGS.FF_BOLD; fontAndColorStorage.SetItem(symbol.ClassificationName, colorInfo); break; case "Italic": props = props.SetItalic(symbol.Italic); symbol.ClassificationMap.SetTextProperties(symbol.ClassificationType, props); break; case "ForegroundColor": props = props.SetForeground(symbol.ForegroundColor); symbol.ClassificationMap.SetTextProperties(symbol.ClassificationType, props); break; case "BackgroundColor": props = props.SetBackground(symbol.BackgroundColor); symbol.ClassificationMap.SetTextProperties(symbol.ClassificationType, props); break; default: break; } symbol.ClassificationMap.EndBatchUpdate(); fontAndColorStorage.CloseCategory(); }
/// <summary> /// Implements IVsFontAndColorEvents.OnItemChanged /// </summary> protected int OnItemChanged(ref Guid rguidCategory, string szItem, int iItem, ColorableItemInfo[] pInfo, uint crLiteralForeground, uint crLiteralBackground) { OnChange(ref rguidCategory); return VSConstants.S_OK; }
int IVsFontAndColorEvents.OnItemChanged(ref Guid rguidCategory, string szItem, int iItem, ColorableItemInfo[] pInfo, uint crLiteralForeground, uint crLiteralBackground) { OnChange(ref rguidCategory); return OnItemChanged(ref rguidCategory, szItem, iItem, pInfo, crLiteralForeground, crLiteralBackground); }
private Color LoadColor(IVsFontAndColorStorage vsStorage, ColorKey colorKey) { var array = new ColorableItemInfo[1]; ErrorHandler.ThrowOnFailure(vsStorage.GetItem(colorKey.Name, array)); int isValid = colorKey.IsForeground ? array[0].bForegroundValid : array[0].bBackgroundValid; if (isValid == 0) { throw new Exception(); } uint colorRef = colorKey.IsForeground ? array[0].crForeground : array[0].crBackground; return FromColorRef(vsStorage, colorRef); }