Merge language and theme into resource folder

This commit is contained in:
bao-qian
2016-01-07 20:04:37 +00:00
parent 8504d01688
commit ec40956721
19 changed files with 26 additions and 33 deletions

View File

@@ -0,0 +1,26 @@
using System.Collections.Generic;
namespace Wox.Core.Resource
{
internal static class AvailableLanguages
{
public static Language English = new Language("en", "English");
public static Language Chinese = new Language("zh-cn", "中文");
public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)");
public static Language Russian = new Language("ru", "Русский");
public static Language French = new Language("fr", "Français");
public static List<Language> GetAvailableLanguages()
{
List<Language> languages = new List<Language>
{
English,
Chinese,
Chinese_TW,
Russian,
French
};
return languages;
}
}
}

View File

@@ -0,0 +1,73 @@
using System;
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace Wox.Core.Resource
{
public static class FontHelper
{
static FontWeightConverter fontWeightConverter = new FontWeightConverter();
public static FontWeight GetFontWeightFromInvariantStringOrNormal(string value)
{
if (value == null) return FontWeights.Normal;
try
{
return (FontWeight) fontWeightConverter.ConvertFromInvariantString(value);
}
catch {
return FontWeights.Normal;
}
}
static FontStyleConverter fontStyleConverter = new FontStyleConverter();
public static FontStyle GetFontStyleFromInvariantStringOrNormal(string value)
{
if (value == null) return FontStyles.Normal;
try
{
return (FontStyle)fontStyleConverter.ConvertFromInvariantString(value);
}
catch
{
return FontStyles.Normal;
}
}
static FontStretchConverter fontStretchConverter = new FontStretchConverter();
public static FontStretch GetFontStretchFromInvariantStringOrNormal(string value)
{
if (value == null) return FontStretches.Normal;
try
{
return (FontStretch)fontStretchConverter.ConvertFromInvariantString(value);
}
catch
{
return FontStretches.Normal;
}
}
public static FamilyTypeface ChooseRegularFamilyTypeface(this FontFamily family)
{
return family.FamilyTypefaces.OrderBy(o =>
{
return Math.Abs(o.Stretch.ToOpenTypeStretch() - FontStretches.Normal.ToOpenTypeStretch()) * 100 +
Math.Abs(o.Weight.ToOpenTypeWeight() - FontWeights.Normal.ToOpenTypeWeight()) +
(o.Style == FontStyles.Normal ? 0 : o.Style == FontStyles.Oblique ? 1 : 2) * 1000;
}).FirstOrDefault() ?? family.FamilyTypefaces.FirstOrDefault();
}
public static FamilyTypeface ConvertFromInvariantStringsOrNormal(this FontFamily family, string style, string weight, string stretch)
{
var styleObj = GetFontStyleFromInvariantStringOrNormal(style);
var weightObj = GetFontWeightFromInvariantStringOrNormal(weight);
var stretchObj = GetFontStretchFromInvariantStringOrNormal(stretch);
return family.FamilyTypefaces.FirstOrDefault(o => o.Style == styleObj && o.Weight == weightObj && o.Stretch == stretchObj)
?? family.ChooseRegularFamilyTypeface();
}
}
}

View File

