Flow.Launcher/Flow.Launcher.Core/Resource/Theme.cs

721 lines
29 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
2024-06-02 12:17:42 +00:00
using System.Xml;
using System.Windows;
using System.Windows.Controls;
2018-12-22 17:53:13 +00:00
using System.Windows.Markup;
using System.Windows.Media;
2020-05-07 04:30:55 +00:00
using System.Windows.Media.Effects;
2025-02-19 09:13:51 +00:00
using System.Windows.Shell;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.UserSettings;
2025-02-24 17:42:27 +00:00
using Microsoft.Win32;
using Flow.Launcher.Plugin;
2025-03-13 04:50:09 +00:00
using System.Windows.Threading;
2025-03-16 06:52:55 +00:00
using TextBox = System.Windows.Controls.TextBox;
using System.Threading.Tasks;
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Core.Resource
{
public class Theme
{
2025-03-16 06:52:55 +00:00
#region Properties & Fields
public string CurrentTheme => _settings.Theme;
public bool BlurEnabled { get; set; }
2024-06-03 07:25:42 +00:00
private const string ThemeMetadataNamePrefix = "Name:";
private const string ThemeMetadataIsDarkPrefix = "IsDark:";
private const string ThemeMetadataHasBlurPrefix = "HasBlur:";
2022-09-15 02:01:13 +00:00
private const int ShadowExtraMargin = 32;
2021-06-12 14:38:40 +00:00
2025-02-23 11:48:38 +00:00
private readonly IPublicAPI _api;
private readonly Settings _settings;
private readonly List<string> _themeDirectories = new();
2017-02-28 00:12:53 +00:00
private ResourceDictionary _oldResource;
private string _oldTheme;
2020-11-15 19:29:24 +00:00
private const string Folder = Constant.Themes;
2017-02-28 00:12:53 +00:00
private const string Extension = ".xaml";
2025-03-16 06:43:53 +00:00
private static string DirectoryPath => Path.Combine(Constant.ProgramDirectory, Folder);
private static string UserDirectoryPath => Path.Combine(DataLocation.DataDirectory(), Folder);
2025-03-16 06:52:55 +00:00
#endregion
#region Constructor
public Theme(IPublicAPI publicAPI, Settings settings)
{
2025-02-23 11:48:38 +00:00
_api = publicAPI;
_settings = settings;
2017-02-21 02:40:43 +00:00
_themeDirectories.Add(DirectoryPath);
_themeDirectories.Add(UserDirectoryPath);
2023-01-09 15:56:48 +00:00
MakeSureThemeDirectoriesExist();
2017-02-28 00:12:53 +00:00
var dicts = Application.Current.Resources.MergedDictionaries;
_oldResource = dicts.First(d =>
{
2020-04-28 11:10:42 +00:00
if (d.Source == null)
return false;
2017-02-28 00:12:53 +00:00
var p = d.Source.AbsolutePath;
var dir = Path.GetDirectoryName(p).NonNull();
var info = new DirectoryInfo(dir);
var f = info.Name;
var e = Path.GetExtension(p);
var found = f == Folder && e == Extension;
return found;
});
_oldTheme = Path.GetFileNameWithoutExtension(_oldResource.Source.AbsolutePath);
}
#endregion
2025-03-16 06:52:55 +00:00
#region Theme Resources
2025-03-14 01:00:31 +00:00
2025-03-16 06:52:55 +00:00
private void MakeSureThemeDirectoriesExist()
{
2025-03-16 06:52:55 +00:00
foreach (var dir in _themeDirectories.Where(dir => !Directory.Exists(dir)))
2025-03-14 01:00:31 +00:00
{
2025-03-16 06:52:55 +00:00
try
2025-03-14 01:00:31 +00:00
{
2025-03-16 06:52:55 +00:00
Directory.CreateDirectory(dir);
2025-03-14 01:00:31 +00:00
}
2025-03-16 06:52:55 +00:00
catch (Exception e)
2025-03-14 01:00:31 +00:00
{
2025-03-16 06:52:55 +00:00
Log.Exception($"|Theme.MakesureThemeDirectoriesExist|Exception when create directory <{dir}>", e);
2025-03-14 01:00:31 +00:00
}
2025-03-16 06:52:55 +00:00
}
}
2025-03-16 06:52:55 +00:00
private void UpdateResourceDictionary(ResourceDictionary dictionaryToUpdate)
2025-03-04 04:46:36 +00:00
{
2025-03-16 06:52:55 +00:00
var dicts = Application.Current.Resources.MergedDictionaries;
dicts.Remove(_oldResource);
dicts.Add(dictionaryToUpdate);
_oldResource = dictionaryToUpdate;
2025-03-04 04:46:36 +00:00
}
2025-03-16 06:52:55 +00:00
private ResourceDictionary GetThemeResourceDictionary(string theme)
2025-03-04 04:46:36 +00:00
{
2025-03-16 06:52:55 +00:00
var uri = GetThemePath(theme);
var dict = new ResourceDictionary
2025-03-04 04:46:36 +00:00
{
2025-03-16 06:52:55 +00:00
Source = new Uri(uri, UriKind.Absolute)
};
2025-03-16 06:52:55 +00:00
return dict;
2025-03-14 01:00:31 +00:00
}
2025-03-16 06:52:55 +00:00
private ResourceDictionary GetResourceDictionary(string theme)
{
2025-03-16 06:52:55 +00:00
var dict = GetThemeResourceDictionary(theme);
if (dict["QueryBoxStyle"] is Style queryBoxStyle &&
dict["QuerySuggestionBoxStyle"] is Style querySuggestionBoxStyle)
2025-03-09 01:16:02 +00:00
{
2025-03-16 06:52:55 +00:00
var fontFamily = new FontFamily(_settings.QueryBoxFont);
var fontStyle = FontHelper.GetFontStyleFromInvariantStringOrNormal(_settings.QueryBoxFontStyle);
var fontWeight = FontHelper.GetFontWeightFromInvariantStringOrNormal(_settings.QueryBoxFontWeight);
var fontStretch = FontHelper.GetFontStretchFromInvariantStringOrNormal(_settings.QueryBoxFontStretch);
2025-03-09 01:16:02 +00:00
2025-03-16 06:52:55 +00:00
queryBoxStyle.Setters.Add(new Setter(TextBox.FontFamilyProperty, fontFamily));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontStyleProperty, fontStyle));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontWeightProperty, fontWeight));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontStretchProperty, fontStretch));
2025-03-11 03:32:27 +00:00
2025-03-16 06:52:55 +00:00
var caretBrushPropertyValue = queryBoxStyle.Setters.OfType<Setter>().Any(x => x.Property.Name == "CaretBrush");
var foregroundPropertyValue = queryBoxStyle.Setters.OfType<Setter>().Where(x => x.Property.Name == "Foreground")
.Select(x => x.Value).FirstOrDefault();
if (!caretBrushPropertyValue && foregroundPropertyValue != null) //otherwise BaseQueryBoxStyle will handle styling
queryBoxStyle.Setters.Add(new Setter(TextBox.CaretBrushProperty, foregroundPropertyValue));
2025-03-09 01:16:02 +00:00
2025-03-16 06:52:55 +00:00
// Query suggestion box's font style is aligned with query box
querySuggestionBoxStyle.Setters.Add(new Setter(TextBox.FontFamilyProperty, fontFamily));
querySuggestionBoxStyle.Setters.Add(new Setter(TextBox.FontStyleProperty, fontStyle));
querySuggestionBoxStyle.Setters.Add(new Setter(TextBox.FontWeightProperty, fontWeight));
querySuggestionBoxStyle.Setters.Add(new Setter(TextBox.FontStretchProperty, fontStretch));
}
2025-03-14 01:00:31 +00:00
2025-03-16 06:52:55 +00:00
if (dict["ItemTitleStyle"] is Style resultItemStyle &&
dict["ItemTitleSelectedStyle"] is Style resultItemSelectedStyle &&
dict["ItemHotkeyStyle"] is Style resultHotkeyItemStyle &&
dict["ItemHotkeySelectedStyle"] is Style resultHotkeyItemSelectedStyle)
{
Setter fontFamily = new Setter(TextBlock.FontFamilyProperty, new FontFamily(_settings.ResultFont));
Setter fontStyle = new Setter(TextBlock.FontStyleProperty, FontHelper.GetFontStyleFromInvariantStringOrNormal(_settings.ResultFontStyle));
Setter fontWeight = new Setter(TextBlock.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(_settings.ResultFontWeight));
Setter fontStretch = new Setter(TextBlock.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(_settings.ResultFontStretch));
2025-03-16 06:52:55 +00:00
Setter[] setters = { fontFamily, fontStyle, fontWeight, fontStretch };
Array.ForEach(
new[] { resultItemStyle, resultItemSelectedStyle, resultHotkeyItemStyle, resultHotkeyItemSelectedStyle }, o
=> Array.ForEach(setters, p => o.Setters.Add(p)));
}
2025-03-11 03:32:27 +00:00
2025-03-16 06:52:55 +00:00
if (
dict["ItemSubTitleStyle"] is Style resultSubItemStyle &&
dict["ItemSubTitleSelectedStyle"] is Style resultSubItemSelectedStyle)
{
Setter fontFamily = new Setter(TextBlock.FontFamilyProperty, new FontFamily(_settings.ResultSubFont));
Setter fontStyle = new Setter(TextBlock.FontStyleProperty, FontHelper.GetFontStyleFromInvariantStringOrNormal(_settings.ResultSubFontStyle));
Setter fontWeight = new Setter(TextBlock.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(_settings.ResultSubFontWeight));
Setter fontStretch = new Setter(TextBlock.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(_settings.ResultSubFontStretch));
Setter[] setters = { fontFamily, fontStyle, fontWeight, fontStretch };
Array.ForEach(
new[] { resultSubItemStyle, resultSubItemSelectedStyle }, o
=> Array.ForEach(setters, p => o.Setters.Add(p)));
}
/* Ignore Theme Window Width and use setting */
var windowStyle = dict["WindowStyle"] as Style;
var width = _settings.WindowSize;
windowStyle.Setters.Add(new Setter(Window.WidthProperty, width));
return dict;
}
2025-03-16 06:52:55 +00:00
private ResourceDictionary GetCurrentResourceDictionary()
2025-02-24 17:42:27 +00:00
{
2025-03-16 06:52:55 +00:00
return GetResourceDictionary(_settings.Theme);
}
2025-02-24 17:42:27 +00:00
2025-03-16 06:52:55 +00:00
private ThemeData GetThemeDataFromPath(string path)
{
using var reader = XmlReader.Create(path);
reader.Read();
2025-02-24 17:42:27 +00:00
2025-03-16 06:52:55 +00:00
var extensionlessName = Path.GetFileNameWithoutExtension(path);
2025-02-24 17:42:27 +00:00
2025-03-16 06:52:55 +00:00
if (reader.NodeType is not XmlNodeType.Comment)
return new ThemeData(extensionlessName, extensionlessName);
var commentLines = reader.Value.Trim().Split('\n').Select(v => v.Trim());
var name = extensionlessName;
bool? isDark = null;
bool? hasBlur = null;
foreach (var line in commentLines)
{
if (line.StartsWith(ThemeMetadataNamePrefix, StringComparison.OrdinalIgnoreCase))
2025-02-24 17:42:27 +00:00
{
2025-03-16 06:52:55 +00:00
name = line[ThemeMetadataNamePrefix.Length..].Trim();
2025-02-24 17:42:27 +00:00
}
2025-03-16 06:52:55 +00:00
else if (line.StartsWith(ThemeMetadataIsDarkPrefix, StringComparison.OrdinalIgnoreCase))
2025-02-24 17:42:27 +00:00
{
2025-03-16 06:52:55 +00:00
isDark = bool.Parse(line[ThemeMetadataIsDarkPrefix.Length..].Trim());
}
else if (line.StartsWith(ThemeMetadataHasBlurPrefix, StringComparison.OrdinalIgnoreCase))
{
hasBlur = bool.Parse(line[ThemeMetadataHasBlurPrefix.Length..].Trim());
2025-02-24 17:42:27 +00:00
}
}
2025-03-16 06:52:55 +00:00
return new ThemeData(extensionlessName, name, isDark, hasBlur);
2025-02-24 17:42:27 +00:00
}
2025-03-16 06:52:55 +00:00
private string GetThemePath(string themeName)
2025-03-13 04:50:09 +00:00
{
2025-03-16 06:52:55 +00:00
foreach (string themeDirectory in _themeDirectories)
2025-03-13 04:50:09 +00:00
{
2025-03-16 06:52:55 +00:00
string path = Path.Combine(themeDirectory, themeName + Extension);
if (File.Exists(path))
2025-03-13 04:50:09 +00:00
{
2025-03-16 06:52:55 +00:00
return path;
2025-03-14 01:00:31 +00:00
}
2025-03-16 06:52:55 +00:00
}
2025-03-13 04:50:09 +00:00
2025-03-16 06:52:55 +00:00
return string.Empty;
}
2025-03-16 06:09:37 +00:00
#endregion
2025-03-16 06:52:55 +00:00
#region Load & Change
public List<ThemeData> LoadAvailableThemes()
{
2025-03-16 06:52:55 +00:00
List<ThemeData> themes = new List<ThemeData>();
foreach (var themeDirectory in _themeDirectories)
{
2025-03-16 06:52:55 +00:00
var filePaths = Directory
.GetFiles(themeDirectory)
.Where(filePath => filePath.EndsWith(Extension) && !filePath.EndsWith("Base.xaml"))
.Select(GetThemeDataFromPath);
themes.AddRange(filePaths);
}
2025-03-16 06:52:55 +00:00
return themes.OrderBy(o => o.Name).ToList();
}
2018-12-22 17:53:13 +00:00
public bool ChangeTheme(string theme)
{
2020-05-07 04:30:55 +00:00
const string defaultTheme = Constant.DefaultTheme;
string path = GetThemePath(theme);
2018-12-22 17:53:13 +00:00
try
{
if (string.IsNullOrEmpty(path))
2018-12-22 17:53:13 +00:00
throw new DirectoryNotFoundException("Theme path can't be found <{path}>");
2024-06-03 07:25:42 +00:00
2022-07-28 10:23:39 +00:00
// reload all resources even if the theme itself hasn't changed in order to pickup changes
// to things like fonts
UpdateResourceDictionary(GetResourceDictionary(theme));
2024-06-03 07:25:42 +00:00
2025-02-23 11:48:38 +00:00
_settings.Theme = theme;
2018-12-22 17:53:13 +00:00
//always allow re-loading default theme, in case of failure of switching to a new theme from default theme
if (_oldTheme != theme || theme == defaultTheme)
2017-02-28 00:12:53 +00:00
{
_oldTheme = Path.GetFileNameWithoutExtension(_oldResource.Source.AbsolutePath);
}
2020-05-07 04:30:55 +00:00
BlurEnabled = IsBlurTheme();
2025-03-12 11:45:14 +00:00
//if (_settings.UseDropShadowEffect)
// AddDropShadowEffectToCurrentTheme();
2025-02-23 00:48:33 +00:00
//Win32Helper.SetBlurForWindow(Application.Current.MainWindow, BlurEnabled);
_ = SetBlurForWindowAsync();
}
catch (DirectoryNotFoundException)
2018-12-22 17:53:13 +00:00
{
Log.Error($"|Theme.ChangeTheme|Theme <{theme}> path can't be found");
if (theme != defaultTheme)
{
2025-02-23 11:48:38 +00:00
_api.ShowMsgBox(string.Format(InternationalizationManager.Instance.GetTranslation("theme_load_failure_path_not_exists"), theme));
2018-12-22 17:53:13 +00:00
ChangeTheme(defaultTheme);
}
return false;
}
catch (XamlParseException)
2018-12-22 17:53:13 +00:00
{
Log.Error($"|Theme.ChangeTheme|Theme <{theme}> fail to parse");
if (theme != defaultTheme)
{
2025-02-23 11:48:38 +00:00
_api.ShowMsgBox(string.Format(InternationalizationManager.Instance.GetTranslation("theme_load_failure_parse_error"), theme));
2018-12-22 17:53:13 +00:00
ChangeTheme(defaultTheme);
}
return false;
}
return true;
}
2025-03-16 06:52:55 +00:00
#endregion
2020-05-07 04:30:55 +00:00
2025-03-16 06:52:55 +00:00
#region Shadow Effect
2020-05-07 04:30:55 +00:00
2025-03-16 06:52:55 +00:00
public void AddDropShadowEffectToCurrentTheme()
{
2025-03-16 06:52:55 +00:00
var dict = GetCurrentResourceDictionary();
2020-05-07 04:30:55 +00:00
2025-03-16 06:52:55 +00:00
var windowBorderStyle = dict["WindowBorderStyle"] as Style;
2024-06-03 07:25:42 +00:00
2025-03-16 06:52:55 +00:00
var effectSetter = new Setter
{
2025-03-16 06:52:55 +00:00
Property = Border.EffectProperty,
Value = new DropShadowEffect
{
Opacity = 0.3,
ShadowDepth = 12,
Direction = 270,
BlurRadius = 30
}
};
2025-03-16 06:52:55 +00:00
if (windowBorderStyle.Setters.FirstOrDefault(setterBase => setterBase is Setter setter && setter.Property == Border.MarginProperty) is not Setter marginSetter)
{
2025-03-16 06:52:55 +00:00
var margin = new Thickness(ShadowExtraMargin, 12, ShadowExtraMargin, ShadowExtraMargin);
marginSetter = new Setter()
{
Property = Border.MarginProperty,
Value = margin,
};
windowBorderStyle.Setters.Add(marginSetter);
2025-03-16 06:52:55 +00:00
SetResizeBoarderThickness(margin);
}
2025-03-16 06:52:55 +00:00
else
{
2025-03-16 06:52:55 +00:00
var baseMargin = (Thickness)marginSetter.Value;
var newMargin = new Thickness(
baseMargin.Left + ShadowExtraMargin,
baseMargin.Top + ShadowExtraMargin,
baseMargin.Right + ShadowExtraMargin,
baseMargin.Bottom + ShadowExtraMargin);
marginSetter.Value = newMargin;
2025-03-16 06:52:55 +00:00
SetResizeBoarderThickness(newMargin);
}
2025-03-16 06:52:55 +00:00
windowBorderStyle.Setters.Add(effectSetter);
UpdateResourceDictionary(dict);
}
2025-03-16 06:52:55 +00:00
public void RemoveDropShadowEffectFromCurrentTheme()
{
2025-03-16 06:52:55 +00:00
var dict = GetCurrentResourceDictionary();
var windowBorderStyle = dict["WindowBorderStyle"] as Style;
if (windowBorderStyle.Setters.FirstOrDefault(setterBase => setterBase is Setter setter && setter.Property == Border.EffectProperty) is Setter effectSetter)
{
2025-03-16 06:52:55 +00:00
windowBorderStyle.Setters.Remove(effectSetter);
}
2024-06-02 12:17:42 +00:00
2025-03-16 06:52:55 +00:00
if (windowBorderStyle.Setters.FirstOrDefault(setterBase => setterBase is Setter setter && setter.Property == Border.MarginProperty) is Setter marginSetter)
{
var currentMargin = (Thickness)marginSetter.Value;
var newMargin = new Thickness(
currentMargin.Left - ShadowExtraMargin,
currentMargin.Top - ShadowExtraMargin,
currentMargin.Right - ShadowExtraMargin,
currentMargin.Bottom - ShadowExtraMargin);
marginSetter.Value = newMargin;
}
SetResizeBoarderThickness(null);
UpdateResourceDictionary(dict);
2024-06-02 12:17:42 +00:00
}
2025-03-16 06:52:55 +00:00
// because adding drop shadow effect will change the margin of the window,
// we need to update the window chrome thickness to correct set the resize border
private static void SetResizeBoarderThickness(Thickness? effectMargin)
2024-06-02 12:17:42 +00:00
{
2025-03-16 06:52:55 +00:00
var window = Application.Current.MainWindow;
if (WindowChrome.GetWindowChrome(window) is WindowChrome windowChrome)
{
Thickness thickness;
if (effectMargin == null)
{
thickness = SystemParameters.WindowResizeBorderThickness;
}
else
{
thickness = new Thickness(
effectMargin.Value.Left + SystemParameters.WindowResizeBorderThickness.Left,
effectMargin.Value.Top + SystemParameters.WindowResizeBorderThickness.Top,
effectMargin.Value.Right + SystemParameters.WindowResizeBorderThickness.Right,
effectMargin.Value.Bottom + SystemParameters.WindowResizeBorderThickness.Bottom);
}
2024-06-02 12:17:42 +00:00
2025-03-16 06:52:55 +00:00
windowChrome.ResizeBorderThickness = thickness;
}
}
2024-06-02 12:17:42 +00:00
2025-03-16 06:52:55 +00:00
#endregion
2024-06-02 12:17:42 +00:00
2025-03-16 06:52:55 +00:00
#region Blur Handling
2024-06-03 07:25:42 +00:00
/// <summary>
/// Refreshes the frame to apply the current theme settings.
/// </summary>
public async Task RefreshFrameAsync()
2025-03-16 06:52:55 +00:00
{
await Application.Current.Dispatcher.InvokeAsync(async () =>
2024-06-02 12:17:42 +00:00
{
2025-03-16 06:52:55 +00:00
// Remove OS minimizing/maximizing animation
// Methods.SetWindowAttribute(new WindowInteropHelper(mainWindow).Handle, DWMWINDOWATTRIBUTE.DWMWA_TRANSITIONS_FORCEDISABLED, 3);
2025-03-16 06:52:55 +00:00
// The timing of adding the shadow effect should vary depending on whether the theme is transparent.
if (BlurEnabled)
2024-06-02 12:17:42 +00:00
{
2025-03-16 06:52:55 +00:00
AutoDropShadow();
2024-06-02 12:17:42 +00:00
}
await SetBlurForWindowAsync();
2025-03-16 06:52:55 +00:00
if (!BlurEnabled)
2024-06-02 12:17:42 +00:00
{
2025-03-16 06:52:55 +00:00
AutoDropShadow();
2024-06-02 12:17:42 +00:00
}
2025-03-16 06:52:55 +00:00
}, DispatcherPriority.Normal);
}
2025-03-16 06:52:55 +00:00
/// <summary>
/// Sets the blur for a window via SetWindowCompositionAttribute
/// </summary>
public async Task SetBlurForWindowAsync()
2025-03-16 06:52:55 +00:00
{
await Application.Current.Dispatcher.InvokeAsync(async () =>
2025-03-16 06:09:37 +00:00
{
2025-03-16 06:52:55 +00:00
var dict = GetThemeResourceDictionary(_settings.Theme);
if (dict == null)
return;
var windowBorderStyle = dict.Contains("WindowBorderStyle") ? dict["WindowBorderStyle"] as Style : null;
if (windowBorderStyle == null)
return;
Window mainWindow = Application.Current.MainWindow;
if (mainWindow == null)
return;
// Check if the theme supports blur
bool hasBlur = dict.Contains("ThemeBlurEnabled") && dict["ThemeBlurEnabled"] is bool b && b;
if (!hasBlur)
2025-03-04 04:46:36 +00:00
{
2025-03-16 06:52:55 +00:00
_settings.BackdropType = BackdropTypes.None;
2025-03-16 06:09:37 +00:00
}
2025-03-04 04:46:36 +00:00
2025-03-16 06:52:55 +00:00
if (BlurEnabled && hasBlur && Win32Helper.IsBackdropSupported())
2025-03-04 04:46:36 +00:00
{
2025-03-16 06:52:55 +00:00
// If the BackdropType is Mica or MicaAlt, set the windowborderstyle's background to transparent
if (_settings.BackdropType == BackdropTypes.Mica || _settings.BackdropType == BackdropTypes.MicaAlt)
{
windowBorderStyle.Setters.Remove(windowBorderStyle.Setters.OfType<Setter>().FirstOrDefault(x => x.Property.Name == "Background"));
windowBorderStyle.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Color.FromArgb(1, 0, 0, 0))));
}
else if (_settings.BackdropType == BackdropTypes.Acrylic)
{
windowBorderStyle.Setters.Remove(windowBorderStyle.Setters.OfType<Setter>().FirstOrDefault(x => x.Property.Name == "Background"));
windowBorderStyle.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Colors.Transparent)));
}
2025-03-01 22:51:20 +00:00
2025-03-16 06:52:55 +00:00
// Apply the blur effect
Win32Helper.DWMSetBackdropForWindow(mainWindow, _settings.BackdropType);
ColorizeWindow();
}
else
{
// Apply default style when Blur is disabled
Win32Helper.DWMSetBackdropForWindow(mainWindow, BackdropTypes.None);
ColorizeWindow();
}
2020-05-07 04:30:55 +00:00
2025-03-04 04:46:36 +00:00
UpdateResourceDictionary(dict);
2025-03-16 06:52:55 +00:00
}, DispatcherPriority.Normal);
2020-05-07 04:30:55 +00:00
}
private void AutoDropShadow()
{
SetWindowCornerPreference("Default");
RemoveDropShadowEffectFromCurrentTheme();
if (_settings.UseDropShadowEffect)
{
if (BlurEnabled && Win32Helper.IsBackdropSupported())
{
SetWindowCornerPreference("Round");
}
else
{
SetWindowCornerPreference("Default");
AddDropShadowEffectToCurrentTheme();
}
}
else
{
if (BlurEnabled && Win32Helper.IsBackdropSupported())
{
SetWindowCornerPreference("Default");
}
else
{
RemoveDropShadowEffectFromCurrentTheme();
}
}
}
private static void SetWindowCornerPreference(string cornerType)
{
Window mainWindow = Application.Current.MainWindow;
if (mainWindow == null)
return;
Win32Helper.DWMSetCornerPreferenceForWindow(mainWindow, cornerType);
}
2025-03-16 06:52:55 +00:00
// Get Background Color from WindowBorderStyle when there not color for BG.
// for theme has not "LightBG" or "DarkBG" case.
private Color GetWindowBorderStyleBackground()
2020-05-07 04:30:55 +00:00
{
2025-03-16 06:52:55 +00:00
var Resources = GetThemeResourceDictionary(_settings.Theme);
var windowBorderStyle = (Style)Resources["WindowBorderStyle"];
2025-03-01 22:51:20 +00:00
2025-03-16 06:52:55 +00:00
var backgroundSetter = windowBorderStyle.Setters
.OfType<Setter>()
.FirstOrDefault(s => s.Property == Border.BackgroundProperty);
if (backgroundSetter != null)
2025-03-04 04:46:36 +00:00
{
2025-03-16 06:52:55 +00:00
// Background's Value is DynamicColor Case
var backgroundValue = backgroundSetter.Value;
if (backgroundValue is SolidColorBrush solidColorBrush)
{
return solidColorBrush.Color; // Return SolidColorBrush's Color
}
else if (backgroundValue is DynamicResourceExtension dynamicResource)
{
// When DynamicResource Extension it is, Key is resource's name.
var resourceKey = backgroundSetter.Value.ToString();
// find key in resource and return color.
if (Resources.Contains(resourceKey))
{
var colorResource = Resources[resourceKey];
if (colorResource is SolidColorBrush colorBrush)
{
return colorBrush.Color;
}
else if (colorResource is Color color)
{
return color;
}
}
}
2025-03-04 04:46:36 +00:00
}
2025-03-16 06:09:37 +00:00
2025-03-16 06:52:55 +00:00
return Colors.Transparent; // Default is transparent
}
private void ApplyPreviewBackground(Color? bgColor = null)
{
if (bgColor == null) return;
// Copy the existing WindowBorderStyle
var previewStyle = new Style(typeof(Border));
if (Application.Current.Resources.Contains("WindowBorderStyle"))
2025-03-04 04:46:36 +00:00
{
if (Application.Current.Resources["WindowBorderStyle"] is Style originalStyle)
2025-03-16 06:52:55 +00:00
{
foreach (var setter in originalStyle.Setters.OfType<Setter>())
2025-03-16 06:52:55 +00:00
{
previewStyle.Setters.Add(new Setter(setter.Property, setter.Value));
2025-03-16 06:52:55 +00:00
}
}
}
2020-05-07 04:30:55 +00:00
// Apply background color (remove transparency in color)
// WPF does not allow the use of an acrylic brush within the window's internal area,
// so transparency effects are not applied to the preview.
Color backgroundColor = Color.FromRgb(bgColor.Value.R, bgColor.Value.G, bgColor.Value.B);
previewStyle.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(backgroundColor)));
// The blur theme keeps the corner round fixed (applying DWM code to modify it causes rendering issues).
// The non-blur theme retains the previously set WindowBorderStyle.
if (BlurEnabled)
{
previewStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(5)));
previewStyle.Setters.Add(new Setter(Border.BorderThicknessProperty, new Thickness(1)));
}
Application.Current.Resources["PreviewWindowBorderStyle"] = previewStyle;
2020-05-07 04:30:55 +00:00
}
2025-03-16 06:52:55 +00:00
private void ColorizeWindow()
{
var dict = GetThemeResourceDictionary(_settings.Theme);
if (dict == null) return;
2025-03-16 06:52:55 +00:00
var mainWindow = Application.Current.MainWindow;
if (mainWindow == null) return;
2025-03-16 06:52:55 +00:00
// Check if the theme supports blur
bool hasBlur = dict.Contains("ThemeBlurEnabled") && dict["ThemeBlurEnabled"] is bool b && b;
2025-03-16 06:52:55 +00:00
// SystemBG value check (Auto, Light, Dark)
string systemBG = dict.Contains("SystemBG") ? dict["SystemBG"] as string : "Auto"; // 기본값 Auto
2025-03-16 06:52:55 +00:00
// Check the user's ColorScheme setting
string colorScheme = _settings.ColorScheme;
2025-03-16 06:52:55 +00:00
// Check system dark mode setting (read AppsUseLightTheme value)
int themeValue = (int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "AppsUseLightTheme", 1);
bool isSystemDark = themeValue == 0;
2025-03-16 06:52:55 +00:00
// Final decision on whether to use dark mode
bool useDarkMode = false;
2025-03-16 06:52:55 +00:00
// If systemBG is not "Auto", prioritize it over ColorScheme and set the mode based on systemBG value
if (systemBG == "Dark")
{
useDarkMode = true; // Dark
}
else if (systemBG == "Light")
{
useDarkMode = false; // Light
}
else if (systemBG == "Auto")
{
// If systemBG is "Auto", decide based on ColorScheme
if (colorScheme == "Dark")
useDarkMode = true;
else if (colorScheme == "Light")
useDarkMode = false;
else
useDarkMode = isSystemDark; // Auto (based on system setting)
}
2025-03-16 06:52:55 +00:00
// Apply DWM Dark Mode
Win32Helper.DWMSetDarkModeForWindow(mainWindow, useDarkMode);
2025-03-16 06:52:55 +00:00
Color LightBG;
Color DarkBG;
2025-03-16 06:52:55 +00:00
// Retrieve LightBG value (fallback to WindowBorderStyle background color if not found)
try
{
LightBG = dict.Contains("LightBG") ? (Color)dict["LightBG"] : GetWindowBorderStyleBackground();
}
catch (Exception)
{
LightBG = GetWindowBorderStyleBackground();
}
2025-03-16 06:52:55 +00:00
// Retrieve DarkBG value (fallback to LightBG if not found)
try
{
DarkBG = dict.Contains("DarkBG") ? (Color)dict["DarkBG"] : LightBG;
}
catch (Exception)
{
DarkBG = LightBG;
}
2025-03-16 06:52:55 +00:00
// Select background color based on ColorScheme and SystemBG
Color selectedBG = useDarkMode ? DarkBG : LightBG;
ApplyPreviewBackground(selectedBG);
2025-03-16 06:52:55 +00:00
bool isBlurAvailable = hasBlur && Win32Helper.IsBackdropSupported(); // Windows 11 미만이면 hasBlur를 강제 false
2025-03-16 06:52:55 +00:00
if (!isBlurAvailable)
{
mainWindow.Background = Brushes.Transparent;
}
else
{
// Only set the background to transparent if the theme supports blur
if (_settings.BackdropType == BackdropTypes.Mica || _settings.BackdropType == BackdropTypes.MicaAlt)
2025-03-16 06:52:55 +00:00
{
mainWindow.Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));
}
else
{
mainWindow.Background = new SolidColorBrush(selectedBG);
}
}
2025-03-16 06:52:55 +00:00
}
2025-03-16 06:52:55 +00:00
private static bool IsBlurTheme()
{
if (!Win32Helper.IsBackdropSupported()) // Windows 11 미만이면 무조건 false
return false;
var resource = Application.Current.TryFindResource("ThemeBlurEnabled");
return resource is bool b && b;
}
2025-03-16 06:52:55 +00:00
#endregion
#region Classes
2024-06-03 07:25:42 +00:00
public record ThemeData(string FileNameWithoutExtension, string Name, bool? IsDark = null, bool? HasBlur = null);
#endregion
}
}