-
-
Notifications
You must be signed in to change notification settings - Fork 350
/
Copy pathPublicAPIInstance.cs
295 lines (234 loc) · 10.6 KB
/
PublicAPIInstance.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using Squirrel;
using Flow.Launcher.Core.Plugin;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Helper;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Hotkey;
using Flow.Launcher.Infrastructure.Image;
using Flow.Launcher.Plugin;
using Flow.Launcher.ViewModel;
using Flow.Launcher.Plugin.SharedModels;
using Flow.Launcher.Plugin.SharedCommands;
using System.Threading;
using System.IO;
using Flow.Launcher.Infrastructure.Http;
using JetBrains.Annotations;
using System.Runtime.CompilerServices;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.Storage;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace Flow.Launcher
{
public class PublicAPIInstance : IPublicAPI
{
private readonly SettingWindowViewModel _settingsVM;
private readonly MainViewModel _mainVM;
private readonly PinyinAlphabet _alphabet;
#region Constructor
public PublicAPIInstance(SettingWindowViewModel settingsVM, MainViewModel mainVM, PinyinAlphabet alphabet)
{
_settingsVM = settingsVM;
_mainVM = mainVM;
_alphabet = alphabet;
GlobalHotkey.hookedKeyboardCallback = KListener_hookedKeyboardCallback;
WebRequest.RegisterPrefix("data", new DataWebRequestFactory());
}
#endregion
#region Public API
public void ChangeQuery(string query, bool requery = false)
{
_mainVM.ChangeQueryText(query, requery);
}
public void RestartApp()
{
_mainVM.Hide();
// we must manually save
// UpdateManager.RestartApp() will call Environment.Exit(0)
// which will cause ungraceful exit
SaveAppAllSettings();
// Restart requires Squirrel's Update.exe to be present in the parent folder,
// it is only published from the project's release pipeline. When debugging without it,
// the project may not restart or just terminates. This is expected.
UpdateManager.RestartApp(Constant.ApplicationFileName);
}
[Obsolete("Typo")]
public void RestarApp() => RestartApp();
public void ShowMainWindow() => _mainVM.Show();
public void CheckForNewUpdate() => _settingsVM.UpdateApp();
public void SaveAppAllSettings()
{
PluginManager.Save();
_mainVM.Save();
_settingsVM.Save();
ImageLoader.Save();
}
public Task ReloadAllPluginData() => PluginManager.ReloadDataAsync();
public void ShowMsgError(string title, string subTitle = "") =>
ShowMsg(title, subTitle, Constant.ErrorIcon, true);
public void ShowMsg(string title, string subTitle = "", string iconPath = "") =>
ShowMsg(title, subTitle, iconPath, true);
public void ShowMsg(string title, string subTitle, string iconPath, bool useMainWindowAsOwner = true)
{
Notification.Show(title, subTitle, iconPath);
}
public void OpenSettingDialog()
{
Application.Current.Dispatcher.Invoke(() =>
{
SettingWindow sw = SingletonWindowOpener.Open<SettingWindow>(this, _settingsVM);
});
}
public void ShellRun(string cmd, string filename = "cmd.exe")
{
var args = filename == "cmd.exe" ? $"/C {cmd}" : $"{cmd}";
var startInfo = ShellCommand.SetProcessStartInfo(filename, arguments: args, createNoWindow: true);
ShellCommand.Execute(startInfo);
}
public void CopyToClipboard(string text)
{
Clipboard.SetDataObject(text);
}
public void StartLoadingBar() => _mainVM.ProgressBarVisibility = Visibility.Visible;
public void StopLoadingBar() => _mainVM.ProgressBarVisibility = Visibility.Collapsed;
public string GetTranslation(string key) => InternationalizationManager.Instance.GetTranslation(key);
public List<PluginPair> GetAllPlugins() => PluginManager.AllPlugins.ToList();
public MatchResult FuzzySearch(string query, string stringToCompare) =>
StringMatcher.FuzzySearch(query, stringToCompare);
public Task<string> HttpGetStringAsync(string url, CancellationToken token = default) => Http.GetAsync(url);
public Task<Stream> HttpGetStreamAsync(string url, CancellationToken token = default) =>
Http.GetStreamAsync(url);
public Task HttpDownloadAsync([NotNull] string url, [NotNull] string filePath,
CancellationToken token = default) => Http.DownloadAsync(url, filePath, token);
public void AddActionKeyword(string pluginId, string newActionKeyword) =>
PluginManager.AddActionKeyword(pluginId, newActionKeyword);
public bool ActionKeywordAssigned(string actionKeyword) => PluginManager.ActionKeywordRegistered(actionKeyword);
public void RemoveActionKeyword(string pluginId, string oldActionKeyword) =>
PluginManager.RemoveActionKeyword(pluginId, oldActionKeyword);
public void LogDebug(string className, string message, [CallerMemberName] string methodName = "") =>
Log.Debug(className, message, methodName);
public void LogInfo(string className, string message, [CallerMemberName] string methodName = "") =>
Log.Info(className, message, methodName);
public void LogWarn(string className, string message, [CallerMemberName] string methodName = "") =>
Log.Warn(className, message, methodName);
public void LogException(string className, string message, Exception e,
[CallerMemberName] string methodName = "") => Log.Exception(className, message, e, methodName);
private readonly ConcurrentDictionary<Type, object> _pluginJsonStorages = new();
/// <summary>
/// Save plugin settings.
/// </summary>
public void SavePluginSettings()
{
foreach (var value in _pluginJsonStorages.Values)
{
var method = value.GetType().GetMethod("Save");
method?.Invoke(value, null);
}
}
public T LoadSettingJsonStorage<T>() where T : new()
{
var type = typeof(T);
if (!_pluginJsonStorages.ContainsKey(type))
_pluginJsonStorages[type] = new PluginJsonStorage<T>();
return ((PluginJsonStorage<T>)_pluginJsonStorages[type]).Load();
}
public void SaveSettingJsonStorage<T>() where T : new()
{
var type = typeof(T);
if (!_pluginJsonStorages.ContainsKey(type))
_pluginJsonStorages[type] = new PluginJsonStorage<T>();
((PluginJsonStorage<T>)_pluginJsonStorages[type]).Save();
}
public void SaveJsonStorage<T>(T settings) where T : new()
{
var type = typeof(T);
_pluginJsonStorages[type] = new PluginJsonStorage<T>(settings);
((PluginJsonStorage<T>)_pluginJsonStorages[type]).Save();
}
public void OpenDirectory(string DirectoryPath, string FileNameOrFilePath = null)
{
using var explorer = new Process();
var explorerInfo = _settingsVM.Settings.CustomExplorer;
explorer.StartInfo = new ProcessStartInfo
{
FileName = explorerInfo.Path,
UseShellExecute = true,
Arguments = FileNameOrFilePath is null
? explorerInfo.DirectoryArgument.Replace("%d", DirectoryPath)
: explorerInfo.FileArgument
.Replace("%d", DirectoryPath)
.Replace("%f",
Path.IsPathRooted(FileNameOrFilePath) ? FileNameOrFilePath : Path.Combine(DirectoryPath, FileNameOrFilePath)
)
};
explorer.Start();
}
private void OpenUri(Uri uri, bool? inPrivate = null, string additionalArgs = "")
{
if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
{
var browserInfo = _settingsVM.Settings.CustomBrowser;
var path = browserInfo.Path == "*" ? "" : browserInfo.Path;
if (browserInfo.OpenInTab)
{
uri.AbsoluteUri.OpenInBrowserTab(path, inPrivate ?? browserInfo.EnablePrivate, browserInfo.PrivateArg, additionalArgs);
}
else
{
uri.AbsoluteUri.OpenInBrowserWindow(path, inPrivate ?? browserInfo.EnablePrivate, browserInfo.PrivateArg, additionalArgs);
}
}
else
{
Process.Start(new ProcessStartInfo()
{
FileName = uri.AbsoluteUri,
UseShellExecute = true
})?.Dispose();
return;
}
}
public void OpenUrl(string url, bool? inPrivate = null, string additionalArgs = "")
{
OpenUri(new Uri(url), inPrivate, additionalArgs);
}
public void OpenUrl(Uri url, bool? inPrivate = null, string additionalArgs = "")
{
OpenUri(url, inPrivate, additionalArgs);
}
public void OpenAppUri(string appUri)
{
OpenUri(new Uri(appUri));
}
public void OpenAppUri(Uri appUri)
{
OpenUri(appUri);
}
public event FlowLauncherGlobalKeyboardEventHandler GlobalKeyboardEvent;
private readonly List<Func<int, int, SpecialKeyState, bool>> _globalKeyboardHandlers = new();
public void RegisterGlobalKeyboardCallback(Func<int, int, SpecialKeyState, bool> callback) => _globalKeyboardHandlers.Add(callback);
public void RemoveGlobalKeyboardCallback(Func<int, int, SpecialKeyState, bool> callback) => _globalKeyboardHandlers.Remove(callback);
#endregion
#region Private Methods
private bool KListener_hookedKeyboardCallback(KeyEvent keyevent, int vkcode, SpecialKeyState state)
{
var continueHook = true;
if (GlobalKeyboardEvent != null)
{
continueHook = GlobalKeyboardEvent((int)keyevent, vkcode, state);
}
foreach (var x in _globalKeyboardHandlers)
{
continueHook &= x((int)keyevent, vkcode, state);
}
return continueHook;
}
#endregion
}
}