Merge pull request #469 from Wox-launcher/dev

Refactoring directory handling
Fix #353
This commit is contained in:
bao-qian 2016-01-08 02:23:04 +00:00
commit d676ecfaa8
99 changed files with 652 additions and 585 deletions

View file

@ -3,10 +3,10 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Windows.Forms; using System.Windows.Forms;
using WindowsInput; using WindowsInput;
using WindowsInput.Native; using WindowsInput.Native;
using Wox.Infrastructure;
using Wox.Infrastructure.Hotkey; using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
using Control = System.Windows.Controls.Control; using Control = System.Windows.Controls.Control;
@ -59,11 +59,11 @@ namespace Wox.Plugin.CMD
!results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase)) && !results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase)) &&
!results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase))).ToList(); !results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase))).ToList();
autocomplete.Sort(); autocomplete.Sort();
results.AddRange(autocomplete.ConvertAll(m => new Result() results.AddRange(autocomplete.ConvertAll(m => new Result
{ {
Title = m, Title = m,
IcoPath = "Images/cmd.png", IcoPath = "Images/cmd.png",
Action = (c) => Action = c =>
{ {
ExecuteCMD(m); ExecuteCMD(m);
return true; return true;
@ -96,7 +96,7 @@ namespace Wox.Plugin.CMD
Title = m.Key, Title = m.Key,
SubTitle = string.Format(context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value), SubTitle = string.Format(context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
IcoPath = "Images/cmd.png", IcoPath = "Images/cmd.png",
Action = (c) => Action = c =>
{ {
ExecuteCMD(m.Key); ExecuteCMD(m.Key);
return true; return true;
@ -115,7 +115,7 @@ namespace Wox.Plugin.CMD
Score = 5000, Score = 5000,
SubTitle = context.API.GetTranslation("wox_plugin_cmd_execute_through_shell"), SubTitle = context.API.GetTranslation("wox_plugin_cmd_execute_through_shell"),
IcoPath = "Images/cmd.png", IcoPath = "Images/cmd.png",
Action = (c) => Action = c =>
{ {
ExecuteCMD(cmd); ExecuteCMD(cmd);
return true; return true;
@ -133,7 +133,7 @@ namespace Wox.Plugin.CMD
Title = m.Key, Title = m.Key,
SubTitle = string.Format(context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value), SubTitle = string.Format(context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
IcoPath = "Images/cmd.png", IcoPath = "Images/cmd.png",
Action = (c) => Action = c =>
{ {
ExecuteCMD(m.Key); ExecuteCMD(m.Key);
return true; return true;
@ -202,7 +202,7 @@ namespace Wox.Plugin.CMD
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()
@ -219,9 +219,9 @@ namespace Wox.Plugin.CMD
public List<Result> LoadContextMenus(Result selectedResult) public List<Result> LoadContextMenus(Result selectedResult)
{ {
return new List<Result>() return new List<Result>
{ {
new Result() new Result
{ {
Title = context.API.GetTranslation("wox_plugin_cmd_run_as_administrator"), Title = context.API.GetTranslation("wox_plugin_cmd_run_as_administrator"),
Action = c => Action = c =>

View file

@ -1,6 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
@ -17,15 +15,7 @@ namespace Wox.Plugin.CMD
[JsonProperty] [JsonProperty]
public Dictionary<string, int> CMDHistory = new Dictionary<string, int>(); public Dictionary<string, int> CMDHistory = new Dictionary<string, int>();
protected override string ConfigFolder protected override string FileName { get; } = "CMDHistory";
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override string ConfigName
{
get { return "CMDHistory"; }
}
protected override CMDStorage LoadDefault() protected override CMDStorage LoadDefault()
{ {

View file

@ -1,8 +1,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Runtime.InteropServices;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Windows; using System.Windows;
using Wox.Infrastructure;
using YAMP; using YAMP;
namespace Wox.Plugin.Caculator namespace Wox.Plugin.Caculator
@ -18,7 +19,7 @@ namespace Wox.Plugin.Caculator
@"[ei]|[0-9]|[\+\-\*\/\^\., ""]|[\(\)\|\!\[\]]" + @"[ei]|[0-9]|[\+\-\*\/\^\., ""]|[\(\)\|\!\[\]]" +
@")+$", RegexOptions.Compiled); @")+$", RegexOptions.Compiled);
private static Regex regBrackets = new Regex(@"[\(\)\[\]]", RegexOptions.Compiled); private static Regex regBrackets = new Regex(@"[\(\)\[\]]", RegexOptions.Compiled);
private static ParseContext yampContext = null; private static ParseContext yampContext;
private PluginInitContext context { get; set; } private PluginInitContext context { get; set; }
static Calculator() static Calculator()
@ -39,19 +40,21 @@ namespace Wox.Plugin.Caculator
var result = yampContext.Run(query.Search); var result = yampContext.Run(query.Search);
if (result.Output != null && !string.IsNullOrEmpty(result.Result)) if (result.Output != null && !string.IsNullOrEmpty(result.Result))
{ {
return new List<Result>() { new Result() { return new List<Result>
{ new Result
{
Title = result.Result, Title = result.Result,
IcoPath = "Images/calculator.png", IcoPath = "Images/calculator.png",
Score = 300, Score = 300,
SubTitle = "Copy this number to the clipboard", SubTitle = "Copy this number to the clipboard",
Action = (c) => Action = c =>
{ {
try try
{ {
Clipboard.SetText(result.Result); Clipboard.SetText(result.Result);
return true; return true;
} }
catch (System.Runtime.InteropServices.ExternalException e) catch (ExternalException e)
{ {
MessageBox.Show("Copy failed, please try later"); MessageBox.Show("Copy failed, please try later");
return false; return false;
@ -92,7 +95,8 @@ namespace Wox.Plugin.Caculator
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -57,6 +57,10 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Wox.Infrastructure\Wox.Infrastructure.csproj">
<Project>{4FD29318-A8AB-4D8F-AA47-60BC241B8DA3}</Project>
<Name>Wox.Infrastructure</Name>
</ProjectReference>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj"> <ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj">
<Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project> <Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project>
<Name>Wox.Plugin</Name> <Name>Wox.Plugin</Name>

View file

@ -4,8 +4,8 @@ using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Windows; using System.Windows;
using Wox.Infrastructure;
namespace Wox.Plugin.Color namespace Wox.Plugin.Color
{ {
@ -111,7 +111,7 @@ namespace Wox.Plugin.Color
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -55,6 +55,10 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Wox.Infrastructure\Wox.Infrastructure.csproj">
<Project>{4FD29318-A8AB-4D8F-AA47-60BC241B8DA3}</Project>
<Name>Wox.Infrastructure</Name>
</ProjectReference>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj"> <ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj">
<Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project> <Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project>
<Name>Wox.Plugin</Name> <Name>Wox.Plugin</Name>

View file

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using Wox.Infrastructure; using Wox.Infrastructure;
namespace Wox.Plugin.ControlPanel namespace Wox.Plugin.ControlPanel
@ -47,7 +46,7 @@ namespace Wox.Plugin.ControlPanel
var fuzzyMather = FuzzyMatcher.Create(myQuery); var fuzzyMather = FuzzyMatcher.Create(myQuery);
if (MatchProgram(item, fuzzyMather)) if (MatchProgram(item, fuzzyMather))
{ {
results.Add(new Result() results.Add(new Result
{ {
Title = item.LocalizedString, Title = item.LocalizedString,
SubTitle = item.InfoTip, SubTitle = item.InfoTip,
@ -85,7 +84,7 @@ namespace Wox.Plugin.ControlPanel
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -123,7 +123,7 @@ namespace Wox.Plugin.ControlPanel
if (currentKey.GetValue("LocalizedString") != null) if (currentKey.GetValue("LocalizedString") != null)
{ {
localizedStringRaw = currentKey.GetValue("LocalizedString").ToString().Split(new string[] { ",-" }, StringSplitOptions.None); localizedStringRaw = currentKey.GetValue("LocalizedString").ToString().Split(new[] { ",-" }, StringSplitOptions.None);
if (localizedStringRaw.Length > 1) if (localizedStringRaw.Length > 1)
{ {
@ -184,7 +184,7 @@ namespace Wox.Plugin.ControlPanel
if (currentKey.GetValue("InfoTip") != null) if (currentKey.GetValue("InfoTip") != null)
{ {
infoTipRaw = currentKey.GetValue("InfoTip").ToString().Split(new string[] { ",-" }, StringSplitOptions.None); infoTipRaw = currentKey.GetValue("InfoTip").ToString().Split(new[] { ",-" }, StringSplitOptions.None);
if (infoTipRaw.Length == 2) if (infoTipRaw.Length == 2)
{ {
@ -229,7 +229,7 @@ namespace Wox.Plugin.ControlPanel
{ {
if (currentKey.OpenSubKey("DefaultIcon").GetValue(null) != null) if (currentKey.OpenSubKey("DefaultIcon").GetValue(null) != null)
{ {
iconString = new List<string>(currentKey.OpenSubKey("DefaultIcon").GetValue(null).ToString().Split(new char[] { ',' }, 2)); iconString = new List<string>(currentKey.OpenSubKey("DefaultIcon").GetValue(null).ToString().Split(new[] { ',' }, 2));
if (iconString[0][0] == '@') if (iconString[0][0] == '@')
{ {
iconString[0] = iconString[0].Substring(1); iconString[0] = iconString[0].Substring(1);
@ -247,7 +247,7 @@ namespace Wox.Plugin.ControlPanel
if (iconPtr == IntPtr.Zero) if (iconPtr == IntPtr.Zero)
{ {
defaultIconPtr = IntPtr.Zero; defaultIconPtr = IntPtr.Zero;
EnumResourceNamesWithID(dataFilePointer, GROUP_ICON, new EnumResNameDelegate(EnumRes), IntPtr.Zero); //Iterate through resources. EnumResourceNamesWithID(dataFilePointer, GROUP_ICON, EnumRes, IntPtr.Zero); //Iterate through resources.
iconPtr = LoadImage(dataFilePointer, defaultIconPtr, 1, iconSize, iconSize, 0); iconPtr = LoadImage(dataFilePointer, defaultIconPtr, 1, iconSize, iconSize, 0);
} }
@ -312,16 +312,16 @@ namespace Wox.Plugin.ControlPanel
private static uint GET_RESOURCE_ID(IntPtr value) private static uint GET_RESOURCE_ID(IntPtr value)
{ {
if (IS_INTRESOURCE(value) == true) if (IS_INTRESOURCE(value))
return (uint)value; return (uint)value;
throw new System.NotSupportedException("value is not an ID!"); throw new NotSupportedException("value is not an ID!");
} }
private static string GET_RESOURCE_NAME(IntPtr value) private static string GET_RESOURCE_NAME(IntPtr value)
{ {
if (IS_INTRESOURCE(value) == true) if (IS_INTRESOURCE(value))
return value.ToString(); return value.ToString();
return Marshal.PtrToStringUni((IntPtr)value); return Marshal.PtrToStringUni(value);
} }
private static bool EnumRes(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam) private static bool EnumRes(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam)

View file

@ -1,6 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
using JsonProperty = Newtonsoft.Json.JsonPropertyAttribute; using JsonProperty = Newtonsoft.Json.JsonPropertyAttribute;
@ -15,15 +13,7 @@ namespace Wox.Plugin.Everything
public IPublicAPI API { get; set; } public IPublicAPI API { get; set; }
protected override string ConfigName protected override string FileName { get; } = "EverythingContextMenu";
{
get { return "EverythingContextMenu"; }
}
protected override string ConfigFolder
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override void OnAfterLoad(ContextMenuStorage obj) protected override void OnAfterLoad(ContextMenuStorage obj)
{ {

View file

@ -233,7 +233,7 @@ namespace Wox.Plugin.Everything.Everything
{ {
Everything_GetResultFullPathName(idx, buffer, bufferSize); Everything_GetResultFullPathName(idx, buffer, bufferSize);
var result = new SearchResult() { FullPath = buffer.ToString() }; var result = new SearchResult { FullPath = buffer.ToString() };
if (Everything_IsFolderResult(idx)) if (Everything_IsFolderResult(idx))
result.Type = ResultType.Folder; result.Type = ResultType.Folder;
else if (Everything_IsFileResult(idx)) else if (Everything_IsFileResult(idx))

View file

@ -3,18 +3,20 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Runtime.InteropServices;
using System.ServiceProcess; using System.ServiceProcess;
using System.Windows;
using Wox.Infrastructure;
using Wox.Plugin.Everything.Everything; using Wox.Plugin.Everything.Everything;
namespace Wox.Plugin.Everything namespace Wox.Plugin.Everything
{ {
public class Main : IPlugin, IPluginI18n, IContextMenu public class Main : IPlugin, IPluginI18n, IContextMenu
{ {
PluginInitContext context; private PluginInitContext _context;
EverythingAPI api = new EverythingAPI(); private readonly EverythingAPI _api = new EverythingAPI();
private static List<string> imageExts = new List<string>() { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".ico" }; private static readonly List<string> ImageExts = new List<string> { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".ico" };
private static List<string> executableExts = new List<string>() { ".exe" }; private static readonly List<string> ExecutableExts = new List<string> { ".exe" };
public List<Result> Query(Query query) public List<Result> Query(Query query)
{ {
@ -34,7 +36,7 @@ namespace Wox.Plugin.Everything
r.Title = "Uninstall Everything"; r.Title = "Uninstall Everything";
r.SubTitle = "You need to uninstall everything service if you can not move/delete wox folder"; r.SubTitle = "You need to uninstall everything service if you can not move/delete wox folder";
r.IcoPath = "Images\\find.png"; r.IcoPath = "Images\\find.png";
r.Action = (c) => r.Action = c =>
{ {
UnInstallEverything(); UnInstallEverything();
return true; return true;
@ -45,7 +47,7 @@ namespace Wox.Plugin.Everything
try try
{ {
var searchList = api.Search(keyword, maxCount: ContextMenuStorage.Instance.MaxSearchCount).ToList(); var searchList = _api.Search(keyword, maxCount: ContextMenuStorage.Instance.MaxSearchCount).ToList();
foreach (var s in searchList) foreach (var s in searchList)
{ {
var path = s.FullPath; var path = s.FullPath;
@ -53,9 +55,9 @@ namespace Wox.Plugin.Everything
r.Title = Path.GetFileName(path); r.Title = Path.GetFileName(path);
r.SubTitle = path; r.SubTitle = path;
r.IcoPath = GetIconPath(s); r.IcoPath = GetIconPath(s);
r.Action = (c) => r.Action = c =>
{ {
context.API.HideApp(); _context.API.HideApp();
Process.Start(new ProcessStartInfo Process.Start(new ProcessStartInfo
{ {
FileName = path, FileName = path,
@ -70,22 +72,22 @@ namespace Wox.Plugin.Everything
catch (IPCErrorException) catch (IPCErrorException)
{ {
StartEverything(); StartEverything();
results.Add(new Result() results.Add(new Result
{ {
Title = context.API.GetTranslation("wox_plugin_everything_is_not_running"), Title = _context.API.GetTranslation("wox_plugin_everything_is_not_running"),
IcoPath = "Images\\warning.png" IcoPath = "Images\\warning.png"
}); });
} }
catch (Exception e) catch (Exception e)
{ {
results.Add(new Result() results.Add(new Result
{ {
Title = context.API.GetTranslation("wox_plugin_everything_query_error"), Title = _context.API.GetTranslation("wox_plugin_everything_query_error"),
SubTitle = e.Message, SubTitle = e.Message,
Action = _ => Action = _ =>
{ {
System.Windows.Clipboard.SetText(e.Message + "\r\n" + e.StackTrace); Clipboard.SetText(e.Message + "\r\n" + e.StackTrace);
context.API.ShowMsg(context.API.GetTranslation("wox_plugin_everything_copied"), null, string.Empty); _context.API.ShowMsg(_context.API.GetTranslation("wox_plugin_everything_copied"), null, string.Empty);
return false; return false;
}, },
IcoPath = "Images\\error.png" IcoPath = "Images\\error.png"
@ -93,7 +95,7 @@ namespace Wox.Plugin.Everything
} }
} }
api.Reset(); _api.Reset();
return results; return results;
} }
@ -107,11 +109,11 @@ namespace Wox.Plugin.Everything
} }
else if (!string.IsNullOrEmpty(ext)) else if (!string.IsNullOrEmpty(ext))
{ {
if (imageExts.Contains(ext.ToLower())) if (ImageExts.Contains(ext.ToLower()))
{ {
return "Images\\image.png"; return "Images\\image.png";
} }
else if (executableExts.Contains(ext.ToLower())) else if (ExecutableExts.Contains(ext.ToLower()))
{ {
return s.FullPath; return s.FullPath;
} }
@ -120,15 +122,15 @@ namespace Wox.Plugin.Everything
return "Images\\file.png"; return "Images\\file.png";
} }
[System.Runtime.InteropServices.DllImport("kernel32.dll")] [DllImport("kernel32.dll")]
private static extern int LoadLibrary(string name); private static extern int LoadLibrary(string name);
private List<ContextMenu> GetDefaultContextMenu() private List<ContextMenu> GetDefaultContextMenu()
{ {
List<ContextMenu> defaultContextMenus = new List<ContextMenu>(); List<ContextMenu> defaultContextMenus = new List<ContextMenu>();
ContextMenu openFolderContextMenu = new ContextMenu() ContextMenu openFolderContextMenu = new ContextMenu
{ {
Name = context.API.GetTranslation("wox_plugin_everything_open_containing_folder"), Name = _context.API.GetTranslation("wox_plugin_everything_open_containing_folder"),
Command = "explorer.exe", Command = "explorer.exe",
Argument = " /select,\"{path}\"", Argument = " /select,\"{path}\"",
ImagePath = "Images\\folder.png" ImagePath = "Images\\folder.png"
@ -140,7 +142,7 @@ namespace Wox.Plugin.Everything
public void Init(PluginInitContext context) public void Init(PluginInitContext context)
{ {
this.context = context; _context = context;
ContextMenuStorage.Instance.API = context.API; ContextMenuStorage.Instance.API = context.API;
LoadLibrary(Path.Combine( LoadLibrary(Path.Combine(
@ -223,7 +225,7 @@ namespace Wox.Plugin.Everything
} }
catch (Exception e) catch (Exception e)
{ {
context.API.ShowMsg("Start Everything failed"); _context.API.ShowMsg("Start Everything failed");
} }
} }
@ -248,23 +250,25 @@ namespace Wox.Plugin.Everything
private string GetEverythingPath() private string GetEverythingPath()
{ {
string everythingFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "PortableEverything"); string directory = Path.Combine(_context.CurrentPluginMetadata.PluginDirectory,
return Path.Combine(everythingFolder, "Everything.exe"); "PortableEverything",
"Everything.exe");
return directory;
} }
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()
{ {
return context.API.GetTranslation("wox_plugin_everything_plugin_name"); return _context.API.GetTranslation("wox_plugin_everything_plugin_name");
} }
public string GetTranslatedPluginDescription() public string GetTranslatedPluginDescription()
{ {
return context.API.GetTranslation("wox_plugin_everything_plugin_description"); return _context.API.GetTranslation("wox_plugin_everything_plugin_description");
} }
public List<Result> LoadContextMenus(Result selectedResult) public List<Result> LoadContextMenus(Result selectedResult)
@ -282,7 +286,7 @@ namespace Wox.Plugin.Everything
foreach (ContextMenu contextMenu in availableContextMenus) foreach (ContextMenu contextMenu in availableContextMenus)
{ {
var menu = contextMenu; var menu = contextMenu;
contextMenus.Add(new Result() contextMenus.Add(new Result
{ {
Title = contextMenu.Name, Title = contextMenu.Name,
Action = _ => Action = _ =>
@ -294,7 +298,7 @@ namespace Wox.Plugin.Everything
} }
catch catch
{ {
context.API.ShowMsg(string.Format(context.API.GetTranslation("wox_plugin_everything_canot_start"), record.FullPath), string.Empty, string.Empty); _context.API.ShowMsg(string.Format(_context.API.GetTranslation("wox_plugin_everything_canot_start"), record.FullPath), string.Empty, string.Empty);
return false; return false;
} }
return true; return true;

View file

@ -12,7 +12,7 @@ namespace Wox.Plugin.Folder
public string Nickname public string Nickname
{ {
get { return Path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.None).Last(); } get { return Path.Split(new[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.None).Last(); }
} }
} }
} }

View file

@ -3,9 +3,9 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using Wox.Infrastructure;
namespace Wox.Plugin.Folder namespace Wox.Plugin.Folder
{ {
@ -51,7 +51,7 @@ namespace Wox.Plugin.Folder
{ {
List<Result> contextMenus = new List<Result>(); List<Result> contextMenus = new List<Result>();
string folderPath = ((FolderLink) targetResult.ContextData).Path; string folderPath = ((FolderLink) targetResult.ContextData).Path;
contextMenus.Add(new Result() contextMenus.Add(new Result
{ {
Title = "Copy to this folder", Title = "Copy to this folder",
IcoPath = "Images/copy.png", IcoPath = "Images/copy.png",
@ -246,7 +246,7 @@ namespace Wox.Plugin.Folder
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -1,7 +1,11 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Forms; using System.Windows.Forms;
using DataFormats = System.Windows.DataFormats;
using DragDropEffects = System.Windows.DragDropEffects;
using DragEventArgs = System.Windows.DragEventArgs;
using MessageBox = System.Windows.MessageBox; using MessageBox = System.Windows.MessageBox;
using UserControl = System.Windows.Controls.UserControl; using UserControl = System.Windows.Controls.UserControl;
@ -66,10 +70,10 @@ namespace Wox.Plugin.Folder
private void btnAdd_Click(object sender, RoutedEventArgs e) private void btnAdd_Click(object sender, RoutedEventArgs e)
{ {
var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); var folderBrowserDialog = new FolderBrowserDialog();
if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{ {
var newFolder = new FolderLink() var newFolder = new FolderLink
{ {
Path = folderBrowserDialog.SelectedPath Path = folderBrowserDialog.SelectedPath
}; };
@ -86,9 +90,9 @@ namespace Wox.Plugin.Folder
lbxFolders.Items.Refresh(); lbxFolders.Items.Refresh();
} }
private void lbxFolders_Drop(object sender, System.Windows.DragEventArgs e) private void lbxFolders_Drop(object sender, DragEventArgs e)
{ {
string[] files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop); string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Count() > 0) if (files != null && files.Count() > 0)
{ {
@ -99,9 +103,9 @@ namespace Wox.Plugin.Folder
foreach (string s in files) foreach (string s in files)
{ {
if (System.IO.Directory.Exists(s) == true) if (Directory.Exists(s))
{ {
var newFolder = new FolderLink() var newFolder = new FolderLink
{ {
Path = s Path = s
}; };
@ -115,15 +119,15 @@ namespace Wox.Plugin.Folder
} }
} }
private void lbxFolders_DragEnter(object sender, System.Windows.DragEventArgs e) private void lbxFolders_DragEnter(object sender, DragEventArgs e)
{ {
if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop)) if (e.Data.GetDataPresent(DataFormats.FileDrop))
{ {
e.Effects = System.Windows.DragDropEffects.Link; e.Effects = DragDropEffects.Link;
} }
else else
{ {
e.Effects = System.Windows.DragDropEffects.None; e.Effects = DragDropEffects.None;
} }
} }
} }

View file

@ -1,6 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
@ -10,14 +8,7 @@ namespace Wox.Plugin.Folder
{ {
[JsonProperty] [JsonProperty]
public List<FolderLink> FolderLinks { get; set; } public List<FolderLink> FolderLinks { get; set; }
protected override string ConfigFolder
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override string ConfigName protected override string FileName { get; } = "settings_folder_plugin";
{
get { return "setting"; }
}
} }
} }

View file

@ -1,9 +1,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure;
namespace Wox.Plugin.PluginIndicator namespace Wox.Plugin.PluginIndicator
{ {
@ -25,11 +25,11 @@ namespace Wox.Plugin.PluginIndicator
SubTitle = $"Activate {metadata.Name} plugin", SubTitle = $"Activate {metadata.Name} plugin",
Score = 100, Score = 100,
IcoPath = metadata.FullIcoPath, IcoPath = metadata.FullIcoPath,
Action = (c) => Action = c =>
{ {
context.API.ChangeQuery($"{keyword}{Plugin.Query.TermSeperater}"); context.API.ChangeQuery($"{keyword}{Plugin.Query.TermSeperater}");
return false; return false;
}, }
}; };
return results.ToList(); return results.ToList();
} }
@ -41,7 +41,7 @@ namespace Wox.Plugin.PluginIndicator
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -3,11 +3,11 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Windows; using System.Windows;
using Newtonsoft.Json; using Newtonsoft.Json;
using Wox.Infrastructure;
namespace Wox.Plugin.PluginManagement namespace Wox.Plugin.PluginManagement
{ {
@ -244,7 +244,7 @@ namespace Wox.Plugin.PluginManagement
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -55,6 +55,10 @@
<Compile Include="WoxPluginResult.cs" /> <Compile Include="WoxPluginResult.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Wox.Infrastructure\Wox.Infrastructure.csproj">
<Project>{4FD29318-A8AB-4D8F-AA47-60BC241B8DA3}</Project>
<Name>Wox.Infrastructure</Name>
</ProjectReference>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj"> <ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj">
<Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project> <Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project>
<Name>Wox.Plugin</Name> <Name>Wox.Plugin</Name>

View file

@ -1,4 +1,5 @@
using System.Windows; using System.Windows;
using System.Windows.Forms;
namespace Wox.Plugin.Program namespace Wox.Plugin.Program
{ {
@ -16,51 +17,51 @@ namespace Wox.Plugin.Program
public AddProgramSource(ProgramSource edit) : this() public AddProgramSource(ProgramSource edit) : this()
{ {
this._editing = edit; _editing = edit;
this.Directory.Text = this._editing.Location; Directory.Text = _editing.Location;
this.MaxDepth.Text = this._editing.MaxDepth.ToString(); MaxDepth.Text = _editing.MaxDepth.ToString();
this.Suffixes.Text = this._editing.Suffixes; Suffixes.Text = _editing.Suffixes;
} }
private void BrowseButton_Click(object sender, RoutedEventArgs e) private void BrowseButton_Click(object sender, RoutedEventArgs e)
{ {
var dialog = new System.Windows.Forms.FolderBrowserDialog(); var dialog = new FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog(); DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK) if (result == System.Windows.Forms.DialogResult.OK)
{ {
this.Directory.Text = dialog.SelectedPath; Directory.Text = dialog.SelectedPath;
} }
} }
private void ButtonAdd_OnClick(object sender, RoutedEventArgs e) private void ButtonAdd_OnClick(object sender, RoutedEventArgs e)
{ {
int max; int max;
if(!int.TryParse(this.MaxDepth.Text, out max)) if(!int.TryParse(MaxDepth.Text, out max))
{ {
max = -1; max = -1;
} }
if(this._editing == null) if(_editing == null)
{ {
ProgramStorage.Instance.ProgramSources.Add(new ProgramSource() ProgramStorage.Instance.ProgramSources.Add(new ProgramSource
{ {
Location = this.Directory.Text, Location = Directory.Text,
MaxDepth = max, MaxDepth = max,
Suffixes = this.Suffixes.Text, Suffixes = Suffixes.Text,
Type = "FileSystemProgramSource", Type = "FileSystemProgramSource",
Enabled = true Enabled = true
}); });
} }
else else
{ {
this._editing.Location = this.Directory.Text; _editing.Location = Directory.Text;
this._editing.MaxDepth = max; _editing.MaxDepth = max;
this._editing.Suffixes = this.Suffixes.Text; _editing.Suffixes = Suffixes.Text;
} }
ProgramStorage.Instance.Save(); ProgramStorage.Instance.Save();
this.DialogResult = true; DialogResult = true;
this.Close(); Close();
} }
} }
} }

View file

@ -7,7 +7,7 @@ namespace Wox.Plugin.Program
{ {
internal class FileChangeWatcher internal class FileChangeWatcher
{ {
private static bool isIndexing = false; private static bool isIndexing;
private static List<string> watchedPath = new List<string>(); private static List<string> watchedPath = new List<string>();
public static void AddWatch(string path, bool includingSubDirectory = true) public static void AddWatch(string path, bool includingSubDirectory = true)

View file

@ -23,7 +23,7 @@ namespace Wox.Plugin.Program
protected Program CreateEntry(string file) protected Program CreateEntry(string file)
{ {
var p = new Program() var p = new Program
{ {
Title = Path.GetFileNameWithoutExtension(file), Title = Path.GetFileNameWithoutExtension(file),
IcoPath = file, IcoPath = file,

View file

@ -1,4 +1,6 @@
using System; using System;
using System.Text.RegularExpressions;
using System.Threading;
using Wox.Infrastructure; using Wox.Infrastructure;
namespace Wox.Plugin.Program namespace Wox.Plugin.Program
@ -6,7 +8,7 @@ namespace Wox.Plugin.Program
[Serializable] [Serializable]
public class Program public class Program
{ {
private static readonly global::System.Text.RegularExpressions.Regex AbbrRegexp = new global::System.Text.RegularExpressions.Regex("[^A-Z0-9]", global::System.Text.RegularExpressions.RegexOptions.Compiled); private static readonly Regex AbbrRegexp = new Regex("[^A-Z0-9]", RegexOptions.Compiled);
private string m_Title; private string m_Title;
public string Title public string Title
{ {
@ -19,7 +21,7 @@ namespace Wox.Plugin.Program
m_Title = value; m_Title = value;
string pinyin = m_Title.Unidecode(); string pinyin = m_Title.Unidecode();
PinyinTitle = pinyin; PinyinTitle = pinyin;
AbbrTitle = AbbrRegexp.Replace(global::System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(pinyin), ""); AbbrTitle = AbbrRegexp.Replace(Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(pinyin), "");
if (AbbrTitle.Length < 2) AbbrTitle = null; if (AbbrTitle.Length < 2) AbbrTitle = null;
} }
} }

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
namespace Wox.Plugin.Program namespace Wox.Plugin.Program
@ -11,14 +9,6 @@ namespace Wox.Plugin.Program
{ {
public List<Program> Programs = new List<Program>(); public List<Program> Programs = new List<Program>();
protected override string ConfigFolder protected override string FileName { get; } = "ProgramIndexCache";
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override string ConfigName
{
get { return "ProgramIndexCache"; }
}
} }
} }

View file

@ -1,4 +1,4 @@
using System; using System.IO;
using System.Threading; using System.Threading;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
@ -31,9 +31,9 @@ namespace Wox.Plugin.Program
programSourceView.Items.Refresh(); programSourceView.Items.Refresh();
ThreadPool.QueueUserWorkItem(t => ThreadPool.QueueUserWorkItem(t =>
{ {
Dispatcher.Invoke(new Action(() => { indexingPanel.Visibility = Visibility.Visible; })); Dispatcher.Invoke(() => { indexingPanel.Visibility = Visibility.Visible; });
Programs.IndexPrograms(); Programs.IndexPrograms();
Dispatcher.Invoke(new Action(() => { indexingPanel.Visibility = Visibility.Hidden; })); Dispatcher.Invoke(() => { indexingPanel.Visibility = Visibility.Hidden; });
}); });
} }
@ -42,7 +42,7 @@ namespace Wox.Plugin.Program
var add = new AddProgramSource(); var add = new AddProgramSource();
if(add.ShowDialog() ?? false) if(add.ShowDialog() ?? false)
{ {
this.ReIndexing(); ReIndexing();
} }
} }
@ -75,7 +75,7 @@ namespace Wox.Plugin.Program
var add = new AddProgramSource(selectedProgramSource); var add = new AddProgramSource(selectedProgramSource);
if (add.ShowDialog() ?? false) if (add.ShowDialog() ?? false)
{ {
this.ReIndexing(); ReIndexing();
} }
} }
else else
@ -116,9 +116,9 @@ namespace Wox.Plugin.Program
{ {
foreach (string s in files) foreach (string s in files)
{ {
if (System.IO.Directory.Exists(s) == true) if (Directory.Exists(s))
{ {
ProgramStorage.Instance.ProgramSources.Add(new ProgramSource() ProgramStorage.Instance.ProgramSources.Add(new ProgramSource
{ {
Location = s, Location = s,
Type = "FileSystemProgramSource", Type = "FileSystemProgramSource",

View file

@ -16,7 +16,7 @@ namespace Wox.Plugin.Program
public override string ToString() public override string ToString()
{ {
return (this.Type ?? "") + ":" + this.Location ?? ""; return (Type ?? "") + ":" + Location ?? "";
} }
} }
} }

View file

@ -1,11 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using Microsoft.Win32;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
namespace Wox.Plugin.Program.ProgramSources namespace Wox.Plugin.Program.ProgramSources
{ {
[Serializable] [Serializable]
[System.ComponentModel.Browsable(false)] [Browsable(false)]
public class AppPathsProgramSource : AbstractProgramSource public class AppPathsProgramSource : AbstractProgramSource
{ {
public AppPathsProgramSource() public AppPathsProgramSource()
@ -28,7 +31,7 @@ namespace Wox.Plugin.Program.ProgramSources
private void ReadAppPaths(string rootpath, List<Program> list) private void ReadAppPaths(string rootpath, List<Program> list)
{ {
using (var root = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(rootpath)) using (var root = Registry.LocalMachine.OpenSubKey(rootpath))
{ {
if (root == null) return; if (root == null) return;
foreach (var item in root.GetSubKeyNames()) foreach (var item in root.GetSubKeyNames())
@ -49,7 +52,7 @@ namespace Wox.Plugin.Program.ProgramSources
path = path.Substring(begin + 1, path.Length - 2); path = path.Substring(begin + 1, path.Length - 2);
} }
if (!System.IO.File.Exists(path)) continue; if (!File.Exists(path)) continue;
var entry = CreateEntry(path); var entry = CreateEntry(path);
entry.ExecuteName = item; entry.ExecuteName = item;
list.Add(entry); list.Add(entry);

View file

@ -1,11 +1,12 @@
using System; using System;
using System.ComponentModel;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace Wox.Plugin.Program.ProgramSources namespace Wox.Plugin.Program.ProgramSources
{ {
[Serializable] [Serializable]
[global::System.ComponentModel.Browsable(false)] [Browsable(false)]
public class CommonStartMenuProgramSource : FileSystemProgramSource public class CommonStartMenuProgramSource : FileSystemProgramSource
{ {
[DllImport("shell32.dll")] [DllImport("shell32.dll")]
@ -28,7 +29,7 @@ namespace Wox.Plugin.Program.ProgramSources
public CommonStartMenuProgramSource(ProgramSource source) public CommonStartMenuProgramSource(ProgramSource source)
: this() : this()
{ {
this.BonusPoints = source.BonusPoints; BonusPoints = source.BonusPoints;
} }
public override string ToString() public override string ToString()

View file

@ -27,7 +27,7 @@ namespace Wox.Plugin.Program.ProgramSources
public FileSystemProgramSource(ProgramSource source) public FileSystemProgramSource(ProgramSource source)
: this(source.Location, source.MaxDepth, source.Suffixes) : this(source.Location, source.MaxDepth, source.Suffixes)
{ {
this.BonusPoints = source.BonusPoints; BonusPoints = source.BonusPoints;
} }
public override List<Program> LoadPrograms() public override List<Program> LoadPrograms()
@ -78,7 +78,7 @@ namespace Wox.Plugin.Program.ProgramSources
public override string ToString() public override string ToString()
{ {
return typeof(FileSystemProgramSource).Name + ":" + this.baseDirectory; return typeof(FileSystemProgramSource).Name + ":" + baseDirectory;
} }
} }
} }

View file

@ -1,9 +1,10 @@
using System; using System;
using System.ComponentModel;
namespace Wox.Plugin.Program.ProgramSources namespace Wox.Plugin.Program.ProgramSources
{ {
[Serializable] [Serializable]
[global::System.ComponentModel.Browsable(false)] [Browsable(false)]
public class UserStartMenuProgramSource : FileSystemProgramSource public class UserStartMenuProgramSource : FileSystemProgramSource
{ {
public UserStartMenuProgramSource() public UserStartMenuProgramSource()
@ -14,7 +15,7 @@ namespace Wox.Plugin.Program.ProgramSources
public UserStartMenuProgramSource(ProgramSource source) public UserStartMenuProgramSource(ProgramSource source)
: this() : this()
{ {
this.BonusPoints = source.BonusPoints; BonusPoints = source.BonusPoints;
} }
public override string ToString() public override string ToString()

View file

@ -1,7 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.IO;
using System.Reflection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
@ -23,11 +21,6 @@ namespace Wox.Plugin.Program
[DefaultValue(true)] [DefaultValue(true)]
public bool EnableRegistrySource { get; set; } public bool EnableRegistrySource { get; set; }
protected override string ConfigFolder
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override ProgramStorage LoadDefault() protected override ProgramStorage LoadDefault()
{ {
ProgramSources = new List<ProgramSource>(); ProgramSources = new List<ProgramSource>();
@ -44,9 +37,6 @@ namespace Wox.Plugin.Program
} }
} }
protected override string ConfigName protected override string FileName { get; } = "settings_plugin_program";
{
get { return "setting"; }
}
} }
} }

View file

@ -5,6 +5,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using Wox.Infrastructure; using Wox.Infrastructure;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
using Wox.Plugin.Program.ProgramSources; using Wox.Plugin.Program.ProgramSources;
@ -17,11 +18,12 @@ namespace Wox.Plugin.Program
private static object lockObject = new object(); private static object lockObject = new object();
private static List<Program> programs = new List<Program>(); private static List<Program> programs = new List<Program>();
private static List<IProgramSource> sources = new List<IProgramSource>(); private static List<IProgramSource> sources = new List<IProgramSource>();
private static Dictionary<string, Type> SourceTypes = new Dictionary<string, Type>() { private static Dictionary<string, Type> SourceTypes = new Dictionary<string, Type>
{
{"FileSystemProgramSource", typeof(FileSystemProgramSource)}, {"FileSystemProgramSource", typeof(FileSystemProgramSource)},
{"CommonStartMenuProgramSource", typeof(CommonStartMenuProgramSource)}, {"CommonStartMenuProgramSource", typeof(CommonStartMenuProgramSource)},
{"UserStartMenuProgramSource", typeof(UserStartMenuProgramSource)}, {"UserStartMenuProgramSource", typeof(UserStartMenuProgramSource)},
{"AppPathsProgramSource", typeof(AppPathsProgramSource)}, {"AppPathsProgramSource", typeof(AppPathsProgramSource)}
}; };
private PluginInitContext context; private PluginInitContext context;
@ -32,14 +34,14 @@ namespace Wox.Plugin.Program
var results = programs.Where(p => MatchProgram(p, fuzzyMather)). var results = programs.Where(p => MatchProgram(p, fuzzyMather)).
Select(ScoreFilter). Select(ScoreFilter).
OrderByDescending(p => p.Score) OrderByDescending(p => p.Score)
.Select(c => new Result() .Select(c => new Result
{ {
Title = c.Title, Title = c.Title,
SubTitle = c.ExecutePath, SubTitle = c.ExecutePath,
IcoPath = c.IcoPath, IcoPath = c.IcoPath,
Score = c.Score, Score = c.Score,
ContextData = c, ContextData = c,
Action = (e) => Action = e =>
{ {
context.API.HideApp(); context.API.HideApp();
Process.Start(c.ExecutePath); Process.Start(c.ExecutePath);
@ -128,19 +130,19 @@ namespace Wox.Plugin.Program
private static List<ProgramSource> LoadDeaultProgramSources() private static List<ProgramSource> LoadDeaultProgramSources()
{ {
var list = new List<ProgramSource>(); var list = new List<ProgramSource>();
list.Add(new ProgramSource() list.Add(new ProgramSource
{ {
BonusPoints = 0, BonusPoints = 0,
Enabled = ProgramStorage.Instance.EnableStartMenuSource, Enabled = ProgramStorage.Instance.EnableStartMenuSource,
Type = "CommonStartMenuProgramSource" Type = "CommonStartMenuProgramSource"
}); });
list.Add(new ProgramSource() list.Add(new ProgramSource
{ {
BonusPoints = 0, BonusPoints = 0,
Enabled = ProgramStorage.Instance.EnableStartMenuSource, Enabled = ProgramStorage.Instance.EnableStartMenuSource,
Type = "UserStartMenuProgramSource" Type = "UserStartMenuProgramSource"
}); });
list.Add(new ProgramSource() list.Add(new ProgramSource
{ {
BonusPoints = -10, BonusPoints = -10,
Enabled = ProgramStorage.Instance.EnableRegistrySource, Enabled = ProgramStorage.Instance.EnableRegistrySource,
@ -166,7 +168,7 @@ namespace Wox.Plugin.Program
#region ISettingProvider Members #region ISettingProvider Members
public System.Windows.Controls.Control CreateSettingPanel() public Control CreateSettingPanel()
{ {
return new ProgramSetting(context); return new ProgramSetting(context);
} }
@ -175,7 +177,7 @@ namespace Wox.Plugin.Program
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()
{ {
@ -190,9 +192,9 @@ namespace Wox.Plugin.Program
public List<Result> LoadContextMenus(Result selectedResult) public List<Result> LoadContextMenus(Result selectedResult)
{ {
Program p = selectedResult.ContextData as Program; Program p = selectedResult.ContextData as Program;
List<Result> contextMenus = new List<Result>() List<Result> contextMenus = new List<Result>
{ {
new Result() new Result
{ {
Title = context.API.GetTranslation("wox_plugin_program_run_as_administrator"), Title = context.API.GetTranslation("wox_plugin_program_run_as_administrator"),
Action = _ => Action = _ =>
@ -207,7 +209,7 @@ namespace Wox.Plugin.Program
}, },
IcoPath = "Images/cmd.png" IcoPath = "Images/cmd.png"
}, },
new Result() new Result
{ {
Title = context.API.GetTranslation("wox_plugin_program_open_containing_folder"), Title = context.API.GetTranslation("wox_plugin_program_open_containing_folder"),
Action = _ => Action = _ =>

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Globalization;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Markup; using System.Windows.Markup;
@ -6,13 +7,13 @@ namespace Wox.Plugin.Program
{ {
public class StringEmptyConverter : MarkupExtension, IValueConverter public class StringEmptyConverter : MarkupExtension, IValueConverter
{ {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ {
return string.IsNullOrEmpty((string)value) ? parameter : value; return string.IsNullOrEmpty((string)value) ? parameter : value;
} }
public object ConvertBack( public object ConvertBack(
object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) object value, Type targetType, object parameter, CultureInfo culture)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }

View file

@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
using System.Windows.Forms; using System.Windows.Forms;
@ -76,14 +75,14 @@ namespace Wox.Plugin.Sys
private void LoadCommands() private void LoadCommands()
{ {
availableResults.AddRange(new Result[] availableResults.AddRange(new[]
{ {
new Result new Result
{ {
Title = "Shutdown", Title = "Shutdown",
SubTitle = context.API.GetTranslation("wox_plugin_sys_shutdown_computer"), SubTitle = context.API.GetTranslation("wox_plugin_sys_shutdown_computer"),
IcoPath = "Images\\exit.png", IcoPath = "Images\\exit.png",
Action = (c) => Action = c =>
{ {
var reuslt = MessageBox.Show("Are you sure you want to shut the computer down?", var reuslt = MessageBox.Show("Are you sure you want to shut the computer down?",
"Shutdown Computer?", MessageBoxButton.YesNo, MessageBoxImage.Warning); "Shutdown Computer?", MessageBoxButton.YesNo, MessageBoxImage.Warning);
@ -99,7 +98,7 @@ namespace Wox.Plugin.Sys
Title = "Restart", Title = "Restart",
SubTitle = context.API.GetTranslation("wox_plugin_sys_restart_computer"), SubTitle = context.API.GetTranslation("wox_plugin_sys_restart_computer"),
IcoPath = "Images\\restartcomp.png", IcoPath = "Images\\restartcomp.png",
Action = (c) => Action = c =>
{ {
var result = MessageBox.Show("Are you sure you want to restart the computer?", var result = MessageBox.Show("Are you sure you want to restart the computer?",
"Restart Computer?", MessageBoxButton.YesNo, MessageBoxImage.Warning); "Restart Computer?", MessageBoxButton.YesNo, MessageBoxImage.Warning);
@ -115,14 +114,14 @@ namespace Wox.Plugin.Sys
Title = "Log off", Title = "Log off",
SubTitle = context.API.GetTranslation("wox_plugin_sys_log_off"), SubTitle = context.API.GetTranslation("wox_plugin_sys_log_off"),
IcoPath = "Images\\logoff.png", IcoPath = "Images\\logoff.png",
Action = (c) => ExitWindowsEx(EWX_LOGOFF, 0) Action = c => ExitWindowsEx(EWX_LOGOFF, 0)
}, },
new Result new Result
{ {
Title = "Lock", Title = "Lock",
SubTitle = context.API.GetTranslation("wox_plugin_sys_lock"), SubTitle = context.API.GetTranslation("wox_plugin_sys_lock"),
IcoPath = "Images\\lock.png", IcoPath = "Images\\lock.png",
Action = (c) => Action = c =>
{ {
LockWorkStation(); LockWorkStation();
return true; return true;
@ -133,14 +132,14 @@ namespace Wox.Plugin.Sys
Title = "Sleep", Title = "Sleep",
SubTitle = context.API.GetTranslation("wox_plugin_sys_sleep"), SubTitle = context.API.GetTranslation("wox_plugin_sys_sleep"),
IcoPath = "Images\\sleep.png", IcoPath = "Images\\sleep.png",
Action = (c) => FormsApplication.SetSuspendState(PowerState.Suspend, false, false) Action = c => FormsApplication.SetSuspendState(PowerState.Suspend, false, false)
}, },
new Result new Result
{ {
Title = "Empty Recycle Bin", Title = "Empty Recycle Bin",
SubTitle = context.API.GetTranslation("wox_plugin_sys_emptyrecyclebin"), SubTitle = context.API.GetTranslation("wox_plugin_sys_emptyrecyclebin"),
IcoPath = "Images\\recyclebin.png", IcoPath = "Images\\recyclebin.png",
Action = (c) => Action = c =>
{ {
// http://www.pinvoke.net/default.aspx/shell32/SHEmptyRecycleBin.html // http://www.pinvoke.net/default.aspx/shell32/SHEmptyRecycleBin.html
// 0 for nothing // 0 for nothing
@ -160,7 +159,7 @@ namespace Wox.Plugin.Sys
Title = "Exit", Title = "Exit",
SubTitle = context.API.GetTranslation("wox_plugin_sys_exit"), SubTitle = context.API.GetTranslation("wox_plugin_sys_exit"),
IcoPath = "Images\\app.png", IcoPath = "Images\\app.png",
Action = (c) => Action = c =>
{ {
context.API.CloseApp(); context.API.CloseApp();
return true; return true;
@ -171,7 +170,7 @@ namespace Wox.Plugin.Sys
Title = "Restart Wox", Title = "Restart Wox",
SubTitle = context.API.GetTranslation("wox_plugin_sys_restart"), SubTitle = context.API.GetTranslation("wox_plugin_sys_restart"),
IcoPath = "Images\\restart.png", IcoPath = "Images\\restart.png",
Action = (c) => Action = c =>
{ {
context.API.RestarApp(); context.API.RestarApp();
return false; return false;
@ -182,7 +181,7 @@ namespace Wox.Plugin.Sys
Title = "Settings", Title = "Settings",
SubTitle = context.API.GetTranslation("wox_plugin_sys_setting"), SubTitle = context.API.GetTranslation("wox_plugin_sys_setting"),
IcoPath = "Images\\app.png", IcoPath = "Images\\app.png",
Action = (c) => Action = c =>
{ {
context.API.OpenSettingDialog(); context.API.OpenSettingDialog();
return true; return true;
@ -193,7 +192,7 @@ namespace Wox.Plugin.Sys
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -11,7 +11,7 @@ namespace Wox.Plugin.Sys
foreach (var Result in Results) foreach (var Result in Results)
{ {
this.lbxCommands.Items.Add(Result); lbxCommands.Items.Add(Result);
} }
} }
} }

View file

@ -2,8 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Reflection;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Wox.Infrastructure;
namespace Wox.Plugin.Url namespace Wox.Plugin.Url
{ {
@ -105,7 +105,7 @@ namespace Wox.Plugin.Url
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -49,6 +49,10 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Wox.Infrastructure\Wox.Infrastructure.csproj">
<Project>{4FD29318-A8AB-4D8F-AA47-60BC241B8DA3}</Project>
<Name>Wox.Infrastructure</Name>
</ProjectReference>
<ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj"> <ProjectReference Include="..\..\Wox.Plugin\Wox.Plugin.csproj">
<Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project> <Project>{8451ecdd-2ea4-4966-bb0a-7bbc40138e80}</Project>
<Name>Wox.Plugin</Name> <Name>Wox.Plugin</Name>

View file

@ -3,8 +3,8 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Windows.Controls; using System.Windows.Controls;
using Wox.Infrastructure;
using Wox.Plugin.WebSearch.Annotations; using Wox.Plugin.WebSearch.Annotations;
using Wox.Plugin.WebSearch.SuggestionSources; using Wox.Plugin.WebSearch.SuggestionSources;
@ -92,7 +92,7 @@ namespace Wox.Plugin.WebSearch
public string GetLanguagesFolder() public string GetLanguagesFolder()
{ {
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Languages"); return Path.Combine(WoxDirectroy.Executable, "Languages");
} }
public string GetTranslatedPluginTitle() public string GetTranslatedPluginTitle()

View file

@ -1,10 +1,10 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Windows; using System.Windows;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using Microsoft.Win32; using Microsoft.Win32;
using Wox.Infrastructure;
using Wox.Infrastructure.Exception; using Wox.Infrastructure.Exception;
namespace Wox.Plugin.WebSearch namespace Wox.Plugin.WebSearch
@ -12,7 +12,7 @@ namespace Wox.Plugin.WebSearch
public partial class WebSearchSetting : Window public partial class WebSearchSetting : Window
{ {
private const string _imageDirectoryName = "Images"; private const string _imageDirectoryName = "Images";
private string _pluginDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); private string _pluginDirectory = WoxDirectroy.Executable;
private readonly WebSearchesSetting _settingWindow; private readonly WebSearchesSetting _settingWindow;
private bool _isUpdate; private bool _isUpdate;
private WebSearch _updateWebSearch; private WebSearch _updateWebSearch;
@ -110,7 +110,7 @@ namespace Wox.Plugin.WebSearch
MessageBox.Show(exception.Message); MessageBox.Show(exception.Message);
return; return;
} }
WebSearchStorage.Instance.WebSearches.Add(new WebSearch() WebSearchStorage.Instance.WebSearches.Add(new WebSearch
{ {
ActionKeyword = newActionKeyword, ActionKeyword = newActionKeyword,
Enabled = cbEnable.IsChecked ?? false, Enabled = cbEnable.IsChecked ?? false,
@ -130,7 +130,7 @@ namespace Wox.Plugin.WebSearch
if (!Directory.Exists(_pluginDirectory)) if (!Directory.Exists(_pluginDirectory))
{ {
_pluginDirectory = _pluginDirectory =
Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); Path.GetDirectoryName(WoxDirectroy.Executable);
} }
var dlg = new OpenFileDialog var dlg = new OpenFileDialog

View file

@ -1,6 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
@ -17,14 +15,167 @@ namespace Wox.Plugin.WebSearch
[JsonProperty] [JsonProperty]
public string WebSearchSuggestionSource { get; set; } public string WebSearchSuggestionSource { get; set; }
protected override string ConfigFolder protected override string FileName { get; } = "settings_plugin_websearch";
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override string ConfigName protected override WebSearchStorage LoadDefault()
{ {
get { return "setting"; } WebSearches = new List<WebSearch>(new List<WebSearch>()
{
new WebSearch
{
Title = "Google",
ActionKeyword = "g",
IconPath = "Images\\google.png",
Url = "https://www.google.com/search?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Wikipedia",
ActionKeyword = "wiki",
IconPath = "Images\\wiki.png",
Url = "http://en.wikipedia.org/wiki/new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "FindIcon",
ActionKeyword = "findicon",
IconPath = "Images\\pictures.png",
Url = "http://findicons.com/search/new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Facebook",
ActionKeyword = "facebook",
IconPath = "Images\\facebook.png",
Url = "http://www.facebook.com/search/?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Twitter",
ActionKeyword = "twitter",
IconPath = "Images\\twitter.png",
Url = "http://twitter.com/search?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Google Maps",
ActionKeyword = "maps",
IconPath = "Images\\google_maps.png",
Url = "http://maps.google.com/maps?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Google Translate",
ActionKeyword = "translate",
IconPath = "Images\\google_translate.png",
Url = "http://translate.google.com/#auto|en|new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Duckduckgo",
ActionKeyword = "duckduckgo",
IconPath = "Images\\duckduckgo.png",
Url = "https://duckduckgo.com/?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Github",
ActionKeyword = "github",
IconPath = "Images\\github.png",
Url = "https://github.com/search?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Github Gist",
ActionKeyword = "gist",
IconPath = "Images\\gist.png",
Url = "https://gist.github.com/search?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Gmail",
ActionKeyword = "gmail",
IconPath = "Images\\gmail.png",
Url = "https://mail.google.com/mail/ca/u/0/#apps/new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Google Drive",
ActionKeyword = "drive",
IconPath = "Images\\google_drive.png",
Url = "http://drive.google.com/?hl=en&tab=bo#search/new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Wolframalpha",
ActionKeyword = "wolframalpha",
IconPath = "Images\\wolframalpha.png",
Url = "http://www.wolframalpha.com/input/?i=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Stackoverflow",
ActionKeyword = "stackoverflow",
IconPath = "Images\\stackoverflow.png",
Url = "http://stackoverflow.com/search?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "I'm Feeling Lucky",
ActionKeyword = "lucky",
IconPath = "Images\\google.png",
Url = "http://google.com/search?q=new WebSearch {q}&btnI=I",
Enabled = true
},
new WebSearch
{
Title = "Google Image",
ActionKeyword = "image",
IconPath = "Images\\google.png",
Url = "https://www.google.com/search?q=new WebSearch {q}&tbm=isch",
Enabled = true
},
new WebSearch
{
Title = "Youtube",
ActionKeyword = "youtube",
IconPath = "Images\\youtube.png",
Url = "http://www.youtube.com/results?search_query=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Bing",
ActionKeyword = "bing",
IconPath = "Images\\bing.png",
Url = "https://www.bing.com/search?q=new WebSearch {q}",
Enabled = true
},
new WebSearch
{
Title = "Yahoo",
ActionKeyword = "yahoo",
IconPath = "Images\\yahoo.png",
Url = "http://www.search.yahoo.com/search?p=new WebSearch {q}",
Enabled = true
}
});
return this;
} }
} }
} }

View file

@ -29,10 +29,10 @@ namespace Wox.Plugin.WebSearch
? Visibility.Visible ? Visibility.Visible
: Visibility.Collapsed; : Visibility.Collapsed;
List<ComboBoxItem> items = new List<ComboBoxItem>() List<ComboBoxItem> items = new List<ComboBoxItem>
{ {
new ComboBoxItem() {Content = "Google"}, new ComboBoxItem {Content = "Google"},
new ComboBoxItem() {Content = "Baidu"}, new ComboBoxItem {Content = "Baidu"}
}; };
ComboBoxItem selected = items.FirstOrDefault(o => o.Content.ToString() == WebSearchStorage.Instance.WebSearchSuggestionSource); ComboBoxItem selected = items.FirstOrDefault(o => o.Content.ToString() == WebSearchStorage.Instance.WebSearchSuggestionSource);
if (selected == null) if (selected == null)

View file

@ -136,9 +136,6 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Include="setting.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<Page Include="WebSearchesSetting.xaml"> <Page Include="WebSearchesSetting.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType> <SubType>Designer</SubType>

View file

@ -29,7 +29,7 @@ namespace Wox.Core.Plugin
foreach (Type type in types) foreach (Type type in types)
{ {
PluginPair pair = new PluginPair() PluginPair pair = new PluginPair
{ {
Plugin = Activator.CreateInstance(type) as IPlugin, Plugin = Activator.CreateInstance(type) as IPlugin,
Metadata = metadata Metadata = metadata
@ -38,7 +38,7 @@ namespace Wox.Core.Plugin
plugins.Add(pair); plugins.Add(pair);
} }
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Error(new WoxPluginException(metadata.Name, $"Couldn't load plugin", e)); Log.Error(new WoxPluginException(metadata.Name, $"Couldn't load plugin", e));
} }

View file

@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
@ -41,7 +42,7 @@ namespace Wox.Core.Plugin
foreach (JsonRPCResult result in queryResponseModel.Result) foreach (JsonRPCResult result in queryResponseModel.Result)
{ {
JsonRPCResult result1 = result; JsonRPCResult result1 = result;
result.Action = (c) => result.Action = c =>
{ {
if (result1.JsonRPCAction == null) return false; if (result1.JsonRPCAction == null) return false;
@ -72,7 +73,7 @@ namespace Wox.Core.Plugin
} }
return results; return results;
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Error(e); Log.Error(e);
} }
@ -89,7 +90,7 @@ namespace Wox.Core.Plugin
{ {
methodInfo.Invoke(PluginManager.API, parameters); methodInfo.Invoke(PluginManager.API, parameters);
} }
catch (System.Exception) catch (Exception)
{ {
#if (DEBUG) #if (DEBUG)
{ {
@ -150,7 +151,7 @@ namespace Wox.Core.Plugin
} }
} }
} }
catch(System.Exception e) catch(Exception e)
{ {
throw new WoxJsonRPCException(e.Message); throw new WoxJsonRPCException(e.Message);
} }

View file

@ -11,7 +11,7 @@ namespace Wox.Core.Plugin
T jsonRPCPlugin = new T(); T jsonRPCPlugin = new T();
List<PluginMetadata> jsonRPCPluginMetadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == jsonRPCPlugin.SupportedLanguage.ToUpper()).ToList(); List<PluginMetadata> jsonRPCPluginMetadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == jsonRPCPlugin.SupportedLanguage.ToUpper()).ToList();
return jsonRPCPluginMetadatas.Select(metadata => new PluginPair() return jsonRPCPluginMetadatas.Select(metadata => new PluginPair
{ {
Plugin = new T(), //every JsonRPC plugin should has its own plugin instance Plugin = new T(), //every JsonRPC plugin should has its own plugin instance
Metadata = metadata Metadata = metadata

View file

@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -45,7 +46,7 @@ namespace Wox.Core.Plugin
Directory.Delete(directory, true); Directory.Delete(directory, true);
continue; continue;
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Fatal(e); Log.Fatal(e);
} }
@ -77,7 +78,7 @@ namespace Wox.Core.Plugin
// for plugin still use old ActionKeyword // for plugin still use old ActionKeyword
metadata.ActionKeyword = metadata.ActionKeywords?[0]; metadata.ActionKeyword = metadata.ActionKeywords?[0];
} }
catch (System.Exception e) catch (Exception e)
{ {
string msg = $"Parse plugin config {configPath} failed: json format is not valid"; string msg = $"Parse plugin config {configPath} failed: json format is not valid";
Log.Error(new WoxException(msg)); Log.Error(new WoxException(msg));

View file

@ -107,12 +107,12 @@ namespace Wox.Core.Plugin
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath)); metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginDirectory = pluginDirectory; metadata.PluginDirectory = pluginDirectory;
} }
catch (System.Exception) catch (Exception)
{ {
string error = $"Parse plugin config {configPath} failed: json format is not valid"; string error = $"Parse plugin config {configPath} failed: json format is not valid";
#if (DEBUG) #if (DEBUG)
{ {
throw new System.Exception(error); throw new Exception(error);
} }
#endif #endif
return null; return null;
@ -124,7 +124,7 @@ namespace Wox.Core.Plugin
string error = $"Parse plugin config {configPath} failed: invalid language {metadata.Language}"; string error = $"Parse plugin config {configPath} failed: invalid language {metadata.Language}";
#if (DEBUG) #if (DEBUG)
{ {
throw new System.Exception(error); throw new Exception(error);
} }
#endif #endif
return null; return null;
@ -134,7 +134,7 @@ namespace Wox.Core.Plugin
string error = $"Parse plugin config {configPath} failed: ExecuteFile {metadata.ExecuteFilePath} didn't exist"; string error = $"Parse plugin config {configPath} failed: ExecuteFile {metadata.ExecuteFilePath} didn't exist";
#if (DEBUG) #if (DEBUG)
{ {
throw new System.Exception(error); throw new Exception(error);
} }
#endif #endif
return null; return null;

View file

@ -2,10 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Threading; using System.Threading;
using Wox.Core.i18n; using Wox.Core.Resource;
using Wox.Core.UI;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure; using Wox.Infrastructure;
using Wox.Infrastructure.Exception; using Wox.Infrastructure.Exception;
@ -20,35 +18,33 @@ namespace Wox.Core.Plugin
public static class PluginManager public static class PluginManager
{ {
public const string DirectoryName = "Plugins"; public const string DirectoryName = "Plugins";
private static IEnumerable<PluginPair> contextMenuPlugins; private static IEnumerable<PluginPair> _contextMenuPlugins;
/// <summary> /// <summary>
/// Directories that will hold Wox plugin directory /// Directories that will hold Wox plugin directory
/// </summary> /// </summary>
private static List<string> pluginDirectories = new List<string>(); private static readonly List<string> PluginDirectories = new List<string>();
public static IEnumerable<PluginPair> AllPlugins { get; private set; } public static IEnumerable<PluginPair> AllPlugins { get; private set; }
public static List<PluginPair> GlobalPlugins { get; } = new List<PluginPair>(); public static readonly List<PluginPair> GlobalPlugins = new List<PluginPair>();
public static Dictionary<string, PluginPair> NonGlobalPlugins { get; set; } = new Dictionary<string, PluginPair>();
public static readonly Dictionary<string, PluginPair> NonGlobalPlugins = new Dictionary<string, PluginPair>();
private static IEnumerable<PluginPair> InstantQueryPlugins { get; set; } private static IEnumerable<PluginPair> InstantQueryPlugins { get; set; }
public static IPublicAPI API { private set; get; } public static IPublicAPI API { private set; get; }
public static string PluginDirectory public static readonly string PluginDirectory = Path.Combine(WoxDirectroy.Executable, DirectoryName);
{
get { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DirectoryName); }
}
private static void SetupPluginDirectories() private static void SetupPluginDirectories()
{ {
pluginDirectories.Add(PluginDirectory); PluginDirectories.Add(PluginDirectory);
MakesurePluginDirectoriesExist(); MakesurePluginDirectoriesExist();
} }
private static void MakesurePluginDirectoriesExist() private static void MakesurePluginDirectoriesExist()
{ {
foreach (string pluginDirectory in pluginDirectories) foreach (string pluginDirectory in PluginDirectories)
{ {
if (!Directory.Exists(pluginDirectory)) if (!Directory.Exists(pluginDirectory))
{ {
@ -74,7 +70,7 @@ namespace Wox.Core.Plugin
SetupPluginDirectories(); SetupPluginDirectories();
API = api; API = api;
var metadatas = PluginConfig.Parse(pluginDirectories); var metadatas = PluginConfig.Parse(PluginDirectories);
AllPlugins = (new CSharpPluginLoader().LoadPlugin(metadatas)). AllPlugins = (new CSharpPluginLoader().LoadPlugin(metadatas)).
Concat(new JsonRPCPluginLoader<PythonPlugin>().LoadPlugin(metadatas)); Concat(new JsonRPCPluginLoader<PythonPlugin>().LoadPlugin(metadatas));
@ -103,7 +99,7 @@ namespace Wox.Core.Plugin
ThreadPool.QueueUserWorkItem(o => ThreadPool.QueueUserWorkItem(o =>
{ {
InstantQueryPlugins = GetPluginsForInterface<IInstantQuery>(); InstantQueryPlugins = GetPluginsForInterface<IInstantQuery>();
contextMenuPlugins = GetPluginsForInterface<IContextMenu>(); _contextMenuPlugins = GetPluginsForInterface<IContextMenu>();
foreach (var plugin in AllPlugins) foreach (var plugin in AllPlugins)
{ {
if (IsGlobalPlugin(plugin.Metadata)) if (IsGlobalPlugin(plugin.Metadata))
@ -232,7 +228,7 @@ namespace Wox.Core.Plugin
public static List<Result> GetContextMenusForPlugin(Result result) public static List<Result> GetContextMenusForPlugin(Result result)
{ {
var pluginPair = contextMenuPlugins.FirstOrDefault(o => o.Metadata.ID == result.PluginID); var pluginPair = _contextMenuPlugins.FirstOrDefault(o => o.Metadata.ID == result.PluginID);
var plugin = (IContextMenu)pluginPair?.Plugin; var plugin = (IContextMenu)pluginPair?.Plugin;
if (plugin != null) if (plugin != null)
{ {

View file

@ -1,64 +1,59 @@
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Reflection;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure;
using Wox.Plugin; using Wox.Plugin;
namespace Wox.Core.Plugin namespace Wox.Core.Plugin
{ {
internal class PythonPlugin : JsonRPCPlugin internal class PythonPlugin : JsonRPCPlugin
{ {
private static string woxDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); private static readonly string PythonHome = Path.Combine(WoxDirectroy.Executable, "PythonHome");
private ProcessStartInfo startInfo; private readonly ProcessStartInfo _startInfo;
public override string SupportedLanguage public override string SupportedLanguage => AllowedLanguage.Python;
{
get { return AllowedLanguage.Python; }
}
public PythonPlugin() public PythonPlugin()
{ {
startInfo = new ProcessStartInfo _startInfo = new ProcessStartInfo
{ {
UseShellExecute = false, UseShellExecute = false,
CreateNoWindow = true, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardOutput = true,
RedirectStandardError = true RedirectStandardError = true
}; };
string additionalPythonPath = string.Format("{0};{1}", string additionalPythonPath = $"{Path.Combine(PythonHome, "DLLs")};{Path.Combine(PythonHome, "Lib", "site-packages")}";
Path.Combine(woxDirectory, "PythonHome\\DLLs"), if (!_startInfo.EnvironmentVariables.ContainsKey("PYTHONPATH"))
Path.Combine(woxDirectory, "PythonHome\\Lib\\site-packages"));
if (!startInfo.EnvironmentVariables.ContainsKey("PYTHONPATH"))
{ {
startInfo.EnvironmentVariables.Add("PYTHONPATH", additionalPythonPath); _startInfo.EnvironmentVariables.Add("PYTHONPATH", additionalPythonPath);
} }
else else
{ {
startInfo.EnvironmentVariables["PYTHONPATH"] = additionalPythonPath; _startInfo.EnvironmentVariables["PYTHONPATH"] = additionalPythonPath;
} }
} }
protected override string ExecuteQuery(Query query) protected override string ExecuteQuery(Query query)
{ {
JsonRPCServerRequestModel request = new JsonRPCServerRequestModel() JsonRPCServerRequestModel request = new JsonRPCServerRequestModel
{ {
Method = "query", Method = "query",
Parameters = new object[] { query.GetAllRemainingParameter() }, Parameters = new object[] { query.GetAllRemainingParameter() },
HttpProxy = HttpProxy.Instance HttpProxy = HttpProxy.Instance
}; };
//Add -B flag to tell python don't write .py[co] files. Because .pyc contains location infos which will prevent python portable //Add -B flag to tell python don't write .py[co] files. Because .pyc contains location infos which will prevent python portable
startInfo.FileName = Path.Combine(woxDirectory, "PythonHome\\pythonw.exe"); _startInfo.FileName = Path.Combine(PythonHome, "pythonw.exe");
startInfo.Arguments = string.Format("-B \"{0}\" \"{1}\"", context.CurrentPluginMetadata.ExecuteFilePath, request); _startInfo.Arguments = $"-B \"{context.CurrentPluginMetadata.ExecuteFilePath}\" \"{request}\"";
return Execute(startInfo); return Execute(_startInfo);
} }
protected override string ExecuteCallback(JsonRPCRequestModel rpcRequest) protected override string ExecuteCallback(JsonRPCRequestModel rpcRequest)
{ {
startInfo.FileName = Path.Combine(woxDirectory, "PythonHome\\pythonw.exe"); _startInfo.FileName = Path.Combine(PythonHome, "pythonw.exe");
startInfo.Arguments = string.Format("-B \"{0}\" \"{1}\"", context.CurrentPluginMetadata.ExecuteFilePath, rpcRequest); _startInfo.Arguments = $"-B \"{context.CurrentPluginMetadata.ExecuteFilePath}\" \"{rpcRequest}\"";
return Execute(startInfo); return Execute(_startInfo);
} }
} }
} }

View file

@ -1,6 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace Wox.Core.i18n namespace Wox.Core.Resource
{ {
internal static class AvailableLanguages internal static class AvailableLanguages
{ {
@ -18,7 +18,7 @@ namespace Wox.Core.i18n
Chinese, Chinese,
Chinese_TW, Chinese_TW,
Russian, Russian,
French, French
}; };
return languages; return languages;
} }

View file

@ -3,7 +3,7 @@ using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Media; using System.Windows.Media;
namespace Wox.Core.Theme namespace Wox.Core.Resource
{ {
public static class FontHelper public static class FontHelper
{ {

View file

@ -2,35 +2,31 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Windows; using System.Windows;
using Wox.Core.UI;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure.Exception; using Wox.Infrastructure.Exception;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
using Wox.Plugin; using Wox.Plugin;
namespace Wox.Core.i18n namespace Wox.Core.Resource
{ {
public class Internationalization : IInternationalization, IUIResource public class Internationalization : Resource
{ {
public const string DirectoryName = "Languages"; public Internationalization()
private static readonly string DefaultDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DirectoryName);
static Internationalization()
{ {
DirectoryName = "Languages";
MakesureThemeDirectoriesExist(); MakesureThemeDirectoriesExist();
} }
private static void MakesureThemeDirectoriesExist() private void MakesureThemeDirectoriesExist()
{ {
if (!Directory.Exists(DefaultDirectory)) if (!Directory.Exists(DirectoryPath))
{ {
try try
{ {
Directory.CreateDirectory(DefaultDirectory); Directory.CreateDirectory(DirectoryPath);
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Error(e); Log.Error(e);
} }
@ -64,20 +60,22 @@ namespace Wox.Core.i18n
path = GetLanguagePath(AvailableLanguages.English); path = GetLanguagePath(AvailableLanguages.English);
if (string.IsNullOrEmpty(path)) if (string.IsNullOrEmpty(path))
{ {
throw new System.Exception("Change Language failed"); throw new Exception("Change Language failed");
} }
} }
UserSettingStorage.Instance.Language = language.LanguageCode; UserSettingStorage.Instance.Language = language.LanguageCode;
UserSettingStorage.Instance.Save(); UserSettingStorage.Instance.Save();
ResourceMerger.UpdateResources(this); ResourceMerger.UpdateResource(this);
} }
public ResourceDictionary GetResourceDictionary()
public override ResourceDictionary GetResourceDictionary()
{ {
return new ResourceDictionary return new ResourceDictionary
{ {
Source = new Uri(GetLanguageFile(DefaultDirectory), UriKind.Absolute) Source = new Uri(GetLanguageFile(DirectoryPath), UriKind.Absolute)
}; };
} }
@ -115,7 +113,7 @@ namespace Wox.Core.i18n
pluginPair.Metadata.Name = pluginI18n.GetTranslatedPluginTitle(); pluginPair.Metadata.Name = pluginI18n.GetTranslatedPluginTitle();
pluginPair.Metadata.Description = pluginI18n.GetTranslatedPluginDescription(); pluginPair.Metadata.Description = pluginI18n.GetTranslatedPluginDescription();
} }
catch (System.Exception e) catch (Exception e)
{ {
var woxPluginException = new WoxPluginException(pluginPair.Metadata.Name, "Update Plugin metadata translation failed:", e); var woxPluginException = new WoxPluginException(pluginPair.Metadata.Name, "Update Plugin metadata translation failed:", e);
Log.Error(woxPluginException); Log.Error(woxPluginException);
@ -124,7 +122,7 @@ namespace Wox.Core.i18n
private string GetLanguagePath(Language language) private string GetLanguagePath(Language language)
{ {
string path = Path.Combine(DefaultDirectory, language.LanguageCode + ".xaml"); string path = Path.Combine(DirectoryPath, language.LanguageCode + ".xaml");
if (File.Exists(path)) if (File.Exists(path))
{ {
return path; return path;
@ -156,4 +154,5 @@ namespace Wox.Core.i18n
} }
} }
} }

View file

@ -1,4 +1,4 @@
namespace Wox.Core.i18n namespace Wox.Core.Resource
{ {
public static class InternationalizationManager public static class InternationalizationManager
{ {

View file

@ -1,4 +1,4 @@
namespace Wox.Core.i18n namespace Wox.Core.Resource
{ {
public class Language public class Language
{ {

View file

@ -0,0 +1,15 @@
using System.IO;
using System.Windows;
using Wox.Infrastructure;
namespace Wox.Core.Resource
{
public abstract class Resource
{
public string DirectoryName { get; protected set; }
protected string DirectoryPath => Path.Combine(WoxDirectroy.Executable, DirectoryName);
public abstract ResourceDictionary GetResourceDictionary();
}
}

View file

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

View file

@ -2,26 +2,24 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Interop; using System.Windows.Interop;
using System.Windows.Media; using System.Windows.Media;
using Wox.Core.UI;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
namespace Wox.Core.Theme namespace Wox.Core.Resource
{ {
public class Theme : IUIResource public class Theme : Resource
{ {
public const string DirectoryName = "Themes";
private static List<string> themeDirectories = new List<string>(); private static List<string> themeDirectories = new List<string>();
static Theme() public Theme()
{ {
themeDirectories.Add(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DirectoryName)); DirectoryName = "Themes";
themeDirectories.Add(DirectoryPath);
MakesureThemeDirectoriesExist(); MakesureThemeDirectoriesExist();
} }
@ -35,7 +33,7 @@ namespace Wox.Core.Theme
{ {
Directory.CreateDirectory(pluginDirectory); Directory.CreateDirectory(pluginDirectory);
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Error(e); Log.Error(e);
} }
@ -51,7 +49,7 @@ namespace Wox.Core.Theme
themePath = GetThemePath("Dark"); themePath = GetThemePath("Dark");
if (string.IsNullOrEmpty(themePath)) if (string.IsNullOrEmpty(themePath))
{ {
throw new System.Exception("Change theme failed"); throw new Exception("Change theme failed");
} }
} }
@ -67,7 +65,7 @@ namespace Wox.Core.Theme
} }
} }
public ResourceDictionary GetResourceDictionary() public override ResourceDictionary GetResourceDictionary()
{ {
var dict = new ResourceDictionary var dict = new ResourceDictionary
{ {
@ -94,8 +92,8 @@ namespace Wox.Core.Theme
Setter fontWeight = new Setter(TextBlock.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontWeight)); Setter fontWeight = new Setter(TextBlock.FontWeightProperty, FontHelper.GetFontWeightFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontWeight));
Setter fontStretch = new Setter(TextBlock.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontStretch)); Setter fontStretch = new Setter(TextBlock.FontStretchProperty, FontHelper.GetFontStretchFromInvariantStringOrNormal(UserSettingStorage.Instance.ResultItemFontStretch));
Setter[] setters = new Setter[] { fontFamily, fontStyle, fontWeight, fontStretch }; Setter[] setters = { fontFamily, fontStyle, fontWeight, fontStretch };
Array.ForEach(new Style[] { resultItemStyle, resultSubItemStyle, resultItemSelectedStyle, resultSubItemSelectedStyle }, o => Array.ForEach(setters, p => o.Setters.Add(p))); Array.ForEach(new[] { resultItemStyle, resultSubItemStyle, resultItemSelectedStyle, resultSubItemSelectedStyle }, o => Array.ForEach(setters, p => o.Setters.Add(p)));
} }
return dict; return dict;
} }

View file

@ -1,4 +1,4 @@
namespace Wox.Core.Theme namespace Wox.Core.Resource
{ {
public class ThemeManager public class ThemeManager
{ {

View file

@ -1,12 +0,0 @@
using System.Windows;
namespace Wox.Core.UI
{
/// <summary>
/// Object implement this interface will have the ability to has its own UI styles
/// </summary>
public interface IUIResource
{
ResourceDictionary GetResourceDictionary();
}
}

View file

@ -9,7 +9,7 @@ namespace Wox.Core.Updater
public int MINOR { get; set; } public int MINOR { get; set; }
public int PATCH { get; set; } public int PATCH { get; set; }
public SemanticVersion(System.Version version) public SemanticVersion(Version version)
{ {
MAJOR = version.Major; MAJOR = version.Major;
MINOR = version.Minor; MINOR = version.Minor;

View file

@ -8,7 +8,7 @@ using NAppUpdate.Framework.Common;
using NAppUpdate.Framework.Sources; using NAppUpdate.Framework.Sources;
using NAppUpdate.Framework.Tasks; using NAppUpdate.Framework.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Wox.Core.i18n; using Wox.Core.Resource;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure.Http; using Wox.Infrastructure.Http;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
@ -92,7 +92,7 @@ namespace Wox.Core.Updater
StartUpdate(); StartUpdate();
} }
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Error(e); Log.Error(e);
} }
@ -112,7 +112,7 @@ namespace Wox.Core.Updater
{ {
((UpdateProcessAsyncResult)asyncResult).EndInvoke(); ((UpdateProcessAsyncResult)asyncResult).EndInvoke();
} }
catch (System.Exception e) catch (Exception e)
{ {
Log.Error(e); Log.Error(e);
updManager.CleanUp(); updManager.CleanUp();
@ -148,7 +148,7 @@ namespace Wox.Core.Updater
{ {
UpdateManager.Instance.ApplyUpdates(true, UserSettingStorage.Instance.EnableUpdateLog, false); UpdateManager.Instance.ApplyUpdates(true, UserSettingStorage.Instance.EnableUpdateLog, false);
} }
catch (System.Exception e) catch (Exception e)
{ {
string updateError = InternationalizationManager.Instance.GetTranslation("update_wox_update_error"); string updateError = InternationalizationManager.Instance.GetTranslation("update_wox_update_error");
Log.Error(e); Log.Error(e);

View file

@ -15,30 +15,30 @@ namespace Wox.Core.Updater
public WoxUpdateSource(string feedUrl,IWebProxy proxy) public WoxUpdateSource(string feedUrl,IWebProxy proxy)
{ {
this.FeedUrl = feedUrl; FeedUrl = feedUrl;
this.Proxy = proxy; Proxy = proxy;
} }
private void TryResolvingHost() private void TryResolvingHost()
{ {
Uri uri = new Uri(this.FeedUrl); Uri uri = new Uri(FeedUrl);
try try
{ {
Dns.GetHostEntry(uri.Host); Dns.GetHostEntry(uri.Host);
} }
catch (System.Exception ex) catch (Exception ex)
{ {
throw new WebException(string.Format("Failed to resolve {0}. Check your connectivity.", (object)uri.Host), WebExceptionStatus.ConnectFailure); throw new WebException(string.Format("Failed to resolve {0}. Check your connectivity.", uri.Host), WebExceptionStatus.ConnectFailure);
} }
} }
public string GetUpdatesFeed() public string GetUpdatesFeed()
{ {
this.TryResolvingHost(); TryResolvingHost();
string str = string.Empty; string str = string.Empty;
WebRequest webRequest = WebRequest.Create(this.FeedUrl); WebRequest webRequest = WebRequest.Create(FeedUrl);
webRequest.Method = "GET"; webRequest.Method = "GET";
webRequest.Proxy = this.Proxy; webRequest.Proxy = Proxy;
using (WebResponse response = webRequest.GetResponse()) using (WebResponse response = webRequest.GetResponse())
{ {
Stream responseStream = response.GetResponseStream(); Stream responseStream = response.GetResponseStream();
@ -56,7 +56,7 @@ namespace Wox.Core.Updater
if (!string.IsNullOrEmpty(baseUrl) && !baseUrl.EndsWith("/")) if (!string.IsNullOrEmpty(baseUrl) && !baseUrl.EndsWith("/"))
baseUrl += "/"; baseUrl += "/";
FileDownloader fileDownloader = !Uri.IsWellFormedUriString(url, UriKind.Absolute) ? (!Uri.IsWellFormedUriString(baseUrl, UriKind.Absolute) ? (string.IsNullOrEmpty(baseUrl) ? new FileDownloader(url) : new FileDownloader(new Uri(new Uri(baseUrl), url))) : new FileDownloader(new Uri(new Uri(baseUrl, UriKind.Absolute), url))) : new FileDownloader(url); FileDownloader fileDownloader = !Uri.IsWellFormedUriString(url, UriKind.Absolute) ? (!Uri.IsWellFormedUriString(baseUrl, UriKind.Absolute) ? (string.IsNullOrEmpty(baseUrl) ? new FileDownloader(url) : new FileDownloader(new Uri(new Uri(baseUrl), url))) : new FileDownloader(new Uri(new Uri(baseUrl, UriKind.Absolute), url))) : new FileDownloader(url);
fileDownloader.Proxy = this.Proxy; fileDownloader.Proxy = Proxy;
if (string.IsNullOrEmpty(tempLocation) || !Directory.Exists(Path.GetDirectoryName(tempLocation))) if (string.IsNullOrEmpty(tempLocation) || !Directory.Exists(Path.GetDirectoryName(tempLocation)))
tempLocation = Path.GetTempFileName(); tempLocation = Path.GetTempFileName();
return fileDownloader.DownloadToFile(tempLocation, onProgress); return fileDownloader.DownloadToFile(tempLocation, onProgress);

View file

@ -107,17 +107,7 @@ namespace Wox.Core.UserSettings
[JsonProperty] [JsonProperty]
public int MaxResultsToShow { get; set; } public int MaxResultsToShow { get; set; }
protected override string ConfigFolder protected override string FileName { get; } = "Settings";
{
get { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config"); }
}
protected override string ConfigName
{
get { return "config"; }
}
public void IncreaseActivateTimes() public void IncreaseActivateTimes()
{ {
@ -172,7 +162,7 @@ namespace Wox.Core.UserSettings
var customizedPluginConfig = CustomizedPluginConfigs.FirstOrDefault(o => o.ID == metadata.ID); var customizedPluginConfig = CustomizedPluginConfigs.FirstOrDefault(o => o.ID == metadata.ID);
if (customizedPluginConfig == null) if (customizedPluginConfig == null)
{ {
CustomizedPluginConfigs.Add(new CustomizedPluginConfig() CustomizedPluginConfigs.Add(new CustomizedPluginConfig
{ {
Disabled = false, Disabled = false,
ID = metadata.ID, ID = metadata.ID,

View file

@ -65,14 +65,13 @@
<Compile Include="Updater\UpdaterManager.cs" /> <Compile Include="Updater\UpdaterManager.cs" />
<Compile Include="Updater\WoxUpdateSource.cs" /> <Compile Include="Updater\WoxUpdateSource.cs" />
<Compile Include="UserSettings\HttpProxy.cs" /> <Compile Include="UserSettings\HttpProxy.cs" />
<Compile Include="i18n\AvailableLanguages.cs" /> <Compile Include="Resource\AvailableLanguages.cs" />
<Compile Include="i18n\IInternationalization.cs" /> <Compile Include="Resource\Internationalization.cs" />
<Compile Include="i18n\Internationalization.cs" /> <Compile Include="Resource\InternationalizationManager.cs" />
<Compile Include="i18n\InternationalizationManager.cs" /> <Compile Include="Resource\Language.cs" />
<Compile Include="i18n\Language.cs" /> <Compile Include="Resource\ThemeManager.cs" />
<Compile Include="Theme\ThemeManager.cs" /> <Compile Include="Resource\Resource.cs" />
<Compile Include="UI\IUIResource.cs" /> <Compile Include="Resource\ResourceMerger.cs" />
<Compile Include="UI\ResourceMerger.cs" />
<Compile Include="Plugin\PluginInstaller.cs" /> <Compile Include="Plugin\PluginInstaller.cs" />
<Compile Include="Plugin\JsonRPCPlugin.cs" /> <Compile Include="Plugin\JsonRPCPlugin.cs" />
<Compile Include="Plugin\JsonRPCPluginLoader.cs" /> <Compile Include="Plugin\JsonRPCPluginLoader.cs" />
@ -83,8 +82,8 @@
<Compile Include="Plugin\PluginManager.cs" /> <Compile Include="Plugin\PluginManager.cs" />
<Compile Include="Plugin\PythonPlugin.cs" /> <Compile Include="Plugin\PythonPlugin.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Theme\FontHelper.cs" /> <Compile Include="Resource\FontHelper.cs" />
<Compile Include="Theme\Theme.cs" /> <Compile Include="Resource\Theme.cs" />
<Compile Include="UserSettings\CustomizedPluginConfig.cs" /> <Compile Include="UserSettings\CustomizedPluginConfig.cs" />
<Compile Include="UserSettings\PluginHotkey.cs" /> <Compile Include="UserSettings\PluginHotkey.cs" />
<Compile Include="UserSettings\UserSettingStorage.cs" /> <Compile Include="UserSettings\UserSettingStorage.cs" />

View file

@ -1,24 +0,0 @@
using System.Collections.Generic;
namespace Wox.Core.i18n
{
interface IInternationalization
{
List<Language> LoadAvailableLanguages();
string GetTranslation(string key);
/// <summary>
/// Get language file for current user selected language
/// if couldn't find the current selected language file, it will first try to load en.xaml
/// if en.xaml couldn't find, return empty string
/// </summary>
/// <param name="folder"></param>
/// <returns></returns>
string GetLanguageFile(string folder);
void ChangeLanguage(Language language);
void ChangeLanguage(string languageCode);
}
}

View file

@ -3,7 +3,7 @@ using System.Threading;
using System.Windows; using System.Windows;
using System.Windows.Documents; using System.Windows.Documents;
using Exceptionless; using Exceptionless;
using Wox.Core.i18n; using Wox.Core.Resource;
using Wox.Core.Updater; using Wox.Core.Updater;
namespace Wox.CrashReporter namespace Wox.CrashReporter
@ -47,10 +47,10 @@ namespace Wox.CrashReporter
.SetUserDescription(reproduceSteps) .SetUserDescription(reproduceSteps)
.Submit(); .Submit();
ExceptionlessClient.Current.ProcessQueue(); ExceptionlessClient.Current.ProcessQueue();
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
Close(); Close();
})); });
}); });
} }

View file

@ -28,7 +28,7 @@ namespace Wox.Infrastructure
public MatchResult Evaluate(string str) public MatchResult Evaluate(string str)
{ {
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(query)) return new MatchResult() { Success = false }; if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(query)) return new MatchResult { Success = false };
var len = str.Length; var len = str.Length;
var compareString = opt.IgnoreCase ? str.ToLower() : str; var compareString = opt.IgnoreCase ? str.ToLower() : str;
@ -67,7 +67,7 @@ namespace Wox.Infrastructure
// return rendered string if we have a match for every char // return rendered string if we have a match for every char
if (patternIdx == pattern.Length) if (patternIdx == pattern.Length)
{ {
return new MatchResult() return new MatchResult
{ {
Success = true, Success = true,
Value = sb.ToString(), Value = sb.ToString(),
@ -75,7 +75,7 @@ namespace Wox.Infrastructure
}; };
} }
return new MatchResult() { Success = false }; return new MatchResult { Success = false };
} }
private int CalScore(string str, int firstIndex, int matchLen) private int CalScore(string str, int firstIndex, int matchLen)
@ -107,9 +107,9 @@ namespace Wox.Infrastructure
{ {
public MatchOption() public MatchOption()
{ {
this.Prefix = ""; Prefix = "";
this.Suffix = ""; Suffix = "";
this.IgnoreCase = true; IgnoreCase = true;
} }
/// <summary> /// <summary>

View file

@ -131,7 +131,7 @@ namespace Wox.Infrastructure.Hotkey
if (CharKey != Key.None) if (CharKey != Key.None)
{ {
text += specialSymbolDictionary.ContainsKey(CharKey) text += specialSymbolDictionary.ContainsKey(CharKey)
? specialSymbolDictionary[CharKey].ToString() ? specialSymbolDictionary[CharKey]
: CharKey.ToString(); : CharKey.ToString();
} }
else if (!string.IsNullOrEmpty(text)) else if (!string.IsNullOrEmpty(text))

View file

@ -1,6 +1,6 @@
namespace Wox.Infrastructure.Hotkey namespace Wox.Infrastructure.Hotkey
{ {
public enum KeyEvent:int public enum KeyEvent
{ {
/// <summary> /// <summary>
/// Key down /// Key down

View file

@ -1,6 +1,7 @@
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Text; using System.Text;
using Wox.Infrastructure.Logger;
using Wox.Plugin; using Wox.Plugin;
namespace Wox.Infrastructure.Http namespace Wox.Infrastructure.Http
@ -56,7 +57,7 @@ namespace Wox.Infrastructure.Http
} }
catch (System.Exception e) catch (System.Exception e)
{ {
Logger.Log.Error(e); Log.Error(e);
return string.Empty; return string.Empty;
} }
@ -109,7 +110,7 @@ namespace Wox.Infrastructure.Http
} }
catch (System.Exception e) catch (System.Exception e)
{ {
Logger.Log.Error(e); Log.Error(e);
return string.Empty; return string.Empty;
} }

View file

@ -1,5 +1,9 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Wox.Infrastructure")] [assembly: AssemblyTitle("Wox.Infrastructure")]
[assembly: Guid("aee57a31-29e5-4f03-a41f-7917910fe90f")] [assembly: Guid("aee57a31-29e5-4f03-a41f-7917910fe90f")]
[assembly: InternalsVisibleTo("Wox")]
[assembly: InternalsVisibleTo("Wox.Core")]
[assembly: InternalsVisibleTo("Wox.Test")]

View file

@ -4,23 +4,18 @@ using System.IO;
namespace Wox.Infrastructure.Storage namespace Wox.Infrastructure.Storage
{ {
[Serializable] [Serializable]
public abstract class BaseStorage<T> : IStorage where T : class,IStorage, new() public abstract class BaseStorage<T> : IStorage where T : class, IStorage, new()
{ {
protected abstract string ConfigFolder { get; } protected string DirectoryPath { get; } = Path.Combine(WoxDirectroy.Executable, "Config");
protected string ConfigPath protected string FilePath => Path.Combine(DirectoryPath, FileName + FileSuffix);
{
get
{
return Path.Combine(ConfigFolder, ConfigName + FileSuffix);
}
}
protected abstract string FileSuffix { get; } protected abstract string FileSuffix { get; }
protected abstract string ConfigName { get; } protected abstract string FileName { get; }
private static object locker = new object(); private static object locker = new object();
protected static T serializedObject; protected static T serializedObject;
public event Action<T> AfterLoad; public event Action<T> AfterLoad;
@ -64,13 +59,13 @@ namespace Wox.Infrastructure.Storage
public void Load() public void Load()
{ {
if (!File.Exists(ConfigPath)) if (!File.Exists(FilePath))
{ {
if (!Directory.Exists(ConfigFolder)) if (!Directory.Exists(DirectoryPath))
{ {
Directory.CreateDirectory(ConfigFolder); Directory.CreateDirectory(DirectoryPath);
} }
File.Create(ConfigPath).Close(); File.Create(FilePath).Close();
} }
LoadInternal(); LoadInternal();
OnAfterLoad(serializedObject); OnAfterLoad(serializedObject);

View file

@ -28,7 +28,7 @@ namespace Wox.Infrastructure.Storage
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
try try
{ {
using (FileStream fileStream = new FileStream(ConfigPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{ {
if (fileStream.Length > 0) if (fileStream.Length > 0)
{ {
@ -69,7 +69,7 @@ namespace Wox.Infrastructure.Storage
} }
} }
private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{ {
Assembly ayResult = null; Assembly ayResult = null;
string sShortAssemblyName = args.Name.Split(',')[0]; string sShortAssemblyName = args.Name.Split(',')[0];
@ -93,7 +93,7 @@ namespace Wox.Infrastructure.Storage
{ {
try try
{ {
FileStream fileStream = new FileStream(ConfigPath, FileMode.Create); FileStream fileStream = new FileStream(FilePath, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter BinaryFormatter binaryFormatter = new BinaryFormatter
{ {
AssemblyFormat = FormatterAssemblyStyle.Simple AssemblyFormat = FormatterAssemblyStyle.Simple

View file

@ -17,7 +17,7 @@ namespace Wox.Infrastructure.Storage
protected override void LoadInternal() protected override void LoadInternal()
{ {
string json = File.ReadAllText(ConfigPath); string json = File.ReadAllText(FilePath);
if (!string.IsNullOrEmpty(json)) if (!string.IsNullOrEmpty(json))
{ {
try try
@ -42,7 +42,7 @@ namespace Wox.Infrastructure.Storage
lock (syncObject) lock (syncObject)
{ {
string json = JsonConvert.SerializeObject(serializedObject, Formatting.Indented); string json = JsonConvert.SerializeObject(serializedObject, Formatting.Indented);
File.WriteAllText(ConfigPath, json); File.WriteAllText(FilePath, json);
} }
}); });
} }

View file

@ -63,6 +63,7 @@
<Compile Include="Hotkey\InterceptKeys.cs" /> <Compile Include="Hotkey\InterceptKeys.cs" />
<Compile Include="Hotkey\KeyEvent.cs" /> <Compile Include="Hotkey\KeyEvent.cs" />
<Compile Include="Logger\Log.cs" /> <Compile Include="Logger\Log.cs" />
<Compile Include="WoxDirectroy.cs" />
<Compile Include="Stopwatch.cs" /> <Compile Include="Stopwatch.cs" />
<Compile Include="Storage\BinaryStorage.cs" /> <Compile Include="Storage\BinaryStorage.cs" />
<Compile Include="Storage\IStorage.cs" /> <Compile Include="Storage\IStorage.cs" />

View file

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wox.Infrastructure
{
public static class WoxDirectroy
{
public static string Executable { get; internal set; }
}
}

View file

@ -15,10 +15,7 @@ namespace Wox.Plugin
public string Website { get; set; } public string Website { get; set; }
public string ExecuteFilePath public string ExecuteFilePath => Path.Combine(PluginDirectory, ExecuteFileName);
{
get { return Path.Combine(PluginDirectory, ExecuteFileName); }
}
public string ExecuteFileName { get; set; } public string ExecuteFileName { get; set; }

View file

@ -2,6 +2,7 @@
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using Wox.Infrastructure; using Wox.Infrastructure;
using Wox.Plugin;
namespace Wox.Test namespace Wox.Test
{ {
@ -11,20 +12,20 @@ namespace Wox.Test
[Test] [Test]
public void MatchTest() public void MatchTest()
{ {
var sources = new List<string>() var sources = new List<string>
{ {
"file open in browser-test", "file open in browser-test",
"Install Package", "Install Package",
"add new bsd", "add new bsd",
"Inste", "Inste",
"aac", "aac"
}; };
var results = new List<Wox.Plugin.Result>(); var results = new List<Result>();
foreach (var str in sources) foreach (var str in sources)
{ {
results.Add(new Plugin.Result() results.Add(new Result
{ {
Title = str, Title = str,
Score = FuzzyMatcher.Create("inst").Evaluate(str).Score Score = FuzzyMatcher.Create("inst").Evaluate(str).Score

View file

@ -36,18 +36,10 @@ namespace Wox.UpdateFeedGenerator
if (string.IsNullOrEmpty(config.OutputDirectory)) if (string.IsNullOrEmpty(config.OutputDirectory))
{ {
config.OutputDirectory = @"Update"; config.OutputDirectory = @"Update";
ConfigStorage.Instance.Save(); Instance.Save();
} }
} }
protected override string ConfigFolder protected override string FileName { get; } = "config";
{
get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
}
protected override string ConfigName
{
get { return "config"; }
}
} }
} }

View file

@ -1,5 +1,6 @@
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using NAppUpdate.Framework.Utils;
namespace Wox.UpdateFeedGenerator namespace Wox.UpdateFeedGenerator
{ {
@ -31,7 +32,7 @@ namespace Wox.UpdateFeedGenerator
myFileInfo = new FileInfo(fileName); myFileInfo = new FileInfo(fileName);
myFileVersion = FileVersionInfo.GetVersionInfo(fileName).FileVersion; myFileVersion = FileVersionInfo.GetVersionInfo(fileName).FileVersion;
if (myFileVersion != null) myFileVersion = myFileVersion.Replace(", ", "."); if (myFileVersion != null) myFileVersion = myFileVersion.Replace(", ", ".");
myHash = NAppUpdate.Framework.Utils.FileChecksum.GetSHA256Checksum(fileName); myHash = FileChecksum.GetSHA256Checksum(fileName);
RelativeName = fileName.Substring(rootDirectoryLength + 1); RelativeName = fileName.Substring(rootDirectoryLength + 1);
} }
} }

View file

@ -162,9 +162,9 @@ namespace Wox.UpdateFeedGenerator
if (fileTypesToMatch.IndexOfAny(new[] { ':', '<', '>', '/', '\\' }) >= 0) throw new ArgumentException("invalid cahracters in wildcard pattern", "fileTypesToMatch"); if (fileTypesToMatch.IndexOfAny(new[] { ':', '<', '>', '/', '\\' }) >= 0) throw new ArgumentException("invalid cahracters in wildcard pattern", "fileTypesToMatch");
m_includeSubDirs = includeSubDirs; m_includeSubDirs = includeSubDirs;
m_paths = pathsToSearch.Split(new[] { ';', ',' }); m_paths = pathsToSearch.Split(';', ',');
string[] specs = fileTypesToMatch.Split(new[] { ';', ',' }); string[] specs = fileTypesToMatch.Split(';', ',');
m_fileSpecs = new List<Regex>(specs.Length); m_fileSpecs = new List<Regex>(specs.Length);
foreach (string spec in specs) { foreach (string spec in specs) {
// trim whitespace off file spec and convert Win32 wildcards to regular expressions // trim whitespace off file spec and convert Win32 wildcards to regular expressions

View file

@ -1,6 +1,6 @@
using System.Windows; using System.Windows;
using Wox.Core.i18n;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Infrastructure.Exception; using Wox.Infrastructure.Exception;
using Wox.Plugin; using Wox.Plugin;
@ -19,7 +19,6 @@ namespace Wox
{ {
MessageBox.Show(InternationalizationManager.Instance.GetTranslation("cannotFindSpecifiedPlugin")); MessageBox.Show(InternationalizationManager.Instance.GetTranslation("cannotFindSpecifiedPlugin"));
Close(); Close();
return;
} }
} }

View file

@ -1,14 +1,18 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Threading; using System.Threading;
using System.Windows; using System.Windows;
using Wox.CommandArgs; using Wox.CommandArgs;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Helper; using Wox.Helper;
using Wox.Infrastructure;
using Stopwatch = Wox.Infrastructure.Stopwatch; using Stopwatch = Wox.Infrastructure.Stopwatch;
namespace Wox namespace Wox
{ {
public partial class App : Application, ISingleInstanceApp public partial class App : Application, ISingleInstanceApp
@ -33,6 +37,7 @@ namespace Wox
Stopwatch.Debug("Startup Time", () => Stopwatch.Debug("Startup Time", () =>
{ {
base.OnStartup(e); base.OnStartup(e);
WoxDirectroy.Executable = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();
RegisterUnhandledException(); RegisterUnhandledException();
ThreadPool.QueueUserWorkItem(o => { ImageLoader.ImageLoader.PreloadImages(); }); ThreadPool.QueueUserWorkItem(o => { ImageLoader.ImageLoader.PreloadImages(); });
Window = new MainWindow(); Window = new MainWindow();

View file

@ -8,8 +8,6 @@ namespace Wox.Converters
{ {
public class StringNullOrEmptyToVisibilityConverter : ConvertorBase<StringNullOrEmptyToVisibilityConverter> public class StringNullOrEmptyToVisibilityConverter : ConvertorBase<StringNullOrEmptyToVisibilityConverter>
{ {
public StringNullOrEmptyToVisibilityConverter() { }
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ {
return string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible; return string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible;

View file

@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
using Wox.Core.i18n; using Wox.Core.Resource;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
namespace Wox namespace Wox
@ -38,7 +38,7 @@ namespace Wox
UserSettingStorage.Instance.CustomPluginHotkeys = new List<CustomPluginHotkey>(); UserSettingStorage.Instance.CustomPluginHotkeys = new List<CustomPluginHotkey>();
} }
var pluginHotkey = new CustomPluginHotkey() var pluginHotkey = new CustomPluginHotkey
{ {
Hotkey = ctlHotkey.CurrentHotkey.ToString(), Hotkey = ctlHotkey.CurrentHotkey.ToString(),
ActionKeyword = tbAction.Text ActionKeyword = tbAction.Text

View file

@ -25,7 +25,7 @@ namespace Wox.Helper
{ {
if (!DropShadow(window)) if (!DropShadow(window))
{ {
window.SourceInitialized += new EventHandler(window_SourceInitialized); window.SourceInitialized += window_SourceInitialized;
} }
} }
@ -35,7 +35,7 @@ namespace Wox.Helper
DropShadow(window); DropShadow(window);
window.SourceInitialized -= new EventHandler(window_SourceInitialized); window.SourceInitialized -= window_SourceInitialized;
} }
/// <summary> /// <summary>

View file

@ -16,14 +16,14 @@ namespace Wox.Helper
public static void UnhandledExceptionHandle(object sender, UnhandledExceptionEventArgs e) public static void UnhandledExceptionHandle(object sender, UnhandledExceptionEventArgs e)
{ {
//handle non-ui thread exceptions //handle non-ui thread exceptions
App.Window.Dispatcher.Invoke(new Action(() => App.Window.Dispatcher.Invoke(() =>
{ {
Report((Exception)e.ExceptionObject); Report((Exception)e.ExceptionObject);
if (!(e.ExceptionObject is WoxException)) if (!(e.ExceptionObject is WoxException))
{ {
Environment.Exit(0); Environment.Exit(0);
} }
})); });
} }
public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)

View file

@ -9,6 +9,7 @@ using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters;
using System.Security; using System.Security;
using System.Text;
using System.Threading; using System.Threading;
using System.Windows; using System.Windows;
using System.Windows.Threading; using System.Windows.Threading;
@ -131,7 +132,7 @@ namespace Wox.Helper
// This is the hard-coded message value used by WinForms for Shell_NotifyIcon. // This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
// It's relatively safe to reuse. // It's relatively safe to reuse.
TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
APP = 0x8000, APP = 0x8000
} }
[SuppressUnmanagedCodeSecurity] [SuppressUnmanagedCodeSecurity]
@ -342,7 +343,7 @@ namespace Wox.Helper
{ {
try try
{ {
using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode)) using (TextReader reader = new StreamReader(cmdLinePath, Encoding.Unicode))
{ {
args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd()); args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
} }
@ -465,7 +466,7 @@ namespace Wox.Helper
{ {
// Do an asynchronous call to ActivateFirstInstance function // Do an asynchronous call to ActivateFirstInstance function
Application.Current.Dispatcher.BeginInvoke( Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance<TApplication>.ActivateFirstInstanceCallback), args); DispatcherPriority.Normal, new DispatcherOperationCallback(ActivateFirstInstanceCallback), args);
} }
} }

View file

@ -35,7 +35,7 @@ namespace Wox.Helper
{ {
try try
{ {
var parts = result.ToString().Trim().Split(new char[] {' '}, 3).Select(byte.Parse).ToList(); var parts = result.ToString().Trim().Split(new[] {' '}, 3).Select(byte.Parse).ToList();
return Color.FromRgb(parts[0], parts[1], parts[2]); return Color.FromRgb(parts[0], parts[1], parts[2]);
} }
catch catch

View file

@ -5,7 +5,7 @@ using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using NHotkey.Wpf; using NHotkey.Wpf;
using Wox.Core.i18n; using Wox.Core.Resource;
using Wox.Infrastructure.Hotkey; using Wox.Infrastructure.Hotkey;
using Wox.Plugin; using Wox.Plugin;

View file

@ -10,19 +10,11 @@ namespace Wox.ImageLoader
[Serializable] [Serializable]
public class ImageCacheStroage : BinaryStorage<ImageCacheStroage> public class ImageCacheStroage : BinaryStorage<ImageCacheStroage>
{ {
private int counter = 0; private int counter;
private const int maxCached = 200; private const int maxCached = 200;
public Dictionary<string, int> TopUsedImages = new Dictionary<string, int>(); public Dictionary<string, int> TopUsedImages = new Dictionary<string, int>();
protected override string ConfigFolder protected override string FileName { get; } = "ImageCache";
{
get { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config"); }
}
protected override string ConfigName
{
get { return "ImageCache"; }
}
public void Add(string path) public void Add(string path)
{ {

View file

@ -4,6 +4,7 @@ using System.Drawing;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
using System.Windows.Interop;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using Wox.Infrastructure; using Wox.Infrastructure;
@ -43,7 +44,7 @@ namespace Wox.ImageLoader
Icon icon = GetFileIcon(fileName) ?? Icon.ExtractAssociatedIcon(fileName); Icon icon = GetFileIcon(fileName) ?? Icon.ExtractAssociatedIcon(fileName);
if (icon != null) if (icon != null)
{ {
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, return Imaging.CreateBitmapSourceFromHIcon(icon.Handle,
new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions()); new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions());
} }
} }
@ -206,7 +207,7 @@ namespace Wox.ImageLoader
public string szDisplayName; public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NAMESIZE)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NAMESIZE)]
public string szTypeName; public string szTypeName;
}; }
private const uint SHGFI_ICON = 0x000000100; // get icon private const uint SHGFI_ICON = 0x000000100; // get icon
private const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name private const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name

View file

@ -10,13 +10,13 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media.Animation; using System.Windows.Media.Animation;
using NHotkey; using NHotkey;
using NHotkey.Wpf; using NHotkey.Wpf;
using Wox.Core.i18n;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Core.Theme; using Wox.Core.Resource;
using Wox.Core.Updater; using Wox.Core.Updater;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Helper; using Wox.Helper;
@ -24,11 +24,16 @@ using Wox.Infrastructure;
using Wox.Infrastructure.Hotkey; using Wox.Infrastructure.Hotkey;
using Wox.Plugin; using Wox.Plugin;
using Wox.Storage; using Wox.Storage;
using Application = System.Windows.Application;
using ContextMenu = System.Windows.Forms.ContextMenu; using ContextMenu = System.Windows.Forms.ContextMenu;
using NotifyIcon = System.Windows.Forms.NotifyIcon; using DataFormats = System.Windows.DataFormats;
using Screen = System.Windows.Forms.Screen; using DragEventArgs = System.Windows.DragEventArgs;
using IDataObject = System.Windows.IDataObject;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MenuItem = System.Windows.Forms.MenuItem; using MenuItem = System.Windows.Forms.MenuItem;
using MessageBox = System.Windows.MessageBox;
using Stopwatch = Wox.Infrastructure.Stopwatch; using Stopwatch = Wox.Infrastructure.Stopwatch;
using ToolTip = System.Windows.Controls.ToolTip;
namespace Wox namespace Wox
{ {
@ -43,7 +48,7 @@ namespace Wox
private Query _lastQuery = new Query(); private Query _lastQuery = new Query();
private ToolTip toolTip = new ToolTip(); private ToolTip toolTip = new ToolTip();
private bool _ignoreTextChange = false; private bool _ignoreTextChange;
private List<Result> CurrentContextMenus = new List<Result>(); private List<Result> CurrentContextMenus = new List<Result>();
private string textBeforeEnterContextMenuMode; private string textBeforeEnterContextMenuMode;
@ -53,7 +58,7 @@ namespace Wox
public void ChangeQuery(string query, bool requery = false) public void ChangeQuery(string query, bool requery = false)
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
tbQuery.Text = query; tbQuery.Text = query;
tbQuery.CaretIndex = tbQuery.Text.Length; tbQuery.CaretIndex = tbQuery.Text.Length;
@ -61,12 +66,12 @@ namespace Wox
{ {
TbQuery_OnTextChanged(null, null); TbQuery_OnTextChanged(null, null);
} }
})); });
} }
public void ChangeQueryText(string query, bool selectAll = false) public void ChangeQueryText(string query, bool selectAll = false)
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
_ignoreTextChange = true; _ignoreTextChange = true;
tbQuery.Text = query; tbQuery.Text = query;
@ -75,7 +80,7 @@ namespace Wox
{ {
tbQuery.SelectAll(); tbQuery.SelectAll();
} }
})); });
} }
public void CloseApp() public void CloseApp()
@ -96,50 +101,50 @@ namespace Wox
public void HideApp() public void HideApp()
{ {
Dispatcher.Invoke(new Action(HideWox)); Dispatcher.Invoke(HideWox);
} }
public void ShowApp() public void ShowApp()
{ {
Dispatcher.Invoke(new Action(() => ShowWox())); Dispatcher.Invoke(() => ShowWox());
} }
public void ShowMsg(string title, string subTitle, string iconPath) public void ShowMsg(string title, string subTitle, string iconPath)
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
var m = new Msg { Owner = GetWindow(this) }; var m = new Msg { Owner = GetWindow(this) };
m.Show(title, subTitle, iconPath); m.Show(title, subTitle, iconPath);
})); });
} }
public void OpenSettingDialog(string tabName = "general") public void OpenSettingDialog(string tabName = "general")
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
SettingWindow sw = SingletonWindowOpener.Open<SettingWindow>(this); SettingWindow sw = SingletonWindowOpener.Open<SettingWindow>(this);
sw.SwitchTo(tabName); sw.SwitchTo(tabName);
})); });
} }
public void StartLoadingBar() public void StartLoadingBar()
{ {
Dispatcher.Invoke(new Action(StartProgress)); Dispatcher.Invoke(StartProgress);
} }
public void StopLoadingBar() public void StopLoadingBar()
{ {
Dispatcher.Invoke(new Action(StopProgress)); Dispatcher.Invoke(StopProgress);
} }
public void InstallPlugin(string path) public void InstallPlugin(string path)
{ {
Dispatcher.Invoke(new Action(() => PluginManager.InstallPlugin(path))); Dispatcher.Invoke(() => PluginManager.InstallPlugin(path));
} }
public void ReloadPlugins() public void ReloadPlugins()
{ {
Dispatcher.Invoke(new Action(() => PluginManager.Init(this))); Dispatcher.Invoke(() => PluginManager.Init(this));
} }
public string GetTranslation(string key) public string GetTranslation(string key)
@ -241,7 +246,7 @@ namespace Wox
UserSettingStorage.Instance.WindowLeft = Left; UserSettingStorage.Instance.WindowLeft = Left;
UserSettingStorage.Instance.WindowTop = Top; UserSettingStorage.Instance.WindowTop = Top;
UserSettingStorage.Instance.Save(); UserSettingStorage.Instance.Save();
this.HideWox(); HideWox();
e.Cancel = true; e.Cancel = true;
} }
@ -293,10 +298,10 @@ namespace Wox
private void OnPrepareUpdateReady(object sender, EventArgs e) private void OnPrepareUpdateReady(object sender, EventArgs e)
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
new WoxUpdate().ShowDialog(); new WoxUpdate().ShowDialog();
})); });
} }
public void SetHotkey(string hotkeyStr, EventHandler<HotkeyEventArgs> action) public void SetHotkey(string hotkeyStr, EventHandler<HotkeyEventArgs> action)
@ -664,7 +669,7 @@ namespace Wox
case Key.Back: case Key.Back:
if (BackKeyDownEvent != null) if (BackKeyDownEvent != null)
{ {
BackKeyDownEvent(new WoxKeyDownEventArgs() BackKeyDownEvent(new WoxKeyDownEventArgs
{ {
Query = tbQuery.Text, Query = tbQuery.Text,
keyEventArgs = e keyEventArgs = e
@ -736,13 +741,14 @@ namespace Wox
var executeQueryHistoryTitle = GetTranslation("executeQuery"); var executeQueryHistoryTitle = GetTranslation("executeQuery");
var lastExecuteTime = GetTranslation("lastExecuteTime"); var lastExecuteTime = GetTranslation("lastExecuteTime");
pnlResult.RemoveResultsExcept(historyMetadata); pnlResult.RemoveResultsExcept(historyMetadata);
UpdateResultViewInternal(new List<Result>() UpdateResultViewInternal(new List<Result>
{ {
new Result(){ new Result
{
Title = string.Format(executeQueryHistoryTitle,history.Query), Title = string.Format(executeQueryHistoryTitle,history.Query),
SubTitle = string.Format(lastExecuteTime,history.ExecutedDateTime), SubTitle = string.Format(lastExecuteTime,history.ExecutedDateTime),
IcoPath = "Images\\history.png", IcoPath = "Images\\history.png",
PluginDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), PluginDirectory = WoxDirectroy.Executable,
Action = _ =>{ Action = _ =>{
ChangeQuery(history.Query,true); ChangeQuery(history.Query,true);
return false; return false;
@ -815,7 +821,7 @@ namespace Wox
{ {
if (result.Action != null) if (result.Action != null)
{ {
bool hideWindow = result.Action(new ActionContext() bool hideWindow = result.Action(new ActionContext
{ {
SpecialKeyState = GlobalHotkey.Instance.CheckModifiers() SpecialKeyState = GlobalHotkey.Instance.CheckModifiers()
}); });
@ -831,9 +837,8 @@ namespace Wox
private void UpdateResultView(List<Result> list, PluginMetadata metadata, Query originQuery) private void UpdateResultView(List<Result> list, PluginMetadata metadata, Query originQuery)
{ {
Thread.Sleep(3000);
_queryHasReturn = true; _queryHasReturn = true;
progressBar.Dispatcher.Invoke(new Action(StopProgress)); progressBar.Dispatcher.Invoke(StopProgress);
list.ForEach(o => list.ForEach(o =>
{ {
@ -847,11 +852,11 @@ namespace Wox
private void UpdateResultViewInternal(List<Result> list, PluginMetadata metadata) private void UpdateResultViewInternal(List<Result> list, PluginMetadata metadata)
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(() =>
{ {
Stopwatch.Normal($"UI update cost for {metadata.Name}", Stopwatch.Normal($"UI update cost for {metadata.Name}",
() => { pnlResult.AddResults(list, metadata.ID); }); () => { pnlResult.AddResults(list, metadata.ID); });
})); });
} }
private Result GetTopMostContextMenu(Result result) private Result GetTopMostContextMenu(Result result)
@ -860,7 +865,7 @@ namespace Wox
{ {
return new Result(GetTranslation("cancelTopMostInThisQuery"), "Images\\down.png") return new Result(GetTranslation("cancelTopMostInThisQuery"), "Images\\down.png")
{ {
PluginDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), PluginDirectory = WoxDirectroy.Executable,
Action = _ => Action = _ =>
{ {
TopMostRecordStorage.Instance.Remove(result); TopMostRecordStorage.Instance.Remove(result);
@ -873,7 +878,7 @@ namespace Wox
{ {
return new Result(GetTranslation("setAsTopMostInThisQuery"), "Images\\up.png") return new Result(GetTranslation("setAsTopMostInThisQuery"), "Images\\up.png")
{ {
PluginDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), PluginDirectory = WoxDirectroy.Executable,
Action = _ => Action = _ =>
{ {
TopMostRecordStorage.Instance.AddOrUpdate(result); TopMostRecordStorage.Instance.AddOrUpdate(result);

View file

@ -12,7 +12,7 @@ namespace Wox
public partial class Msg : Window public partial class Msg : Window
{ {
Storyboard fadeOutStoryboard = new Storyboard(); Storyboard fadeOutStoryboard = new Storyboard();
private bool closing = false; private bool closing;
public Msg() public Msg()
{ {
@ -21,13 +21,13 @@ namespace Wox
var dipWorkingArea = WindowIntelopHelper.TransformPixelsToDIP(this, var dipWorkingArea = WindowIntelopHelper.TransformPixelsToDIP(this,
screen.WorkingArea.Width, screen.WorkingArea.Width,
screen.WorkingArea.Height); screen.WorkingArea.Height);
Left = dipWorkingArea.X - this.Width; Left = dipWorkingArea.X - Width;
Top = dipWorkingArea.Y; Top = dipWorkingArea.Y;
showAnimation.From = dipWorkingArea.Y; showAnimation.From = dipWorkingArea.Y;
showAnimation.To = dipWorkingArea.Y - Height; showAnimation.To = dipWorkingArea.Y - Height;
// Create the fade out storyboard // Create the fade out storyboard
fadeOutStoryboard.Completed += new EventHandler(fadeOutStoryboard_Completed); fadeOutStoryboard.Completed += fadeOutStoryboard_Completed;
DoubleAnimation fadeOutAnimation = new DoubleAnimation(dipWorkingArea.Y - Height, dipWorkingArea.Y, new Duration(TimeSpan.FromSeconds(0.3))) DoubleAnimation fadeOutAnimation = new DoubleAnimation(dipWorkingArea.Y - Height, dipWorkingArea.Y, new Duration(TimeSpan.FromSeconds(0.3)))
{ {
AccelerationRatio = 0.2 AccelerationRatio = 0.2

View file

@ -1,9 +1,10 @@
using System.Reflection; using System.Reflection;
using System.Windows; using System.Windows;
using Exceptionless.Configuration;
[assembly: AssemblyTitle("Wox")] [assembly: AssemblyTitle("Wox")]
[assembly: ThemeInfo( [assembly: ThemeInfo(
ResourceDictionaryLocation.None, ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly ResourceDictionaryLocation.SourceAssembly
)] )]
[assembly: Exceptionless.Configuration.Exceptionless("e0b256fbe9384498ba89aae2a6b7f8ab")] [assembly: Exceptionless("e0b256fbe9384498ba89aae2a6b7f8ab")]

View file

@ -11,13 +11,11 @@ using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using Microsoft.Win32; using Microsoft.Win32;
using Wox.Core.i18n;
using Wox.Core.Plugin; using Wox.Core.Plugin;
using Wox.Core.Theme; using Wox.Core.Resource;
using Wox.Core.Updater; using Wox.Core.Updater;
using Wox.Core.UserSettings; using Wox.Core.UserSettings;
using Wox.Helper; using Wox.Helper;
using Wox.Infrastructure.Exception;
using Wox.Plugin; using Wox.Plugin;
using Application = System.Windows.Forms.Application; using Application = System.Windows.Forms.Application;
using Stopwatch = Wox.Infrastructure.Stopwatch; using Stopwatch = Wox.Infrastructure.Stopwatch;
@ -27,13 +25,13 @@ namespace Wox
public partial class SettingWindow : Window public partial class SettingWindow : Window
{ {
public readonly MainWindow MainWindow; public readonly MainWindow MainWindow;
bool settingsLoaded = false; bool settingsLoaded;
private Dictionary<ISettingProvider, Control> featureControls = new Dictionary<ISettingProvider, Control>(); private Dictionary<ISettingProvider, Control> featureControls = new Dictionary<ISettingProvider, Control>();
private bool themeTabLoaded = false; private bool themeTabLoaded;
public SettingWindow(MainWindow mainWindow) public SettingWindow(MainWindow mainWindow)
{ {
this.MainWindow = mainWindow; MainWindow = mainWindow;
InitializeComponent(); InitializeComponent();
Loaded += Setting_Loaded; Loaded += Setting_Loaded;
} }
@ -248,7 +246,7 @@ namespace Wox
#region Hotkey #region Hotkey
void ctlHotkey_OnHotkeyChanged(object sender, System.EventArgs e) void ctlHotkey_OnHotkeyChanged(object sender, EventArgs e)
{ {
if (ctlHotkey.CurrentHotkeyAvailable) if (ctlHotkey.CurrentHotkeyAvailable)
{ {
@ -362,50 +360,50 @@ namespace Wox
)); ));
} }
resultPanelPreview.AddResults(new List<Result>() resultPanelPreview.AddResults(new List<Result>
{ {
new Result() new Result
{ {
Title = "Wox is an effective launcher for windows", Title = "Wox is an effective launcher for windows",
SubTitle = "Wox provide bundles of features let you access infomations quickly.", SubTitle = "Wox provide bundles of features let you access infomations quickly.",
IcoPath = "Images/app.png", IcoPath = "Images/app.png",
PluginDirectory = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath)
}, },
new Result() new Result
{ {
Title = "Search applications", Title = "Search applications",
SubTitle = "Search applications, files (via everything plugin) and browser bookmarks", SubTitle = "Search applications, files (via everything plugin) and browser bookmarks",
IcoPath = "Images/app.png", IcoPath = "Images/app.png",
PluginDirectory = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath)
}, },
new Result() new Result
{ {
Title = "Search web contents with shortcuts", Title = "Search web contents with shortcuts",
SubTitle = "e.g. search google with g keyword or youtube keyword)", SubTitle = "e.g. search google with g keyword or youtube keyword)",
IcoPath = "Images/app.png", IcoPath = "Images/app.png",
PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath) PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath)
}, },
new Result() new Result
{ {
Title = "clipboard history ", Title = "clipboard history ",
IcoPath = "Images/app.png", IcoPath = "Images/app.png",
PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath) PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath)
}, },
new Result() new Result
{ {
Title = "Themes support", Title = "Themes support",
SubTitle = "get more themes from http://www.getwox.com/theme", SubTitle = "get more themes from http://www.getwox.com/theme",
IcoPath = "Images/app.png", IcoPath = "Images/app.png",
PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath) PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath)
}, },
new Result() new Result
{ {
Title = "Plugins support", Title = "Plugins support",
SubTitle = "get more plugins from http://www.getwox.com/plugin", SubTitle = "get more plugins from http://www.getwox.com/plugin",
IcoPath = "Images/app.png", IcoPath = "Images/app.png",
PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath) PluginDirectory = Path.GetDirectoryName(Application.ExecutablePath)
}, },
new Result() new Result
{ {
Title = "Wox is an open-source software", Title = "Wox is an open-source software",
SubTitle = "Wox benefits from the open-source community a lot", SubTitle = "Wox benefits from the open-source community a lot",
@ -416,7 +414,7 @@ namespace Wox
foreach (string theme in ThemeManager.Theme.LoadAvailableThemes()) foreach (string theme in ThemeManager.Theme.LoadAvailableThemes())
{ {
string themeName = System.IO.Path.GetFileNameWithoutExtension(theme); string themeName = Path.GetFileNameWithoutExtension(theme);
themeComboBox.Items.Add(themeName); themeComboBox.Items.Add(themeName);
} }
@ -453,7 +451,7 @@ namespace Wox
if (!settingsLoaded) return; if (!settingsLoaded) return;
string queryBoxFontName = cbQueryBoxFont.SelectedItem.ToString(); string queryBoxFontName = cbQueryBoxFont.SelectedItem.ToString();
UserSettingStorage.Instance.QueryBoxFont = queryBoxFontName; UserSettingStorage.Instance.QueryBoxFont = queryBoxFontName;
this.cbQueryBoxFontFaces.SelectedItem = ((FontFamily)cbQueryBoxFont.SelectedItem).ChooseRegularFamilyTypeface(); cbQueryBoxFontFaces.SelectedItem = ((FontFamily)cbQueryBoxFont.SelectedItem).ChooseRegularFamilyTypeface();
UserSettingStorage.Instance.Save(); UserSettingStorage.Instance.Save();
ThemeManager.Theme.ChangeTheme(UserSettingStorage.Instance.Theme); ThemeManager.Theme.ChangeTheme(UserSettingStorage.Instance.Theme);
} }
@ -466,8 +464,6 @@ namespace Wox
{ {
if (cbQueryBoxFontFaces.Items.Count > 0) if (cbQueryBoxFontFaces.Items.Count > 0)
cbQueryBoxFontFaces.SelectedIndex = 0; cbQueryBoxFontFaces.SelectedIndex = 0;
return;
} }
else else
{ {
@ -484,7 +480,7 @@ namespace Wox
if (!settingsLoaded) return; if (!settingsLoaded) return;
string resultItemFont = cbResultItemFont.SelectedItem.ToString(); string resultItemFont = cbResultItemFont.SelectedItem.ToString();
UserSettingStorage.Instance.ResultItemFont = resultItemFont; UserSettingStorage.Instance.ResultItemFont = resultItemFont;
this.cbResultItemFontFaces.SelectedItem = ((FontFamily)cbResultItemFont.SelectedItem).ChooseRegularFamilyTypeface(); cbResultItemFontFaces.SelectedItem = ((FontFamily)cbResultItemFont.SelectedItem).ChooseRegularFamilyTypeface();
UserSettingStorage.Instance.Save(); UserSettingStorage.Instance.Save();
ThemeManager.Theme.ChangeTheme(UserSettingStorage.Instance.Theme); ThemeManager.Theme.ChangeTheme(UserSettingStorage.Instance.Theme);
} }
@ -596,7 +592,7 @@ namespace Wox
if (customizedPluginConfig == null) if (customizedPluginConfig == null)
{ {
// todo when this part will be invoked // todo when this part will be invoked
UserSettingStorage.Instance.CustomizedPluginConfigs.Add(new CustomizedPluginConfig() UserSettingStorage.Instance.CustomizedPluginConfigs.Add(new CustomizedPluginConfig
{ {
Disabled = cbDisabled.IsChecked ?? true, Disabled = cbDisabled.IsChecked ?? true,
ID = id, ID = id,
@ -800,7 +796,7 @@ namespace Wox
#endregion #endregion
private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{ {
// Hide window with ESC, but make sure it is not pressed as a hotkey // Hide window with ESC, but make sure it is not pressed as a hotkey
if (e.Key == Key.Escape && !ctlHotkey.IsFocused) if (e.Key == Key.Escape && !ctlHotkey.IsFocused)

View file

@ -15,20 +15,12 @@ namespace Wox.Storage
private List<HistoryItem> History = new List<HistoryItem>(); private List<HistoryItem> History = new List<HistoryItem>();
private int MaxHistory = 300; private int MaxHistory = 300;
private int cursor = 0; private int cursor;
public static PluginMetadata MetaData { get; } = new PluginMetadata public static PluginMetadata MetaData { get; } = new PluginMetadata
{ ID = "Query history", Name = "Query history" }; { ID = "Query history", Name = "Query history" };
protected override string ConfigFolder protected override string FileName { get; } = "QueryHistory";
{
get { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config"); }
}
protected override string ConfigName
{
get { return "QueryHistory"; }
}
public HistoryItem Previous() public HistoryItem Previous()
{ {
@ -61,7 +53,7 @@ namespace Wox.Storage
} }
else else
{ {
History.Add(new HistoryItem() History.Add(new HistoryItem
{ {
Query = query, Query = query,
ExecutedDateTime = DateTime.Now ExecutedDateTime = DateTime.Now

View file

@ -3,6 +3,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using Wox.Infrastructure.Storage; using Wox.Infrastructure.Storage;
using Wox.Plugin;
namespace Wox.Storage namespace Wox.Storage
{ {
@ -10,17 +11,9 @@ namespace Wox.Storage
{ {
public Dictionary<string, TopMostRecord> records = new Dictionary<string, TopMostRecord>(); public Dictionary<string, TopMostRecord> records = new Dictionary<string, TopMostRecord>();
protected override string ConfigFolder protected override string FileName { get; } = "TopMostRecords";
{
get { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config"); }
}
protected override string ConfigName internal bool IsTopMost(Result result)
{
get { return "TopMostRecords"; }
}
internal bool IsTopMost(Plugin.Result result)
{ {
return records.Any(o => o.Value.Title == result.Title return records.Any(o => o.Value.Title == result.Title
&& o.Value.SubTitle == result.SubTitle && o.Value.SubTitle == result.SubTitle
@ -28,7 +21,7 @@ namespace Wox.Storage
&& o.Key == result.OriginQuery.RawQuery); && o.Key == result.OriginQuery.RawQuery);
} }
internal void Remove(Plugin.Result result) internal void Remove(Result result)
{ {
if (records.ContainsKey(result.OriginQuery.RawQuery)) if (records.ContainsKey(result.OriginQuery.RawQuery))
{ {
@ -37,7 +30,7 @@ namespace Wox.Storage
} }
} }
internal void AddOrUpdate(Plugin.Result result) internal void AddOrUpdate(Result result)
{ {
if (records.ContainsKey(result.OriginQuery.RawQuery)) if (records.ContainsKey(result.OriginQuery.RawQuery))
{ {
@ -47,12 +40,12 @@ namespace Wox.Storage
} }
else else
{ {
records.Add(result.OriginQuery.RawQuery, new TopMostRecord() records.Add(result.OriginQuery.RawQuery, new TopMostRecord
{ {
PluginID = result.PluginID, PluginID = result.PluginID,
Title = result.Title, Title = result.Title,
SubTitle = result.SubTitle, SubTitle = result.SubTitle
}); });
} }
Save(); Save();

View file

@ -12,15 +12,7 @@ namespace Wox.Storage
[JsonProperty] [JsonProperty]
private Dictionary<string, int> records = new Dictionary<string, int>(); private Dictionary<string, int> records = new Dictionary<string, int>();
protected override string ConfigFolder protected override string FileName { get; } = "UserSelectedRecords";
{
get { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config"); }
}
protected override string ConfigName
{
get { return "UserSelectedRecords"; }
}
public void Add(Result result) public void Add(Result result)
{ {

View file

@ -1,6 +1,6 @@
using System.Windows; using System.Windows;
using MarkdownSharp; using MarkdownSharp;
using Wox.Core.i18n; using Wox.Core.Resource;
using Wox.Core.Updater; using Wox.Core.Updater;
namespace Wox namespace Wox