@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using Wox.Core.UserSettings;
using Wox.Infrastructure.Exception;
using Wox.Infrastructure.Logger;
using Wox.Plugin;
namespace Wox.Core.Resource
{
public class Internationalization : Resource
{
public Internationalization()
{
DirectoryName = "Languages";
MakesureThemeDirectoriesExist();
}
private void MakesureThemeDirectoriesExist()
{
if (!Directory.Exists(DirectoryPath))
{
try
{
Directory.CreateDirectory(DirectoryPath);
}
catch (Exception e)
{
Log.Error(e);
}
}
}
public void ChangeLanguage(string languageCode)
{
Language language = GetLanguageByLanguageCode(languageCode);
ChangeLanguage(language);
}
private Language GetLanguageByLanguageCode(string languageCode)
{
Language language = AvailableLanguages.GetAvailableLanguages().FirstOrDefault(o => o.LanguageCode.ToLower() == languageCode.ToLower());
if (language == null)
{
throw new WoxI18nException("Invalid language code:" + languageCode);
}
return language;
}
public void ChangeLanguage(Language language)
{
if (language == null) throw new WoxI18nException("language can't be null");
string path = GetLanguagePath(language);
if (string.IsNullOrEmpty(path))
{
path = GetLanguagePath(AvailableLanguages.English);
if (string.IsNullOrEmpty(path))
{
throw new Exception("Change Language failed");
}
}
UserSettingStorage.Instance.Language = language.LanguageCode;
UserSettingStorage.Instance.Save();
ResourceMerger.UpdateResource(this);
}
public override ResourceDictionary GetResourceDictionary()
{
return new ResourceDictionary
{
Source = new Uri(GetLanguageFile(DirectoryPath), UriKind.Absolute)
};
}
public List<Language> LoadAvailableLanguages()
{
return AvailableLanguages.GetAvailableLanguages();
}
public string GetTranslation(string key)
{
var translation = Application.Current.TryFindResource(key);
if (translation is string)
{
return translation.ToString();
}
else
{
return "NoTranslation";
}
}
private string GetLanguagePath(string languageCode)
{
Language language = GetLanguageByLanguageCode(languageCode);
return GetLanguagePath(language);
}
internal void UpdatePluginMetadataTranslations(PluginPair pluginPair)
{
var pluginI18n = pluginPair.Plugin as IPluginI18n;
if (pluginI18n == null) return;
try
{
pluginPair.Metadata.Name = pluginI18n.GetTranslatedPluginTitle();
pluginPair.Metadata.Description = pluginI18n.GetTranslatedPluginDescription();
}
catch (Exception e)
{
var woxPluginException = new WoxPluginException(pluginPair.Metadata.Name, "Update Plugin metadata translation failed:", e);
Log.Error(woxPluginException);
}
}
private string GetLanguagePath(Language language)
{
string path = Path.Combine(DirectoryPath, language.LanguageCode + ".xaml");
if (File.Exists(path))
{
return path;
}
return string.Empty;
}
public string GetLanguageFile(string folder)
{
if (!Directory.Exists(folder)) return string.Empty;
string path = Path.Combine(folder, UserSettingStorage.Instance.Language + ".xaml");
if (File.Exists(path))
{
return path;
}
else
{
string english = Path.Combine(folder, "en.xaml");
if (File.Exists(english))
{
return english;
}
return string.Empty;
}
}
}
}

View File

@@ -0,0 +1,26 @@
namespace Wox.Core.Resource
{
public static class InternationalizationManager
{
private static Internationalization instance;
private static object syncObject = new object();
public static Internationalization Instance
{
get
{
if (instance == null)
{
lock (syncObject)
{
if (instance == null)
{
instance = new Internationalization();
}
}
}
return instance;
}
}
}
}

View File

@@ -0,0 +1,18 @@
namespace Wox.Core.Resource
{
public class Language
{
public Language(string code, string display)
{
LanguageCode = code;
Display = display;
}
/// <summary>
/// E.g. En or Zh-CN
/// </summary>
public string LanguageCode { get; set; }
public string Display { get; set; }
}
}

View File

