mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-05 10:46:33 +02:00
Migrate files from Wox to PowerLauncher (#5014)
* Moved all files from Wox to Powerlauncher * Removed Wox project * Changed namespace for imported files * Resolved errors for VM * Added build dependency order * Fixed errors in helper class * Remove Wox files * Fixed errors in SingleInstance class * Fixed wox.tests * Fixed MSI * Removed obsolete methods from PublicAPI * nit fixes * Throw null exception * Fix merge conflict
This commit is contained in:
committed by
GitHub
parent
177546bab6
commit
c85cd4ac24
@@ -11,14 +11,14 @@ using Wox;
|
||||
using Wox.Core;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Core.Resource;
|
||||
using Wox.Helper;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Http;
|
||||
using Wox.Infrastructure.Image;
|
||||
using Wox.Infrastructure.Logger;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.Plugin;
|
||||
using Wox.ViewModel;
|
||||
using PowerLauncher.ViewModel;
|
||||
using Stopwatch = Wox.Infrastructure.Stopwatch;
|
||||
|
||||
namespace PowerLauncher
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
public class DataWebRequestFactory : IWebRequestCreate
|
||||
{
|
||||
class DataWebRequest : WebRequest
|
||||
{
|
||||
private readonly Uri m_uri;
|
||||
|
||||
public DataWebRequest(Uri uri)
|
||||
{
|
||||
m_uri = uri;
|
||||
}
|
||||
|
||||
public override WebResponse GetResponse()
|
||||
{
|
||||
return new DataWebResponse(m_uri);
|
||||
}
|
||||
}
|
||||
|
||||
class DataWebResponse : WebResponse
|
||||
{
|
||||
private readonly string m_contentType;
|
||||
private readonly byte[] m_data;
|
||||
|
||||
public DataWebResponse(Uri uri)
|
||||
{
|
||||
string uriString = uri.AbsoluteUri;
|
||||
|
||||
int commaIndex = uriString.IndexOf(',', StringComparison.InvariantCultureIgnoreCase);
|
||||
var headers = uriString.Substring(0, commaIndex).Split(';');
|
||||
m_contentType = headers[0];
|
||||
string dataString = uriString.Substring(commaIndex + 1);
|
||||
m_data = Convert.FromBase64String(dataString);
|
||||
}
|
||||
|
||||
public override string ContentType
|
||||
{
|
||||
get { return m_contentType; }
|
||||
set
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
|
||||
public override long ContentLength
|
||||
{
|
||||
get { return m_data.Length; }
|
||||
set
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
|
||||
public override Stream GetResponseStream()
|
||||
{
|
||||
return new MemoryStream(m_data);
|
||||
}
|
||||
}
|
||||
|
||||
public WebRequest Create(Uri uri)
|
||||
{
|
||||
return new DataWebRequest(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
46
src/modules/launcher/PowerLauncher/Helper/ErrorReporting.cs
Normal file
46
src/modules/launcher/PowerLauncher/Helper/ErrorReporting.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Windows.Threading;
|
||||
using NLog;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Exception;
|
||||
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
public static class ErrorReporting
|
||||
{
|
||||
private static void Report(Exception e)
|
||||
{
|
||||
if( e != null)
|
||||
{
|
||||
var logger = LogManager.GetLogger("UnHandledException");
|
||||
logger.Fatal(ExceptionFormatter.FormatException(e));
|
||||
|
||||
var reportWindow = new ReportWindow(e);
|
||||
reportWindow.Show();
|
||||
}
|
||||
}
|
||||
|
||||
public static void UnhandledExceptionHandle(object sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
//handle non-ui thread exceptions
|
||||
Report((Exception)e?.ExceptionObject);
|
||||
}
|
||||
|
||||
public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
//handle ui thread exceptions
|
||||
Report(e?.Exception);
|
||||
//prevent application exist, so the user can copy prompted error info
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
public static string RuntimeInfo()
|
||||
{
|
||||
var info = $"\nVersion: {Constant.Version}" +
|
||||
$"\nOS Version: {Environment.OSVersion.VersionString}" +
|
||||
$"\nIntPtr Length: {IntPtr.Size}" +
|
||||
$"\nx64: {Environment.Is64BitOperatingSystem}";
|
||||
return info;
|
||||
}
|
||||
}
|
||||
}
|
||||
37
src/modules/launcher/PowerLauncher/Helper/KeyboardHelper.cs
Normal file
37
src/modules/launcher/PowerLauncher/Helper/KeyboardHelper.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Windows.Input;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
class KeyboardHelper
|
||||
{
|
||||
public static SpecialKeyState CheckModifiers()
|
||||
{
|
||||
SpecialKeyState state = new SpecialKeyState();
|
||||
if ((Keyboard.GetKeyStates(Key.LeftShift) & KeyStates.Down) > 0 ||
|
||||
(Keyboard.GetKeyStates(Key.RightShift) & KeyStates.Down) > 0)
|
||||
{
|
||||
state.ShiftPressed = true;
|
||||
}
|
||||
if ((Keyboard.GetKeyStates(Key.LWin) & KeyStates.Down) > 0 ||
|
||||
(Keyboard.GetKeyStates(Key.RWin) & KeyStates.Down) > 0)
|
||||
{
|
||||
state.WinPressed = true;
|
||||
}
|
||||
if ((Keyboard.GetKeyStates(Key.LeftCtrl) & KeyStates.Down) > 0 ||
|
||||
(Keyboard.GetKeyStates(Key.RightCtrl) & KeyStates.Down) > 0)
|
||||
{
|
||||
state.CtrlPressed = true;
|
||||
}
|
||||
if ((Keyboard.GetKeyStates(Key.LeftAlt) & KeyStates.Down) > 0 ||
|
||||
(Keyboard.GetKeyStates(Key.RightAlt) & KeyStates.Down) > 0)
|
||||
{
|
||||
state.AltPressed = true;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using PowerLauncher.ViewModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
public class ResultCollection : ObservableCollection<ResultViewModel>
|
||||
{
|
||||
|
||||
public void RemoveAll(Predicate<ResultViewModel> predicate)
|
||||
{
|
||||
CheckReentrancy();
|
||||
|
||||
for (int i = Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (predicate(this[i]))
|
||||
{
|
||||
RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update the results collection with new results, try to keep identical results
|
||||
/// </summary>
|
||||
/// <param name="newItems"></param>
|
||||
public void Update(List<ResultViewModel> newItems)
|
||||
{
|
||||
if(newItems == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(newItems));
|
||||
}
|
||||
|
||||
int newCount = newItems.Count;
|
||||
int oldCount = Items.Count;
|
||||
int location = newCount > oldCount ? oldCount : newCount;
|
||||
|
||||
for (int i = 0; i < location; i++)
|
||||
{
|
||||
ResultViewModel oldResult = this[i];
|
||||
ResultViewModel newResult = newItems[i];
|
||||
if (!oldResult.Equals(newResult))
|
||||
{ // result is not the same update it in the current index
|
||||
this[i] = newResult;
|
||||
}
|
||||
else if (oldResult.Result.Score != newResult.Result.Score)
|
||||
{
|
||||
this[i].Result.Score = newResult.Result.Score;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (newCount >= oldCount)
|
||||
{
|
||||
for (int i = oldCount; i < newCount; i++)
|
||||
{
|
||||
Add(newItems[i]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = oldCount - 1; i >= newCount; i--)
|
||||
{
|
||||
RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
416
src/modules/launcher/PowerLauncher/Helper/SingleInstance.cs
Normal file
416
src/modules/launcher/PowerLauncher/Helper/SingleInstance.cs
Normal file
@@ -0,0 +1,416 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.IO.Pipes;
|
||||
using System.Runtime.Serialization.Formatters;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using static PowerLauncher.Helper.WindowsInteropHelper;
|
||||
|
||||
// http://blogs.microsoft.co.il/arik/2010/05/28/wpf-single-instance-application/
|
||||
// modified to allow single instance restart
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
internal enum WM
|
||||
{
|
||||
NULL = 0x0000,
|
||||
CREATE = 0x0001,
|
||||
DESTROY = 0x0002,
|
||||
MOVE = 0x0003,
|
||||
SIZE = 0x0005,
|
||||
ACTIVATE = 0x0006,
|
||||
SETFOCUS = 0x0007,
|
||||
KILLFOCUS = 0x0008,
|
||||
ENABLE = 0x000A,
|
||||
SETREDRAW = 0x000B,
|
||||
SETTEXT = 0x000C,
|
||||
GETTEXT = 0x000D,
|
||||
GETTEXTLENGTH = 0x000E,
|
||||
PAINT = 0x000F,
|
||||
CLOSE = 0x0010,
|
||||
QUERYENDSESSION = 0x0011,
|
||||
QUIT = 0x0012,
|
||||
QUERYOPEN = 0x0013,
|
||||
ERASEBKGND = 0x0014,
|
||||
SYSCOLORCHANGE = 0x0015,
|
||||
SHOWWINDOW = 0x0018,
|
||||
ACTIVATEAPP = 0x001C,
|
||||
SETCURSOR = 0x0020,
|
||||
MOUSEACTIVATE = 0x0021,
|
||||
CHILDACTIVATE = 0x0022,
|
||||
QUEUESYNC = 0x0023,
|
||||
GETMINMAXINFO = 0x0024,
|
||||
|
||||
WINDOWPOSCHANGING = 0x0046,
|
||||
WINDOWPOSCHANGED = 0x0047,
|
||||
|
||||
CONTEXTMENU = 0x007B,
|
||||
STYLECHANGING = 0x007C,
|
||||
STYLECHANGED = 0x007D,
|
||||
DISPLAYCHANGE = 0x007E,
|
||||
GETICON = 0x007F,
|
||||
SETICON = 0x0080,
|
||||
NCCREATE = 0x0081,
|
||||
NCDESTROY = 0x0082,
|
||||
NCCALCSIZE = 0x0083,
|
||||
NCHITTEST = 0x0084,
|
||||
NCPAINT = 0x0085,
|
||||
NCACTIVATE = 0x0086,
|
||||
GETDLGCODE = 0x0087,
|
||||
SYNCPAINT = 0x0088,
|
||||
NCMOUSEMOVE = 0x00A0,
|
||||
NCLBUTTONDOWN = 0x00A1,
|
||||
NCLBUTTONUP = 0x00A2,
|
||||
NCLBUTTONDBLCLK = 0x00A3,
|
||||
NCRBUTTONDOWN = 0x00A4,
|
||||
NCRBUTTONUP = 0x00A5,
|
||||
NCRBUTTONDBLCLK = 0x00A6,
|
||||
NCMBUTTONDOWN = 0x00A7,
|
||||
NCMBUTTONUP = 0x00A8,
|
||||
NCMBUTTONDBLCLK = 0x00A9,
|
||||
|
||||
SYSKEYDOWN = 0x0104,
|
||||
SYSKEYUP = 0x0105,
|
||||
SYSCHAR = 0x0106,
|
||||
SYSDEADCHAR = 0x0107,
|
||||
COMMAND = 0x0111,
|
||||
SYSCOMMAND = 0x0112,
|
||||
|
||||
MOUSEMOVE = 0x0200,
|
||||
LBUTTONDOWN = 0x0201,
|
||||
LBUTTONUP = 0x0202,
|
||||
LBUTTONDBLCLK = 0x0203,
|
||||
RBUTTONDOWN = 0x0204,
|
||||
RBUTTONUP = 0x0205,
|
||||
RBUTTONDBLCLK = 0x0206,
|
||||
MBUTTONDOWN = 0x0207,
|
||||
MBUTTONUP = 0x0208,
|
||||
MBUTTONDBLCLK = 0x0209,
|
||||
MOUSEWHEEL = 0x020A,
|
||||
XBUTTONDOWN = 0x020B,
|
||||
XBUTTONUP = 0x020C,
|
||||
XBUTTONDBLCLK = 0x020D,
|
||||
MOUSEHWHEEL = 0x020E,
|
||||
|
||||
|
||||
CAPTURECHANGED = 0x0215,
|
||||
|
||||
ENTERSIZEMOVE = 0x0231,
|
||||
EXITSIZEMOVE = 0x0232,
|
||||
|
||||
IME_SETCONTEXT = 0x0281,
|
||||
IME_NOTIFY = 0x0282,
|
||||
IME_CONTROL = 0x0283,
|
||||
IME_COMPOSITIONFULL = 0x0284,
|
||||
IME_SELECT = 0x0285,
|
||||
IME_CHAR = 0x0286,
|
||||
IME_REQUEST = 0x0288,
|
||||
IME_KEYDOWN = 0x0290,
|
||||
IME_KEYUP = 0x0291,
|
||||
|
||||
NCMOUSELEAVE = 0x02A2,
|
||||
|
||||
DWMCOMPOSITIONCHANGED = 0x031E,
|
||||
DWMNCRENDERINGCHANGED = 0x031F,
|
||||
DWMCOLORIZATIONCOLORCHANGED = 0x0320,
|
||||
DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
|
||||
|
||||
#region Windows 7
|
||||
DWMSENDICONICTHUMBNAIL = 0x0323,
|
||||
DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
|
||||
#endregion
|
||||
|
||||
USER = 0x0400,
|
||||
|
||||
// This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
|
||||
// It's relatively safe to reuse.
|
||||
TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
|
||||
APP = 0x8000
|
||||
}
|
||||
|
||||
[SuppressUnmanagedCodeSecurity]
|
||||
internal static class NativeMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// Delegate declaration that matches WndProc signatures.
|
||||
/// </summary>
|
||||
public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
|
||||
|
||||
[DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs);
|
||||
|
||||
|
||||
[DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
|
||||
internal static extern IntPtr _LocalFree(IntPtr hMem);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern IntPtr GetDesktopWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern IntPtr GetShellWindow();
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
internal static extern int GetWindowRect(IntPtr hwnd, out RECT rc);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
internal static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
|
||||
|
||||
[DllImport("user32.DLL", CharSet = CharSet.Unicode)]
|
||||
internal static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
|
||||
|
||||
public static string[] CommandLineToArgvW(string cmdLine)
|
||||
{
|
||||
IntPtr argv = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
int numArgs = 0;
|
||||
|
||||
argv = _CommandLineToArgvW(cmdLine, out numArgs);
|
||||
if (argv == IntPtr.Zero)
|
||||
{
|
||||
throw new Win32Exception();
|
||||
}
|
||||
var result = new string[numArgs];
|
||||
|
||||
for (int i = 0; i < numArgs; i++)
|
||||
{
|
||||
IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
|
||||
result[i] = Marshal.PtrToStringUni(currArg);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
IntPtr p = _LocalFree(argv);
|
||||
// Otherwise LocalFree failed.
|
||||
// Assert.AreEqual(IntPtr.Zero, p);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public interface ISingleInstanceApp
|
||||
{
|
||||
void OnSecondAppStarted();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This class checks to make sure that only one instance of
|
||||
/// this application is running at a time.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Note: this class should be used with some caution, because it does no
|
||||
/// security checking. For example, if one instance of an app that uses this class
|
||||
/// is running as Administrator, any other instance, even if it is not
|
||||
/// running as Administrator, can activate it with command line arguments.
|
||||
/// For most apps, this will not be much of an issue.
|
||||
/// </remarks>
|
||||
public static class SingleInstance<TApplication>
|
||||
where TApplication: Application , ISingleInstanceApp
|
||||
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
/// <summary>
|
||||
/// String delimiter used in channel names.
|
||||
/// </summary>
|
||||
private const string Delimiter = ":";
|
||||
|
||||
/// <summary>
|
||||
/// Suffix to the channel name.
|
||||
/// </summary>
|
||||
private const string ChannelNameSuffix = "SingeInstanceIPCChannel";
|
||||
|
||||
/// <summary>
|
||||
/// Application mutex.
|
||||
/// </summary>
|
||||
internal static Mutex singleInstanceMutex;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the instance of the application attempting to start is the first instance.
|
||||
/// If not, activates the first instance.
|
||||
/// </summary>
|
||||
/// <returns>True if this is the first instance of the application.</returns>
|
||||
internal static bool InitializeAsFirstInstance( string uniqueName )
|
||||
{
|
||||
// Build unique application Id and the IPC channel name.
|
||||
string applicationIdentifier = uniqueName + Environment.UserName;
|
||||
|
||||
string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix);
|
||||
|
||||
// Create mutex based on unique application Id to check if this is the first instance of the application.
|
||||
bool firstInstance;
|
||||
singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance);
|
||||
if (firstInstance)
|
||||
{
|
||||
_ = CreateRemoteService(channelName);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_ = SignalFirstInstance(channelName);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up single-instance code, clearing shared resources, mutexes, etc.
|
||||
/// </summary>
|
||||
internal static void Cleanup()
|
||||
{
|
||||
singleInstanceMutex?.ReleaseMutex();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
/// <summary>
|
||||
/// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved.
|
||||
/// </summary>
|
||||
/// <returns>List of command line arg strings.</returns>
|
||||
private static IList<string> GetCommandLineArgs( string uniqueApplicationName )
|
||||
{
|
||||
string[] args = null;
|
||||
|
||||
try
|
||||
{
|
||||
// The application was not clickonce deployed, get args from standard API's
|
||||
args = Environment.GetCommandLineArgs();
|
||||
}
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
|
||||
// The application was clickonce deployed
|
||||
// Clickonce deployed apps cannot receive traditional commandline arguments
|
||||
// As a workaround commandline arguments can be written to a shared location before
|
||||
// the app is launched and the app can obtain its commandline arguments from the
|
||||
// shared location
|
||||
string appFolderPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);
|
||||
|
||||
string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
|
||||
if (File.Exists(cmdLinePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
using (TextReader reader = new StreamReader(cmdLinePath, Encoding.Unicode))
|
||||
{
|
||||
args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
|
||||
}
|
||||
|
||||
File.Delete(cmdLinePath);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (args == null)
|
||||
{
|
||||
args = Array.Empty<string>();
|
||||
}
|
||||
|
||||
return new List<string>(args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a remote server pipe for communication.
|
||||
/// Once receives signal from client, will activate first instance.
|
||||
/// </summary>
|
||||
/// <param name="channelName">Application's IPC channel name.</param>
|
||||
private static async Task CreateRemoteService(string channelName)
|
||||
{
|
||||
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(channelName, PipeDirection.In))
|
||||
{
|
||||
while(true)
|
||||
{
|
||||
// Wait for connection to the pipe
|
||||
await pipeServer.WaitForConnectionAsync().ConfigureAwait(false);
|
||||
if (Application.Current != null)
|
||||
{
|
||||
// Do an asynchronous call to ActivateFirstInstance function
|
||||
Application.Current.Dispatcher.Invoke(ActivateFirstInstance);
|
||||
}
|
||||
// Disconnect client
|
||||
pipeServer.Disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a client pipe and sends a signal to server to launch first instance
|
||||
/// </summary>
|
||||
/// <param name="channelName">Application's IPC channel name.</param>
|
||||
/// <param name="args">
|
||||
/// Command line arguments for the second instance, passed to the first instance to take appropriate action.
|
||||
/// </param>
|
||||
private static async Task SignalFirstInstance(string channelName)
|
||||
{
|
||||
// Create a client pipe connected to server
|
||||
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", channelName, PipeDirection.Out))
|
||||
{
|
||||
// Connect to the available pipe
|
||||
await pipeClient.ConnectAsync(0).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback for activating first instance of the application.
|
||||
/// </summary>
|
||||
/// <param name="arg">Callback argument.</param>
|
||||
/// <returns>Always null.</returns>
|
||||
private static object ActivateFirstInstanceCallback(object _)
|
||||
{
|
||||
ActivateFirstInstance();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Activates the first instance of the application with arguments from a second instance.
|
||||
/// </summary>
|
||||
/// <param name="args">List of arguments to supply the first instance of the application.</param>
|
||||
private static void ActivateFirstInstance()
|
||||
{
|
||||
// Set main window state and process command line args
|
||||
if (Application.Current == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
((TApplication)Application.Current).OnSecondAppStarted();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Windows;
|
||||
using System.Windows.Forms;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using Point = System.Windows.Point;
|
||||
|
||||
namespace PowerLauncher.Helper
|
||||
{
|
||||
public static class WindowsInteropHelper
|
||||
{
|
||||
private const int GWL_STYLE = -16; //WPF's Message code for Title Bar's Style
|
||||
private const int WS_SYSMENU = 0x80000; //WPF's Message code for System Menu
|
||||
private static IntPtr _hwnd_shell;
|
||||
private static IntPtr _hwnd_desktop;
|
||||
|
||||
//Accessors for shell and desktop handlers
|
||||
//Will set the variables once and then will return them
|
||||
private static IntPtr HWND_SHELL
|
||||
{
|
||||
get
|
||||
{
|
||||
return _hwnd_shell != IntPtr.Zero ? _hwnd_shell : _hwnd_shell = NativeMethods.GetShellWindow();
|
||||
}
|
||||
}
|
||||
|
||||
private static IntPtr HWND_DESKTOP
|
||||
{
|
||||
get
|
||||
{
|
||||
return _hwnd_desktop != IntPtr.Zero ? _hwnd_desktop : _hwnd_desktop = NativeMethods.GetDesktopWindow();
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct INPUT
|
||||
{
|
||||
public INPUTTYPE type;
|
||||
public InputUnion data;
|
||||
|
||||
public static int Size
|
||||
{
|
||||
get { return Marshal.SizeOf(typeof(INPUT)); }
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Explicit)]
|
||||
internal struct InputUnion
|
||||
{
|
||||
[FieldOffset(0)]
|
||||
internal MOUSEINPUT mi;
|
||||
[FieldOffset(0)]
|
||||
internal KEYBDINPUT ki;
|
||||
[FieldOffset(0)]
|
||||
internal HARDWAREINPUT hi;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct MOUSEINPUT
|
||||
{
|
||||
internal int dx;
|
||||
internal int dy;
|
||||
internal int mouseData;
|
||||
internal uint dwFlags;
|
||||
internal uint time;
|
||||
internal UIntPtr dwExtraInfo;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct KEYBDINPUT
|
||||
{
|
||||
internal short wVk;
|
||||
internal short wScan;
|
||||
internal uint dwFlags;
|
||||
internal int time;
|
||||
internal UIntPtr dwExtraInfo;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct HARDWAREINPUT
|
||||
{
|
||||
internal int uMsg;
|
||||
internal short wParamL;
|
||||
internal short wParamH;
|
||||
}
|
||||
|
||||
internal enum INPUTTYPE : uint
|
||||
{
|
||||
INPUTMOUSE = 0,
|
||||
INPUTKEYBOARD = 1,
|
||||
INPUTHARDWARE = 2,
|
||||
}
|
||||
|
||||
const string WINDOW_CLASS_CONSOLE = "ConsoleWindowClass";
|
||||
const string WINDOW_CLASS_WINTAB = "Flip3D";
|
||||
const string WINDOW_CLASS_PROGMAN = "Progman";
|
||||
const string WINDOW_CLASS_WORKERW = "WorkerW";
|
||||
|
||||
public static bool IsWindowFullscreen()
|
||||
{
|
||||
//get current active window
|
||||
IntPtr hWnd = NativeMethods.GetForegroundWindow();
|
||||
|
||||
if (hWnd != null && !hWnd.Equals(IntPtr.Zero))
|
||||
{
|
||||
//if current active window is NOT desktop or shell
|
||||
if (!(hWnd.Equals(HWND_DESKTOP) || hWnd.Equals(HWND_SHELL)))
|
||||
{
|
||||
StringBuilder sb = new StringBuilder(256);
|
||||
_ = NativeMethods.GetClassName(hWnd, sb, sb.Capacity);
|
||||
string windowClass = sb.ToString();
|
||||
|
||||
//for Win+Tab (Flip3D)
|
||||
if (windowClass == WINDOW_CLASS_WINTAB)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
RECT appBounds;
|
||||
_ = NativeMethods.GetWindowRect(hWnd, out appBounds);
|
||||
|
||||
//for console (ConsoleWindowClass), we have to check for negative dimensions
|
||||
if (windowClass == WINDOW_CLASS_CONSOLE)
|
||||
{
|
||||
return appBounds.Top < 0 && appBounds.Bottom < 0;
|
||||
}
|
||||
|
||||
//for desktop (Progman or WorkerW, depends on the system), we have to check
|
||||
if (windowClass == WINDOW_CLASS_PROGMAN || windowClass == WINDOW_CLASS_WORKERW)
|
||||
{
|
||||
IntPtr hWndDesktop = NativeMethods.FindWindowEx(hWnd, IntPtr.Zero, "SHELLDLL_DefView", null);
|
||||
hWndDesktop = NativeMethods.FindWindowEx(hWndDesktop, IntPtr.Zero, "SysListView32", "FolderView");
|
||||
if (hWndDesktop != null && !hWndDesktop.Equals(IntPtr.Zero))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle screenBounds = Screen.FromHandle(hWnd).Bounds;
|
||||
if ((appBounds.Bottom - appBounds.Top) == screenBounds.Height && (appBounds.Right - appBounds.Left) == screenBounds.Width)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// disable windows toolbar's control box
|
||||
/// this will also disable system menu with Alt+Space hotkey
|
||||
/// </summary>
|
||||
public static void DisableControlBox(Window win)
|
||||
{
|
||||
var hwnd = new WindowInteropHelper(win).Handle;
|
||||
_ = NativeMethods.SetWindowLong(hwnd, GWL_STYLE, NativeMethods.GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Transforms pixels to Device Independent Pixels used by WPF
|
||||
/// </summary>
|
||||
/// <param name="visual">current window, required to get presentation source</param>
|
||||
/// <param name="unitX">horizontal position in pixels</param>
|
||||
/// <param name="unitY">vertical position in pixels</param>
|
||||
/// <returns>point containing device independent pixels</returns>
|
||||
public static Point TransformPixelsToDIP(Visual visual, double unitX, double unitY)
|
||||
{
|
||||
Matrix matrix;
|
||||
var source = PresentationSource.FromVisual(visual);
|
||||
if (source != null)
|
||||
{
|
||||
matrix = source.CompositionTarget.TransformFromDevice;
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var src = new HwndSource(new HwndSourceParameters()))
|
||||
{
|
||||
matrix = src.CompositionTarget.TransformFromDevice;
|
||||
}
|
||||
}
|
||||
return new Point((int)(matrix.M11 * unitX), (int)(matrix.M22 * unitY));
|
||||
}
|
||||
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct RECT
|
||||
{
|
||||
public int Left;
|
||||
public int Top;
|
||||
public int Right;
|
||||
public int Bottom;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<Window x:Class="PowerLauncher.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="clr-namespace:Wox.ViewModel;assembly=Wox"
|
||||
xmlns:vm="clr-namespace:PowerLauncher.ViewModel"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:PowerLauncher"
|
||||
|
||||
@@ -3,9 +3,9 @@ using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media.Animation;
|
||||
using Wox.Helper;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.ViewModel;
|
||||
using PowerLauncher.ViewModel;
|
||||
|
||||
using Screen = System.Windows.Forms.Screen;
|
||||
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
|
||||
@@ -66,11 +66,11 @@ namespace PowerLauncher
|
||||
private void BringProcessToForeground()
|
||||
{
|
||||
// Use SendInput hack to allow Activate to work - required to resolve focus issue https://github.com/microsoft/PowerToys/issues/4270
|
||||
WindowsInteropHelper.INPUT input = new WindowsInteropHelper.INPUT { type = WindowsInteropHelper.INPUTTYPE.INPUT_MOUSE, data = { } };
|
||||
WindowsInteropHelper.INPUT input = new WindowsInteropHelper.INPUT { type = WindowsInteropHelper.INPUTTYPE.INPUTMOUSE, data = { } };
|
||||
WindowsInteropHelper.INPUT[] inputs = new WindowsInteropHelper.INPUT[] { input };
|
||||
|
||||
// Send empty mouse event. This makes this thread the last to send input, and hence allows it to pass foreground permission checks
|
||||
_ = WindowsInteropHelper.SendInput(1, inputs, WindowsInteropHelper.INPUT.Size);
|
||||
_ = NativeMethods.SendInput(1, inputs, WindowsInteropHelper.INPUT.Size);
|
||||
Activate();
|
||||
}
|
||||
|
||||
|
||||
@@ -114,17 +114,20 @@
|
||||
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.112.2" />
|
||||
<PackageReference Include="System.Runtime" Version="4.3.1" />
|
||||
<PackageReference Include="Microsoft.VCRTForwarders.140" Version="1.0.6" />
|
||||
<PackageReference Include="System.Data.OleDb" Version="4.7.1" />
|
||||
<PackageReference Include="tlbimp-Microsoft.Search.Interop" Version="1.0.0">
|
||||
<NoWarn>NU1701</NoWarn>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\common\interop\interop.vcxproj" />
|
||||
<ProjectReference Include="..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
|
||||
<ProjectReference Include="..\..\..\core\Microsoft.PowerToys.Settings.UI.Lib\Microsoft.PowerToys.Settings.UI.Lib.csproj" />
|
||||
<ProjectReference Include="..\PowerLauncher.Telemetry\PowerLauncher.Telemetry.csproj" />
|
||||
<ProjectReference Include="..\Wox.Core\Wox.Core.csproj" />
|
||||
<ProjectReference Include="..\Wox.Infrastructure\Wox.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\Wox.Plugin\Wox.Plugin.csproj" />
|
||||
<ProjectReference Include="..\Wox\Wox.csproj">
|
||||
<NoWarn>NU1701</NoWarn>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
132
src/modules/launcher/PowerLauncher/PublicAPIInstance.cs
Normal file
132
src/modules/launcher/PowerLauncher/PublicAPIInstance.cs
Normal file
@@ -0,0 +1,132 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Core.Resource;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Image;
|
||||
using Wox.Plugin;
|
||||
using PowerLauncher.ViewModel;
|
||||
|
||||
namespace Wox
|
||||
{
|
||||
public class PublicAPIInstance : IPublicAPI, IDisposable
|
||||
{
|
||||
private readonly SettingWindowViewModel _settingsVM;
|
||||
private readonly MainViewModel _mainVM;
|
||||
private readonly Alphabet _alphabet;
|
||||
private bool _disposed = false;
|
||||
private readonly ThemeManager _themeManager;
|
||||
|
||||
public event ThemeChangedHandler ThemeChanged;
|
||||
|
||||
#region Constructor
|
||||
|
||||
public PublicAPIInstance(SettingWindowViewModel settingsVM, MainViewModel mainVM, Alphabet alphabet, ThemeManager themeManager)
|
||||
{
|
||||
_settingsVM = settingsVM ?? throw new ArgumentNullException(nameof(settingsVM));
|
||||
_mainVM = mainVM ?? throw new ArgumentNullException(nameof(mainVM));
|
||||
_alphabet = alphabet ?? throw new ArgumentNullException(nameof(alphabet));
|
||||
_themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));
|
||||
_themeManager.ThemeChanged += OnThemeChanged;
|
||||
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.MainWindowVisibility = Visibility.Hidden;
|
||||
|
||||
// we must manually save
|
||||
// UpdateManager.RestartApp() will call Environment.Exit(0)
|
||||
// which will cause ungraceful exit
|
||||
SaveAppAllSettings();
|
||||
|
||||
// Todo : Implement logic to restart this app.
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
public void CheckForNewUpdate()
|
||||
{
|
||||
//_settingsVM.UpdateApp();
|
||||
}
|
||||
|
||||
public void SaveAppAllSettings()
|
||||
{
|
||||
_mainVM.Save();
|
||||
_settingsVM.Save();
|
||||
PluginManager.Save();
|
||||
ImageLoader.Save();
|
||||
_alphabet.Save();
|
||||
}
|
||||
|
||||
public void ReloadAllPluginData()
|
||||
{
|
||||
PluginManager.ReloadData();
|
||||
}
|
||||
|
||||
public void ShowMsg(string title, string subTitle = "", string iconPath = "", bool useMainWindowAsOwner = true)
|
||||
{
|
||||
}
|
||||
|
||||
public void InstallPlugin(string path)
|
||||
{
|
||||
Application.Current.Dispatcher.Invoke(() => PluginManager.InstallPlugin(path));
|
||||
}
|
||||
|
||||
public string GetTranslation(string key)
|
||||
{
|
||||
return InternationalizationManager.Instance.GetTranslation(key);
|
||||
}
|
||||
|
||||
public List<PluginPair> GetAllPlugins()
|
||||
{
|
||||
return PluginManager.AllPlugins.ToList();
|
||||
}
|
||||
|
||||
public Theme GetCurrentTheme()
|
||||
{
|
||||
return _themeManager.GetCurrentTheme();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Protected Methods
|
||||
|
||||
protected void OnThemeChanged(Theme oldTheme, Theme newTheme)
|
||||
{
|
||||
ThemeChanged?.Invoke(oldTheme, newTheme);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_themeManager.ThemeChanged -= OnThemeChanged;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
23
src/modules/launcher/PowerLauncher/ReportWindow.xaml
Normal file
23
src/modules/launcher/PowerLauncher/ReportWindow.xaml
Normal file
@@ -0,0 +1,23 @@
|
||||
<Window x:Class="PowerLauncher.ReportWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
mc:Ignorable="d"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Icon="Images/app_error.png"
|
||||
Topmost="True"
|
||||
ResizeMode="NoResize"
|
||||
Width="600"
|
||||
Height="455"
|
||||
Title="{DynamicResource reportWindow_wox_got_an_error}"
|
||||
d:DesignHeight="300" d:DesignWidth="600" x:ClassModifier="internal">
|
||||
<RichTextBox x:Name="ErrorTextbox"
|
||||
IsDocumentEnabled="True"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
FontSize="14"
|
||||
Margin="10"
|
||||
BorderThickness="0"/>
|
||||
|
||||
</Window>
|
||||
63
src/modules/launcher/PowerLauncher/ReportWindow.xaml.cs
Normal file
63
src/modules/launcher/PowerLauncher/ReportWindow.xaml.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Documents;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Logger;
|
||||
|
||||
namespace PowerLauncher
|
||||
{
|
||||
internal partial class ReportWindow
|
||||
{
|
||||
public ReportWindow(Exception exception)
|
||||
{
|
||||
InitializeComponent();
|
||||
ErrorTextbox.Document.Blocks.FirstBlock.Margin = new Thickness(0);
|
||||
SetException(exception);
|
||||
}
|
||||
|
||||
private void SetException(Exception exception)
|
||||
{
|
||||
string path = Log.CurrentLogDirectory;
|
||||
var directory = new DirectoryInfo(path);
|
||||
var log = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
|
||||
|
||||
var paragraph = Hyperlink("Please open new issue in: ", Constant.Issue);
|
||||
paragraph.Inlines.Add($"1. upload log file: {log.FullName}\n");
|
||||
paragraph.Inlines.Add($"2. copy below exception message");
|
||||
ErrorTextbox.Document.Blocks.Add(paragraph);
|
||||
|
||||
StringBuilder content = new StringBuilder();
|
||||
content.AppendLine(ErrorReporting.RuntimeInfo());
|
||||
content.AppendLine($"Date: {DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
|
||||
content.AppendLine("Exception:");
|
||||
content.AppendLine(exception.ToString());
|
||||
paragraph = new Paragraph();
|
||||
paragraph.Inlines.Add(content.ToString());
|
||||
ErrorTextbox.Document.Blocks.Add(paragraph);
|
||||
}
|
||||
|
||||
private static Paragraph Hyperlink(string textBeforeUrl, string url)
|
||||
{
|
||||
var paragraph = new Paragraph();
|
||||
paragraph.Margin = new Thickness(0);
|
||||
|
||||
var link = new Hyperlink { IsEnabled = true };
|
||||
link.Inlines.Add(url);
|
||||
link.NavigateUri = new Uri(url);
|
||||
link.RequestNavigate += (s, e) => Process.Start(e.Uri.ToString());
|
||||
link.Click += (s, e) => Process.Start(url);
|
||||
|
||||
paragraph.Inlines.Add(textBeforeUrl);
|
||||
paragraph.Inlines.Add(link);
|
||||
paragraph.Inlines.Add("\n");
|
||||
|
||||
return paragraph;
|
||||
}
|
||||
}
|
||||
}
|
||||
28
src/modules/launcher/PowerLauncher/Settings.cs
Normal file
28
src/modules/launcher/PowerLauncher/Settings.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
namespace PowerLauncher.Properties {
|
||||
|
||||
|
||||
// This class allows you to handle specific events on the settings class:
|
||||
// The SettingChanging event is raised before a setting's value is changed.
|
||||
// The PropertyChanged event is raised after a setting's value is changed.
|
||||
// The SettingsLoaded event is raised after the setting values are loaded.
|
||||
// The SettingsSaving event is raised before the setting values are saved.
|
||||
internal sealed partial class Settings {
|
||||
|
||||
public Settings() {
|
||||
// // To add event handlers for saving and changing settings, uncomment the lines below:
|
||||
//
|
||||
// this.SettingChanging += this.SettingChangingEventHandler;
|
||||
//
|
||||
// this.SettingsSaving += this.SettingsSavingEventHandler;
|
||||
//
|
||||
}
|
||||
|
||||
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
|
||||
// Add code to handle the SettingChangingEvent event here.
|
||||
}
|
||||
|
||||
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
|
||||
// Add code to handle the SettingsSaving event here.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ namespace PowerLauncher
|
||||
{
|
||||
_settings = settings;
|
||||
// Set up watcher
|
||||
_watcher = Helper.GetFileWatcher(PowerLauncherSettings.POWERTOYNAME, "settings.json", OverloadSettings);
|
||||
_watcher = Microsoft.PowerToys.Settings.UI.Lib.Utilities.Helper.GetFileWatcher(PowerLauncherSettings.POWERTOYNAME, "settings.json", OverloadSettings);
|
||||
|
||||
// Load initial settings file
|
||||
OverloadSettings();
|
||||
|
||||
45
src/modules/launcher/PowerLauncher/Storage/HistoryItem.cs
Normal file
45
src/modules/launcher/PowerLauncher/Storage/HistoryItem.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
|
||||
namespace PowerLauncher.Storage
|
||||
{
|
||||
public class HistoryItem
|
||||
{
|
||||
public string Query { get; set; }
|
||||
public DateTime ExecutedDateTime { get; set; }
|
||||
|
||||
public string GetTimeAgo()
|
||||
{
|
||||
return DateTimeAgo(ExecutedDateTime);
|
||||
}
|
||||
|
||||
private static string DateTimeAgo(DateTime dt)
|
||||
{
|
||||
var span = DateTime.Now - dt;
|
||||
if (span.Days > 365)
|
||||
{
|
||||
int years = (span.Days / 365);
|
||||
if (span.Days % 365 != 0)
|
||||
years += 1;
|
||||
return $"about {years} {(years == 1 ? "year" : "years")} ago";
|
||||
}
|
||||
if (span.Days > 30)
|
||||
{
|
||||
int months = (span.Days / 30);
|
||||
if (span.Days % 31 != 0)
|
||||
months += 1;
|
||||
return $"about {months} {(months == 1 ? "month" : "months")} ago";
|
||||
}
|
||||
if (span.Days > 0)
|
||||
return $"about {span.Days} {(span.Days == 1 ? "day" : "days")} ago";
|
||||
if (span.Hours > 0)
|
||||
return $"about {span.Hours} {(span.Hours == 1 ? "hour" : "hours")} ago";
|
||||
if (span.Minutes > 0)
|
||||
return $"about {span.Minutes} {(span.Minutes == 1 ? "minute" : "minutes")} ago";
|
||||
if (span.Seconds > 5)
|
||||
return $"about {span.Seconds} seconds ago";
|
||||
if (span.Seconds <= 5)
|
||||
return "just now";
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
37
src/modules/launcher/PowerLauncher/Storage/QueryHistory.cs
Normal file
37
src/modules/launcher/PowerLauncher/Storage/QueryHistory.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.Storage
|
||||
{
|
||||
public class QueryHistory
|
||||
{
|
||||
public List<HistoryItem> Items { get; } = new List<HistoryItem>();
|
||||
|
||||
private int _maxHistory = 300;
|
||||
|
||||
public void Add(string query)
|
||||
{
|
||||
if (string.IsNullOrEmpty(query)) return;
|
||||
if (Items.Count > _maxHistory)
|
||||
{
|
||||
Items.RemoveAt(0);
|
||||
}
|
||||
|
||||
if (Items.Count > 0 && Items.Last().Query == query)
|
||||
{
|
||||
Items.Last().ExecutedDateTime = DateTime.Now;
|
||||
}
|
||||
else
|
||||
{
|
||||
Items.Add(new HistoryItem
|
||||
{
|
||||
Query = query,
|
||||
ExecutedDateTime = DateTime.Now
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
58
src/modules/launcher/PowerLauncher/Storage/TopMostRecord.cs
Normal file
58
src/modules/launcher/PowerLauncher/Storage/TopMostRecord.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.Storage
|
||||
{
|
||||
// todo this class is not thread safe.... but used from multiple threads.
|
||||
public class TopMostRecord
|
||||
{
|
||||
[JsonProperty]
|
||||
private Dictionary<string, Record> records = new Dictionary<string, Record>();
|
||||
|
||||
internal bool IsTopMost(Result result)
|
||||
{
|
||||
if (records.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// since this dictionary should be very small (or empty) going over it should be pretty fast.
|
||||
return records.Any(o => o.Value.Title == result.Title
|
||||
&& o.Value.SubTitle == result.SubTitle
|
||||
&& o.Value.PluginID == result.PluginID
|
||||
&& o.Key == result.OriginQuery.RawQuery);
|
||||
}
|
||||
|
||||
internal void Remove(Result result)
|
||||
{
|
||||
records.Remove(result.OriginQuery.RawQuery);
|
||||
}
|
||||
|
||||
internal void AddOrUpdate(Result result)
|
||||
{
|
||||
var record = new Record
|
||||
{
|
||||
PluginID = result.PluginID,
|
||||
Title = result.Title,
|
||||
SubTitle = result.SubTitle
|
||||
};
|
||||
records[result.OriginQuery.RawQuery] = record;
|
||||
|
||||
}
|
||||
|
||||
public void Load(Dictionary<string, Record> dictionary)
|
||||
{
|
||||
records = dictionary;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class Record
|
||||
{
|
||||
public string Title { get; set; }
|
||||
public string SubTitle { get; set; }
|
||||
public string PluginID { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Wox.Infrastructure.Storage;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.Storage
|
||||
{
|
||||
public class UserSelectedRecord
|
||||
{
|
||||
[JsonProperty]
|
||||
private Dictionary<string, int> records = new Dictionary<string, int>();
|
||||
|
||||
public void Add(Result result)
|
||||
{
|
||||
if (result == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(result));
|
||||
}
|
||||
|
||||
var key = result.ToString();
|
||||
if (records.TryGetValue(key, out int value))
|
||||
{
|
||||
records[key] = value + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
records.Add(key, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public int GetSelectedCount(Result result)
|
||||
{
|
||||
if (result == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(result));
|
||||
}
|
||||
|
||||
if (result != null && records.TryGetValue(result.ToString(), out int value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Microsoft.PowerLauncher.Telemetry;
|
||||
using Microsoft.PowerToys.Telemetry;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
using System.Windows.Input;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.ViewModel
|
||||
{
|
||||
public class ContextMenuItemViewModel : BaseModel
|
||||
{
|
||||
private ICommand _command;
|
||||
|
||||
public string PluginName { get; set; }
|
||||
public string Title { get; set; }
|
||||
public string Glyph { get; set; }
|
||||
public string FontFamily { get; set; }
|
||||
public ICommand Command {
|
||||
get
|
||||
{
|
||||
return this._command;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
// ICommand does not implement the INotifyPropertyChanged interface and must call OnPropertyChanged() to prevent memory leaks
|
||||
if (value != this._command)
|
||||
{
|
||||
this._command = value;
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Key AcceleratorKey { get; set; }
|
||||
public ModifierKeys AcceleratorModifiers { get; set; }
|
||||
public bool IsAcceleratorKeyEnabled { get; set; }
|
||||
|
||||
public void SendTelemetryEvent(LauncherResultActionEvent.TriggerType triggerType)
|
||||
{
|
||||
var eventData = new LauncherResultActionEvent()
|
||||
{
|
||||
PluginName = PluginName,
|
||||
Trigger = triggerType.ToString(),
|
||||
ActionName = Title
|
||||
|
||||
};
|
||||
PowerToysTelemetry.Log.WriteEvent(eventData);
|
||||
}
|
||||
}
|
||||
}
|
||||
802
src/modules/launcher/PowerLauncher/ViewModel/MainViewModel.cs
Normal file
802
src/modules/launcher/PowerLauncher/ViewModel/MainViewModel.cs
Normal file
@@ -0,0 +1,802 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Core.Resource;
|
||||
using PowerLauncher.Helper;
|
||||
using Wox.Infrastructure;
|
||||
using Wox.Infrastructure.Hotkey;
|
||||
using Wox.Infrastructure.Storage;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.Plugin;
|
||||
using Microsoft.PowerLauncher.Telemetry;
|
||||
using PowerLauncher.Storage;
|
||||
using Microsoft.PowerToys.Telemetry;
|
||||
using interop;
|
||||
using System.Globalization;
|
||||
|
||||
namespace PowerLauncher.ViewModel
|
||||
{
|
||||
public class MainViewModel : BaseModel, ISavable, IDisposable
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private Query _lastQuery;
|
||||
private static Query _emptyQuery = new Query();
|
||||
private static bool _disposed;
|
||||
private string _queryTextBeforeLeaveResults;
|
||||
|
||||
private readonly WoxJsonStorage<QueryHistory> _historyItemsStorage;
|
||||
private readonly WoxJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
|
||||
private readonly WoxJsonStorage<TopMostRecord> _topMostRecordStorage;
|
||||
private readonly Settings _settings;
|
||||
private readonly QueryHistory _history;
|
||||
private readonly UserSelectedRecord _userSelectedRecord;
|
||||
private readonly TopMostRecord _topMostRecord;
|
||||
|
||||
private CancellationTokenSource _updateSource { get; set; }
|
||||
private CancellationToken _updateToken;
|
||||
private bool _saved;
|
||||
private HotkeyManager _hotkeyManager { get; set; }
|
||||
private ushort _hotkeyHandle;
|
||||
private readonly Internationalization _translator = InternationalizationManager.Instance;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructor
|
||||
|
||||
public MainViewModel(Settings settings)
|
||||
{
|
||||
_hotkeyManager = new HotkeyManager();
|
||||
_saved = false;
|
||||
_queryTextBeforeLeaveResults = "";
|
||||
_lastQuery = _emptyQuery;
|
||||
_disposed = false;
|
||||
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
|
||||
_historyItemsStorage = new WoxJsonStorage<QueryHistory>();
|
||||
_userSelectedRecordStorage = new WoxJsonStorage<UserSelectedRecord>();
|
||||
_topMostRecordStorage = new WoxJsonStorage<TopMostRecord>();
|
||||
_history = _historyItemsStorage.Load();
|
||||
_userSelectedRecord = _userSelectedRecordStorage.Load();
|
||||
_topMostRecord = _topMostRecordStorage.Load();
|
||||
|
||||
ContextMenu = new ResultsViewModel(_settings);
|
||||
Results = new ResultsViewModel(_settings);
|
||||
History = new ResultsViewModel(_settings);
|
||||
_selectedResults = Results;
|
||||
|
||||
InitializeKeyCommands();
|
||||
RegisterResultsUpdatedEvent();
|
||||
|
||||
_settings.PropertyChanged += (s, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(Settings.Hotkey))
|
||||
{
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
if (!string.IsNullOrEmpty(_settings.PreviousHotkey))
|
||||
{
|
||||
_hotkeyManager.UnregisterHotkey(_hotkeyHandle);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(_settings.Hotkey))
|
||||
{
|
||||
SetHotkey(_settings.Hotkey, OnHotkey);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
SetHotkey(_settings.Hotkey, OnHotkey);
|
||||
SetCustomPluginHotkey();
|
||||
}
|
||||
|
||||
private void RegisterResultsUpdatedEvent()
|
||||
{
|
||||
foreach (var pair in PluginManager.GetPluginsForInterface<IResultUpdated>())
|
||||
{
|
||||
var plugin = (IResultUpdated)pair.Plugin;
|
||||
plugin.ResultsUpdated += (s, e) =>
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
PluginManager.UpdatePluginMetadata(e.Results, pair.Metadata, e.Query);
|
||||
UpdateResultView(e.Results, pair.Metadata, e.Query);
|
||||
}, _updateToken);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private void InitializeKeyCommands()
|
||||
{
|
||||
IgnoreCommand = new RelayCommand(_ => {});
|
||||
|
||||
EscCommand = new RelayCommand(_ =>
|
||||
{
|
||||
if (!SelectedIsFromQueryResults())
|
||||
{
|
||||
SelectedResults = Results;
|
||||
}
|
||||
else
|
||||
{
|
||||
MainWindowVisibility = Visibility.Collapsed;
|
||||
}
|
||||
});
|
||||
|
||||
SelectNextItemCommand = new RelayCommand(_ =>
|
||||
{
|
||||
SelectedResults.SelectNextResult();
|
||||
});
|
||||
|
||||
SelectPrevItemCommand = new RelayCommand(_ =>
|
||||
{
|
||||
SelectedResults.SelectPrevResult();
|
||||
});
|
||||
|
||||
SelectNextTabItemCommand = new RelayCommand(_ =>
|
||||
{
|
||||
SelectedResults.SelectNextTabItem();
|
||||
});
|
||||
|
||||
SelectPrevTabItemCommand = new RelayCommand(_ =>
|
||||
{
|
||||
SelectedResults.SelectPrevTabItem();
|
||||
});
|
||||
|
||||
SelectNextPageCommand = new RelayCommand(_ =>
|
||||
{
|
||||
SelectedResults.SelectNextPage();
|
||||
});
|
||||
|
||||
SelectPrevPageCommand = new RelayCommand(_ =>
|
||||
{
|
||||
SelectedResults.SelectPrevPage();
|
||||
});
|
||||
|
||||
SelectFirstResultCommand = new RelayCommand(_ => SelectedResults.SelectFirstResult());
|
||||
|
||||
StartHelpCommand = new RelayCommand(_ =>
|
||||
{
|
||||
Process.Start("http://doc.wox.one/");
|
||||
});
|
||||
|
||||
OpenResultCommand = new RelayCommand(index =>
|
||||
{
|
||||
var results = SelectedResults;
|
||||
|
||||
if (index != null)
|
||||
{
|
||||
results.SelectedIndex = int.Parse(index.ToString(), CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
if(results.SelectedItem != null)
|
||||
{
|
||||
//If there is a context button selected fire the action for that button before the main command.
|
||||
bool didExecuteContextButton = results.SelectedItem.ExecuteSelectedContextButton();
|
||||
|
||||
if (!didExecuteContextButton)
|
||||
{
|
||||
var result = results.SelectedItem.Result;
|
||||
if (result != null && result.Action != null) // SelectedItem returns null if selection is empty.
|
||||
{
|
||||
MainWindowVisibility = Visibility.Collapsed;
|
||||
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
result.Action(new ActionContext
|
||||
{
|
||||
SpecialKeyState = KeyboardHelper.CheckModifiers()
|
||||
});
|
||||
});
|
||||
|
||||
if (SelectedIsFromQueryResults())
|
||||
{
|
||||
_userSelectedRecord.Add(result);
|
||||
_history.Add(result.OriginQuery.RawQuery);
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedResults = Results;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
LoadContextMenuCommand = new RelayCommand(_ =>
|
||||
{
|
||||
if (SelectedIsFromQueryResults())
|
||||
{
|
||||
SelectedResults = ContextMenu;
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedResults = Results;
|
||||
}
|
||||
});
|
||||
|
||||
LoadHistoryCommand = new RelayCommand(_ =>
|
||||
{
|
||||
if (SelectedIsFromQueryResults())
|
||||
{
|
||||
SelectedResults = History;
|
||||
History.SelectedIndex = _history.Items.Count - 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedResults = Results;
|
||||
}
|
||||
});
|
||||
|
||||
ClearQueryCommand = new RelayCommand(_ =>
|
||||
{
|
||||
if(!string.IsNullOrEmpty(QueryText))
|
||||
{
|
||||
ChangeQueryText(string.Empty,true);
|
||||
//Push Event to UI SystemQuery has changed
|
||||
OnPropertyChanged(nameof(SystemQueryText));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ViewModel Properties
|
||||
|
||||
public Brush MainWindowBackground { get; set; }
|
||||
public Brush MainWindowBorderBrush { get; set; }
|
||||
|
||||
public ResultsViewModel Results { get; private set; }
|
||||
public ResultsViewModel ContextMenu { get; private set; }
|
||||
public ResultsViewModel History { get; private set; }
|
||||
|
||||
public string SystemQueryText { get; set; } = String.Empty;
|
||||
|
||||
public string QueryText { get; set; } = String.Empty;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// we need move cursor to end when we manually changed query
|
||||
/// but we don't want to move cursor to end when query is updated from TextBox.
|
||||
/// Also we don't want to force the results to change unless explicitly told to.
|
||||
/// </summary>
|
||||
/// <param name="queryText"></param>
|
||||
/// <param name="requery">Optional Parameter that if true, will automatically execute a query against the updated text</param>
|
||||
public void ChangeQueryText(string queryText, bool requery=false)
|
||||
{
|
||||
SystemQueryText = queryText;
|
||||
|
||||
if(requery)
|
||||
{
|
||||
QueryText = queryText;
|
||||
Query();
|
||||
}
|
||||
}
|
||||
public bool LastQuerySelected { get; set; }
|
||||
|
||||
private ResultsViewModel _selectedResults;
|
||||
private ResultsViewModel SelectedResults
|
||||
{
|
||||
get { return _selectedResults; }
|
||||
set
|
||||
{
|
||||
_selectedResults = value;
|
||||
if (SelectedIsFromQueryResults())
|
||||
{
|
||||
ContextMenu.Visibility = Visibility.Collapsed;
|
||||
History.Visibility = Visibility.Collapsed;
|
||||
ChangeQueryText(_queryTextBeforeLeaveResults);
|
||||
}
|
||||
else
|
||||
{
|
||||
Results.Visibility = Visibility.Collapsed;
|
||||
_queryTextBeforeLeaveResults = QueryText;
|
||||
|
||||
|
||||
// Because of Fody's optimization
|
||||
// setter won't be called when property value is not changed.
|
||||
// so we need manually call Query()
|
||||
// http://stackoverflow.com/posts/25895769/revisions
|
||||
if (string.IsNullOrEmpty(QueryText))
|
||||
{
|
||||
Query();
|
||||
}
|
||||
else
|
||||
{
|
||||
QueryText = string.Empty;
|
||||
}
|
||||
}
|
||||
_selectedResults.Visibility = Visibility.Visible;
|
||||
}
|
||||
}
|
||||
|
||||
public Visibility ProgressBarVisibility { get; set; }
|
||||
|
||||
private Visibility _visibility;
|
||||
|
||||
public Visibility MainWindowVisibility {
|
||||
get { return _visibility; }
|
||||
set {
|
||||
_visibility = value;
|
||||
if(value == Visibility.Visible)
|
||||
{
|
||||
PowerToysTelemetry.Log.WriteEvent(new LauncherShowEvent());
|
||||
}
|
||||
else
|
||||
{
|
||||
PowerToysTelemetry.Log.WriteEvent(new LauncherHideEvent());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand IgnoreCommand { get; set; }
|
||||
public ICommand EscCommand { get; set; }
|
||||
public ICommand SelectNextItemCommand { get; set; }
|
||||
public ICommand SelectPrevItemCommand { get; set; }
|
||||
|
||||
public ICommand SelectNextTabItemCommand { get; set; }
|
||||
public ICommand SelectPrevTabItemCommand { get; set; }
|
||||
|
||||
public ICommand SelectNextPageCommand { get; set; }
|
||||
public ICommand SelectPrevPageCommand { get; set; }
|
||||
public ICommand SelectFirstResultCommand { get; set; }
|
||||
public ICommand StartHelpCommand { get; set; }
|
||||
public ICommand LoadContextMenuCommand { get; set; }
|
||||
public ICommand LoadHistoryCommand { get; set; }
|
||||
public ICommand OpenResultCommand { get; set; }
|
||||
public ICommand ClearQueryCommand { get; set; }
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
public void Query()
|
||||
{
|
||||
if (SelectedIsFromQueryResults())
|
||||
{
|
||||
QueryResults();
|
||||
}
|
||||
else if (HistorySelected())
|
||||
{
|
||||
QueryHistory();
|
||||
}
|
||||
}
|
||||
|
||||
private void QueryHistory()
|
||||
{
|
||||
const string id = "Query History ID";
|
||||
#pragma warning disable CA1308 // Normalize strings to uppercase
|
||||
var query = QueryText.ToLower(CultureInfo.InvariantCulture).Trim();
|
||||
#pragma warning restore CA1308 // Normalize strings to uppercase
|
||||
History.Clear();
|
||||
|
||||
var results = new List<Result>();
|
||||
foreach (var h in _history.Items)
|
||||
{
|
||||
var title = _translator.GetTranslation("executeQuery");
|
||||
var time = _translator.GetTranslation("lastExecuteTime");
|
||||
var result = new Result
|
||||
{
|
||||
Title = string.Format(CultureInfo.InvariantCulture, title, h.Query),
|
||||
SubTitle = string.Format(CultureInfo.InvariantCulture, time, h.ExecutedDateTime),
|
||||
IcoPath = "Images\\history.png",
|
||||
OriginQuery = new Query { RawQuery = h.Query },
|
||||
Action = _ =>
|
||||
{
|
||||
SelectedResults = Results;
|
||||
ChangeQueryText(h.Query);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
results.Add(result);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(query))
|
||||
{
|
||||
var filtered = results.Where
|
||||
(
|
||||
r => StringMatcher.FuzzySearch(query, r.Title).IsSearchPrecisionScoreMet() ||
|
||||
StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet()
|
||||
).ToList();
|
||||
History.AddResults(filtered, id);
|
||||
}
|
||||
else
|
||||
{
|
||||
History.AddResults(results, id);
|
||||
}
|
||||
}
|
||||
|
||||
private void QueryResults()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(QueryText))
|
||||
{
|
||||
var queryTimer = new System.Diagnostics.Stopwatch();
|
||||
queryTimer.Start();
|
||||
_updateSource?.Cancel();
|
||||
var currentUpdateSource = new CancellationTokenSource();
|
||||
_updateSource = currentUpdateSource;
|
||||
var currentCancellationToken = _updateSource.Token;
|
||||
_updateToken = currentCancellationToken;
|
||||
|
||||
ProgressBarVisibility = Visibility.Hidden;
|
||||
var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
|
||||
if (query != null)
|
||||
{
|
||||
// handle the exclusiveness of plugin using action keyword
|
||||
RemoveOldQueryResults(query);
|
||||
|
||||
_lastQuery = query;
|
||||
var plugins = PluginManager.ValidPluginsForQuery(query);
|
||||
|
||||
Task.Run(() =>
|
||||
{
|
||||
// so looping will stop once it was cancelled
|
||||
var parallelOptions = new ParallelOptions { CancellationToken = currentCancellationToken };
|
||||
try
|
||||
{
|
||||
Parallel.ForEach(plugins, parallelOptions, plugin =>
|
||||
{
|
||||
if (!plugin.Metadata.Disabled)
|
||||
{
|
||||
var results = PluginManager.QueryForPlugin(plugin, query);
|
||||
if (Application.Current.Dispatcher.CheckAccess())
|
||||
{
|
||||
UpdateResultView(results, plugin.Metadata, query);
|
||||
}
|
||||
else
|
||||
{
|
||||
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
|
||||
{
|
||||
UpdateResultView(results, plugin.Metadata, query);
|
||||
}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// nothing to do here
|
||||
}
|
||||
|
||||
|
||||
// this should happen once after all queries are done so progress bar should continue
|
||||
// until the end of all querying
|
||||
if (currentUpdateSource == _updateSource)
|
||||
{ // update to hidden if this is still the current query
|
||||
ProgressBarVisibility = Visibility.Hidden;
|
||||
}
|
||||
|
||||
queryTimer.Stop();
|
||||
var queryEvent = new LauncherQueryEvent()
|
||||
{
|
||||
QueryTimeMs = queryTimer.ElapsedMilliseconds,
|
||||
NumResults = Results.Results.Count,
|
||||
QueryLength = query.RawQuery.Length
|
||||
};
|
||||
PowerToysTelemetry.Log.WriteEvent(queryEvent);
|
||||
|
||||
}, currentCancellationToken);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_updateSource?.Cancel();
|
||||
_lastQuery = _emptyQuery;
|
||||
Results.SelectedItem = null;
|
||||
Results.Clear();
|
||||
Results.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveOldQueryResults(Query query)
|
||||
{
|
||||
string lastKeyword = _lastQuery.ActionKeyword;
|
||||
string keyword = query.ActionKeyword;
|
||||
if (string.IsNullOrEmpty(lastKeyword))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(keyword))
|
||||
{
|
||||
Results.RemoveResultsExcept(PluginManager.NonGlobalPlugins[keyword].Metadata);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(keyword))
|
||||
{
|
||||
Results.RemoveResultsFor(PluginManager.NonGlobalPlugins[lastKeyword].Metadata);
|
||||
}
|
||||
else if (lastKeyword != keyword)
|
||||
{
|
||||
Results.RemoveResultsExcept(PluginManager.NonGlobalPlugins[keyword].Metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private bool SelectedIsFromQueryResults()
|
||||
{
|
||||
var selected = SelectedResults == Results;
|
||||
return selected;
|
||||
}
|
||||
|
||||
private bool ContextMenuSelected()
|
||||
{
|
||||
var selected = SelectedResults == ContextMenu;
|
||||
return selected;
|
||||
}
|
||||
|
||||
|
||||
private bool HistorySelected()
|
||||
{
|
||||
var selected = SelectedResults == History;
|
||||
return selected;
|
||||
}
|
||||
#region Hotkey
|
||||
|
||||
private void SetHotkey(string hotkeyStr, HotkeyCallback action)
|
||||
{
|
||||
var hotkey = new HotkeyModel(hotkeyStr);
|
||||
SetHotkey(hotkey, action);
|
||||
}
|
||||
|
||||
private void SetHotkey(HotkeyModel hotkeyModel, HotkeyCallback action)
|
||||
{
|
||||
string hotkeyStr = hotkeyModel.ToString();
|
||||
try
|
||||
{
|
||||
Hotkey hotkey = new Hotkey();
|
||||
hotkey.Alt = hotkeyModel.Alt;
|
||||
hotkey.Shift = hotkeyModel.Shift;
|
||||
hotkey.Ctrl = hotkeyModel.Ctrl;
|
||||
hotkey.Win = hotkeyModel.Win;
|
||||
hotkey.Key = (byte) KeyInterop.VirtualKeyFromKey(hotkeyModel.CharKey);
|
||||
|
||||
_hotkeyHandle = _hotkeyManager.RegisterHotkey(hotkey, action);
|
||||
}
|
||||
#pragma warning disable CA1031 // Do not catch general exception types
|
||||
catch (Exception)
|
||||
#pragma warning restore CA1031 // Do not catch general exception types
|
||||
{
|
||||
string errorMsg = string.Format(CultureInfo.InvariantCulture, InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"), hotkeyStr);
|
||||
MessageBox.Show(errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if Wox should ignore any hotkeys
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private bool ShouldIgnoreHotkeys()
|
||||
{
|
||||
//double if to omit calling win32 function
|
||||
if (_settings.IgnoreHotkeysOnFullscreen)
|
||||
if (WindowsInteropHelper.IsWindowFullscreen())
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void SetCustomPluginHotkey()
|
||||
{
|
||||
if (_settings.CustomPluginHotkeys == null) return;
|
||||
foreach (CustomPluginHotkey hotkey in _settings.CustomPluginHotkeys)
|
||||
{
|
||||
SetHotkey(hotkey.Hotkey, () =>
|
||||
{
|
||||
if (ShouldIgnoreHotkeys()) return;
|
||||
MainWindowVisibility = Visibility.Visible;
|
||||
ChangeQueryText(hotkey.ActionKeyword);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void OnHotkey()
|
||||
{
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
if (!ShouldIgnoreHotkeys())
|
||||
{
|
||||
|
||||
if (_settings.LastQueryMode == LastQueryMode.Empty)
|
||||
{
|
||||
ChangeQueryText(string.Empty);
|
||||
}
|
||||
else if (_settings.LastQueryMode == LastQueryMode.Preserved)
|
||||
{
|
||||
LastQuerySelected = true;
|
||||
}
|
||||
else if (_settings.LastQueryMode == LastQueryMode.Selected)
|
||||
{
|
||||
LastQuerySelected = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"wrong LastQueryMode: <{_settings.LastQueryMode}>");
|
||||
}
|
||||
|
||||
ToggleWox();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ToggleWox()
|
||||
{
|
||||
if (MainWindowVisibility != Visibility.Visible)
|
||||
{
|
||||
MainWindowVisibility = Visibility.Visible;
|
||||
}
|
||||
else
|
||||
{
|
||||
MainWindowVisibility = Visibility.Collapsed;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public void Save()
|
||||
{
|
||||
if (!_saved)
|
||||
{
|
||||
_historyItemsStorage.Save();
|
||||
_userSelectedRecordStorage.Save();
|
||||
_topMostRecordStorage.Save();
|
||||
|
||||
_saved = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// To avoid deadlock, this method should not called from main thread
|
||||
/// </summary>
|
||||
public void UpdateResultView(List<Result> list, PluginMetadata metadata, Query originQuery)
|
||||
{
|
||||
if(list == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(list));
|
||||
}
|
||||
|
||||
if (metadata == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(metadata));
|
||||
}
|
||||
|
||||
if (originQuery == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(originQuery));
|
||||
}
|
||||
|
||||
foreach (var result in list)
|
||||
{
|
||||
if (_topMostRecord.IsTopMost(result))
|
||||
{
|
||||
result.Score = int.MaxValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
result.Score += _userSelectedRecord.GetSelectedCount(result) * 5;
|
||||
}
|
||||
}
|
||||
|
||||
if (originQuery.RawQuery == _lastQuery.RawQuery)
|
||||
{
|
||||
Results.AddResults(list, metadata.ID);
|
||||
}
|
||||
|
||||
if (Results.Visibility != Visibility.Visible && list.Count > 0)
|
||||
{
|
||||
Results.Visibility = Visibility.Visible;
|
||||
}
|
||||
}
|
||||
|
||||
public void ColdStartFix()
|
||||
{
|
||||
// Fix Cold start for List view xaml island
|
||||
List<Result> list = new List<Result>();
|
||||
Result r = new Result
|
||||
{
|
||||
Title = "hello"
|
||||
};
|
||||
list.Add(r);
|
||||
Results.AddResults(list, "0");
|
||||
Results.Clear();
|
||||
MainWindowVisibility = System.Windows.Visibility.Collapsed;
|
||||
|
||||
// Fix Cold start for plugins
|
||||
string s = "m";
|
||||
var query = QueryBuilder.Build(s.Trim(), PluginManager.NonGlobalPlugins);
|
||||
var plugins = PluginManager.ValidPluginsForQuery(query);
|
||||
foreach (PluginPair plugin in plugins)
|
||||
{
|
||||
if (!plugin.Metadata.Disabled && plugin.Metadata.Name != "Window Walker")
|
||||
{
|
||||
var _ = PluginManager.QueryForPlugin(plugin, query);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void HandleContextMenu(Key AcceleratorKey, ModifierKeys AcceleratorModifiers)
|
||||
{
|
||||
var results = SelectedResults;
|
||||
if (results.SelectedItem != null)
|
||||
{
|
||||
foreach (ContextMenuItemViewModel contextMenuItems in results.SelectedItem.ContextMenuItems)
|
||||
{
|
||||
if (contextMenuItems.AcceleratorKey == AcceleratorKey && contextMenuItems.AcceleratorModifiers == AcceleratorModifiers)
|
||||
{
|
||||
MainWindowVisibility = Visibility.Collapsed;
|
||||
contextMenuItems.Command.Execute(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetAutoCompleteText(int index, string input, String query)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(query))
|
||||
{
|
||||
if (index == 0)
|
||||
{
|
||||
if (input.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) == 0)
|
||||
{
|
||||
// Use the same case as the input query for the matched portion of the string
|
||||
return query + input.Substring(query.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string GetSearchText(int index, String input, string query)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(input))
|
||||
{
|
||||
if (index == 0 && !string.IsNullOrEmpty(query))
|
||||
{
|
||||
if (input.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) == 0)
|
||||
{
|
||||
return query + input.Substring(query.Length);
|
||||
}
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
if (_hotkeyHandle != 0)
|
||||
{
|
||||
_hotkeyManager.UnregisterHotkey(_hotkeyHandle);
|
||||
}
|
||||
_hotkeyManager.Dispose();
|
||||
_updateSource.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
31
src/modules/launcher/PowerLauncher/ViewModel/RelayCommand.cs
Normal file
31
src/modules/launcher/PowerLauncher/ViewModel/RelayCommand.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace PowerLauncher.ViewModel
|
||||
{
|
||||
public class RelayCommand : ICommand
|
||||
{
|
||||
private Action<object> _action;
|
||||
|
||||
public RelayCommand(Action<object> action)
|
||||
{
|
||||
_action = action;
|
||||
}
|
||||
|
||||
public virtual bool CanExecute(object parameter)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public event EventHandler CanExecuteChanged
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public virtual void Execute(object parameter)
|
||||
{
|
||||
_action?.Invoke(parameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
271
src/modules/launcher/PowerLauncher/ViewModel/ResultViewModel.cs
Normal file
271
src/modules/launcher/PowerLauncher/ViewModel/ResultViewModel.cs
Normal file
@@ -0,0 +1,271 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Wox.Core.Plugin;
|
||||
using Wox.Infrastructure.Image;
|
||||
using Wox.Infrastructure.Logger;
|
||||
using Wox.Plugin;
|
||||
using PowerLauncher.Helper;
|
||||
|
||||
namespace PowerLauncher.ViewModel
|
||||
{
|
||||
public class ResultViewModel : BaseModel
|
||||
{
|
||||
public enum ActivationType
|
||||
{
|
||||
Selection,
|
||||
Hover
|
||||
};
|
||||
|
||||
public ObservableCollection<ContextMenuItemViewModel> ContextMenuItems { get; } = new ObservableCollection<ContextMenuItemViewModel>();
|
||||
|
||||
public ICommand ActivateContextButtonsHoverCommand { get; set; }
|
||||
public ICommand ActivateContextButtonsSelectionCommand { get; set; }
|
||||
public ICommand DeactivateContextButtonsHoverCommand { get; set; }
|
||||
|
||||
public ICommand DeactivateContextButtonsSelectionCommand { get; set; }
|
||||
|
||||
public bool IsSelected { get; set; }
|
||||
|
||||
public bool IsHovered { get; set; }
|
||||
|
||||
public bool AreContextButtonsActive { get; set; }
|
||||
|
||||
public int ContextMenuSelectedIndex { get; set; }
|
||||
|
||||
const int NoSelectionIndex = -1;
|
||||
|
||||
public ResultViewModel(Result result)
|
||||
{
|
||||
if (result != null)
|
||||
{
|
||||
Result = result;
|
||||
}
|
||||
|
||||
ContextMenuSelectedIndex = NoSelectionIndex;
|
||||
LoadContextMenu();
|
||||
|
||||
ActivateContextButtonsHoverCommand = new RelayCommand(ActivateContextButtonsHoverAction);
|
||||
ActivateContextButtonsSelectionCommand = new RelayCommand(ActivateContextButtonsSelectionAction);
|
||||
DeactivateContextButtonsHoverCommand = new RelayCommand(DeactivateContextButtonsHoverAction);
|
||||
DeactivateContextButtonsSelectionCommand = new RelayCommand(DeactivateContextButtonsSelectionAction);
|
||||
}
|
||||
|
||||
private void ActivateContextButtonsHoverAction(object sender)
|
||||
{
|
||||
ActivateContextButtons(ActivationType.Hover);
|
||||
}
|
||||
|
||||
private void ActivateContextButtonsSelectionAction(object sender)
|
||||
{
|
||||
ActivateContextButtons(ActivationType.Selection);
|
||||
}
|
||||
public void ActivateContextButtons(ActivationType activationType)
|
||||
{
|
||||
// Result does not contain any context menu items - we don't need to show the context menu ListView at all.
|
||||
if (ContextMenuItems.Count > 0)
|
||||
{
|
||||
AreContextButtonsActive = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
AreContextButtonsActive = false;
|
||||
}
|
||||
|
||||
if (activationType == ActivationType.Selection)
|
||||
{
|
||||
IsSelected = true;
|
||||
EnableContextMenuAcceleratorKeys();
|
||||
}
|
||||
else if (activationType == ActivationType.Hover)
|
||||
{
|
||||
IsHovered = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void DeactivateContextButtonsHoverAction(object sender)
|
||||
{
|
||||
DeactivateContextButtons(ActivationType.Hover);
|
||||
}
|
||||
|
||||
private void DeactivateContextButtonsSelectionAction(object sender)
|
||||
{
|
||||
DeactivateContextButtons(ActivationType.Selection);
|
||||
}
|
||||
|
||||
public void DeactivateContextButtons(ActivationType activationType)
|
||||
{
|
||||
if (activationType == ActivationType.Selection)
|
||||
{
|
||||
IsSelected = false;
|
||||
DisableContextMenuAcceleratorkeys();
|
||||
}
|
||||
else if (activationType == ActivationType.Hover)
|
||||
{
|
||||
IsHovered = false;
|
||||
}
|
||||
|
||||
// Result does not contain any context menu items - we don't need to show the context menu ListView at all.
|
||||
if (ContextMenuItems?.Count > 0)
|
||||
{
|
||||
AreContextButtonsActive = IsSelected || IsHovered;
|
||||
}
|
||||
else
|
||||
{
|
||||
AreContextButtonsActive = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void LoadContextMenu()
|
||||
{
|
||||
var results = PluginManager.GetContextMenusForPlugin(Result);
|
||||
ContextMenuItems.Clear();
|
||||
foreach (var r in results)
|
||||
{
|
||||
ContextMenuItems.Add(new ContextMenuItemViewModel()
|
||||
{
|
||||
PluginName = r.PluginName,
|
||||
Title = r.Title,
|
||||
Glyph = r.Glyph,
|
||||
FontFamily = r.FontFamily,
|
||||
AcceleratorKey = r.AcceleratorKey,
|
||||
AcceleratorModifiers = r.AcceleratorModifiers,
|
||||
Command = new RelayCommand(_ =>
|
||||
{
|
||||
bool hideWindow = r.Action != null && r.Action(new ActionContext
|
||||
{
|
||||
SpecialKeyState = KeyboardHelper.CheckModifiers()
|
||||
});
|
||||
|
||||
if (hideWindow)
|
||||
{
|
||||
//TODO - Do we hide the window
|
||||
// MainWindowVisibility = Visibility.Collapsed;
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void EnableContextMenuAcceleratorKeys()
|
||||
{
|
||||
foreach (var i in ContextMenuItems)
|
||||
{
|
||||
i.IsAcceleratorKeyEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void DisableContextMenuAcceleratorkeys()
|
||||
{
|
||||
foreach (var i in ContextMenuItems)
|
||||
{
|
||||
i.IsAcceleratorKeyEnabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
public ImageSource Image
|
||||
{
|
||||
get
|
||||
{
|
||||
var imagePath = Result.IcoPath;
|
||||
if (string.IsNullOrEmpty(imagePath) && Result.Icon != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Result.Icon();
|
||||
}
|
||||
#pragma warning disable CA1031 // Do not catch general exception types
|
||||
catch (Exception e)
|
||||
#pragma warning restore CA1031 // Do not catch general exception types
|
||||
{
|
||||
Log.Exception($"|ResultViewModel.Image|IcoPath is empty and exception when calling Icon() for result <{Result.Title}> of plugin <{Result.PluginDirectory}>", e);
|
||||
imagePath = ImageLoader.ErrorIconPath;
|
||||
}
|
||||
}
|
||||
|
||||
// will get here either when icoPath has value\icon delegate is null\when had exception in delegate
|
||||
return ImageLoader.Load(imagePath);
|
||||
}
|
||||
}
|
||||
|
||||
//Returns false if we've already reached the last item.
|
||||
public bool SelectNextContextButton()
|
||||
{
|
||||
if (ContextMenuSelectedIndex == (ContextMenuItems.Count - 1))
|
||||
{
|
||||
ContextMenuSelectedIndex = NoSelectionIndex;
|
||||
return false;
|
||||
}
|
||||
|
||||
ContextMenuSelectedIndex++;
|
||||
return true;
|
||||
}
|
||||
|
||||
//Returns false if we've already reached the first item.
|
||||
public bool SelectPrevContextButton()
|
||||
{
|
||||
if (ContextMenuSelectedIndex == NoSelectionIndex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ContextMenuSelectedIndex--;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SelectLastContextButton()
|
||||
{
|
||||
ContextMenuSelectedIndex = ContextMenuItems.Count - 1;
|
||||
}
|
||||
|
||||
public bool HasSelectedContextButton()
|
||||
{
|
||||
var isContextSelected = (ContextMenuSelectedIndex != NoSelectionIndex);
|
||||
return isContextSelected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Triggers the action on the selected context button
|
||||
/// </summary>
|
||||
/// <returns>False if there is nothing selected, otherwise true</returns>
|
||||
public bool ExecuteSelectedContextButton()
|
||||
{
|
||||
if (HasSelectedContextButton())
|
||||
{
|
||||
ContextMenuItems[ContextMenuSelectedIndex].Command.Execute(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public Result Result { get; }
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
var r = obj as ResultViewModel;
|
||||
if (r != null)
|
||||
{
|
||||
return Result.Equals(r.Result);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Result.GetHashCode();
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var display = String.IsNullOrEmpty(Result.QueryTextDisplay) ? Result.Title : Result.QueryTextDisplay;
|
||||
return display;
|
||||
}
|
||||
}
|
||||
}
|
||||
294
src/modules/launcher/PowerLauncher/ViewModel/ResultsViewModel.cs
Normal file
294
src/modules/launcher/PowerLauncher/ViewModel/ResultsViewModel.cs
Normal file
@@ -0,0 +1,294 @@
|
||||
using PowerLauncher.Helper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.ViewModel
|
||||
{
|
||||
public class ResultsViewModel : BaseModel
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
public ResultCollection Results { get; }
|
||||
|
||||
private readonly object _addResultsLock = new object();
|
||||
private readonly object _collectionLock = new object();
|
||||
private readonly Settings _settings;
|
||||
// private int MaxResults => _settings?.MaxResultsToShow ?? 6;
|
||||
|
||||
public ResultsViewModel()
|
||||
{
|
||||
Results = new ResultCollection();
|
||||
BindingOperations.EnableCollectionSynchronization(Results, _collectionLock);
|
||||
}
|
||||
public ResultsViewModel(Settings settings) : this()
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_settings.PropertyChanged += (s, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(_settings.MaxResultsToShow))
|
||||
{
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
OnPropertyChanged(nameof(MaxHeight));
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
public int MaxHeight
|
||||
{
|
||||
get
|
||||
{
|
||||
return _settings.MaxResultsToShow * 75;
|
||||
}
|
||||
}
|
||||
public int SelectedIndex { get; set; }
|
||||
|
||||
private ResultViewModel _selectedItem;
|
||||
public ResultViewModel SelectedItem
|
||||
{
|
||||
get { return _selectedItem; }
|
||||
set
|
||||
{
|
||||
//value can be null when selecting an item in a virtualized list
|
||||
if (value != null)
|
||||
{
|
||||
if (_selectedItem != null)
|
||||
{
|
||||
_selectedItem.DeactivateContextButtons(ResultViewModel.ActivationType.Selection);
|
||||
}
|
||||
|
||||
_selectedItem = value;
|
||||
_selectedItem.ActivateContextButtons(ResultViewModel.ActivationType.Selection);
|
||||
}
|
||||
else
|
||||
{
|
||||
_selectedItem = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Thickness Margin { get; set; }
|
||||
public Visibility Visibility { get; set; } = Visibility.Hidden;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private static int InsertIndexOf(int newScore, IList<ResultViewModel> list)
|
||||
{
|
||||
int index = 0;
|
||||
for (; index < list.Count; index++)
|
||||
{
|
||||
var result = list[index];
|
||||
if (newScore > result.Result.Score)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private int NewIndex(int i)
|
||||
{
|
||||
var n = Results.Count;
|
||||
if (n > 0)
|
||||
{
|
||||
i = (n + i) % n;
|
||||
return i;
|
||||
}
|
||||
else
|
||||
{
|
||||
// SelectedIndex returns -1 if selection is empty.
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public void SelectNextResult()
|
||||
{
|
||||
SelectedIndex = NewIndex(SelectedIndex + 1);
|
||||
}
|
||||
|
||||
public void SelectPrevResult()
|
||||
{
|
||||
SelectedIndex = NewIndex(SelectedIndex - 1);
|
||||
}
|
||||
|
||||
public void SelectNextPage()
|
||||
{
|
||||
SelectedIndex = NewIndex(SelectedIndex + _settings.MaxResultsToShow);
|
||||
}
|
||||
|
||||
public void SelectPrevPage()
|
||||
{
|
||||
SelectedIndex = NewIndex(SelectedIndex - _settings.MaxResultsToShow);
|
||||
}
|
||||
|
||||
public void SelectFirstResult()
|
||||
{
|
||||
SelectedIndex = NewIndex(0);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
Results.Clear();
|
||||
}
|
||||
|
||||
public void RemoveResultsExcept(PluginMetadata metadata)
|
||||
{
|
||||
Results.RemoveAll(r => r.Result.PluginID != metadata.ID);
|
||||
}
|
||||
|
||||
public void RemoveResultsFor(PluginMetadata metadata)
|
||||
{
|
||||
Results.RemoveAll(r => r.Result.PluginID == metadata.ID);
|
||||
}
|
||||
|
||||
public void SelectNextTabItem()
|
||||
{
|
||||
//Do nothing if there is no selected item or we've selected the next context button
|
||||
if(!SelectedItem?.SelectNextContextButton() ?? true)
|
||||
{
|
||||
SelectNextResult();
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectPrevTabItem()
|
||||
{
|
||||
//Do nothing if there is no selected item or we've selected the previous context button
|
||||
if (!SelectedItem?.SelectPrevContextButton() ?? true)
|
||||
{
|
||||
//Tabbing backwards should highlight the last item of the previous row
|
||||
SelectPrevResult();
|
||||
SelectedItem.SelectLastContextButton();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// To avoid deadlock, this method should not called from main thread
|
||||
/// </summary>
|
||||
public void AddResults(List<Result> newRawResults, string resultId)
|
||||
{
|
||||
lock (_addResultsLock)
|
||||
{
|
||||
var newResults = NewResults(newRawResults, resultId);
|
||||
|
||||
// update UI in one run, so it can avoid UI flickering
|
||||
Results.Update(newResults);
|
||||
|
||||
if (Results.Count > 0)
|
||||
{
|
||||
Margin = new Thickness { Top = 8 };
|
||||
SelectedIndex = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
Margin = new Thickness { Top = 0 };
|
||||
Visibility = Visibility.Collapsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<ResultViewModel> NewResults(List<Result> newRawResults, string resultId)
|
||||
{
|
||||
var results = Results.ToList();
|
||||
var newResults = newRawResults.Select(r => new ResultViewModel(r)).ToList();
|
||||
var oldResults = results.Where(r => r.Result.PluginID == resultId).ToList();
|
||||
|
||||
// Find the same results in A (old results) and B (new newResults)
|
||||
var sameResults = oldResults
|
||||
.Where(t1 => newResults.Any(x => x.Result.Equals(t1.Result)))
|
||||
.ToList();
|
||||
|
||||
// remove result of relative complement of B in A
|
||||
foreach (var result in oldResults.Except(sameResults))
|
||||
{
|
||||
results.Remove(result);
|
||||
}
|
||||
|
||||
// update result with B's score and index position
|
||||
foreach (var sameResult in sameResults)
|
||||
{
|
||||
int oldIndex = results.IndexOf(sameResult);
|
||||
int oldScore = results[oldIndex].Result.Score;
|
||||
var newResult = newResults[newResults.IndexOf(sameResult)];
|
||||
int newScore = newResult.Result.Score;
|
||||
if (newScore != oldScore)
|
||||
{
|
||||
var oldResult = results[oldIndex];
|
||||
|
||||
oldResult.Result.Score = newScore;
|
||||
oldResult.Result.OriginQuery = newResult.Result.OriginQuery;
|
||||
|
||||
results.RemoveAt(oldIndex);
|
||||
int newIndex = InsertIndexOf(newScore, results);
|
||||
results.Insert(newIndex, oldResult);
|
||||
}
|
||||
}
|
||||
|
||||
// insert result in relative complement of A in B
|
||||
foreach (var result in newResults.Except(sameResults))
|
||||
{
|
||||
int newIndex = InsertIndexOf(result.Result.Score, results);
|
||||
results.Insert(newIndex, result);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region FormattedText Dependency Property
|
||||
public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached(
|
||||
"FormattedText",
|
||||
typeof(Inline),
|
||||
typeof(ResultsViewModel),
|
||||
new PropertyMetadata(null, FormattedTextPropertyChanged));
|
||||
|
||||
public static void SetFormattedText(DependencyObject textBlock, IList<int> value)
|
||||
{
|
||||
if (textBlock != null)
|
||||
{
|
||||
textBlock.SetValue(FormattedTextProperty, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static Inline GetFormattedText(DependencyObject textBlock)
|
||||
{
|
||||
return (Inline)textBlock?.GetValue(FormattedTextProperty);
|
||||
}
|
||||
|
||||
private static void FormattedTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var textBlock = d as TextBlock;
|
||||
if (textBlock == null) return;
|
||||
|
||||
var inline = (Inline)e.NewValue;
|
||||
|
||||
textBlock.Inlines.Clear();
|
||||
if (inline == null) return;
|
||||
|
||||
textBlock.Inlines.Add(inline);
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Globalization;
|
||||
using Wox.Core.Resource;
|
||||
using Wox.Infrastructure.Storage;
|
||||
using Wox.Infrastructure.UserSettings;
|
||||
using Wox.Plugin;
|
||||
|
||||
namespace PowerLauncher.ViewModel
|
||||
{
|
||||
public class SettingWindowViewModel : BaseModel
|
||||
{
|
||||
private readonly WoxJsonStorage<Settings> _storage;
|
||||
|
||||
public SettingWindowViewModel()
|
||||
{
|
||||
_storage = new WoxJsonStorage<Settings>();
|
||||
Settings = _storage.Load();
|
||||
Settings.PropertyChanged += (s, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(Settings.ActivateTimes))
|
||||
{
|
||||
OnPropertyChanged(nameof(ActivatedTimes));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Settings Settings { get; set; }
|
||||
|
||||
public void Save()
|
||||
{
|
||||
_storage.Save();
|
||||
}
|
||||
|
||||
#region general
|
||||
|
||||
private static Internationalization _translater => InternationalizationManager.Instance;
|
||||
|
||||
#endregion
|
||||
|
||||
#region about
|
||||
|
||||
public string ActivatedTimes => string.Format(CultureInfo.InvariantCulture, _translater.GetTranslation("about_activate_times"), Settings.ActivateTimes);
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user