From 8d10c9aa410119454bfcd62ea05c125b304e939c Mon Sep 17 00:00:00 2001 From: bao-qian Date: Thu, 21 Apr 2016 01:53:21 +0100 Subject: [PATCH] Remove instance logic for BinaryStorage and JsonStorage, part 1 1. part of #389 2. huge refactoring --- Plugins/Wox.Plugin.CMD/CMD.cs | 20 ++- Plugins/Wox.Plugin.CMD/CMDSetting.xaml.cs | 8 +- Plugins/Wox.Plugin.CMD/CMDStorage.cs | 28 +--- .../ContextMenuStorage.cs | 32 +---- Plugins/Wox.Plugin.Everything/Main.cs | 43 ++++-- Plugins/Wox.Plugin.Folder/FolderLink.cs | 2 +- Plugins/Wox.Plugin.Folder/FolderPlugin.cs | 17 ++- .../FolderPluginSettings.xaml.cs | 9 +- Plugins/Wox.Plugin.Folder/FolderStorage.cs | 3 +- .../PluginIndicator.cs | 2 - .../AddProgramSource.xaml.cs | 7 +- .../Wox.Plugin.Program/ProgramCacheStorage.cs | 4 +- .../Wox.Plugin.Program/ProgramSetting.xaml.cs | 8 +- Plugins/Wox.Plugin.Program/ProgramStorage.cs | 39 +----- .../ProgramSuffixes.xaml.cs | 4 +- Plugins/Wox.Plugin.Program/Programs.cs | 30 ++-- Plugins/Wox.Plugin.WebSearch/WebSearch.cs | 1 - .../Wox.Plugin.WebSearch/WebSearchPlugin.cs | 16 ++- .../WebSearchSetting.xaml.cs | 5 +- .../Wox.Plugin.WebSearch/WebSearchStorage.cs | 24 +--- .../WebSearchesSetting.xaml.cs | 7 +- Wox.Core/Plugin/PluginManager.cs | 46 ++++++- Wox.Core/Resource/Internationalization.cs | 3 +- Wox.Core/Resource/Theme.cs | 3 +- Wox.Core/Updater/UpdaterManager.cs | 7 +- .../UserSettings/CustomizedPluginConfig.cs | 2 +- Wox.Core/UserSettings/HttpProxy.cs | 2 +- Wox.Core/UserSettings/PluginHotkey.cs | 1 - Wox.Core/UserSettings/UserSettingStorage.cs | 122 ++++------------- Wox.Infrastructure/Storage/BaseStorage.cs | 82 ----------- Wox.Infrastructure/Storage/BinaryStorage.cs | 128 ++++++++++-------- Wox.Infrastructure/Storage/IStorage.cs | 8 -- Wox.Infrastructure/Storage/JsonStorage.cs | 77 ++++++++--- .../Storage/PluginSettingsStorage.cs | 20 +++ Wox.Infrastructure/Wox.Infrastructure.csproj | 1 + Wox.Plugin/Result.cs | 5 - Wox/ActionKeywords.xaml.cs | 4 +- Wox/App.xaml.cs | 18 ++- Wox/CustomQueryHotkeySetting.xaml.cs | 5 +- Wox/ImageLoader/ImageCacheStroage.cs | 5 +- Wox/ImageLoader/ImageLoader.cs | 32 +++-- Wox/Languages/en.xaml | 2 +- Wox/MainWindow.xaml.cs | 8 +- Wox/Properties/Settings.settings | 2 +- Wox/PublicAPIInstance.cs | 4 +- Wox/SettingWindow.xaml.cs | 54 ++------ Wox/Storage/QueryHistoryStorage.cs | 12 +- Wox/Storage/TopMostRecordStorage.cs | 13 +- Wox/Storage/UserSelectedRecordStorage.cs | 5 +- Wox/ViewModel/MainViewModel.cs | 50 +++++-- Wox/ViewModel/ResultViewModel.cs | 27 +++- Wox/ViewModel/ResultsViewModel.cs | 29 ++-- 52 files changed, 502 insertions(+), 584 deletions(-) delete mode 100644 Wox.Infrastructure/Storage/BaseStorage.cs delete mode 100644 Wox.Infrastructure/Storage/IStorage.cs create mode 100644 Wox.Infrastructure/Storage/PluginSettingsStorage.cs diff --git a/Plugins/Wox.Plugin.CMD/CMD.cs b/Plugins/Wox.Plugin.CMD/CMD.cs index 19f639bb32..56d4bffd75 100644 --- a/Plugins/Wox.Plugin.CMD/CMD.cs +++ b/Plugins/Wox.Plugin.CMD/CMD.cs @@ -8,6 +8,7 @@ using WindowsInput; using WindowsInput.Native; using Wox.Infrastructure.Hotkey; using Wox.Infrastructure.Logger; +using Wox.Infrastructure.Storage; using Control = System.Windows.Controls.Control; namespace Wox.Plugin.CMD @@ -17,7 +18,20 @@ namespace Wox.Plugin.CMD private PluginInitContext context; private bool WinRStroked; private readonly KeyboardSimulator keyboardSimulator = new KeyboardSimulator(new InputSimulator()); - private readonly CMDStorage _settings = CMDStorage.Instance; + + private readonly CMDHistory _settings; + private readonly PluginSettingsStorage _storage; + + public CMD() + { + _storage = new PluginSettingsStorage(); + _settings = _storage.Load(); + } + + ~CMD() + { + _storage.Save(); + } public List Query(Query query) { @@ -81,7 +95,7 @@ namespace Wox.Plugin.CMD private List GetHistoryCmds(string cmd, Result result) { - IEnumerable history = _settings.CMDHistory.Where(o => o.Key.Contains(cmd)) + IEnumerable history = _settings.Count.Where(o => o.Key.Contains(cmd)) .OrderByDescending(o => o.Value) .Select(m => { @@ -127,7 +141,7 @@ namespace Wox.Plugin.CMD private List ResultsFromlHistory() { - IEnumerable history = _settings.CMDHistory.OrderByDescending(o => o.Value) + IEnumerable history = _settings.Count.OrderByDescending(o => o.Value) .Select(m => new Result { Title = m.Key, diff --git a/Plugins/Wox.Plugin.CMD/CMDSetting.xaml.cs b/Plugins/Wox.Plugin.CMD/CMDSetting.xaml.cs index 742a8c1eb6..7b666cd17a 100644 --- a/Plugins/Wox.Plugin.CMD/CMDSetting.xaml.cs +++ b/Plugins/Wox.Plugin.CMD/CMDSetting.xaml.cs @@ -5,9 +5,9 @@ namespace Wox.Plugin.CMD { public partial class CMDSetting : UserControl { - private readonly CMDStorage _settings; + private readonly CMDHistory _settings; - public CMDSetting(CMDStorage settings) + public CMDSetting(CMDHistory settings) { InitializeComponent(); _settings = settings; @@ -21,24 +21,20 @@ namespace Wox.Plugin.CMD cbLeaveCmdOpen.Checked += (o, e) => { _settings.LeaveCmdOpen = true; - _settings.Save(); }; cbLeaveCmdOpen.Unchecked += (o, e) => { _settings.LeaveCmdOpen = false; - _settings.Save(); }; cbReplaceWinR.Checked += (o, e) => { _settings.ReplaceWinR = true; - _settings.Save(); }; cbReplaceWinR.Unchecked += (o, e) => { _settings.ReplaceWinR = false; - _settings.Save(); }; } } diff --git a/Plugins/Wox.Plugin.CMD/CMDStorage.cs b/Plugins/Wox.Plugin.CMD/CMDStorage.cs index 813e4a2c58..a99772678c 100644 --- a/Plugins/Wox.Plugin.CMD/CMDStorage.cs +++ b/Plugins/Wox.Plugin.CMD/CMDStorage.cs @@ -1,40 +1,26 @@ using System.Collections.Generic; +using System.ComponentModel; using Newtonsoft.Json; using Wox.Infrastructure.Storage; namespace Wox.Plugin.CMD { - public class CMDStorage : JsonStrorage + public class CMDHistory { - [JsonProperty] - public bool ReplaceWinR { get; set; } - - [JsonProperty] + public bool ReplaceWinR { get; set; } = true; public bool LeaveCmdOpen { get; set; } - - [JsonProperty] - public Dictionary CMDHistory = new Dictionary(); - - protected override string FileName { get; } = "CMDHistory"; - - protected override CMDStorage LoadDefault() - { - ReplaceWinR = true; - return this; - } + public Dictionary Count = new Dictionary(); public void AddCmdHistory(string cmdName) { - if (CMDHistory.ContainsKey(cmdName)) + if (Count.ContainsKey(cmdName)) { - CMDHistory[cmdName] += 1; + Count[cmdName] += 1; } else { - CMDHistory.Add(cmdName, 1); + Count.Add(cmdName, 1); } - Save(); } - } } diff --git a/Plugins/Wox.Plugin.Everything/ContextMenuStorage.cs b/Plugins/Wox.Plugin.Everything/ContextMenuStorage.cs index 703cbba36f..c1d9c42f0a 100644 --- a/Plugins/Wox.Plugin.Everything/ContextMenuStorage.cs +++ b/Plugins/Wox.Plugin.Everything/ContextMenuStorage.cs @@ -1,44 +1,22 @@ using System.Collections.Generic; +using System.ComponentModel; +using Newtonsoft.Json; using Wox.Infrastructure.Storage; -using JsonProperty = Newtonsoft.Json.JsonPropertyAttribute; namespace Wox.Plugin.Everything { - public class ContextMenuStorage : JsonStrorage + public class Settings { - [JsonProperty] public List ContextMenus = new List(); + public List ContextMenus = new List(); - [JsonProperty] - public int MaxSearchCount { get; set; } - - public IPublicAPI API { get; set; } - - protected override string FileName { get; } = "EverythingContextMenu"; - - protected override void OnAfterLoad(ContextMenuStorage obj) - { - - } - - protected override ContextMenuStorage LoadDefault() - { - MaxSearchCount = 100; - return this; - } + public int MaxSearchCount { get; set; } = 100; } public class ContextMenu { - [JsonProperty] public string Name { get; set; } - - [JsonProperty] public string Command { get; set; } - - [JsonProperty] public string Argument { get; set; } - - [JsonProperty] public string ImagePath { get; set; } } } \ No newline at end of file diff --git a/Plugins/Wox.Plugin.Everything/Main.cs b/Plugins/Wox.Plugin.Everything/Main.cs index 0bccf89cf4..4b63385770 100644 --- a/Plugins/Wox.Plugin.Everything/Main.cs +++ b/Plugins/Wox.Plugin.Everything/Main.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Windows; +using Wox.Infrastructure.Storage; +using Wox.Infrastructure; using Wox.Plugin.Everything.Everything; namespace Wox.Plugin.Everything @@ -16,11 +18,26 @@ namespace Wox.Plugin.Everything private readonly EverythingAPI _api = new EverythingAPI(); private static readonly List ImageExts = new List { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".ico" }; private static readonly List ExecutableExts = new List { ".exe" }; - private const string PortableEverything = "PortableEverything"; + private const string EverythingProcessName = "Everything"; + private const string PortableEverything = "PortableEverything"; + internal static string LibraryPath; private PluginInitContext _context; - private ContextMenuStorage _settings = ContextMenuStorage.Instance; + + private readonly Settings _settings; + private readonly PluginSettingsStorage _storage; + + public Main() + { + _storage = new PluginSettingsStorage(); + _settings = _storage.Load(); + } + + ~Main() + { + _storage.Save(); + } public List Query(Query query) { @@ -31,7 +48,6 @@ namespace Wox.Plugin.Everything if (_settings.MaxSearchCount <= 0) { _settings.MaxSearchCount = 50; - _settings.Save(); } if (keyword == "uninstalleverything") @@ -158,19 +174,22 @@ namespace Wox.Plugin.Everything public void Init(PluginInitContext context) { _context = context; - _settings.API = context.API; - LoadLibrary(Path.Combine(context.CurrentPluginMetadata.PluginDirectory, - PortableEverything, GetCpuType(), "Everything.dll")); + var pluginDirectory = context.CurrentPluginMetadata.PluginDirectory; + var libraryDirectory = Path.Combine(pluginDirectory, PortableEverything, CpuType()); + LibraryPath = Path.Combine(libraryDirectory, "Everything.dll"); + LoadLibrary(LibraryPath); + //Helper.AddDLLDirectory(libraryDirectory); StartEverything(); } - private string GetCpuType() + private string CpuType() { - return (IntPtr.Size == 4) ? "x86" : "x64"; + return Environment.Is64BitOperatingSystem ? "x64" : "x86"; } + private void StartEverything() { if (!CheckEverythingServiceRunning()) @@ -268,9 +287,11 @@ namespace Wox.Plugin.Everything private string GetEverythingPath() { - string directory = Path.Combine(_context.CurrentPluginMetadata.PluginDirectory, - PortableEverything, GetCpuType(), - "Everything.exe"); + string directory = Path.Combine( + _context.CurrentPluginMetadata.PluginDirectory, + PortableEverything, CpuType(), + "Everything.exe" + ); return directory; } diff --git a/Plugins/Wox.Plugin.Folder/FolderLink.cs b/Plugins/Wox.Plugin.Folder/FolderLink.cs index 2a09ec1fdc..c6ff03d622 100644 --- a/Plugins/Wox.Plugin.Folder/FolderLink.cs +++ b/Plugins/Wox.Plugin.Folder/FolderLink.cs @@ -4,7 +4,7 @@ using Newtonsoft.Json; namespace Wox.Plugin.Folder { - [Serializable] + [JsonObject(MemberSerialization.OptIn)] public class FolderLink { [JsonProperty] diff --git a/Plugins/Wox.Plugin.Folder/FolderPlugin.cs b/Plugins/Wox.Plugin.Folder/FolderPlugin.cs index 3de94cede6..6b8582c3e0 100644 --- a/Plugins/Wox.Plugin.Folder/FolderPlugin.cs +++ b/Plugins/Wox.Plugin.Folder/FolderPlugin.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; +using Wox.Infrastructure.Storage; namespace Wox.Plugin.Folder { @@ -12,7 +13,20 @@ namespace Wox.Plugin.Folder { private static List driverNames; private PluginInitContext context; - private FolderStorage _settings = FolderStorage.Instance; + + private readonly Settings _settings; + private readonly PluginSettingsStorage _storage; + + public FolderPlugin() + { + _storage = new PluginSettingsStorage(); + _settings = _storage.Load(); + } + + ~FolderPlugin() + { + _storage.Save(); + } public Control CreateSettingPanel() { @@ -26,7 +40,6 @@ namespace Wox.Plugin.Folder if (_settings.FolderLinks == null) { _settings.FolderLinks = new List(); - _settings.Save(); } } diff --git a/Plugins/Wox.Plugin.Folder/FolderPluginSettings.xaml.cs b/Plugins/Wox.Plugin.Folder/FolderPluginSettings.xaml.cs index aa109aa2ae..2b5b979cef 100644 --- a/Plugins/Wox.Plugin.Folder/FolderPluginSettings.xaml.cs +++ b/Plugins/Wox.Plugin.Folder/FolderPluginSettings.xaml.cs @@ -14,9 +14,9 @@ namespace Wox.Plugin.Folder public partial class FileSystemSettings { private IPublicAPI woxAPI; - private FolderStorage _settings; + private Settings _settings; - public FileSystemSettings(IPublicAPI woxAPI, FolderStorage settings) + public FileSystemSettings(IPublicAPI woxAPI, Settings settings) { this.woxAPI = woxAPI; InitializeComponent(); @@ -35,7 +35,6 @@ namespace Wox.Plugin.Folder { _settings.FolderLinks.Remove(selectedFolder); lbxFolders.Items.Refresh(); - _settings.Save(); } } else @@ -56,8 +55,6 @@ namespace Wox.Plugin.Folder { var link = _settings.FolderLinks.First(x => x.Path == selectedFolder.Path); link.Path = folderBrowserDialog.SelectedPath; - - _settings.Save(); } lbxFolders.Items.Refresh(); @@ -85,7 +82,6 @@ namespace Wox.Plugin.Folder } _settings.FolderLinks.Add(newFolder); - _settings.Save(); } lbxFolders.Items.Refresh(); @@ -112,7 +108,6 @@ namespace Wox.Plugin.Folder }; _settings.FolderLinks.Add(newFolder); - _settings.Save(); } lbxFolders.Items.Refresh(); diff --git a/Plugins/Wox.Plugin.Folder/FolderStorage.cs b/Plugins/Wox.Plugin.Folder/FolderStorage.cs index 5c63d38c36..015db6bce6 100644 --- a/Plugins/Wox.Plugin.Folder/FolderStorage.cs +++ b/Plugins/Wox.Plugin.Folder/FolderStorage.cs @@ -4,11 +4,10 @@ using Wox.Infrastructure.Storage; namespace Wox.Plugin.Folder { - public class FolderStorage : JsonStrorage + public class Settings { [JsonProperty] public List FolderLinks { get; set; } - protected override string FileName { get; } = "settings_folder_plugin"; } } diff --git a/Plugins/Wox.Plugin.PluginIndicator/PluginIndicator.cs b/Plugins/Wox.Plugin.PluginIndicator/PluginIndicator.cs index 1283c77639..531b6732db 100644 --- a/Plugins/Wox.Plugin.PluginIndicator/PluginIndicator.cs +++ b/Plugins/Wox.Plugin.PluginIndicator/PluginIndicator.cs @@ -14,8 +14,6 @@ namespace Wox.Plugin.PluginIndicator var results = from keyword in PluginManager.NonGlobalPlugins.Keys where keyword.StartsWith(query.Terms[0]) let metadata = PluginManager.NonGlobalPlugins[keyword].Metadata - let customizedPluginConfig = UserSettingStorage.Instance.CustomizedPluginConfigs[metadata.ID] - where !customizedPluginConfig.Disabled select new Result { Title = keyword, diff --git a/Plugins/Wox.Plugin.Program/AddProgramSource.xaml.cs b/Plugins/Wox.Plugin.Program/AddProgramSource.xaml.cs index bc1c8cc11c..97456bea19 100644 --- a/Plugins/Wox.Plugin.Program/AddProgramSource.xaml.cs +++ b/Plugins/Wox.Plugin.Program/AddProgramSource.xaml.cs @@ -10,16 +10,16 @@ namespace Wox.Plugin.Program public partial class AddProgramSource { private ProgramSource _editing; - private ProgramStorage _settings; + private Settings _settings; - public AddProgramSource(ProgramStorage settings) + public AddProgramSource(Settings settings) { _settings = settings; InitializeComponent(); Suffixes.Text = string.Join(";", settings.ProgramSuffixes); } - public AddProgramSource(ProgramSource edit, ProgramStorage settings) + public AddProgramSource(ProgramSource edit, Settings settings) { _editing = edit; Directory.Text = _editing.Location; @@ -65,7 +65,6 @@ namespace Wox.Plugin.Program _editing.Suffixes = Suffixes.Text.Split(ProgramSource.SuffixSeperator); } - _settings.Save(); DialogResult = true; Close(); } diff --git a/Plugins/Wox.Plugin.Program/ProgramCacheStorage.cs b/Plugins/Wox.Plugin.Program/ProgramCacheStorage.cs index 0aab30c17c..d3b075a783 100644 --- a/Plugins/Wox.Plugin.Program/ProgramCacheStorage.cs +++ b/Plugins/Wox.Plugin.Program/ProgramCacheStorage.cs @@ -5,10 +5,8 @@ using Wox.Infrastructure.Storage; namespace Wox.Plugin.Program { [Serializable] - public class ProgramCacheStorage : BinaryStorage + public class ProgramIndexCache { public List Programs = new List(); - - protected override string FileName { get; } = "ProgramIndexCache"; } } \ No newline at end of file diff --git a/Plugins/Wox.Plugin.Program/ProgramSetting.xaml.cs b/Plugins/Wox.Plugin.Program/ProgramSetting.xaml.cs index 3faec277d9..7c41d72c62 100644 --- a/Plugins/Wox.Plugin.Program/ProgramSetting.xaml.cs +++ b/Plugins/Wox.Plugin.Program/ProgramSetting.xaml.cs @@ -11,9 +11,9 @@ namespace Wox.Plugin.Program public partial class ProgramSetting : UserControl { private PluginInitContext context; - private ProgramStorage _settings; + private Settings _settings; - public ProgramSetting(PluginInitContext context, ProgramStorage settings) + public ProgramSetting(PluginInitContext context, Settings settings) { this.context = context; InitializeComponent(); @@ -58,7 +58,6 @@ namespace Wox.Plugin.Program if (MessageBox.Show(msg, string.Empty, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { _settings.ProgramSources.Remove(selectedProgramSource); - _settings.Save(); ReIndexing(); } } @@ -127,7 +126,6 @@ namespace Wox.Plugin.Program Enabled = true }); - _settings.Save(); ReIndexing(); } } @@ -137,14 +135,12 @@ namespace Wox.Plugin.Program private void StartMenuEnabled_Click(object sender, RoutedEventArgs e) { _settings.EnableStartMenuSource = StartMenuEnabled.IsChecked ?? false; - _settings.Save(); ReIndexing(); } private void RegistryEnabled_Click(object sender, RoutedEventArgs e) { _settings.EnableRegistrySource = RegistryEnabled.IsChecked ?? false; - _settings.Save(); ReIndexing(); } } diff --git a/Plugins/Wox.Plugin.Program/ProgramStorage.cs b/Plugins/Wox.Plugin.Program/ProgramStorage.cs index 867064d304..9acd01d727 100644 --- a/Plugins/Wox.Plugin.Program/ProgramStorage.cs +++ b/Plugins/Wox.Plugin.Program/ProgramStorage.cs @@ -1,45 +1,16 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using Newtonsoft.Json; -using Wox.Infrastructure.Storage; namespace Wox.Plugin.Program { - [Serializable] - public class ProgramStorage : JsonStrorage + public class Settings { - [JsonProperty] - public List ProgramSources { get; set; } + public List ProgramSources { get; set; } = new List(); + public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"}; + public bool EnableStartMenuSource { get; set; } = true; - [JsonProperty] - public string[] ProgramSuffixes { get; set; } - - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] - [DefaultValue(true)] - public bool EnableStartMenuSource { get; set; } - - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] - [DefaultValue(true)] - public bool EnableRegistrySource { get; set; } - - protected override ProgramStorage LoadDefault() - { - ProgramSources = new List(); - EnableStartMenuSource = true; - EnableRegistrySource = true; - return this; - } - - protected override void OnAfterLoad(ProgramStorage storage) - { - if (storage.ProgramSuffixes == null || storage.ProgramSuffixes.Length == 0) - { - storage.ProgramSuffixes = new[] {"bat", "appref-ms", "exe", "lnk"}; - } - } - - protected override string FileName { get; } = "settings_plugin_program"; + public bool EnableRegistrySource { get; set; } = true; } } diff --git a/Plugins/Wox.Plugin.Program/ProgramSuffixes.xaml.cs b/Plugins/Wox.Plugin.Program/ProgramSuffixes.xaml.cs index 77ab19d651..390e16d164 100644 --- a/Plugins/Wox.Plugin.Program/ProgramSuffixes.xaml.cs +++ b/Plugins/Wox.Plugin.Program/ProgramSuffixes.xaml.cs @@ -9,9 +9,9 @@ namespace Wox.Plugin.Program public partial class ProgramSuffixes { private PluginInitContext context; - private ProgramStorage _settings; + private Settings _settings; - public ProgramSuffixes(PluginInitContext context, ProgramStorage settings) + public ProgramSuffixes(PluginInitContext context, Settings settings) { this.context = context; InitializeComponent(); diff --git a/Plugins/Wox.Plugin.Program/Programs.cs b/Plugins/Wox.Plugin.Program/Programs.cs index 4a4fe374b2..45e4cd3483 100644 --- a/Plugins/Wox.Plugin.Program/Programs.cs +++ b/Plugins/Wox.Plugin.Program/Programs.cs @@ -5,10 +5,10 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; -using System.Windows; using System.Windows.Controls; using Wox.Infrastructure; using Wox.Infrastructure.Logger; +using Wox.Infrastructure.Storage; using Wox.Plugin.Program.ProgramSources; using Stopwatch = Wox.Infrastructure.Stopwatch; @@ -27,8 +27,25 @@ namespace Wox.Plugin.Program {"AppPathsProgramSource", typeof(AppPathsProgramSource)} }; private PluginInitContext _context; - private static ProgramCacheStorage _cache = ProgramCacheStorage.Instance; - private static ProgramStorage _settings = ProgramStorage.Instance; + + private static ProgramIndexCache _cache; + private static BinaryStorage _cacheStorage; + private static Settings _settings ; + private readonly PluginSettingsStorage _settingsStorage; + + public Programs() + { + _settingsStorage = new PluginSettingsStorage(); + _settings = _settingsStorage.Load(); + _cacheStorage = new BinaryStorage(); + _cache = _cacheStorage.Load(); + } + + ~Programs() + { + _settingsStorage.Save(); + _cacheStorage.Save(); + } public List Query(Query query) { @@ -62,15 +79,13 @@ namespace Wox.Plugin.Program public void Init(PluginInitContext context) { - this._context = context; + _context = context; Stopwatch.Debug("Preload programs", () => { programs = _cache.Programs; }); Log.Info($"Preload {programs.Count} programs from cache"); - // happlebao todo fix this - //Stopwatch.Debug("Program Index", IndexPrograms); - IndexPrograms(); + Stopwatch.Debug("Program Index", IndexPrograms); } public static void IndexPrograms() @@ -120,7 +135,6 @@ namespace Wox.Plugin.Program .Select(g => g.First()).ToList(); _cache.Programs = programs; - _cache.Save(); } } diff --git a/Plugins/Wox.Plugin.WebSearch/WebSearch.cs b/Plugins/Wox.Plugin.WebSearch/WebSearch.cs index f92c580c76..0ce1692bd0 100644 --- a/Plugins/Wox.Plugin.WebSearch/WebSearch.cs +++ b/Plugins/Wox.Plugin.WebSearch/WebSearch.cs @@ -2,7 +2,6 @@ namespace Wox.Plugin.WebSearch { - [Serializable] public class WebSearch { public string Title { get; set; } diff --git a/Plugins/Wox.Plugin.WebSearch/WebSearchPlugin.cs b/Plugins/Wox.Plugin.WebSearch/WebSearchPlugin.cs index 03b6138ef8..00762f3845 100644 --- a/Plugins/Wox.Plugin.WebSearch/WebSearchPlugin.cs +++ b/Plugins/Wox.Plugin.WebSearch/WebSearchPlugin.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Controls; +using Wox.Infrastructure.Storage; using Wox.Plugin.WebSearch.Annotations; using Wox.Plugin.WebSearch.SuggestionSources; @@ -10,9 +11,22 @@ namespace Wox.Plugin.WebSearch { public class WebSearchPlugin : IPlugin, ISettingProvider, IPluginI18n, IInstantQuery, IMultipleActionKeywords { - private WebSearchStorage _settings = WebSearchStorage.Instance; public PluginInitContext Context { get; private set; } + private readonly PluginSettingsStorage _storage; + private readonly Settings _settings; + + public WebSearchPlugin() + { + _storage = new PluginSettingsStorage(); + _settings = _storage.Load(); + } + + ~WebSearchPlugin() + { + _storage.Save(); + } + public List Query(Query query) { List results = new List(); diff --git a/Plugins/Wox.Plugin.WebSearch/WebSearchSetting.xaml.cs b/Plugins/Wox.Plugin.WebSearch/WebSearchSetting.xaml.cs index b2f2368d39..d3e4715bcc 100644 --- a/Plugins/Wox.Plugin.WebSearch/WebSearchSetting.xaml.cs +++ b/Plugins/Wox.Plugin.WebSearch/WebSearchSetting.xaml.cs @@ -18,9 +18,9 @@ namespace Wox.Plugin.WebSearch private WebSearch _updateWebSearch; private readonly PluginInitContext _context; private readonly WebSearchPlugin _plugin; - private WebSearchStorage _settings; + private Settings _settings; - public WebSearchSetting(WebSearchesSetting settingWidow, WebSearchStorage settings) + public WebSearchSetting(WebSearchesSetting settingWidow, Settings settings) { _plugin = settingWidow.Plugin; _context = settingWidow.Context; @@ -122,7 +122,6 @@ namespace Wox.Plugin.WebSearch }); } - _settings.Save(); _settingWindow.ReloadWebSearchView(); Close(); } diff --git a/Plugins/Wox.Plugin.WebSearch/WebSearchStorage.cs b/Plugins/Wox.Plugin.WebSearch/WebSearchStorage.cs index f104cb4e75..6c878adfd8 100644 --- a/Plugins/Wox.Plugin.WebSearch/WebSearchStorage.cs +++ b/Plugins/Wox.Plugin.WebSearch/WebSearchStorage.cs @@ -4,22 +4,9 @@ using Wox.Infrastructure.Storage; namespace Wox.Plugin.WebSearch { - public class WebSearchStorage : JsonStrorage + public class Settings { - [JsonProperty] - public List WebSearches { get; set; } - - [JsonProperty] - public bool EnableWebSearchSuggestion { get; set; } - - [JsonProperty] - public string WebSearchSuggestionSource { get; set; } - - protected override string FileName { get; } = "settings_plugin_websearch"; - - protected override WebSearchStorage LoadDefault() - { - WebSearches = new List(new List() + public List WebSearches { get; set; } = new List { new WebSearch { @@ -173,9 +160,10 @@ namespace Wox.Plugin.WebSearch Url = "http://www.search.yahoo.com/search?p={q}", Enabled = true } - }); + }; - return this; - } + public bool EnableWebSearchSuggestion { get; set; } + + public string WebSearchSuggestionSource { get; set; } } } \ No newline at end of file diff --git a/Plugins/Wox.Plugin.WebSearch/WebSearchesSetting.xaml.cs b/Plugins/Wox.Plugin.WebSearch/WebSearchesSetting.xaml.cs index 81f94145c3..cfc2af4c1f 100644 --- a/Plugins/Wox.Plugin.WebSearch/WebSearchesSetting.xaml.cs +++ b/Plugins/Wox.Plugin.WebSearch/WebSearchesSetting.xaml.cs @@ -10,11 +10,11 @@ namespace Wox.Plugin.WebSearch /// public partial class WebSearchesSetting : UserControl { - private WebSearchStorage _settings; + private Settings _settings; public PluginInitContext Context { get; } public WebSearchPlugin Plugin { get; } - public WebSearchesSetting(WebSearchPlugin plugin, WebSearchStorage settings) + public WebSearchesSetting(WebSearchPlugin plugin, Settings settings) { Context = plugin.Context; Plugin = plugin; @@ -97,14 +97,12 @@ namespace Wox.Plugin.WebSearch { comboBoxSuggestionSource.Visibility = Visibility.Visible; _settings.EnableWebSearchSuggestion = true; - _settings.Save(); } private void CbEnableWebSearchSuggestion_OnUnchecked(object sender, RoutedEventArgs e) { comboBoxSuggestionSource.Visibility = Visibility.Collapsed; _settings.EnableWebSearchSuggestion = false; - _settings.Save(); } private void ComboBoxSuggestionSource_OnSelectionChanged(object sender, SelectionChangedEventArgs e) @@ -112,7 +110,6 @@ namespace Wox.Plugin.WebSearch if (e.AddedItems.Count > 0) { _settings.WebSearchSuggestionSource = ((ComboBoxItem)e.AddedItems[0]).Content.ToString(); - _settings.Save(); } } } diff --git a/Wox.Core/Plugin/PluginManager.cs b/Wox.Core/Plugin/PluginManager.cs index 578ed840cd..d8c46d23e9 100644 --- a/Wox.Core/Plugin/PluginManager.cs +++ b/Wox.Core/Plugin/PluginManager.cs @@ -25,7 +25,7 @@ namespace Wox.Core.Plugin /// private static readonly List PluginDirectories = new List(); - public static IEnumerable AllPlugins { get; private set; } + public static List AllPlugins { get; private set; } public static readonly List GlobalPlugins = new List(); @@ -69,10 +69,8 @@ namespace Wox.Core.Plugin SetupPluginDirectories(); var metadatas = PluginConfig.Parse(PluginDirectories); - AllPlugins = (new CSharpPluginLoader().LoadPlugin(metadatas)). - Concat(new JsonRPCPluginLoader().LoadPlugin(metadatas)); - - + AllPlugins = new CSharpPluginLoader().LoadPlugin(metadatas).Concat( + new JsonRPCPluginLoader().LoadPlugin(metadatas)).ToList(); } public static void InitializePlugins(IPublicAPI api) @@ -164,6 +162,42 @@ namespace Wox.Core.Plugin return GlobalPlugins; } } + + //happlebao todo prevent plugin initial when plugin is disabled + public static void DisablePlugin(PluginPair plugin) + { + var actionKeywords = plugin.Metadata.ActionKeywords; + if (actionKeywords == null || actionKeywords.Count == 0 || actionKeywords[0] == Query.GlobalPluginWildcardSign) + { + GlobalPlugins.Remove(plugin); + } + else + { + foreach (var actionkeyword in plugin.Metadata.ActionKeywords) + { + NonGlobalPlugins.Remove(actionkeyword); + } + } + AllPlugins.Remove(plugin); + } + + public static void EnablePlugin(PluginPair plugin) + { + var actionKeywords = plugin.Metadata.ActionKeywords; + if (actionKeywords == null || actionKeywords.Count == 0 || actionKeywords[0] == Query.GlobalPluginWildcardSign) + { + GlobalPlugins.Add(plugin); + } + else + { + foreach (var actionkeyword in plugin.Metadata.ActionKeywords) + { + NonGlobalPlugins[actionkeyword] = plugin; + } + } + AllPlugins.Add(plugin); + } + public static List QueryForPlugin(PluginPair pair, Query query) { var results = new List(); @@ -184,7 +218,7 @@ namespace Wox.Core.Plugin } catch (Exception e) { - throw new WoxPluginException(pair.Metadata.Name, $"QueryForPlugin failed", e); + throw new WoxPluginException(pair.Metadata.Name, "QueryForPlugin failed", e); } return results; } diff --git a/Wox.Core/Resource/Internationalization.cs b/Wox.Core/Resource/Internationalization.cs index 55d640e04c..dafdd671e1 100644 --- a/Wox.Core/Resource/Internationalization.cs +++ b/Wox.Core/Resource/Internationalization.cs @@ -12,7 +12,7 @@ namespace Wox.Core.Resource { public class Internationalization : Resource { - public UserSettingStorage Settings { get; set; } + public UserSettings.Settings Settings { get; set; } public Internationalization() { @@ -67,7 +67,6 @@ namespace Wox.Core.Resource } Settings.Language = language.LanguageCode; - Settings.Save(); ResourceMerger.UpdateResource(this); } diff --git a/Wox.Core/Resource/Theme.cs b/Wox.Core/Resource/Theme.cs index 3cd07e7284..7782b55ad1 100644 --- a/Wox.Core/Resource/Theme.cs +++ b/Wox.Core/Resource/Theme.cs @@ -15,7 +15,7 @@ namespace Wox.Core.Resource public class Theme : Resource { private static List themeDirectories = new List(); - public UserSettingStorage Settings { get; set; } + public UserSettings.Settings Settings { get; set; } public Theme() { @@ -55,7 +55,6 @@ namespace Wox.Core.Resource } Settings.Theme = themeName; - Settings.Save(); ResourceMerger.UpdateResource(this); // Exception of FindResource can't be cathed if global exception handle is set diff --git a/Wox.Core/Updater/UpdaterManager.cs b/Wox.Core/Updater/UpdaterManager.cs index 3e37b764e2..c8f710ba51 100644 --- a/Wox.Core/Updater/UpdaterManager.cs +++ b/Wox.Core/Updater/UpdaterManager.cs @@ -22,7 +22,7 @@ namespace Wox.Core.Updater private const string UpdateFeedURL = "http://upgrade.getwox.com/update.xml"; //private const string UpdateFeedURL = "http://127.0.0.1:8888/update.xml"; private static SemanticVersion currentVersion; - private UserSettingStorage _settings; + public UserSettings.Settings Settings { get; set; } public event EventHandler PrepareUpdateReady; public event EventHandler UpdateError; @@ -44,7 +44,6 @@ namespace Wox.Core.Updater private UpdaterManager() { UpdateManager.Instance.UpdateSource = GetUpdateSource(); - _settings = UserSettingStorage.Instance; } public SemanticVersion CurrentVersion @@ -89,7 +88,7 @@ namespace Wox.Core.Updater try { NewRelease = JsonConvert.DeserializeObject(json); - if (IsNewerThanCurrent(NewRelease) && !_settings.DontPromptUpdateMsg) + if (IsNewerThanCurrent(NewRelease) && !Settings.DontPromptUpdateMsg) { StartUpdate(); } @@ -148,7 +147,7 @@ namespace Wox.Core.Updater // get out of the way so the console window isn't obstructed try { - UpdateManager.Instance.ApplyUpdates(true, _settings.EnableUpdateLog, false); + UpdateManager.Instance.ApplyUpdates(true, Settings.EnableUpdateLog, false); } catch (Exception e) { diff --git a/Wox.Core/UserSettings/CustomizedPluginConfig.cs b/Wox.Core/UserSettings/CustomizedPluginConfig.cs index c58bb96477..1a176f5bea 100644 --- a/Wox.Core/UserSettings/CustomizedPluginConfig.cs +++ b/Wox.Core/UserSettings/CustomizedPluginConfig.cs @@ -3,7 +3,7 @@ namespace Wox.Core.UserSettings { - public class CustomizedPluginConfig + public class PluginSetting { public string ID { get; set; } diff --git a/Wox.Core/UserSettings/HttpProxy.cs b/Wox.Core/UserSettings/HttpProxy.cs index ead2d86df4..ff6d5aaab1 100644 --- a/Wox.Core/UserSettings/HttpProxy.cs +++ b/Wox.Core/UserSettings/HttpProxy.cs @@ -5,7 +5,7 @@ namespace Wox.Core.UserSettings public class HttpProxy : IHttpProxy { private static readonly HttpProxy instance = new HttpProxy(); - public UserSettingStorage Settings { get; set; } + public Settings Settings { get; set; } public static HttpProxy Instance => instance; public bool Enabled => Settings.ProxyEnabled; diff --git a/Wox.Core/UserSettings/PluginHotkey.cs b/Wox.Core/UserSettings/PluginHotkey.cs index 892816f8b9..cedeaf0886 100644 --- a/Wox.Core/UserSettings/PluginHotkey.cs +++ b/Wox.Core/UserSettings/PluginHotkey.cs @@ -2,7 +2,6 @@ namespace Wox.Core.UserSettings { - [Serializable] public class CustomPluginHotkey { public string Hotkey { get; set; } diff --git a/Wox.Core/UserSettings/UserSettingStorage.cs b/Wox.Core/UserSettings/UserSettingStorage.cs index b9a7f8ab7f..da2ae4b0d6 100644 --- a/Wox.Core/UserSettings/UserSettingStorage.cs +++ b/Wox.Core/UserSettings/UserSettingStorage.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Drawing; using System.Linq; using Wox.Core.Plugin; @@ -9,119 +10,66 @@ using Newtonsoft.Json; namespace Wox.Core.UserSettings { - public class UserSettingStorage : JsonStrorage + public class Settings { - public bool DontPromptUpdateMsg { get; set; } - - public int ActivateTimes { get; set; } - - public bool EnableUpdateLog { get; set; } - - public string Hotkey { get; set; } - - public string Language { get; set; } - - public string Theme { get; set; } - - public string QueryBoxFont { get; set; } - + public string Hotkey { get; set; } = "Alt + Space"; + public string Language { get; set; } = "en"; + public string Theme { get; set; } = "Dark"; + public string QueryBoxFont { get; set; } = FontFamily.GenericSansSerif.Name; public string QueryBoxFontStyle { get; set; } - public string QueryBoxFontWeight { get; set; } - public string QueryBoxFontStretch { get; set; } - - public string ResultFont { get; set; } - + public string ResultFont { get; set; } = FontFamily.GenericSansSerif.Name; public string ResultFontStyle { get; set; } - public string ResultFontWeight { get; set; } - public string ResultFontStretch { get; set; } public double WindowLeft { get; set; } - public double WindowTop { get; set; } + public int MaxResultsToShow { get; set; } = 6; + public int ActivateTimes { get; set; } // Order defaults to 0 or -1, so 1 will let this property appear last [JsonProperty(Order = 1)] - public Dictionary CustomizedPluginConfigs { get; set; } + public Dictionary PluginSettings { get; set; } = new Dictionary(); + public List CustomPluginHotkeys { get; set; } = new List(); - public List CustomPluginHotkeys { get; set; } + [Obsolete] + public double Opacity { get; set; } = 1; + + [Obsolete] + public OpacityMode OpacityMode { get; set; } = OpacityMode.Normal; + + public bool DontPromptUpdateMsg { get; set; } + public bool EnableUpdateLog { get; set; } public bool StartWoxOnSystemStartup { get; set; } - - [Obsolete] - public double Opacity { get; set; } - - [Obsolete] - public OpacityMode OpacityMode { get; set; } - public bool LeaveCmdOpen { get; set; } - public bool HideWhenDeactive { get; set; } - public bool RememberLastLaunchLocation { get; set; } - public bool IgnoreHotkeysOnFullscreen { get; set; } public string ProxyServer { get; set; } - public bool ProxyEnabled { get; set; } - public int ProxyPort { get; set; } - public string ProxyUserName { get; set; } - public string ProxyPassword { get; set; } - public int MaxResultsToShow { get; set; } - - protected override string FileName { get; } = "Settings"; - - public void IncreaseActivateTimes() - { - ActivateTimes++; - if (ActivateTimes % 15 == 0) - { - Save(); - } - } - - protected override UserSettingStorage LoadDefault() - { - DontPromptUpdateMsg = false; - Theme = "Dark"; - Language = "en"; - CustomizedPluginConfigs = new Dictionary(); - Hotkey = "Alt + Space"; - QueryBoxFont = FontFamily.GenericSansSerif.Name; - ResultFont = FontFamily.GenericSansSerif.Name; - Opacity = 1; - OpacityMode = OpacityMode.Normal; - LeaveCmdOpen = false; - HideWhenDeactive = false; - CustomPluginHotkeys = new List(); - RememberLastLaunchLocation = false; - MaxResultsToShow = 6; - return this; - } - - protected override void OnAfterLoad(UserSettingStorage storage) + public void UpdatePluginSettings() { var metadatas = PluginManager.AllPlugins.Select(p => p.Metadata); - if (storage.CustomizedPluginConfigs == null) + if (PluginSettings == null) { - var configs = new Dictionary(); + var configs = new Dictionary(); foreach (var metadata in metadatas) { addPluginMetadata(configs, metadata); } - storage.CustomizedPluginConfigs = configs; + PluginSettings = configs; } else { - var configs = storage.CustomizedPluginConfigs; + var configs = PluginSettings; foreach (var metadata in metadatas) { if (configs.ContainsKey(metadata.ID)) @@ -139,26 +87,12 @@ namespace Wox.Core.UserSettings } } } - - - if (storage.QueryBoxFont == null) - { - storage.QueryBoxFont = FontFamily.GenericSansSerif.Name; - } - if (storage.ResultFont == null) - { - storage.ResultFont = FontFamily.GenericSansSerif.Name; - } - if (storage.Language == null) - { - storage.Language = "en"; - } } - private void addPluginMetadata(Dictionary configs, PluginMetadata metadata) + private void addPluginMetadata(Dictionary configs, PluginMetadata metadata) { - configs[metadata.ID] = new CustomizedPluginConfig + configs[metadata.ID] = new PluginSetting { ID = metadata.ID, Name = metadata.Name, @@ -169,10 +103,10 @@ namespace Wox.Core.UserSettings public void UpdateActionKeyword(PluginMetadata metadata) { - var config = CustomizedPluginConfigs[metadata.ID]; + var config = PluginSettings[metadata.ID]; config.ActionKeywords = metadata.ActionKeywords; - Save(); } + } public enum OpacityMode diff --git a/Wox.Infrastructure/Storage/BaseStorage.cs b/Wox.Infrastructure/Storage/BaseStorage.cs deleted file mode 100644 index 03e0311eb7..0000000000 --- a/Wox.Infrastructure/Storage/BaseStorage.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.IO; - -namespace Wox.Infrastructure.Storage -{ - [Serializable] - public abstract class BaseStorage : IStorage where T : class, IStorage, new() - { - protected string DirectoryPath { get; } = Path.Combine(WoxDirectroy.Executable, "Config"); - - protected string FilePath => Path.Combine(DirectoryPath, FileName + FileSuffix); - - protected abstract string FileSuffix { get; } - - protected abstract string FileName { get; } - - private static object locker = new object(); - - protected static T serializedObject; - - public event Action AfterLoad; - - protected virtual void OnAfterLoad(T obj) - { - Action handler = AfterLoad; - if (handler != null) handler(obj); - } - - public static T Instance - { - get - { - if (serializedObject == null) - { - lock (locker) - { - if (serializedObject == null) - { - serializedObject = new T(); - serializedObject.Load(); - } - } - } - return serializedObject; - } - } - - /// - /// if loading storage failed, we will try to load default - /// - /// - protected virtual T LoadDefault() - { - return new T(); - } - - protected abstract void LoadInternal(); - protected abstract void SaveInternal(); - - public void Load() - { - if (!File.Exists(FilePath)) - { - if (!Directory.Exists(DirectoryPath)) - { - Directory.CreateDirectory(DirectoryPath); - } - File.Create(FilePath).Close(); - } - LoadInternal(); - OnAfterLoad(serializedObject); - } - - public void Save() - { - lock (locker) - { - SaveInternal(); - } - } - } -} \ No newline at end of file diff --git a/Wox.Infrastructure/Storage/BinaryStorage.cs b/Wox.Infrastructure/Storage/BinaryStorage.cs index 75258df007..7fc339df99 100644 --- a/Wox.Infrastructure/Storage/BinaryStorage.cs +++ b/Wox.Infrastructure/Storage/BinaryStorage.cs @@ -1,9 +1,9 @@ using System; using System.IO; using System.Reflection; +using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; -using System.Threading; using Wox.Infrastructure.Logger; namespace Wox.Infrastructure.Storage @@ -13,55 +13,73 @@ namespace Wox.Infrastructure.Storage /// Normally, it has better performance, but not readable /// You MUST mark implement class as Serializable /// - [Serializable] - public abstract class BinaryStorage : BaseStorage where T : class, IStorage, new() + public class BinaryStorage where T : class, new() { - private static object syncObject = new object(); - protected override string FileSuffix + private T _binary; + + private string FilePath { get; } + private string FileName { get; } + private const string FileSuffix = ".dat"; + private string DirectoryPath { get; } + private const string DirectoryName = "Config"; + + public BinaryStorage() { - get { return ".dat"; } + FileName = typeof(T).Name; + DirectoryPath = Path.Combine(WoxDirectroy.Executable, DirectoryName); + FilePath = Path.Combine(DirectoryPath, FileName + FileSuffix); ; } - protected override void LoadInternal() + public T Load() { - //http://stackoverflow.com/questions/2120055/binaryformatter-deserialize-gives-serializationexception - AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; - try + if (!Directory.Exists(DirectoryPath)) { - using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + Directory.CreateDirectory(DirectoryPath); + } + + if (File.Exists(FilePath)) + { + using (var stream = new FileStream(FilePath, FileMode.Open)) { - if (fileStream.Length > 0) + if (stream.Length > 0) { - BinaryFormatter binaryFormatter = new BinaryFormatter - { - AssemblyFormat = FormatterAssemblyStyle.Simple - }; - serializedObject = binaryFormatter.Deserialize(fileStream) as T; - if (serializedObject == null) - { - serializedObject = LoadDefault(); -#if (DEBUG) - { - throw new System.Exception("deserialize failed"); - } -#endif - } + Deserialize(stream); } else { - serializedObject = LoadDefault(); + LoadDefault(); } } } - catch (System.Exception e) + else + { + LoadDefault(); + } + return _binary; + } + + private void Deserialize(FileStream stream) + { + //http://stackoverflow.com/questions/2120055/binaryformatter-deserialize-gives-serializationexception + AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; + BinaryFormatter binaryFormatter = new BinaryFormatter + { + AssemblyFormat = FormatterAssemblyStyle.Simple + }; + + try + { + _binary = (T)binaryFormatter.Deserialize(stream); + } + catch (SerializationException e) { Log.Error(e); - serializedObject = LoadDefault(); -#if (DEBUG) - { - throw; - } -#endif + LoadDefault(); + } + catch (InvalidCastException e) + { + Log.Error(e); + LoadDefault(); } finally { @@ -69,6 +87,11 @@ namespace Wox.Infrastructure.Storage } } + private void LoadDefault() + { + _binary = new T(); + } + private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { Assembly ayResult = null; @@ -85,33 +108,24 @@ namespace Wox.Infrastructure.Storage return ayResult; } - protected override void SaveInternal() + public void Save() { - ThreadPool.QueueUserWorkItem(o => + using (var stream = new FileStream(FilePath, FileMode.Create)) { - lock (syncObject) + BinaryFormatter binaryFormatter = new BinaryFormatter { - try - { - FileStream fileStream = new FileStream(FilePath, FileMode.Create); - BinaryFormatter binaryFormatter = new BinaryFormatter - { - AssemblyFormat = FormatterAssemblyStyle.Simple - }; - binaryFormatter.Serialize(fileStream, serializedObject); - fileStream.Close(); - } - catch (System.Exception e) - { - Log.Error(e); -#if (DEBUG) - { - throw; - } -#endif - } + AssemblyFormat = FormatterAssemblyStyle.Simple + }; + + try + { + binaryFormatter.Serialize(stream, _binary); } - }); + catch (SerializationException e) + { + Log.Error(e); + } + } } } } diff --git a/Wox.Infrastructure/Storage/IStorage.cs b/Wox.Infrastructure/Storage/IStorage.cs deleted file mode 100644 index 9f305804dd..0000000000 --- a/Wox.Infrastructure/Storage/IStorage.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Wox.Infrastructure.Storage -{ - public interface IStorage - { - void Load(); - void Save(); - } -} diff --git a/Wox.Infrastructure/Storage/JsonStorage.cs b/Wox.Infrastructure/Storage/JsonStorage.cs index 16f6278059..367c502b01 100644 --- a/Wox.Infrastructure/Storage/JsonStorage.cs +++ b/Wox.Infrastructure/Storage/JsonStorage.cs @@ -1,50 +1,85 @@ using System.IO; -using System.Threading; using Newtonsoft.Json; +using Wox.Infrastructure.Logger; namespace Wox.Infrastructure.Storage { /// /// Serialize object using json format. /// - public abstract class JsonStrorage : BaseStorage where T : class, IStorage, new() + public class JsonStrorage where T : new() { - private static object syncObject = new object(); - protected override string FileSuffix + private T _json; + private readonly JsonSerializerSettings _serializerSettings; + + protected string FileName { get; set; } + protected string FilePath { get; set; } + protected const string FileSuffix = ".json"; + protected string DirectoryPath { get; set; } + protected const string DirectoryName = "Config"; + + internal JsonStrorage() { - get { return ".json"; } + FileName = typeof(T).Name; + DirectoryPath = Path.Combine(WoxDirectroy.Executable, DirectoryName); + FilePath = Path.Combine(DirectoryPath, FileName + FileSuffix); + + // use property initialization instead of DefaultValueAttribute + // easier and flexible for default value of object + _serializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; } - protected override void LoadInternal() + public T Load() { - string json = File.ReadAllText(FilePath); - if (!string.IsNullOrEmpty(json)) + if (!Directory.Exists(DirectoryPath)) { - try + Directory.CreateDirectory(DirectoryPath); + } + + if (File.Exists(FilePath)) + { + var searlized = File.ReadAllText(FilePath); + if (!string.IsNullOrWhiteSpace(searlized)) { - serializedObject = JsonConvert.DeserializeObject(json); + Deserialize(searlized); } - catch (System.Exception) + else { - serializedObject = LoadDefault(); + LoadDefault(); } } else { - serializedObject = LoadDefault(); + LoadDefault(); } + + return _json; } - protected override void SaveInternal() + private void Deserialize(string searlized) { - ThreadPool.QueueUserWorkItem(o => + try { - lock (syncObject) - { - string json = JsonConvert.SerializeObject(serializedObject, Formatting.Indented); - File.WriteAllText(FilePath, json); - } - }); + _json = JsonConvert.DeserializeObject(searlized, _serializerSettings); + } + catch (JsonSerializationException e) + { + LoadDefault(); + Log.Error(e); + } + + } + + private void LoadDefault() + { + _json = JsonConvert.DeserializeObject("{}", _serializerSettings); + Save(); + } + + public void Save() + { + string serialized = JsonConvert.SerializeObject(_json, Formatting.Indented); + File.WriteAllText(FilePath, serialized); } } } diff --git a/Wox.Infrastructure/Storage/PluginSettingsStorage.cs b/Wox.Infrastructure/Storage/PluginSettingsStorage.cs new file mode 100644 index 0000000000..009f386868 --- /dev/null +++ b/Wox.Infrastructure/Storage/PluginSettingsStorage.cs @@ -0,0 +1,20 @@ +using System.IO; + +namespace Wox.Infrastructure.Storage +{ + public class PluginSettingsStorage :JsonStrorage where T : new() + { + public PluginSettingsStorage() + { + var pluginDirectoryName = "Plugins"; + + // C# releated, add python releated below + var type = typeof (T); + FileName = type.Name; + var assemblyName = type.Assembly.GetName().Name; + DirectoryPath = Path.Combine(WoxDirectroy.Executable, DirectoryName, pluginDirectoryName, assemblyName); + + FilePath = Path.Combine(DirectoryPath, FileName + FileSuffix); + } + } +} diff --git a/Wox.Infrastructure/Wox.Infrastructure.csproj b/Wox.Infrastructure/Wox.Infrastructure.csproj index c83eb65231..40db92072a 100644 --- a/Wox.Infrastructure/Wox.Infrastructure.csproj +++ b/Wox.Infrastructure/Wox.Infrastructure.csproj @@ -63,6 +63,7 @@ + diff --git a/Wox.Plugin/Result.cs b/Wox.Plugin/Result.cs index ced01e38b3..c60bba2842 100644 --- a/Wox.Plugin/Result.cs +++ b/Wox.Plugin/Result.cs @@ -69,11 +69,6 @@ namespace Wox.Plugin return Title + SubTitle; } - public Result() - { - - } - public Result(string Title = null, string IcoPath = null, string SubTitle = null) { this.Title = Title; diff --git a/Wox/ActionKeywords.xaml.cs b/Wox/ActionKeywords.xaml.cs index f4119ac131..ffcdb8a10e 100644 --- a/Wox/ActionKeywords.xaml.cs +++ b/Wox/ActionKeywords.xaml.cs @@ -10,9 +10,9 @@ namespace Wox public partial class ActionKeywords : Window { private PluginPair _plugin; - private UserSettingStorage _settings; + private Settings _settings; - public ActionKeywords(string pluginId, UserSettingStorage settings) + public ActionKeywords(string pluginId, Settings settings) { InitializeComponent(); _plugin = PluginManager.GetPluginForId(pluginId); diff --git a/Wox/App.xaml.cs b/Wox/App.xaml.cs index 7eeb44f27a..d76f0d4fcc 100644 --- a/Wox/App.xaml.cs +++ b/Wox/App.xaml.cs @@ -9,9 +9,11 @@ using System.Windows; using Wox.CommandArgs; using Wox.Core.Plugin; using Wox.Core.Resource; +using Wox.Core.Updater; using Wox.Core.UserSettings; using Wox.Helper; using Wox.Infrastructure; +using Wox.Infrastructure.Storage; using Wox.ViewModel; using Stopwatch = Wox.Infrastructure.Stopwatch; @@ -49,18 +51,14 @@ namespace Wox ThreadPool.QueueUserWorkItem(_ => { ImageLoader.ImageLoader.PreloadImages(); }); PluginManager.Initialize(); - UserSettingStorage settings = UserSettingStorage.Instance; - - // happlebao temp fix for instance code logic - HttpProxy.Instance.Settings = settings; - InternationalizationManager.Instance.Settings = settings; - ThemeManager.Instance.Settings = settings; - - MainViewModel mainVM = new MainViewModel(settings); - API = new PublicAPIInstance(mainVM, settings); + + MainViewModel mainVM = new MainViewModel(); + API = new PublicAPIInstance(mainVM, mainVM._settings); PluginManager.InitializePlugins(API); - Window = new MainWindow (settings, mainVM); + mainVM._settings.UpdatePluginSettings(); + + Window = new MainWindow (mainVM._settings, mainVM); NotifyIconManager notifyIconManager = new NotifyIconManager(API); CommandArgsFactory.Execute(e.Args.ToList()); diff --git a/Wox/CustomQueryHotkeySetting.xaml.cs b/Wox/CustomQueryHotkeySetting.xaml.cs index 56344ea7a7..0132756ab4 100644 --- a/Wox/CustomQueryHotkeySetting.xaml.cs +++ b/Wox/CustomQueryHotkeySetting.xaml.cs @@ -15,9 +15,9 @@ namespace Wox private SettingWindow _settingWidow; private bool update; private CustomPluginHotkey updateCustomHotkey; - private UserSettingStorage _settings; + private Settings _settings; - public CustomQueryHotkeySetting(SettingWindow settingWidow, UserSettingStorage settings) + public CustomQueryHotkeySetting(SettingWindow settingWidow, Settings settings) { _settingWidow = settingWidow; InitializeComponent(); @@ -78,7 +78,6 @@ namespace Wox MessageBox.Show(InternationalizationManager.Instance.GetTranslation("succeed")); } - _settings.Save(); _settingWidow.ReloadCustomPluginHotkeyView(); Close(); } diff --git a/Wox/ImageLoader/ImageCacheStroage.cs b/Wox/ImageLoader/ImageCacheStroage.cs index bc032f8d03..e317c70c9a 100644 --- a/Wox/ImageLoader/ImageCacheStroage.cs +++ b/Wox/ImageLoader/ImageCacheStroage.cs @@ -6,14 +6,12 @@ using Wox.Infrastructure.Storage; namespace Wox.ImageLoader { [Serializable] - public class ImageCacheStroage : BinaryStorage + public class ImageCache { private int counter; private const int maxCached = 200; public Dictionary TopUsedImages = new Dictionary(); - protected override string FileName { get; } = "ImageCache"; - public void Add(string path) { if (TopUsedImages.ContainsKey(path)) @@ -35,7 +33,6 @@ namespace Wox.ImageLoader if (++counter == 30) { counter = 0; - Save(); } } diff --git a/Wox/ImageLoader/ImageLoader.cs b/Wox/ImageLoader/ImageLoader.cs index c5453d47b0..17e7974dea 100644 --- a/Wox/ImageLoader/ImageLoader.cs +++ b/Wox/ImageLoader/ImageLoader.cs @@ -8,12 +8,13 @@ using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using Wox.Infrastructure; +using Wox.Infrastructure.Storage; namespace Wox.ImageLoader { public class ImageLoader { - private static readonly Dictionary imageCache = new Dictionary(); + private static readonly Dictionary ImageSources = new Dictionary(); private static readonly List imageExts = new List { @@ -36,11 +37,18 @@ namespace Wox.ImageLoader ".appref-ms" }; - private static ImageCacheStroage _imageCache; + private static readonly ImageCache _cache; + private static readonly BinaryStorage _storage; static ImageLoader() { - _imageCache = ImageCacheStroage.Instance; + _storage = new BinaryStorage(); + _cache = _storage.Load(); + } + + ~ImageLoader() + { + _storage.Save(); } private static ImageSource GetIcon(string fileName) @@ -63,21 +71,21 @@ namespace Wox.ImageLoader public static void PreloadImages() { //ImageCacheStroage.Instance.TopUsedImages can be changed during foreach, so we need to make a copy - var imageList = new Dictionary(_imageCache.TopUsedImages); + var imageList = new Dictionary(_cache.TopUsedImages); Stopwatch.Debug($"Preload {imageList.Count} images", () => { foreach (var image in imageList) { - if (!imageCache.ContainsKey(image.Key)) + if (!ImageSources.ContainsKey(image.Key)) { ImageSource img = Load(image.Key, false); if (img != null) { img.Freeze(); //to make it copy to UI thread - if (!imageCache.ContainsKey(image.Key)) + if (!ImageSources.ContainsKey(image.Key)) { KeyValuePair copyedImg = image; - imageCache.Add(copyedImg.Key, img); + ImageSources.Add(copyedImg.Key, img); } } } @@ -94,13 +102,13 @@ namespace Wox.ImageLoader if (addToCache) { - _imageCache.Add(path); + _cache.Add(path); } - if (imageCache.ContainsKey(path)) + if (ImageSources.ContainsKey(path)) { - img = imageCache[path]; + img = ImageSources[path]; } else { @@ -122,9 +130,9 @@ namespace Wox.ImageLoader if (img != null && addToCache) { - if (!imageCache.ContainsKey(path)) + if (!ImageSources.ContainsKey(path)) { - imageCache.Add(path, img); + ImageSources.Add(path, img); } } } diff --git a/Wox/Languages/en.xaml b/Wox/Languages/en.xaml index c7cbfa81c0..2e75ca24a8 100644 --- a/Wox/Languages/en.xaml +++ b/Wox/Languages/en.xaml @@ -15,7 +15,7 @@ Exit - Wox Settings + Wox Settings General Start Wox on system startup Hide Wox when loses focus diff --git a/Wox/MainWindow.xaml.cs b/Wox/MainWindow.xaml.cs index 6cb0ea5f69..77f30e46a3 100644 --- a/Wox/MainWindow.xaml.cs +++ b/Wox/MainWindow.xaml.cs @@ -25,11 +25,11 @@ namespace Wox #region Private Fields private readonly Storyboard _progressBarStoryboard = new Storyboard(); - private UserSettingStorage _settings; + private Settings _settings; #endregion - public MainWindow(UserSettingStorage settings, MainViewModel mainVM) + public MainWindow(Settings settings, MainViewModel mainVM) { DataContext = mainVM; InitializeComponent(); @@ -43,7 +43,6 @@ namespace Wox { _settings.WindowLeft = Left; _settings.WindowTop = Top; - _settings.Save(); } private void OnLoaded(object sender, RoutedEventArgs _) @@ -71,13 +70,12 @@ namespace Wox QueryTextBox.Focus(); Left = GetWindowsLeft(); Top = GetWindowsTop(); - _settings.IncreaseActivateTimes(); + _settings.ActivateTimes++; } else { _settings.WindowLeft = Left; _settings.WindowTop = Top; - _settings.Save(); } }; diff --git a/Wox/Properties/Settings.settings b/Wox/Properties/Settings.settings index 033d7a5e9e..a585a6308c 100644 --- a/Wox/Properties/Settings.settings +++ b/Wox/Properties/Settings.settings @@ -1,5 +1,5 @@  - + diff --git a/Wox/PublicAPIInstance.cs b/Wox/PublicAPIInstance.cs index 28abf3c345..64171fc9e4 100644 --- a/Wox/PublicAPIInstance.cs +++ b/Wox/PublicAPIInstance.cs @@ -19,10 +19,10 @@ namespace Wox { public class PublicAPIInstance : IPublicAPI { - private UserSettingStorage _settings; + private Settings _settings; #region Constructor - public PublicAPIInstance(MainViewModel mainVM, UserSettingStorage settings) + public PublicAPIInstance(MainViewModel mainVM, Settings settings) { MainVM = mainVM; _settings = settings; diff --git a/Wox/SettingWindow.xaml.cs b/Wox/SettingWindow.xaml.cs index 4271f1f4a0..151a8d338b 100644 --- a/Wox/SettingWindow.xaml.cs +++ b/Wox/SettingWindow.xaml.cs @@ -32,9 +32,9 @@ namespace Wox bool settingsLoaded; private Dictionary featureControls = new Dictionary(); private bool themeTabLoaded; - private UserSettingStorage _settings; + private Settings _settings; - public SettingWindow(IPublicAPI api, UserSettingStorage settings) + public SettingWindow(IPublicAPI api, Settings settings) { InitializeComponent(); _settings = settings; @@ -49,50 +49,42 @@ namespace Wox cbHideWhenDeactive.Checked += (o, e) => { _settings.HideWhenDeactive = true; - _settings.Save(); }; cbHideWhenDeactive.Unchecked += (o, e) => { _settings.HideWhenDeactive = false; - _settings.Save(); }; cbRememberLastLocation.Checked += (o, e) => { _settings.RememberLastLaunchLocation = true; - _settings.Save(); }; cbRememberLastLocation.Unchecked += (o, e) => { _settings.RememberLastLaunchLocation = false; - _settings.Save(); }; cbDontPromptUpdateMsg.Checked += (o, e) => { _settings.DontPromptUpdateMsg = true; - _settings.Save(); }; cbDontPromptUpdateMsg.Unchecked += (o, e) => { _settings.DontPromptUpdateMsg = false; - _settings.Save(); }; cbIgnoreHotkeysOnFullscreen.Checked += (o, e) => { _settings.IgnoreHotkeysOnFullscreen = true; - _settings.Save(); }; cbIgnoreHotkeysOnFullscreen.Unchecked += (o, e) => { _settings.IgnoreHotkeysOnFullscreen = false; - _settings.Save(); }; @@ -100,7 +92,6 @@ namespace Wox comboMaxResultsToShow.SelectionChanged += (o, e) => { _settings.MaxResultsToShow = (int)comboMaxResultsToShow.SelectedItem; - _settings.Save(); //MainWindow.pnlResult.lbResults.GetBindingExpression(MaxHeightProperty).UpdateTarget(); }; @@ -215,14 +206,12 @@ namespace Wox { AddApplicationToStartup(); _settings.StartWoxOnSystemStartup = true; - _settings.Save(); } private void CbStartWithWindows_OnUnchecked(object sender, RoutedEventArgs e) { RemoveApplicationFromStartup(); _settings.StartWoxOnSystemStartup = false; - _settings.Save(); } private void AddApplicationToStartup() @@ -270,7 +259,6 @@ namespace Wox }); RemoveHotkey(_settings.Hotkey); _settings.Hotkey = ctlHotkey.CurrentHotkey.ToString(); - _settings.Save(); } } @@ -317,7 +305,6 @@ namespace Wox { _settings.CustomPluginHotkeys.Remove(item); lvCustomHotkey.Items.Refresh(); - _settings.Save(); RemoveHotkey(item.Hotkey); } } @@ -481,7 +468,6 @@ namespace Wox string queryBoxFontName = cbQueryBoxFont.SelectedItem.ToString(); _settings.QueryBoxFont = queryBoxFontName; cbQueryBoxFontFaces.SelectedItem = ((FontFamily)cbQueryBoxFont.SelectedItem).ChooseRegularFamilyTypeface(); - _settings.Save(); ThemeManager.Instance.ChangeTheme(_settings.Theme); } @@ -499,7 +485,6 @@ namespace Wox _settings.QueryBoxFontStretch = typeface.Stretch.ToString(); _settings.QueryBoxFontWeight = typeface.Weight.ToString(); _settings.QueryBoxFontStyle = typeface.Style.ToString(); - _settings.Save(); ThemeManager.Instance.ChangeTheme(_settings.Theme); } } @@ -510,7 +495,6 @@ namespace Wox string resultItemFont = ResultFontComboBox.SelectedItem.ToString(); _settings.ResultFont = resultItemFont; ResultFontFacesComboBox.SelectedItem = ((FontFamily)ResultFontComboBox.SelectedItem).ChooseRegularFamilyTypeface(); - _settings.Save(); ThemeManager.Instance.ChangeTheme(_settings.Theme); } @@ -528,7 +512,6 @@ namespace Wox _settings.ResultFontStretch = typeface.Stretch.ToString(); _settings.ResultFontWeight = typeface.Weight.ToString(); _settings.ResultFontStyle = typeface.Style.ToString(); - _settings.Save(); ThemeManager.Instance.ChangeTheme(_settings.Theme); } } @@ -569,7 +552,7 @@ namespace Wox pluginId = pair.Metadata.ID; pluginIcon.Source = ImageLoader.ImageLoader.Load(pair.Metadata.FullIcoPath); - var customizedPluginConfig = _settings.CustomizedPluginConfigs[pluginId]; + var customizedPluginConfig = _settings.PluginSettings[pluginId]; cbDisablePlugin.IsChecked = customizedPluginConfig != null && customizedPluginConfig.Disabled; PluginContentPanel.Content = null; @@ -609,31 +592,19 @@ namespace Wox if (cbDisabled == null) return; var pair = lbPlugins.SelectedItem as PluginPair; - var id = string.Empty; - var name = string.Empty; if (pair != null) { - //third-party plugin - id = pair.Metadata.ID; - name = pair.Metadata.Name; - } - var customizedPluginConfig = _settings.CustomizedPluginConfigs[id]; - if (customizedPluginConfig == null) - { - // todo when this part will be invoked - _settings.CustomizedPluginConfigs[id] = new CustomizedPluginConfig + var id = pair.Metadata.ID; + var customizedPluginConfig = _settings.PluginSettings[id]; + if (customizedPluginConfig.Disabled) { - Disabled = cbDisabled.IsChecked ?? true, - ID = id, - Name = name, - ActionKeywords = null - }; + PluginManager.DisablePlugin(pair); + } + else + { + PluginManager.EnablePlugin(pair); + } } - else - { - customizedPluginConfig.Disabled = cbDisabled.IsChecked ?? true; - } - _settings.Save(); } private void PluginActionKeywords_OnMouseUp(object sender, MouseButtonEventArgs e) @@ -744,7 +715,6 @@ namespace Wox _settings.ProxyPort = port; _settings.ProxyUserName = tbProxyUserName.Text; _settings.ProxyPassword = tbProxyPassword.Password; - _settings.Save(); MessageBox.Show(InternationalizationManager.Instance.GetTranslation("saveProxySuccessfully")); } diff --git a/Wox/Storage/QueryHistoryStorage.cs b/Wox/Storage/QueryHistoryStorage.cs index 74ca3f1aa4..d66113fe7f 100644 --- a/Wox/Storage/QueryHistoryStorage.cs +++ b/Wox/Storage/QueryHistoryStorage.cs @@ -7,10 +7,9 @@ using Wox.Plugin; namespace Wox.Storage { - public class QueryHistoryStorage : JsonStrorage + public class QueryHistory { - [JsonProperty] - private List History = new List(); + public List History = new List(); private int MaxHistory = 300; private int cursor; @@ -18,8 +17,6 @@ namespace Wox.Storage public static PluginMetadata MetaData { get; } = new PluginMetadata { ID = "Query history", Name = "Query history" }; - protected override string FileName { get; } = "QueryHistory"; - public HistoryItem Previous() { if (History.Count == 0 || cursor == 0) return null; @@ -58,11 +55,6 @@ namespace Wox.Storage }); } - if (History.Count % 5 == 0) - { - Save(); - } - Reset(); } diff --git a/Wox/Storage/TopMostRecordStorage.cs b/Wox/Storage/TopMostRecordStorage.cs index aebaf54798..4d33f91ebb 100644 --- a/Wox/Storage/TopMostRecordStorage.cs +++ b/Wox/Storage/TopMostRecordStorage.cs @@ -5,11 +5,9 @@ using Wox.Plugin; namespace Wox.Storage { - public class TopMostRecordStorage : JsonStrorage + public class TopMostRecord { - public Dictionary records = new Dictionary(); - - protected override string FileName { get; } = "TopMostRecords"; + public Dictionary records = new Dictionary(); internal bool IsTopMost(Result result) { @@ -24,7 +22,6 @@ namespace Wox.Storage if (records.ContainsKey(result.OriginQuery.RawQuery)) { records.Remove(result.OriginQuery.RawQuery); - Save(); } } @@ -38,20 +35,18 @@ namespace Wox.Storage } else { - records.Add(result.OriginQuery.RawQuery, new TopMostRecord + records.Add(result.OriginQuery.RawQuery, new Record { PluginID = result.PluginID, Title = result.Title, SubTitle = result.SubTitle }); } - - Save(); } } - public class TopMostRecord + public class Record { public string Title { get; set; } public string SubTitle { get; set; } diff --git a/Wox/Storage/UserSelectedRecordStorage.cs b/Wox/Storage/UserSelectedRecordStorage.cs index 0d12826e4c..9005590410 100644 --- a/Wox/Storage/UserSelectedRecordStorage.cs +++ b/Wox/Storage/UserSelectedRecordStorage.cs @@ -5,13 +5,11 @@ using Wox.Plugin; namespace Wox.Storage { - public class UserSelectedRecordStorage : JsonStrorage + public class UserSelectedRecord { [JsonProperty] private Dictionary records = new Dictionary(); - protected override string FileName { get; } = "UserSelectedRecords"; - public void Add(Result result) { if (records.ContainsKey(result.ToString())) @@ -22,7 +20,6 @@ namespace Wox.Storage { records.Add(result.ToString(), 1); } - Save(); } public int GetSelectedCount(Result result) diff --git a/Wox/ViewModel/MainViewModel.cs b/Wox/ViewModel/MainViewModel.cs index bd44f5cd48..ed606ccad4 100644 --- a/Wox/ViewModel/MainViewModel.cs +++ b/Wox/ViewModel/MainViewModel.cs @@ -7,10 +7,12 @@ using System.Windows; using System.Windows.Input; using Wox.Core.Plugin; using Wox.Core.Resource; +using Wox.Core.Updater; using Wox.Core.UserSettings; using Wox.Helper; using Wox.Infrastructure; using Wox.Infrastructure.Hotkey; +using Wox.Infrastructure.Storage; using Wox.Plugin; using Wox.Storage; using Stopwatch = Wox.Infrastructure.Stopwatch; @@ -36,24 +38,41 @@ namespace Wox.ViewModel private string _queryTextBeforeLoadContextMenu; private string _queryText; - private UserSettingStorage _settings; - private QueryHistoryStorage _queryHistory; - private UserSelectedRecordStorage _userSelectedRecord; - private TopMostRecordStorage _topMostRecord; + private readonly JsonStrorage _settingsStorage; + private readonly JsonStrorage _queryHistoryStorage; + private readonly JsonStrorage _userSelectedRecordStorage; + private readonly JsonStrorage _topMostRecordStorage; + // todo happlebao this field should be private in the future + public readonly Settings _settings; + private readonly QueryHistory _queryHistory; + private readonly UserSelectedRecord _userSelectedRecord; + private readonly TopMostRecord _topMostRecord; #endregion #region Constructor - public MainViewModel(UserSettingStorage settings) + public MainViewModel() { _queryTextBeforeLoadContextMenu = ""; _queryText = ""; _lastQuery = new Query(); - _settings = settings; - _queryHistory = QueryHistoryStorage.Instance; - _userSelectedRecord = UserSelectedRecordStorage.Instance; - _topMostRecord = TopMostRecordStorage.Instance; + + _settingsStorage = new JsonStrorage(); + _settings = _settingsStorage.Load(); + + // happlebao todo temp fix for instance code logic + HttpProxy.Instance.Settings = _settings; + UpdaterManager.Instance.Settings = _settings; + InternationalizationManager.Instance.Settings = _settings; + ThemeManager.Instance.Settings = _settings; + + _queryHistoryStorage = new JsonStrorage(); + _userSelectedRecordStorage = new JsonStrorage(); + _topMostRecordStorage = new JsonStrorage(); + _queryHistory = _queryHistoryStorage.Load(); + _userSelectedRecord = _userSelectedRecordStorage.Load(); + _topMostRecord = _topMostRecordStorage.Load(); InitializeResultListBox(); InitializeContextMenu(); @@ -61,9 +80,12 @@ namespace Wox.ViewModel } - public MainViewModel() + ~MainViewModel() { - + _settingsStorage.Save(); + _queryHistoryStorage.Save(); + _userSelectedRecordStorage.Save(); + _topMostRecordStorage.Save(); } #endregion @@ -433,7 +455,7 @@ namespace Wox.ViewModel var plugins = PluginManager.ValidPluginsForQuery(query); foreach (var plugin in plugins) { - var config = _settings.CustomizedPluginConfigs[plugin.Metadata.ID]; + var config = _settings.PluginSettings[plugin.Metadata.ID]; if (!config.Disabled) { ThreadPool.QueueUserWorkItem(o => @@ -450,7 +472,7 @@ namespace Wox.ViewModel private void ResetQueryHistoryIndex() { - Results.RemoveResultsFor(QueryHistoryStorage.MetaData); + Results.RemoveResultsFor(QueryHistory.MetaData); _queryHistory.Reset(); } @@ -464,7 +486,7 @@ namespace Wox.ViewModel { if (history != null) { - var historyMetadata = QueryHistoryStorage.MetaData; + var historyMetadata = QueryHistory.MetaData; QueryText = history.Query; OnTextBoxSelected(); diff --git a/Wox/ViewModel/ResultViewModel.cs b/Wox/ViewModel/ResultViewModel.cs index 9cb32cfdd2..35fb206ff8 100644 --- a/Wox/ViewModel/ResultViewModel.cs +++ b/Wox/ViewModel/ResultViewModel.cs @@ -37,6 +37,25 @@ namespace Wox.ViewModel public string FullIcoPath => RawResult.FullIcoPath; + public string PluginID => RawResult.PluginID; + public int Score + { + get { return RawResult.Score; } + set { RawResult.Score = value; } + } + + public Query OriginQuery + { + get { return RawResult.OriginQuery; } + set { RawResult.OriginQuery = value; } + } + + public Func Action + { + get { return RawResult.Action; } + set { RawResult.Action = value; } + } + public bool IsSelected { get { return _isSelected; } @@ -51,10 +70,16 @@ namespace Wox.ViewModel #region Properties - public Result RawResult { get; } + internal Result RawResult { get; } #endregion + public void Update(ResultViewModel newResult) + { + RawResult.Score = newResult.RawResult.Score; + RawResult.OriginQuery = newResult.RawResult.OriginQuery; + } + public override bool Equals(object obj) { ResultViewModel r = obj as ResultViewModel; diff --git a/Wox/ViewModel/ResultsViewModel.cs b/Wox/ViewModel/ResultsViewModel.cs index c87a3110cb..cc5577b1b1 100644 --- a/Wox/ViewModel/ResultsViewModel.cs +++ b/Wox/ViewModel/ResultsViewModel.cs @@ -20,10 +20,10 @@ namespace Wox.ViewModel private Thickness _margin; private readonly object _resultsUpdateLock = new object(); - private UserSettingStorage _settings; - private TopMostRecordStorage _topMostRecord; + private Settings _settings; + private TopMostRecord _topMostRecord; - public ResultsViewModel(UserSettingStorage settings, TopMostRecordStorage topMostRecord) + public ResultsViewModel(Settings settings, TopMostRecord topMostRecord) { _settings = settings; _topMostRecord = topMostRecord; @@ -191,7 +191,7 @@ namespace Wox.ViewModel { lock (_resultsUpdateLock) { - Results.RemoveAll(r => r.RawResult.PluginID == metadata.ID); + Results.RemoveAll(r => r.PluginID == metadata.ID); } } @@ -202,7 +202,7 @@ namespace Wox.ViewModel var newResults = newRawResults.Select(r => new ResultViewModel(r)).ToList(); // todo use async to do new result calculation var resultsCopy = Results.ToList(); - var oldResults = resultsCopy.Where(r => r.RawResult.PluginID == resultId).ToList(); + var oldResults = resultsCopy.Where(r => r.PluginID == resultId).ToList(); // intersection of A (old results) and B (new newResults) var intersection = oldResults.Intersect(newResults).ToList(); // remove result of relative complement of B in A @@ -216,7 +216,7 @@ namespace Wox.ViewModel { if (IsTopMostResult(result.RawResult)) { - result.RawResult.Score = int.MaxValue; + result.Score = int.MaxValue; } } @@ -224,23 +224,26 @@ namespace Wox.ViewModel foreach (var commonResult in intersection) { int oldIndex = resultsCopy.IndexOf(commonResult); - int oldScore = resultsCopy[oldIndex].RawResult.Score; - int newScore = newResults[newResults.IndexOf(commonResult)].RawResult.Score; + int oldScore = resultsCopy[oldIndex].Score; + var newResult = newResults[newResults.IndexOf(commonResult)]; + int newScore = newResult.Score; if (newScore != oldScore) { var oldResult = resultsCopy[oldIndex]; - oldResult.RawResult.Score = newScore; + + oldResult.Score = newScore; + oldResult.OriginQuery = newResult.OriginQuery; + resultsCopy.RemoveAt(oldIndex); int newIndex = InsertIndexOf(newScore, resultsCopy); resultsCopy.Insert(newIndex, oldResult); - } } // insert result in relative complement of A in B foreach (var result in newResults.Except(intersection)) { - int newIndex = InsertIndexOf(result.RawResult.Score, resultsCopy); + int newIndex = InsertIndexOf(result.Score, resultsCopy); resultsCopy.Insert(newIndex, result); } @@ -299,9 +302,9 @@ namespace Wox.ViewModel { this[i] = newResult; } - else if (oldResult.RawResult.Score != newResult.RawResult.Score) + else if (oldResult.Score != newResult.Score) { - this[i].RawResult.Score = newResult.RawResult.Score; + this[i].Score = newResult.Score; } }