Cleaned FileSystemPlugin + Enhanced

THIS NEEDS TESTING!
This commit is contained in:
Aaron Campf 2014-05-09 18:24:16 -07:00
parent 498634fd13
commit 81467a86cc
9 changed files with 626 additions and 718 deletions

View File

@ -8,16 +8,13 @@ using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Wox.Plugin.PluginManagement namespace Wox.Plugin.PluginManagement {
{ public class WoxPlugin {
public class WoxPlugin
{
public int apiVersion { get; set; } public int apiVersion { get; set; }
public List<WoxPluginResult> result { get; set; } public List<WoxPluginResult> result { get; set; }
} }
public class WoxPluginResult public class WoxPluginResult {
{
public string actionkeyword; public string actionkeyword;
public string download; public string download;
public string author; public string author;
@ -29,47 +26,29 @@ namespace Wox.Plugin.PluginManagement
public string website; public string website;
} }
public class Main : IPlugin public class Main : IPlugin {
{
private static string PluginPath = AppDomain.CurrentDomain.BaseDirectory + "Plugins"; private static string PluginPath = AppDomain.CurrentDomain.BaseDirectory + "Plugins";
private static string PluginConfigName = "plugin.json"; private static string PluginConfigName = "plugin.json";
private static string pluginSearchUrl = "http://www.getwox.com/api/plugin/search/"; private static string pluginSearchUrl = "http://www.getwox.com/api/plugin/search/";
private PluginInitContext context; private PluginInitContext context;
public List<Result> Query(Query query) public List<Result> Query(Query query) {
{
List<Result> results = new List<Result>(); List<Result> results = new List<Result>();
if (query.ActionParameters.Count == 0) if (query.ActionParameters.Count == 0) {
{ results.Add(new Result("wpm install <pluginName>", "Images\\plugin.png", "search and install wox plugins") {
results.Add(new Result() Action = e => {
{
Title = "wpm install <pluginName>",
SubTitle = "search and install wox plugins",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm install "); context.ChangeQuery("wpm install ");
return false; return false;
} }
}); });
results.Add(new Result() results.Add(new Result("wpm uninstall <pluginName>", "Images\\plugin.png", "uninstall plugin") {
{ Action = e => {
Title = "wpm uninstall <pluginName>",
SubTitle = "uninstall plugin",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm uninstall "); context.ChangeQuery("wpm uninstall ");
return false; return false;
} }
}); });
results.Add(new Result() results.Add(new Result("wpm list", "Images\\plugin.png", "list plugins installed") {
{ Action = e => {
Title = "wpm list",
SubTitle = "list plugins installed",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm list"); context.ChangeQuery("wpm list");
return false; return false;
} }
@ -77,11 +56,9 @@ namespace Wox.Plugin.PluginManagement
return results; return results;
} }
if (query.ActionParameters.Count > 0) if (query.ActionParameters.Count > 0) {
{
bool hit = false; bool hit = false;
switch (query.ActionParameters[0].ToLower()) switch (query.ActionParameters[0].ToLower()) {
{
case "list": case "list":
hit = true; hit = true;
results = ListInstalledPlugins(); results = ListInstalledPlugins();
@ -94,52 +71,32 @@ namespace Wox.Plugin.PluginManagement
case "install": case "install":
hit = true; hit = true;
if (query.ActionParameters.Count > 1) if (query.ActionParameters.Count > 1) {
{
results = InstallPlugin(query); results = InstallPlugin(query);
} }
break; break;
} }
if (!hit) if (!hit) {
{ if ("install".Contains(query.ActionParameters[0].ToLower())) {
if ("install".Contains(query.ActionParameters[0].ToLower())) results.Add(new Result("wpm install <pluginName>", "Images\\plugin.png", "search and install wox plugins") {
{ Action = e => {
results.Add(new Result()
{
Title = "wpm install <pluginName>",
SubTitle = "search and install wox plugins",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm install "); context.ChangeQuery("wpm install ");
return false; return false;
} }
}); });
} }
if ("uninstall".Contains(query.ActionParameters[0].ToLower())) if ("uninstall".Contains(query.ActionParameters[0].ToLower())) {
{ results.Add(new Result("wpm uninstall <pluginName>", "Images\\plugin.png", "uninstall plugin") {
results.Add(new Result() Action = e => {
{
Title = "wpm uninstall <pluginName>",
SubTitle = "uninstall plugin",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm uninstall "); context.ChangeQuery("wpm uninstall ");
return false; return false;
} }
}); });
} }
if ("list".Contains(query.ActionParameters[0].ToLower())) if ("list".Contains(query.ActionParameters[0].ToLower())) {
{ results.Add(new Result("wpm list", "Images\\plugin.png", "list plugins installed") {
results.Add(new Result() Action = e => {
{
Title = "wpm list",
SubTitle = "list plugins installed",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm list"); context.ChangeQuery("wpm list");
return false; return false;
} }
@ -151,52 +108,41 @@ namespace Wox.Plugin.PluginManagement
return results; return results;
} }
private List<Result> InstallPlugin(Query query) private List<Result> InstallPlugin(Query query) {
{
List<Result> results = new List<Result>(); List<Result> results = new List<Result>();
HttpWebResponse response = HttpRequest.CreateGetHttpResponse(pluginSearchUrl + query.ActionParameters[1], null, null, null); HttpWebResponse response = HttpRequest.CreateGetHttpResponse(pluginSearchUrl + query.ActionParameters[1], null, null, null);
Stream s = response.GetResponseStream(); Stream s = response.GetResponseStream();
if (s != null) if (s != null) {
{
StreamReader reader = new StreamReader(s, Encoding.UTF8); StreamReader reader = new StreamReader(s, Encoding.UTF8);
string json = reader.ReadToEnd(); string json = reader.ReadToEnd();
WoxPlugin o = JsonConvert.DeserializeObject<WoxPlugin>(json); WoxPlugin o = JsonConvert.DeserializeObject<WoxPlugin>(json);
foreach (WoxPluginResult r in o.result) foreach (WoxPluginResult r in o.result) {
{
WoxPluginResult r1 = r; WoxPluginResult r1 = r;
results.Add(new Result() results.Add(new Result() {
{
Title = r.name, Title = r.name,
SubTitle = r.description, SubTitle = r.description,
IcoPath = "Images\\plugin.png", IcoPath = "Images\\plugin.png",
Action = e => Action = e => {
{
DialogResult result = MessageBox.Show("Are your sure to install " + r.name + " plugin", DialogResult result = MessageBox.Show("Are your sure to install " + r.name + " plugin",
"Install plugin", MessageBoxButtons.YesNo); "Install plugin", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes) if (result == DialogResult.Yes) {
{
string folder = Path.Combine(Path.GetTempPath(), "WoxPluginDownload"); string folder = Path.Combine(Path.GetTempPath(), "WoxPluginDownload");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
string filePath = Path.Combine(folder, Guid.NewGuid().ToString() + ".wox"); string filePath = Path.Combine(folder, Guid.NewGuid().ToString() + ".wox");
context.StartLoadingBar(); context.StartLoadingBar();
ThreadPool.QueueUserWorkItem(delegate ThreadPool.QueueUserWorkItem(delegate {
{ using (WebClient Client = new WebClient()) {
using (WebClient Client = new WebClient()) try {
{
try
{
Client.DownloadFile(r1.download, filePath); Client.DownloadFile(r1.download, filePath);
context.InstallPlugin(filePath); context.InstallPlugin(filePath);
context.ReloadPlugins(); context.ReloadPlugins();
} }
catch (Exception exception) catch (Exception exception) {
{
MessageBox.Show("download plugin " + r.name + "failed. " + exception.Message); MessageBox.Show("download plugin " + r.name + "failed. " + exception.Message);
} }
finally finally {
{
context.StopLoadingBar(); context.StopLoadingBar();
} }
} }
@ -210,26 +156,21 @@ namespace Wox.Plugin.PluginManagement
return results; return results;
} }
private List<Result> ListUnInstalledPlugins(Query query) private List<Result> ListUnInstalledPlugins(Query query) {
{
List<Result> results = new List<Result>(); List<Result> results = new List<Result>();
List<PluginMetadata> allInstalledPlugins = ParseThirdPartyPlugins(); List<PluginMetadata> allInstalledPlugins = ParseThirdPartyPlugins();
if (query.ActionParameters.Count > 1) if (query.ActionParameters.Count > 1) {
{
string pluginName = query.ActionParameters[1]; string pluginName = query.ActionParameters[1];
allInstalledPlugins = allInstalledPlugins =
allInstalledPlugins.Where(o => o.Name.ToLower().Contains(pluginName.ToLower())).ToList(); allInstalledPlugins.Where(o => o.Name.ToLower().Contains(pluginName.ToLower())).ToList();
} }
foreach (PluginMetadata plugin in allInstalledPlugins) foreach (PluginMetadata plugin in allInstalledPlugins) {
{ results.Add(new Result() {
results.Add(new Result()
{
Title = plugin.Name, Title = plugin.Name,
SubTitle = plugin.Description, SubTitle = plugin.Description,
IcoPath = "Images\\plugin.png", IcoPath = "Images\\plugin.png",
Action = e => Action = e => {
{
UnInstalledPlugins(plugin); UnInstalledPlugins(plugin);
return false; return false;
} }
@ -238,23 +179,18 @@ namespace Wox.Plugin.PluginManagement
return results; return results;
} }
private void UnInstalledPlugins(PluginMetadata plugin) private void UnInstalledPlugins(PluginMetadata plugin) {
{
string content = string.Format("Do you want to uninstall following plugin?\r\n\r\nName: {0}\r\nVersion: {1}\r\nAuthor: {2}", plugin.Name, plugin.Version, plugin.Author); string content = string.Format("Do you want to uninstall following plugin?\r\n\r\nName: {0}\r\nVersion: {1}\r\nAuthor: {2}", plugin.Name, plugin.Version, plugin.Author);
if (MessageBox.Show(content, "Wox", MessageBoxButtons.YesNo) == DialogResult.Yes) if (MessageBox.Show(content, "Wox", MessageBoxButtons.YesNo) == DialogResult.Yes) {
{
File.Create(Path.Combine(plugin.PluginDirecotry, "NeedDelete.txt")).Close(); File.Create(Path.Combine(plugin.PluginDirecotry, "NeedDelete.txt")).Close();
MessageBox.Show("This plugin has been removed, restart Wox to take effect"); MessageBox.Show("This plugin has been removed, restart Wox to take effect");
} }
} }
private List<Result> ListInstalledPlugins() private List<Result> ListInstalledPlugins() {
{
List<Result> results = new List<Result>(); List<Result> results = new List<Result>();
foreach (PluginMetadata plugin in ParseThirdPartyPlugins()) foreach (PluginMetadata plugin in ParseThirdPartyPlugins()) {
{ results.Add(new Result() {
results.Add(new Result()
{
Title = plugin.Name + " - " + plugin.ActionKeyword, Title = plugin.Name + " - " + plugin.ActionKeyword,
SubTitle = plugin.Description, SubTitle = plugin.Description,
IcoPath = "Images\\plugin.png" IcoPath = "Images\\plugin.png"
@ -263,15 +199,13 @@ namespace Wox.Plugin.PluginManagement
return results; return results;
} }
private static List<PluginMetadata> ParseThirdPartyPlugins() private static List<PluginMetadata> ParseThirdPartyPlugins() {
{
List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>(); List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>();
if (!Directory.Exists(PluginPath)) if (!Directory.Exists(PluginPath))
Directory.CreateDirectory(PluginPath); Directory.CreateDirectory(PluginPath);
string[] directories = Directory.GetDirectories(PluginPath); string[] directories = Directory.GetDirectories(PluginPath);
foreach (string directory in directories) foreach (string directory in directories) {
{
PluginMetadata metadata = GetMetadataFromJson(directory); PluginMetadata metadata = GetMetadataFromJson(directory);
if (metadata != null) pluginMetadatas.Add(metadata); if (metadata != null) pluginMetadatas.Add(metadata);
} }
@ -279,37 +213,31 @@ namespace Wox.Plugin.PluginManagement
return pluginMetadatas; return pluginMetadatas;
} }
private static PluginMetadata GetMetadataFromJson(string pluginDirectory) private static PluginMetadata GetMetadataFromJson(string pluginDirectory) {
{
string configPath = Path.Combine(pluginDirectory, PluginConfigName); string configPath = Path.Combine(pluginDirectory, PluginConfigName);
PluginMetadata metadata; PluginMetadata metadata;
if (!File.Exists(configPath)) if (!File.Exists(configPath)) {
{
return null; return null;
} }
try try {
{
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath)); metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginType = PluginType.ThirdParty; metadata.PluginType = PluginType.ThirdParty;
metadata.PluginDirecotry = pluginDirectory; metadata.PluginDirecotry = pluginDirectory;
} }
catch (Exception) catch (Exception) {
{
string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath); string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath);
return null; return null;
} }
if (!AllowedLanguage.IsAllowed(metadata.Language)) if (!AllowedLanguage.IsAllowed(metadata.Language)) {
{
string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath, string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath,
metadata.Language); metadata.Language);
return null; return null;
} }
if (!File.Exists(metadata.ExecuteFilePath)) if (!File.Exists(metadata.ExecuteFilePath)) {
{
string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath, string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath,
metadata.ExecuteFilePath); metadata.ExecuteFilePath);
return null; return null;
@ -318,8 +246,7 @@ namespace Wox.Plugin.PluginManagement
return metadata; return metadata;
} }
public void Init(PluginInitContext context) public void Init(PluginInitContext context) {
{
this.context = context; this.context = context;
} }
} }

View File

@ -88,7 +88,8 @@ namespace Python.Runtime {
PyTrue = Runtime.PyObject_GetAttrString(op, "True"); PyTrue = Runtime.PyObject_GetAttrString(op, "True");
PyFalse = Runtime.PyObject_GetAttrString(op, "False"); PyFalse = Runtime.PyObject_GetAttrString(op, "False");
PyBoolType = Runtime.PyObject_Type(PyTrue); PyBoolType = Runtime.PyObject_Type(PyTrue);> Python.Runtime.Runtime.Initialize() C#
PyNoneType = Runtime.PyObject_Type(PyNone); PyNoneType = Runtime.PyObject_Type(PyNone);
PyTypeType = Runtime.PyObject_Type(PyNoneType); PyTypeType = Runtime.PyObject_Type(PyNoneType);

View File

@ -3,139 +3,82 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using Wox.Infrastructure; using Wox.Infrastructure;
using Wox.Infrastructure.Storage.UserSettings; using Wox.Infrastructure.Storage.UserSettings;
namespace Wox.Plugin.SystemPlugins.FileSystem { namespace Wox.Plugin.SystemPlugins.FileSystem {
public class FileSystemPlugin : BaseSystemPlugin, ISettingProvider { public class FileSystemPlugin : BaseSystemPlugin, ISettingProvider {
#region Properties
private PluginInitContext context; private PluginInitContext context;
private static List<string> driverNames = null; private static List<string> driverNames = null;
private static Dictionary<string, DirectoryInfo[]> parentDirectories = new Dictionary<string, DirectoryInfo[]>(); private static Dictionary<string, DirectoryInfo[]> parentDirectories = new Dictionary<string, DirectoryInfo[]>();
public override string Description { get { return base.Description; } }
public override string Name { get { return "File System"; } }
public override string IcoPath { get { return @"Images\folder.png"; } }
protected override List<Result> QueryInternal(Query query) { #endregion Properties
//TODO: Consider always clearing the cache
List<Result> results = new List<Result>();
if (string.IsNullOrEmpty(query.RawQuery)) {
// clear the cache
if (parentDirectories.Count > 0)
parentDirectories.Clear();
return results; #region Misc
protected override void InitInternal(PluginInitContext context) {
this.context = context;
if (UserSettingStorage.Instance.FolderLinks == null) {
UserSettingStorage.Instance.FolderLinks = new List<FolderLink>();
UserSettingStorage.Instance.Save();
}
} }
InitialDriverList(); public System.Windows.Controls.Control CreateSettingPanel() {
return new FileSystemSettings();
}
#endregion Misc
protected override List<Result> QueryInternal(Query query) {
#region 1
//TODO: Consider always clearing the cache
List<Result> results = new List<Result>();
//if (string.IsNullOrEmpty(query.RawQuery)) {
// // clear the cache
// if (parentDirectories.Count > 0) parentDirectories.Clear();
// return results;
//}
#endregion 1
var input = query.RawQuery.ToLower(); var input = query.RawQuery.ToLower();
var inputName = input.Split(new string[] { @"\" }, StringSplitOptions.None).First().ToLower(); var inputName = input.Split(new string[] { @"\" }, StringSplitOptions.None).First().ToLower();
var link = UserSettingStorage.Instance.FolderLinks.FirstOrDefault(x => x.Nickname.Equals(inputName, StringComparison.OrdinalIgnoreCase));
var currentPath = link == null ? input : link.Path + input.Remove(0, inputName.Length);
var link = UserSettingStorage.Instance.FolderLinks.FirstOrDefault(x => InitialDriverList();
x.Nickname.Equals(inputName, StringComparison.OrdinalIgnoreCase));
var currentPath = link != null ? link.Path : null;
foreach (var item in UserSettingStorage.Instance.FolderLinks) { foreach (var item in UserSettingStorage.Instance.FolderLinks.Where(x => x.Nickname.StartsWith(input, StringComparison.OrdinalIgnoreCase))) {
var Name = item.Nickname; //if (item.Nickname.StartsWith(input, StringComparison.OrdinalIgnoreCase)) { //&& item.Nickname.Length != input.Length) {
results.Add(new Result(item.Nickname, "Images/folder.png") {
if (Name.StartsWith(input, StringComparison.OrdinalIgnoreCase) && Name.Length != input.Length) {
Result result = new Result {
Title = Name,
IcoPath = "Images/folder.png",
Action = (c) => { Action = (c) => {
context.ChangeQuery(item.Nickname); context.ChangeQuery(item.Nickname);
return false; return false;
} }
}; });
//}
results.Add(result);
}
} }
if (currentPath == null) { if (link == null && !driverNames.Any(input.StartsWith))
if (!driverNames.Any(input.StartsWith))
return results; return results;
currentPath = input; QueryInternal_Directory_Exists(currentPath, input, results);
}
else
currentPath += input.Remove(0, inputName.Length);
if (Directory.Exists(currentPath)) { return results;
// show all child directory
if (input.EndsWith("\\") || input.EndsWith("/")) {
var dirInfo = new DirectoryInfo(currentPath);
var dirs = dirInfo.GetDirectories();
var parentDirKey = input.TrimEnd('\\', '/');
if (!parentDirectories.ContainsKey(parentDirKey))
parentDirectories.Add(parentDirKey, dirs);
foreach (var dir in dirs) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
var dirPath = dir.FullName;
Result result = new Result {
Title = dir.Name,
IcoPath = "Images/folder.png",
Action = (c) => {
context.ChangeQuery(dirPath);
return false;
}
};
results.Add(result);
}
if (results.Count == 0) {
Result result = new Result {
Title = "Open this directory",
SubTitle = "No files in this directory",
IcoPath = "Images/folder.png",
Action = (c) => {
Process.Start(currentPath);
return true;
}
};
results.Add(result);
}
foreach (var dir in dirInfo.GetFiles()) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
var dirPath = dir.FullName;
Result result = new Result {
Title = global::System.IO.Path.GetFileNameWithoutExtension(dirPath),
IcoPath = dirPath,
Action = (c) => {
try {
Process.Start(dirPath);
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Could not start " + dir.Name);
}
return true;
}
};
results.Add(result);
}
}
else {
Result result = new Result {
Title = "Open this directory",
SubTitle = string.Format("path: {0}", currentPath),
Score = 50,
IcoPath = "Images/folder.png",
Action = (c) => {
Process.Start(currentPath);
return true;
}
};
results.Add(result);
}
}
/*
// change to search in current directory // change to search in current directory
string parentDir = null; string parentDir = null;
try { try {
@ -143,38 +86,37 @@ namespace Wox.Plugin.SystemPlugins.FileSystem {
} }
catch { } catch { }
if (!string.IsNullOrEmpty(parentDir) && results.Count == 0) {
parentDir = parentDir.TrimEnd('\\', '/');
if (parentDirectories.ContainsKey(parentDir)) {
var dirs = parentDirectories[parentDir];
var queryFileName = Path.GetFileName(currentPath).ToLower();
var fuzzy = FuzzyMatcher.Create(queryFileName);
foreach (var dir in dirs) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
var matchResult = fuzzy.Evaluate(dir.Name);
if (!matchResult.Success)
continue;
var dirPath = dir.FullName;
Result result = new Result {
Title = dir.Name,
IcoPath = "Images/folder.png",
Score = matchResult.Score,
Action = (c) => {
context.ChangeQuery(dirPath);
return false;
}
};
results.Add(result);
}
}
}
return results; return results;
if (!string.IsNullOrEmpty(parentDir) && results.Count == 0) {
parentDir = parentDir.TrimEnd('\\', '/');
//TODO: Why are we doing the following check
//FUCK THIS CODE o.O!!!!!!!
if (parentDirectories.ContainsKey(parentDir)) {
var fuzzy = FuzzyMatcher.Create(Path.GetFileName(currentPath).ToLower());
foreach (var dir in parentDirectories[parentDir]) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
var matchResult = fuzzy.Evaluate(dir.Name);
if (!matchResult.Success) continue;
results.Add(new Result(dir.Name, "Images/folder.png") {
Score = matchResult.Score,
Action = (c) => {
context.ChangeQuery(dir.FullName);
return false;
}
});
}
}
}
return results;
*/
} }
private void InitialDriverList() { private void InitialDriverList() {
@ -187,30 +129,103 @@ namespace Wox.Plugin.SystemPlugins.FileSystem {
} }
} }
protected override void InitInternal(PluginInitContext context) { private void QueryInternal_Directory_Exists(string currentPath, string input, List<Result> results) {
this.context = context; string path = Directory.Exists(currentPath) ? new DirectoryInfo(currentPath).FullName : Path.GetDirectoryName(input);
if (UserSettingStorage.Instance.FolderLinks == null) { if (path != null) {
UserSettingStorage.Instance.FolderLinks = new List<FolderLink>(); var dirs = new DirectoryInfo(path).GetDirectories();
UserSettingStorage.Instance.Save();
var parentDirKey = input.TrimEnd('\\', '/');
if (!parentDirectories.ContainsKey(parentDirKey)) parentDirectories.Add(parentDirKey, dirs);
var fuzzy = FuzzyMatcher.Create(Path.GetFileName(currentPath).ToLower());
foreach (var dir in dirs) { //.Where(x => (x.Attributes & FileAttributes.Hidden) != 0)) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
var result = new Result(dir.Name, "Images/folder.png") {
Action = (c) => {
context.ChangeQuery(dir.FullName);
return false;
} }
};
if (Path.GetFileName(currentPath).ToLower() != "") {
var matchResult = fuzzy.Evaluate(dir.Name);
result.Score = matchResult.Score;
if (!matchResult.Success) continue;
} }
public override string Name { results.Add(result);
get { return "File System"; }
} }
public override string IcoPath { //if (results.Count == 0) {
get { return @"Images\folder.png"; } // results.Add(new Result("Open this directory", "Images/folder.png", "No files in this directory") {
// Action = (c) => {
// Process.Start(currentPath);
// return true;
// }
// });
//}
}
else {
//results.Add(new Result("Open this directory", "Images/folder.png", string.Format("path: {0}", currentPath)) {
// Score = 50,
// Action = (c) => {
// Process.Start(currentPath);
// return true;
// }
//});
} }
public System.Windows.Controls.Control CreateSettingPanel() { /**************************************************************/
return new FileSystemSettings(); /**************************************************************/
if (results.Count == 0) {
results.Add(new Result("Open this directory", "Images/folder.png", "No files in this directory") {
Action = (c) => {
Process.Start(currentPath);
return true;
}
});
} }
public override string Description {
get { return base.Description; }
/**************************************************************/
/**************************************************************/
var Folder = Path.GetDirectoryName(currentPath);
if (Folder != null) {
var dirInfo1 = new DirectoryInfo(Folder);
var fuzzy = FuzzyMatcher.Create(Path.GetFileName(currentPath).ToLower());
foreach (var dir in dirInfo1.GetFiles()) { //.Where(x => (x.Attributes & FileAttributes.Hidden) != 0)) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
var dirPath = dir.FullName;
Result result = new Result(System.IO.Path.GetFileNameWithoutExtension(dirPath), dirPath) {
Action = (c) => {
try {
Process.Start(dirPath);
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Could not start " + dir.Name);
}
return true;
}
};
if (Path.GetFileName(currentPath).ToLower() != "") {
var matchResult = fuzzy.Evaluate(dir.Name);
result.Score = matchResult.Score;
if (!matchResult.Success) continue;
}
results.Add(result);
}
}
} }
} }
} }

View File

@ -2,10 +2,8 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace Wox.Plugin namespace Wox.Plugin {
{ public class Result {
public class Result
{
public string Title { get; set; } public string Title { get; set; }
public string SubTitle { get; set; } public string SubTitle { get; set; }
public string IcoPath { get; set; } public string IcoPath { get; set; }
@ -32,17 +30,28 @@ namespace Wox.Plugin
/// </summary> /// </summary>
public string PluginDirectory { get; set; } public string PluginDirectory { get; set; }
public new bool Equals(object obj) public new bool Equals(object obj) {
{
if (obj == null || !(obj is Result)) return false; if (obj == null || !(obj is Result)) return false;
Result r = (Result)obj; Result r = (Result)obj;
return r.Title == Title && r.SubTitle == SubTitle; return r.Title == Title && r.SubTitle == SubTitle;
} }
public override string ToString() public override string ToString() {
{
return Title + SubTitle; return Title + SubTitle;
} }
public Result() {
}
public Result(string Title = null, string IcoPath = null, string SubTitle = null) {
this.Title = Title;
this.IcoPath = IcoPath;
this.SubTitle = SubTitle;
}
} }
} }

View File

@ -18,13 +18,10 @@ using MessageBoxOptions = System.Windows.Forms.MessageBoxOptions;
using StartupEventArgs = System.Windows.StartupEventArgs; using StartupEventArgs = System.Windows.StartupEventArgs;
using UnhandledExceptionEventArgs = System.UnhandledExceptionEventArgs; using UnhandledExceptionEventArgs = System.UnhandledExceptionEventArgs;
namespace Wox namespace Wox {
{ public static class EntryPoint {
public static class EntryPoint
{
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args) {
{
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle; AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle;
System.Windows.Forms.Application.ThreadException += ErrorReporting.ThreadException; System.Windows.Forms.Application.ThreadException += ErrorReporting.ThreadException;
@ -44,17 +41,15 @@ namespace Wox
// * OnStartup is fired when the first instance loads // * OnStartup is fired when the first instance loads
// * OnStartupNextInstance is fired when the application is re-run again // * OnStartupNextInstance is fired when the application is re-run again
// NOTE: it is redirected to this instance thanks to IsSingleInstance // NOTE: it is redirected to this instance thanks to IsSingleInstance
public class SingleInstanceManager : WindowsFormsApplicationBase [System.Diagnostics.DebuggerStepThrough]
{ public class SingleInstanceManager : WindowsFormsApplicationBase {
App app; App app;
public SingleInstanceManager() public SingleInstanceManager() {
{
this.IsSingleInstance = true; this.IsSingleInstance = true;
} }
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e) protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e) {
{
// First time app is launched // First time app is launched
app = new App(); app = new App();
//app.InitializeComponent(); //app.InitializeComponent();
@ -62,40 +57,33 @@ namespace Wox
return true; return true;
} }
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
{
// Subsequent launches // Subsequent launches
base.OnStartupNextInstance(eventArgs); base.OnStartupNextInstance(eventArgs);
app.Activate(eventArgs.CommandLine.ToArray()); app.Activate(eventArgs.CommandLine.ToArray());
} }
} }
public partial class App : Application public partial class App : Application {
{
private static MainWindow window; private static MainWindow window;
public static MainWindow Window public static MainWindow Window {
{ get {
get
{
return window; return window;
} }
} }
protected override void OnStartup(StartupEventArgs e) protected override void OnStartup(StartupEventArgs e) {
{
this.DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException; this.DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
base.OnStartup(e); base.OnStartup(e);
//for install plugin command when wox didn't start up //for install plugin command when wox didn't start up
//we shouldn't init MainWindow, just intall plugin and exit. //we shouldn't init MainWindow, just intall plugin and exit.
if (e.Args.Length > 0 && e.Args[0].ToLower() == "installplugin") if (e.Args.Length > 0 && e.Args[0].ToLower() == "installplugin") {
{
var path = e.Args[1]; var path = e.Args[1];
if (!File.Exists(path)) if (!File.Exists(path)) {
{
MessageBox.Show("Plugin " + path + " didn't exist"); MessageBox.Show("Plugin " + path + " didn't exist");
return; return;
} }
@ -104,25 +92,21 @@ namespace Wox
return; return;
} }
if (e.Args.Length > 0 && e.Args[0].ToLower() == "plugindebugger") if (e.Args.Length > 0 && e.Args[0].ToLower() == "plugindebugger") {
{
var path = e.Args[1]; var path = e.Args[1];
PluginLoader.Plugins.ActivatePluginDebugger(path); PluginLoader.Plugins.ActivatePluginDebugger(path);
} }
window = new MainWindow(); window = new MainWindow();
if (e.Args.Length == 0 || e.Args[0].ToLower() != "hidestart") if (e.Args.Length == 0 || e.Args[0].ToLower() != "hidestart") {
{
window.ShowApp(); window.ShowApp();
} }
window.ParseArgs(e.Args); window.ParseArgs(e.Args);
} }
public void Activate(string[] args) public void Activate(string[] args) {
{ if (args.Length == 0 || args[0].ToLower() != "hidestart") {
if (args.Length == 0 || args[0].ToLower() != "hidestart")
{
window.ShowApp(); window.ShowApp();
} }
window.ParseArgs(args); window.ParseArgs(args);

View File

@ -9,53 +9,45 @@ using Wox.Helper;
using Wox.Plugin; using Wox.Plugin;
using Wox.Plugin.SystemPlugins; using Wox.Plugin.SystemPlugins;
namespace Wox.PluginLoader namespace Wox.PluginLoader {
{ public abstract class BasePluginLoader {
public abstract class BasePluginLoader
{
private static string PluginPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Plugins"); private static string PluginPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Plugins");
private static string PluginConfigName = "plugin.json"; private static string PluginConfigName = "plugin.json";
protected static List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>(); protected static List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>();
public abstract List<PluginPair> LoadPlugin(); public abstract List<PluginPair> LoadPlugin();
public static void ParsePluginsConfig() public static void ParsePluginsConfig() {
{
pluginMetadatas.Clear(); pluginMetadatas.Clear();
ParseSystemPlugins(); ParseSystemPlugins();
ParseThirdPartyPlugins(); ParseThirdPartyPlugins();
if (Plugins.DebuggerMode != null) if (Plugins.DebuggerMode != null) {
{
PluginMetadata metadata = GetMetadataFromJson(Plugins.DebuggerMode); PluginMetadata metadata = GetMetadataFromJson(Plugins.DebuggerMode);
if (metadata != null) pluginMetadatas.Add(metadata); if (metadata != null) pluginMetadatas.Add(metadata);
} }
} }
private static void ParseSystemPlugins() private static void ParseSystemPlugins() {
{ pluginMetadatas.Add(new PluginMetadata() {
PluginMetadata metadata = new PluginMetadata(); Name = "System Plugins",
metadata.Name = "System Plugins"; Author = "System",
metadata.Author = "System"; Description = "system plugins collection",
metadata.Description = "system plugins collection"; Language = AllowedLanguage.CSharp,
metadata.Language = AllowedLanguage.CSharp; Version = "1.0",
metadata.Version = "1.0"; PluginType = PluginType.System,
metadata.PluginType = PluginType.System; ActionKeyword = "*",
metadata.ActionKeyword = "*"; ExecuteFileName = "Wox.Plugin.SystemPlugins.dll",
metadata.ExecuteFileName = "Wox.Plugin.SystemPlugins.dll"; PluginDirecotry = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)
metadata.PluginDirecotry = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); });
pluginMetadatas.Add(metadata);
} }
private static void ParseThirdPartyPlugins() private static void ParseThirdPartyPlugins() {
{
if (!Directory.Exists(PluginPath)) if (!Directory.Exists(PluginPath))
Directory.CreateDirectory(PluginPath); Directory.CreateDirectory(PluginPath);
string[] directories = Directory.GetDirectories(PluginPath); string[] directories = Directory.GetDirectories(PluginPath);
foreach (string directory in directories) foreach (string directory in directories) {
{ if (File.Exists((Path.Combine(directory, "NeedDelete.txt")))) {
if (File.Exists((Path.Combine(directory, "NeedDelete.txt"))))
{
Directory.Delete(directory, true); Directory.Delete(directory, true);
continue; continue;
} }
@ -64,25 +56,21 @@ namespace Wox.PluginLoader
} }
} }
private static PluginMetadata GetMetadataFromJson(string pluginDirectory) private static PluginMetadata GetMetadataFromJson(string pluginDirectory) {
{
string configPath = Path.Combine(pluginDirectory, PluginConfigName); string configPath = Path.Combine(pluginDirectory, PluginConfigName);
PluginMetadata metadata; PluginMetadata metadata;
if (!File.Exists(configPath)) if (!File.Exists(configPath)) {
{
Log.Warn(string.Format("parse plugin {0} failed: didn't find config file.", configPath)); Log.Warn(string.Format("parse plugin {0} failed: didn't find config file.", configPath));
return null; return null;
} }
try try {
{
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath)); metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginType = PluginType.ThirdParty; metadata.PluginType = PluginType.ThirdParty;
metadata.PluginDirecotry = pluginDirectory; metadata.PluginDirecotry = pluginDirectory;
} }
catch (Exception) catch (Exception) {
{
string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath); string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath);
Log.Warn(error); Log.Warn(error);
#if (DEBUG) #if (DEBUG)
@ -94,10 +82,8 @@ namespace Wox.PluginLoader
} }
if (!AllowedLanguage.IsAllowed(metadata.Language)) if (!AllowedLanguage.IsAllowed(metadata.Language)) {
{ string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath, metadata.Language);
string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath,
metadata.Language);
Log.Warn(error); Log.Warn(error);
#if (DEBUG) #if (DEBUG)
{ {
@ -106,10 +92,8 @@ namespace Wox.PluginLoader
#endif #endif
return null; return null;
} }
if (!File.Exists(metadata.ExecuteFilePath)) if (!File.Exists(metadata.ExecuteFilePath)) {
{ string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath, metadata.ExecuteFilePath);
string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath,
metadata.ExecuteFilePath);
Log.Warn(error); Log.Warn(error);
#if (DEBUG) #if (DEBUG)
{ {

View File

@ -1,54 +1,43 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading;
using Wox.Helper; using Wox.Helper;
using Wox.Plugin; using Wox.Plugin;
using Wox.Plugin.SystemPlugins; using Wox.Plugin.SystemPlugins;
namespace Wox.PluginLoader namespace Wox.PluginLoader {
{
public class CSharpPluginLoader : BasePluginLoader public class CSharpPluginLoader : BasePluginLoader {
{
public override List<PluginPair> LoadPlugin() public override List<PluginPair> LoadPlugin() {
{
List<PluginPair> plugins = new List<PluginPair>(); List<PluginPair> plugins = new List<PluginPair>();
List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.CSharp.ToUpper()).ToList(); List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.CSharp.ToUpper()).ToList();
foreach (PluginMetadata metadata in metadatas) foreach (PluginMetadata metadata in metadatas) {
{ try {
try
{
Assembly asm = Assembly.Load(AssemblyName.GetAssemblyName(metadata.ExecuteFilePath)); Assembly asm = Assembly.Load(AssemblyName.GetAssemblyName(metadata.ExecuteFilePath));
List<Type> types = asm.GetTypes().Where(o => o.IsClass && !o.IsAbstract && (o.BaseType == typeof(BaseSystemPlugin) || o.GetInterfaces().Contains(typeof(IPlugin)))).ToList(); List<Type> types = asm.GetTypes().Where(o => o.IsClass && !o.IsAbstract && (o.BaseType == typeof(BaseSystemPlugin) || o.GetInterfaces().Contains(typeof(IPlugin)))).ToList();
if (types.Count == 0) if (types.Count == 0) {
{ Log.Warn(string.Format("Cound't load plugin {0}: didn't find the class who implement IPlugin", metadata.Name));
Log.Warn(string.Format("Cound't load plugin {0}: didn't find the class who implement IPlugin",
metadata.Name));
continue; continue;
} }
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
}; };
var sys = pair.Plugin as BaseSystemPlugin; var sys = pair.Plugin as BaseSystemPlugin;
if (sys != null) if (sys != null) {
{
sys.PluginDirectory = metadata.PluginDirecotry; sys.PluginDirectory = metadata.PluginDirecotry;
} }
plugins.Add(pair); plugins.Add(pair);
} }
} }
catch (Exception e) catch (Exception e) {
{
Log.Error(string.Format("Cound't load plugin {0}: {1}", metadata.Name, e.Message)); Log.Error(string.Format("Cound't load plugin {0}: {1}", metadata.Name, e.Message));
#if (DEBUG) #if (DEBUG)
{ {
@ -56,7 +45,6 @@ namespace Wox.PluginLoader
} }
#endif #endif
} }
} }
return plugins; return plugins;

View File

@ -33,7 +33,7 @@
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>