PowerToys/Wox.Core/Resource/Theme.cs

260 lines
9.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using Wox.Infrastructure;
using Wox.Infrastructure.Logger;
2016-06-19 23:18:43 +08:00
using Wox.Infrastructure.UserSettings;
namespace Wox.Core.Resource
{
public class Theme
{
2017-02-21 10:40:43 +08:00
private readonly List<string> _themeDirectories = new List<string>();
2017-02-28 08:12:53 +08:00
private ResourceDictionary _oldResource;
private string _oldTheme;
2016-06-19 23:18:43 +08:00
public Settings Settings { get; set; }
2017-02-28 08:12:53 +08:00
private const string Folder = "Themes";
private const string Extension = ".xaml";
private string DirectoryPath => Path.Combine(Constant.ProgramDirectory, Folder);
private string UserDirectoryPath => Path.Combine(Constant.DataDirectory, Folder);
public Theme()
{
2017-02-21 10:40:43 +08:00
_themeDirectories.Add(DirectoryPath);
_themeDirectories.Add(UserDirectoryPath);
MakesureThemeDirectoriesExist();
2017-02-28 08:12:53 +08:00
var dicts = Application.Current.Resources.MergedDictionaries;
_oldResource = dicts.First(d =>
{
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);
}
2017-02-21 10:40:43 +08:00
private void MakesureThemeDirectoriesExist()
{
2017-02-21 10:40:43 +08:00
foreach (string dir in _themeDirectories)
{
2017-02-21 10:40:43 +08:00
if (!Directory.Exists(dir))
{
try
{
2017-02-21 10:40:43 +08:00
Directory.CreateDirectory(dir);
}
2016-01-07 05:34:42 +08:00
catch (Exception e)
{
2017-02-21 10:40:43 +08:00
Log.Exception($"|Theme.MakesureThemeDirectoriesExist|Exception when create directory <{dir}>", e);
}
}
}
}
public void ChangeTheme(string theme)
{
const string dark = "Dark";
bool valid;
string path = GetThemePath(theme);
if (string.IsNullOrEmpty(path))
{
Log.Error($"|Theme.ChangeTheme|Theme path can't be found <{path}>, use default dark theme");
path = GetThemePath(dark);
if (string.IsNullOrEmpty(path))
{
valid = false;
Log.Error($"|Theme.ChangeTheme|Default theme path can't be found <{path}>");
}
else
{
valid = true;
theme = dark;
}
}
else
{
valid = true;
}
if (valid)
{
Settings.Theme = theme;
var dicts = Application.Current.Resources.MergedDictionaries;
2017-02-28 08:12:53 +08:00
if (_oldTheme != theme)
{
dicts.Remove(_oldResource);
//fixme if something goes wrong here
2017-02-28 08:12:53 +08:00
var newResource = GetResourceDictionary();
dicts.Add(newResource);
_oldResource = newResource;
_oldTheme = Path.GetFileNameWithoutExtension(_oldResource.Source.AbsolutePath);
}
}
}
public ResourceDictionary GetResourceDictionary()
{
2017-02-20 07:29:13 +08:00
var uri = GetThemePath(Settings.Theme);
var dict = new ResourceDictionary
{
2017-02-20 07:29:13 +08:00
Source = new Uri(uri, UriKind.Absolute)
};
Style queryBoxStyle = dict["QueryBoxStyle"] as Style;
if (queryBoxStyle != null)
{
queryBoxStyle.Setters.Add(new Setter(TextBox.FontFamilyProperty, new FontFamily(Settings.QueryBoxFont)));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontStyleProperty, FontHelper.GetFontStyleFromInvariantStringOrNormal(Settings.QueryBoxFontStyle)));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(Settings.QueryBoxFontWeight)));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(Settings.QueryBoxFontStretch)));
}
Style resultItemStyle = dict["ItemTitleStyle"] as Style;
Style resultSubItemStyle = dict["ItemSubTitleStyle"] as Style;
Style resultItemSelectedStyle = dict["ItemTitleSelectedStyle"] as Style;
Style resultSubItemSelectedStyle = dict["ItemSubTitleSelectedStyle"] as Style;
if (resultItemStyle != null && resultSubItemStyle != null && resultSubItemSelectedStyle != null && resultItemSelectedStyle != null)
{
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));
2016-01-07 05:34:42 +08:00
Setter[] setters = { fontFamily, fontStyle, fontWeight, fontStretch };
Array.ForEach(new[] { resultItemStyle, resultSubItemStyle, resultItemSelectedStyle, resultSubItemSelectedStyle }, o => Array.ForEach(setters, p => o.Setters.Add(p)));
}
return dict;
}
public List<string> LoadAvailableThemes()
{
List<string> themes = new List<string>();
2017-02-21 10:40:43 +08:00
foreach (var themeDirectory in _themeDirectories)
{
themes.AddRange(
Directory.GetFiles(themeDirectory)
2017-02-28 08:12:53 +08:00
.Where(filePath => filePath.EndsWith(Extension) && !filePath.EndsWith("Base.xaml"))
.ToList());
}
return themes.OrderBy(o => o).ToList();
}
private string GetThemePath(string themeName)
{
2017-02-21 10:40:43 +08:00
foreach (string themeDirectory in _themeDirectories)
{
2017-02-28 08:12:53 +08:00
string path = Path.Combine(themeDirectory, themeName + Extension);
if (File.Exists(path))
{
return path;
}
}
return string.Empty;
}
#region Blur Handling
/*
Found on https://github.com/riverar/sample-win10-aeroglass
*/
2015-11-29 15:19:58 +08:00
private enum AccentState
{
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
}
[StructLayout(LayoutKind.Sequential)]
2015-11-29 15:19:58 +08:00
private struct AccentPolicy
{
public AccentState AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
[StructLayout(LayoutKind.Sequential)]
2015-11-29 15:19:58 +08:00
private struct WindowCompositionAttributeData
{
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
2015-11-29 15:19:58 +08:00
private enum WindowCompositionAttribute
{
WCA_ACCENT_POLICY = 19
}
[DllImport("user32.dll")]
private static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
/// <summary>
/// Sets the blur for a window via SetWindowCompositionAttribute
/// </summary>
public void SetBlurForWindow()
{
// Exception of FindResource can't be cathed if global exception handle is set
if (Environment.OSVersion.Version >= new Version(6, 2))
{
var resource = Application.Current.TryFindResource("ThemeBlurEnabled");
bool blur;
if (resource is bool)
{
blur = (bool)resource;
}
else
{
blur = false;
}
if (blur)
{
SetWindowAccent(Application.Current.MainWindow, AccentState.ACCENT_ENABLE_BLURBEHIND);
}
else
{
SetWindowAccent(Application.Current.MainWindow, AccentState.ACCENT_DISABLED);
}
}
}
private void SetWindowAccent(Window w, AccentState state)
{
var windowHelper = new WindowInteropHelper(w);
var accent = new AccentPolicy { AccentState = state };
var accentStructSize = Marshal.SizeOf(accent);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData
{
Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
SetWindowCompositionAttribute(windowHelper.Handle, ref data);
Marshal.FreeHGlobal(accentPtr);
}
#endregion
}
}