@@ -2,7 +2,7 @@
using System.Windows;
using Wox.Infrastructure;
namespace Wox.Core.UI
namespace Wox.Core.Resource
{
public abstract class Resource
{

View File

@@ -2,11 +2,10 @@
using System.IO;
using System.Linq;
using System.Windows;
using Wox.Core.i18n;
using Wox.Core.Plugin;
using Wox.Plugin;
namespace Wox.Core.UI
namespace Wox.Core.Resource
{
public static class ResourceMerger
{
@@ -25,7 +24,7 @@ namespace Wox.Core.UI
}
}
public static void UpdateResource<T>(T t) where T : Resource
public static void UpdateResource<T>(T t) where T : Core.Resource.Resource
{
RemoveResource(t.DirectoryName);
Application.Current.Resources.MergedDictionaries.Add(t.GetResourceDictionary());

200
Wox.Core/Resource/Theme.cs Normal file
View File

@@ -0,0 +1,200 @@
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.Core.UserSettings;
using Wox.Infrastructure.Logger;
namespace Wox.Core.Resource
{
public class Theme : Resource
{
private static List<string> themeDirectories = new List<string>();
public Theme()
{
DirectoryName = "Themes";
themeDirectories.Add(DirectoryPath);
MakesureThemeDirectoriesExist();
}
private static void MakesureThemeDirectoriesExist()
{
foreach (string pluginDirectory in themeDirectories)
{
if (!Directory.Exists(pluginDirectory))
{
try
{
Directory.CreateDirectory(pluginDirectory);
}
catch (Exception e)
{
Log.Error(e);
}
}
}
}
public void ChangeTheme(string themeName)
{
string themePath = GetThemePath(themeName);
if (string.IsNullOrEmpty(themePath))
{
themePath = GetThemePath("Dark");
if (string.IsNullOrEmpty(themePath))
{
throw new Exception("Change theme failed");
}
}
UserSettingStorage.Instance.Theme = themeName;
UserSettingStorage.Instance.Save();
ResourceMerger.UpdateResource(this);
// Exception of FindResource can't be cathed if global exception handle is set
var isBlur = Application.Current.TryFindResource("ThemeBlurEnabled");
if (isBlur is bool)
{
SetBlurForWindow(Application.Current.MainWindow, (bool)isBlur);
}
}
public override ResourceDictionary GetResourceDictionary()
{
var dict = new ResourceDictionary
{
Source = new Uri(GetThemePath(UserSettingStorage.Instance.Theme), UriKind.Absolute)
};
Style queryBoxStyle = dict["QueryBoxStyle"] as Style;
if (queryBoxStyle != null)
{
queryBoxStyle.Setters.Add(new Setter(TextBox.FontFamilyProperty, new FontFamily(UserSettingStorage.Instance.QueryBoxFont)));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontStyleProperty, FontHelper.GetFontStyleFromInvariantStringOrNormal(UserSettingStorage.Instance.QueryBoxFontStyle)));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(UserSettingStorage.Instance.QueryBoxFontWeight)));
queryBoxStyle.Setters.Add(new Setter(TextBox.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(UserSettingStorage.Instance.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(UserSettingStorage.Instance.ResultItemFont));
Setter fontStyle = new Setter(TextBlock.FontStyleProperty, FontHelper.GetFontStyleFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontStyle));
Setter fontWeight = new Setter(TextBlock.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontWeight));
Setter fontStretch = new Setter(TextBlock.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontStretch));
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>();
foreach (var themeDirectory in themeDirectories)
{
themes.AddRange(
Directory.GetFiles(themeDirectory)
.Where(filePath => filePath.EndsWith(".xaml") && !filePath.EndsWith("Base.xaml"))
.ToList());
}
return themes.OrderBy(o => o).ToList();
}
private string GetThemePath(string themeName)
{
foreach (string themeDirectory in themeDirectories)
{
string path = Path.Combine(themeDirectory, themeName + ".xaml");
if (File.Exists(path))
{
return path;
}
}
return string.Empty;
}
#region Blur Handling
/*
Found on https://github.com/riverar/sample-win10-aeroglass
*/
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)]
private struct AccentPolicy
{
public AccentState AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
[StructLayout(LayoutKind.Sequential)]
private struct WindowCompositionAttributeData
{
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
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>
/// <param name="wind">window to blur</param>
/// <param name="isBlur">true/false - on or off correspondingly</param>
private void SetBlurForWindow(Window wind, bool isBlur)
{
if (isBlur)
{
SetWindowAccent(wind, AccentState.ACCENT_ENABLE_BLURBEHIND);
}
}
private void SetWindowAccent(Window wind, AccentState themeAccentMode)
{
var windowHelper = new WindowInteropHelper(wind);
var accent = new AccentPolicy { AccentState = themeAccentMode };
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
}
}

View File

@@ -0,0 +1,26 @@
namespace Wox.Core.Resource
{
public class ThemeManager
{
private static Theme instance;
private static object syncObject = new object();
public static Theme Theme
{
get
{
if (instance == null)
{
lock (syncObject)
{
if (instance == null)
{
instance = new Theme();
}
}
}
return instance;
}
}
}
}