mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-01-08 21:36:54 +01:00
Compare commits
41 Commits
leilzh/azt
...
dev/FHL/ch
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b32c75e1d0 | ||
|
|
0ebfbca2a7 | ||
|
|
79403667ef | ||
|
|
7850f5eb79 | ||
|
|
959a54bcd9 | ||
|
|
491d51afaf | ||
|
|
f263042aeb | ||
|
|
c09a5337c4 | ||
|
|
9a658eb884 | ||
|
|
4eb11d6f9b | ||
|
|
a5a354a70f | ||
|
|
744316c400 | ||
|
|
f2370912f3 | ||
|
|
5cc30df4db | ||
|
|
f81f65db3d | ||
|
|
9f008a65d6 | ||
|
|
c656dcc9c5 | ||
|
|
83cea39b66 | ||
|
|
3970e89ee7 | ||
|
|
74214f611e | ||
|
|
908a690316 | ||
|
|
6515374ce9 | ||
|
|
273a45ff1f | ||
|
|
17f3c12a11 | ||
|
|
fa4471a9e6 | ||
|
|
727de3e1fc | ||
|
|
c6f9701818 | ||
|
|
9453e38881 | ||
|
|
a1a02889d5 | ||
|
|
0592e74d3d | ||
|
|
9d148d0a3a | ||
|
|
0a51687b65 | ||
|
|
771fcaba96 | ||
|
|
82e386f63c | ||
|
|
91b53cdc13 | ||
|
|
5c2c74a6c9 | ||
|
|
cb5baad677 | ||
|
|
ec136d7bb7 | ||
|
|
e33efb7f10 | ||
|
|
68afc6623f | ||
|
|
5008d77105 |
6
.github/actions/spell-check/allow/code.txt
vendored
6
.github/actions/spell-check/allow/code.txt
vendored
@@ -263,6 +263,10 @@ onefuzz
|
||||
|
||||
# NameInCode
|
||||
leilzh
|
||||
mengyuanchen
|
||||
|
||||
# DllName
|
||||
testhost
|
||||
|
||||
#Tools
|
||||
OIP
|
||||
OIP
|
||||
|
||||
3
.github/actions/spell-check/expect.txt
vendored
3
.github/actions/spell-check/expect.txt
vendored
@@ -734,6 +734,7 @@ KEYBDINPUT
|
||||
keyboardeventhandlers
|
||||
keyboardmanagercommon
|
||||
KEYBOARDMANAGEREDITOR
|
||||
KEYBOARDMANAGEREDITORLIBRARYWRAPPER
|
||||
keyboardmanagerstate
|
||||
keyboardmanagerui
|
||||
KEYEVENTF
|
||||
@@ -1282,7 +1283,7 @@ rectp
|
||||
RECTSOURCE
|
||||
recyclebin
|
||||
Redist
|
||||
reencode
|
||||
Reencode
|
||||
reencoded
|
||||
REFCLSID
|
||||
REFGUID
|
||||
|
||||
@@ -128,6 +128,7 @@
|
||||
"PowerToys.KeyboardManager.dll",
|
||||
"KeyboardManagerEditor\\PowerToys.KeyboardManagerEditor.exe",
|
||||
"KeyboardManagerEngine\\PowerToys.KeyboardManagerEngine.exe",
|
||||
"PowerToys.KeyboardManagerEditorLibraryWrapper.dll",
|
||||
|
||||
"PowerToys.Launcher.dll",
|
||||
"PowerToys.PowerLauncher.dll",
|
||||
|
||||
@@ -456,12 +456,6 @@ jobs:
|
||||
Copy-Item src\gpo\assets\* "$(JobOutputDirectory)/gpo" -Recurse
|
||||
displayName: Stage GPO files
|
||||
|
||||
- ${{ if eq(parameters.publishArtifacts, true) }}:
|
||||
- publish: $(JobOutputDirectory)
|
||||
artifact: $(JobOutputArtifactName)
|
||||
displayName: Publish all outputs
|
||||
condition: always()
|
||||
|
||||
# Running the tests may result in future jobs consuming artifacts out of this build
|
||||
- ${{ if eq(parameters.runTests, true) }}:
|
||||
- task: CopyFiles@2
|
||||
@@ -471,17 +465,8 @@ jobs:
|
||||
contents: '$(BuildPlatform)/$(BuildConfiguration)/**/*'
|
||||
targetFolder: '$(JobOutputDirectory)\$(BuildPlatform)\$(BuildConfiguration)'
|
||||
|
||||
- task: CopyFiles@2
|
||||
displayName: Stage entire build output
|
||||
inputs:
|
||||
sourceFolder: $(JobOutputDirectory)
|
||||
contents: |-
|
||||
**
|
||||
!**\*.pdb
|
||||
!**\*.lib
|
||||
targetFolder: '$(JobOutputDirectory)\TestArtifacts'
|
||||
|
||||
- publish: $(JobOutputDirectory)\TestArtifacts
|
||||
artifact: $(JobOutputArtifactName)-TestArtifacts
|
||||
displayName: Publish all outputs for testing
|
||||
- ${{ if eq(parameters.publishArtifacts, true) }}:
|
||||
- publish: $(JobOutputDirectory)
|
||||
artifact: $(JobOutputArtifactName)
|
||||
displayName: Publish all outputs
|
||||
condition: always()
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
BuildPlatform: ${{ parameters.platform }}
|
||||
BuildConfiguration: ${{ parameters.configuration }}
|
||||
SrcPath: $(Build.Repository.LocalPath)
|
||||
TestArtifactsName: build-${{ parameters.platform }}-${{ parameters.configuration }}${{ parameters.inputArtifactStem }}-TestArtifacts
|
||||
TestArtifactsName: build-${{ parameters.platform }}-${{ parameters.configuration }}${{ parameters.inputArtifactStem }}
|
||||
pool:
|
||||
${{ if eq(variables['System.CollectionId'], 'cb55739e-4afe-46a3-970f-1b49d8ee7564') }}:
|
||||
${{ if ne(parameters.platform, 'ARM64') }}:
|
||||
@@ -61,13 +61,9 @@ jobs:
|
||||
reg add "HKLM\Software\Policies\Microsoft\Edge\WebView2\ReleaseChannels" /v PowerToys.exe /t REG_SZ /d "3"
|
||||
displayName: "Enable WebView2 Canary Channel"
|
||||
|
||||
- download: current
|
||||
displayName: Download artifacts
|
||||
artifact: $(TestArtifactsName)
|
||||
patterns: |-
|
||||
**
|
||||
!**\*.pdb
|
||||
!**\*.lib
|
||||
- template: steps-download-artifacts-with-azure-cli.yml
|
||||
parameters:
|
||||
artifactName: $(TestArtifactsName)
|
||||
|
||||
- template: steps-ensure-dotnet-version.yml
|
||||
parameters:
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
parameters:
|
||||
- name: artifactName
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
# Why use az cli to download? → The ARM agent may run into OutOfMemory issues.
|
||||
# Why use the Azure CLI ZIP version? → It comes with its own Python and works fine under emulation on ARM64.
|
||||
# Why not use AzureCLI@2 task? → It requires azureSubscription, which is unnecessary for downloading artifacts.
|
||||
|
||||
steps:
|
||||
- powershell: |
|
||||
Write-Host "Downloading Azure CLI ZIP..."
|
||||
$azCliUrl = "https://aka.ms/installazurecliwindowszipx64"
|
||||
$azCliZip = "$(Build.ArtifactStagingDirectory)\azure-cli.zip"
|
||||
|
||||
Invoke-WebRequest -Uri $azCliUrl -OutFile $azCliZip
|
||||
displayName: 'Install Azure CLI from ZIP'
|
||||
|
||||
- task: ExtractFiles@1
|
||||
inputs:
|
||||
archiveFilePatterns: '$(Build.ArtifactStagingDirectory)\azure-cli.zip'
|
||||
destinationFolder: '$(Build.ArtifactStagingDirectory)\AzureCLI'
|
||||
|
||||
- pwsh: |
|
||||
$azureCliPath = "$(Build.ArtifactStagingDirectory)\AzureCLI\bin"
|
||||
$env:Path = "$azureCliPath;" + $env:Path
|
||||
Write-Host "Configuring Azure DevOps defaults..."
|
||||
az devops configure --defaults organization='$(System.TeamFoundationCollectionUri)' project='$(System.TeamProject)' --use-git-aliases true
|
||||
Write-Host "Downloading artifacts..."
|
||||
az pipelines runs artifact download --artifact-name ${{parameters.artifactName}} --path "$(Pipeline.Workspace)/${{parameters.artifactName}}" --run-id $(Build.BuildId) --debug
|
||||
displayName: 'Download artifacts with Azure CLI'
|
||||
env:
|
||||
AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
|
||||
@@ -15,8 +15,8 @@ Param(
|
||||
$referencedFileVersionsPerDll = @{}
|
||||
$totalFailures = 0
|
||||
|
||||
Get-ChildItem $targetDir -Recurse -Filter *.deps.json -Exclude UITests-FancyZones*,MouseJump.Common.UnitTests*,AdvancedPaste.FuzzTests* | ForEach-Object {
|
||||
# Temporarily exclude FancyZones UI tests because of Appium.WebDriver dependencies
|
||||
Get-ChildItem $targetDir -Recurse -Filter *.deps.json -Exclude *UITest*,MouseJump.Common.UnitTests*,*.FuzzTests* | ForEach-Object {
|
||||
# Temporarily exclude All UI-Test, Fuzzer-Test projects because of Appium.WebDriver dependencies
|
||||
$depsJsonFullFileName = $_.FullName
|
||||
$depsJsonFileName = $_.Name
|
||||
$depsJson = Get-Content $depsJsonFullFileName | ConvertFrom-Json
|
||||
|
||||
@@ -1322,6 +1322,7 @@ EXHIBIT A -Mozilla Public License.
|
||||
- Microsoft.CodeAnalysis.NetAnalyzers 9.0.0
|
||||
- Microsoft.Data.Sqlite 9.0.2
|
||||
- Microsoft.Diagnostics.Tracing.TraceEvent 3.1.16
|
||||
- Microsoft.DotNet.ILCompiler (A)
|
||||
- Microsoft.Extensions.DependencyInjection 9.0.2
|
||||
- Microsoft.Extensions.Hosting 9.0.2
|
||||
- Microsoft.Extensions.Hosting.WindowsServices 9.0.2
|
||||
|
||||
659
PowerToys.sln
659
PowerToys.sln
File diff suppressed because it is too large
Load Diff
91
doc/devdocs/UITests.md
Normal file
91
doc/devdocs/UITests.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# UI tests framework
|
||||
|
||||
A specialized UI test framework for PowerToys that makes it easy to write UI tests for PowerToys modules or settings. Let's start writing UI tests!
|
||||
|
||||
## Before running tests
|
||||
|
||||
- Install Windows Application Driver v1.2.1 from https://github.com/microsoft/WinAppDriver/releases/tag/v1.2.1 to the default directory (`C:\Program Files (x86)\Windows Application Driver`)
|
||||
|
||||
- Enable Developer Mode in Windows settings
|
||||
|
||||
## Running tests
|
||||
|
||||
- Exit PowerToys if it's running.
|
||||
|
||||
- Open `PowerToys.sln` in Visual Studio and build the solution.
|
||||
|
||||
- Run tests in the Test Explorer (`Test > Test Explorer` or `Ctrl+E, T`).
|
||||
|
||||
|
||||
## How to add the first UI tests for your modules
|
||||
|
||||
- Create a new project and add the following references to the project file. Change the OutputPath to your own module's path.
|
||||
```
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<!-- This is a UI test, so don't run as part of MSBuild -->
|
||||
<RunVSTest>false</RunVSTest>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputPath>..\..\..\..\$(Platform)\$(Configuration)\tests\KeyboardManagerUITests\</OutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest" />
|
||||
<ProjectReference Include="..\..\..\common\UITestAutomation\UITestAutomation.csproj" />
|
||||
<Folder Include="Properties\" />
|
||||
</ItemGroup>
|
||||
```
|
||||
- Inherit your test class from UITestBase.
|
||||
>Set Scope: The default scope starts from the PowerToys settings UI. If you want to start from your own module, set the constructor as shown below:
|
||||
|
||||
>Specify Scope:
|
||||
```
|
||||
[TestClass]
|
||||
public class RunFancyZonesTest : UITestBase
|
||||
{
|
||||
public RunFancyZonesTest()
|
||||
: base(PowerToysModule.FancyZone)
|
||||
{
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Then you can start using session to perform the UI operations.
|
||||
|
||||
**Example**
|
||||
```
|
||||
using Microsoft.PowerToys.UITest;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace UITests_KeyboardManager
|
||||
{
|
||||
[TestClass]
|
||||
public class RunKeyboardManagerUITests : UITestBase
|
||||
{
|
||||
[TestMethod]
|
||||
public void OpenKeyboardManagerEditor()
|
||||
{
|
||||
// Open KeyboardManagerEditor
|
||||
this.Session.Find<Button>(By.Name("Remap a key")).Click();
|
||||
this.Session.Attach("Remap keys");
|
||||
|
||||
// Maximize window
|
||||
var window = Session.Find<Window>(By.Name("Remap keys")).Maximize();
|
||||
|
||||
// Add Key Remapping
|
||||
this.Session.Find<Button>(By.Name("Add key remapping")).Click();
|
||||
window.Close();
|
||||
|
||||
// Back to Settings
|
||||
this.Session.Attach(PowerToysModule.PowerToysSettings);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Extra tools and information
|
||||
|
||||
**Accessibility Tools**:
|
||||
While working on tests, you may need a tool that helps you to view the element's accessibility data, e.g. for finding the button to click. For this purpose, you could use [AccessibilityInsights](https://accessibilityinsights.io/docs/windows/overview)
|
||||
@@ -3,8 +3,9 @@
|
||||
- [ ] The plugin is a project under `modules\launcher\Plugins`
|
||||
- [ ] Microsoft plugin project name pattern: `Microsoft.PowerToys.Run.Plugin.{PluginName}`
|
||||
- [ ] Community plugin project name pattern: `Community.PowerToys.Run.Plugin.{PluginName}`
|
||||
- [ ] The plugin target framework should be `net8.0-windows`
|
||||
- [ ] The plugin target framework should be `net9.0-windows10.0.22621.0`
|
||||
- [ ] If the plugin uses any 3rd party dependencies the project file should import `DynamicPlugin.props`
|
||||
- [ ] 3rd party dependencies must be compatible with .NET 9
|
||||
- [ ] The plugin has to contain a `plugin.json` file of the following format in its root folder:
|
||||
|
||||
```json
|
||||
@@ -35,7 +36,6 @@ public static string PluginID => "xxxxxxx"; // The part xxxxxxx stands for the p
|
||||
- [ ] Plugin's output code and assets have to be included in the installer [`Product.wxs`](/installer/PowerToysSetup/Product.wxs)
|
||||
- [ ] Test the plugin with a local build. Build the installer, install, check that the plugin works as expected
|
||||
- [ ] All plugin's binaries have to be included in the signed build [`pipeline.user.windows.yml`](/.pipelines/pipeline.user.windows.yml)
|
||||
- [ ] The plugin target framework has to be net8.0-windows. All dependencies should be compatible with .NET 8.
|
||||
|
||||
Some localization steps can only be done after the first pass by the localization team to provide the localized resources.
|
||||
In the PR that adds a new plugin, reference a new issue to track the work for fully enabling localization for the new plugin.
|
||||
|
||||
@@ -4,18 +4,10 @@ Contains the executable starting point, initialization code and the list of know
|
||||
#### [`powertoy_module.h`](/src/runner/powertoy_module.h) and [`powertoy_module.cpp`](/src/runner/powertoy_module.cpp)
|
||||
Contains code for initializing and managing the PowerToy modules. `PowertoyModule` is a RAII-style holder for the `PowertoyModuleIface` pointer, which we got by [invoking module DLL's `powertoy_create` function](https://github.com/microsoft/PowerToys/blob/1760af50c8803588cb575167baae0439af38a9c1/src/runner/powertoy_module.cpp#L13-L24).
|
||||
|
||||
#### [`powertoys_events.cpp`](/src/runner/powertoys_events.cpp)
|
||||
Contains code that handles the various events listeners, and forwards those events to the PowerToys modules. You can learn more about the current event architecture in [shared hooks](/doc/devdocs/shared-hooks.md).
|
||||
|
||||
#### [`lowlevel_keyboard_event.cpp`](/src/runner/lowlevel_keyboard_event.cpp)
|
||||
Contains code for registering the low level keyboard event hook that listens for keyboard events. Please note that `signal_event` is called from the main thread for this event.
|
||||
|
||||
#### [`win_hook_event.cpp`](/src/runner/win_hook_event.cpp)
|
||||
Contains code for registering a Windows event hook through `SetWinEventHook`, that listens for various events raised when a window is interacted with. Please note, that `signal_event` is called from a separate `dispatch_thread_proc` worker thread, so you must provide thread-safety for your `signal_event` if you intend to receive it. This is a subject to change.
|
||||
|
||||
#### [`tray_icon.cpp`](/src/runner/tray_icon.cpp)
|
||||
Contains code for managing the PowerToys tray icon and its menu commands. Note that `dispatch_run_on_main_ui_thread` is used to
|
||||
transfer received json message from the [Settings window](/doc/devdocs/settings.md) to the main thread, since we're communicating with it from [a dedicated thread](https://github.com/microsoft/PowerToys/blob/7357e40d3f54de51176efe54fda6d57028837b8c/src/runner/settings_window.cpp#L267-L271).
|
||||
|
||||
#### [`settings_window.cpp`](/src/runner/settings_window.cpp)
|
||||
Contains code for starting the PowerToys settings window and communicating with it. Settings window is a separate process, so we're using [Windows pipes](https://learn.microsoft.com/windows/win32/ipc/pipes) as a transport for json messages.
|
||||
|
||||
@@ -33,3 +25,24 @@ Contains code for telemetry.
|
||||
|
||||
#### [`svgs`](/src/runner/svgs/)
|
||||
Contains the SVG assets used by the PowerToys modules.
|
||||
|
||||
#### [`bug_report.cpp`](/src/runner/bug_report.cpp)
|
||||
Contains logic to start bug report tool.
|
||||
|
||||
#### [`centralized_hotkeys.cpp`](/src/runner/centralized_hotkeys.cpp)
|
||||
Contains hot key logic registration and un-registration.
|
||||
|
||||
#### [`centralized_kb_hook.cpp`](/src/runner/centralized_kb_hook.cpp)
|
||||
Contains logic to handle PowerToys' keyboard shortcut functionality.
|
||||
|
||||
#### [`restart_elevated.cpp`](/src/runner/restart_elevated.cpp)
|
||||
Contains logic for restarting the current process with different elevation levels.
|
||||
|
||||
#### [`RestartManagement.cpp`](/src/runner/RestartManagement.cpp)
|
||||
Contains code for restarting a process.
|
||||
|
||||
#### [`settings_telemetry.cpp`](/src/runner/settings_telemetry.cpp)
|
||||
Contains logic that periodically triggers module-specific setting's telemetry delivery and manages timing and error handling for the process.
|
||||
|
||||
#### [`UpdateUtils.cpp`](/src/runner/UpdateUtils.cpp)
|
||||
Contains code to handle the automatic update checking, notification, and installation process for PowerToys.
|
||||
@@ -1,6 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Look at Directory.Build.props in root for common stuff as well -->
|
||||
<Import Project="..\..\Common.Dotnet.CsWinRT.props" />
|
||||
<Import Project="..\..\Common.Dotnet.AotCompatibility.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<UseWPF>true</UseWPF>
|
||||
|
||||
@@ -91,20 +91,20 @@ namespace Common.UI
|
||||
{
|
||||
try
|
||||
{
|
||||
var assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
|
||||
var fullPath = new DirectoryInfo(assemblyPath).FullName;
|
||||
var directoryPath = System.AppContext.BaseDirectory;
|
||||
if (mainExecutableIsOnTheParentFolder)
|
||||
{
|
||||
// Need to go into parent folder for PowerToys.exe. Likely a WinUI3 App SDK application.
|
||||
fullPath = fullPath + "\\..\\PowerToys.exe";
|
||||
directoryPath = Path.Combine(directoryPath, "..");
|
||||
directoryPath = Path.Combine(directoryPath, "PowerToys.exe");
|
||||
}
|
||||
else
|
||||
{
|
||||
// PowerToys.exe is in the same path as the application.
|
||||
fullPath = fullPath + "\\PowerToys.exe";
|
||||
directoryPath = Path.Combine(directoryPath, "PowerToys.exe");
|
||||
}
|
||||
|
||||
Process.Start(new ProcessStartInfo(fullPath) { Arguments = "--open-settings=" + SettingsWindowNameToString(window) });
|
||||
Process.Start(new ProcessStartInfo(directoryPath) { Arguments = "--open-settings=" + SettingsWindowNameToString(window) });
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -11,7 +11,7 @@ using Microsoft.Win32;
|
||||
|
||||
namespace Common.UI
|
||||
{
|
||||
public class ThemeManager : IDisposable
|
||||
public partial class ThemeManager : IDisposable
|
||||
{
|
||||
private readonly Application _app;
|
||||
private const string LightTheme = "Light.Accent1";
|
||||
|
||||
@@ -184,6 +184,10 @@ namespace winrt::PowerToys::GPOWrapper::implementation
|
||||
{
|
||||
return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredWorkspacesEnabledValue());
|
||||
}
|
||||
GpoRuleConfigured GPOWrapper::GetConfiguredCharacterMapEnabledValue()
|
||||
{
|
||||
return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredCharacterMapEnabledValue());
|
||||
}
|
||||
GpoRuleConfigured GPOWrapper::GetConfiguredMwbClipboardSharingEnabledValue()
|
||||
{
|
||||
return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredMwbClipboardSharingEnabledValue());
|
||||
|
||||
@@ -52,6 +52,7 @@ namespace winrt::PowerToys::GPOWrapper::implementation
|
||||
static GpoRuleConfigured GetAllowedAdvancedPasteOnlineAIModelsValue();
|
||||
static GpoRuleConfigured GetConfiguredNewPlusEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredWorkspacesEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredCharacterMapEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredMwbClipboardSharingEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredMwbFileTransferEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredMwbUseOriginalUserInterfaceValue();
|
||||
|
||||
@@ -56,6 +56,7 @@ namespace PowerToys
|
||||
static GpoRuleConfigured GetAllowedAdvancedPasteOnlineAIModelsValue();
|
||||
static GpoRuleConfigured GetConfiguredNewPlusEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredWorkspacesEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredCharacterMapEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredMwbClipboardSharingEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredMwbFileTransferEnabledValue();
|
||||
static GpoRuleConfigured GetConfiguredMwbUseOriginalUserInterfaceValue();
|
||||
|
||||
@@ -6,6 +6,7 @@ using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using ManagedCommon.Serialization;
|
||||
|
||||
namespace ManagedCommon
|
||||
{
|
||||
@@ -35,7 +36,7 @@ namespace ManagedCommon
|
||||
inputStream.Close();
|
||||
reader.Dispose();
|
||||
|
||||
return JsonSerializer.Deserialize<OutGoingLanguageSettings>(data).LanguageTag;
|
||||
return JsonSerializer.Deserialize<OutGoingLanguageSettings>(data, SourceGenerationContext.Default.OutGoingLanguageSettings).LanguageTag;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
@@ -15,15 +15,23 @@ namespace ManagedCommon
|
||||
{
|
||||
public static class Logger
|
||||
{
|
||||
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();
|
||||
private static readonly string Version = FileVersionInfo.GetVersionInfo(Assembly.Location).ProductVersion;
|
||||
|
||||
private static readonly string Error = "Error";
|
||||
private static readonly string Warning = "Warning";
|
||||
private static readonly string Info = "Info";
|
||||
private static readonly string Debug = "Debug";
|
||||
private static readonly string TraceFlag = "Trace";
|
||||
|
||||
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();
|
||||
|
||||
/*
|
||||
* Please pay more attention!
|
||||
* If you want to publish it with Native AOT enabled (or publish as a single file).
|
||||
* You need to find another way to remove Assembly.Location usage.
|
||||
*/
|
||||
#pragma warning disable IL3000 // Avoid accessing Assembly file path when publishing as a single file
|
||||
private static readonly string Version = FileVersionInfo.GetVersionInfo(Assembly.Location).ProductVersion;
|
||||
#pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the logger and sets the path for logging.
|
||||
/// </summary>
|
||||
@@ -53,18 +61,16 @@ namespace ManagedCommon
|
||||
Trace.AutoFlush = true;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static void LogError(string message)
|
||||
public static void LogError(string message, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
|
||||
{
|
||||
Log(message, Error);
|
||||
Log(message, Error, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static void LogError(string message, Exception ex)
|
||||
public static void LogError(string message, Exception ex, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
|
||||
{
|
||||
if (ex == null)
|
||||
{
|
||||
Log(message, Error);
|
||||
Log(message, Error, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -83,38 +89,33 @@ namespace ManagedCommon
|
||||
"Stack trace: " + Environment.NewLine +
|
||||
ex.StackTrace;
|
||||
|
||||
Log(exMessage, Error);
|
||||
Log(exMessage, Error, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static void LogWarning(string message)
|
||||
public static void LogWarning(string message, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
|
||||
{
|
||||
Log(message, Warning);
|
||||
Log(message, Warning, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static void LogInfo(string message)
|
||||
public static void LogInfo(string message, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
|
||||
{
|
||||
Log(message, Info);
|
||||
Log(message, Info, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static void LogDebug(string message)
|
||||
public static void LogDebug(string message, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
|
||||
{
|
||||
Log(message, Debug);
|
||||
Log(message, Debug, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static void LogTrace()
|
||||
public static void LogTrace([System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
|
||||
{
|
||||
Log(string.Empty, TraceFlag);
|
||||
Log(string.Empty, TraceFlag, memberName, sourceFilePath, sourceLineNumber);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static void Log(string message, string type)
|
||||
private static void Log(string message, string type, string memberName, string sourceFilePath, int sourceLineNumber)
|
||||
{
|
||||
Trace.WriteLine("[" + DateTime.Now.TimeOfDay + "] [" + type + "] " + GetCallerInfo());
|
||||
Trace.WriteLine("[" + DateTime.Now.TimeOfDay + "] [" + type + "] " + GetCallerInfo(memberName, sourceFilePath, sourceLineNumber));
|
||||
Trace.Indent();
|
||||
if (message != string.Empty)
|
||||
{
|
||||
@@ -124,49 +125,27 @@ namespace ManagedCommon
|
||||
Trace.Unindent();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static string GetCallerInfo()
|
||||
private static string GetCallerInfo(string memberName, string sourceFilePath, int sourceLineNumber)
|
||||
{
|
||||
StackTrace stackTrace = new();
|
||||
|
||||
var callerMethod = GetCallerMethod(stackTrace);
|
||||
|
||||
return $"{callerMethod?.DeclaringType?.Name}::{callerMethod.Name}";
|
||||
}
|
||||
|
||||
private static MethodBase GetCallerMethod(StackTrace stackTrace)
|
||||
{
|
||||
const int topFrame = 3;
|
||||
|
||||
var topMethod = stackTrace.GetFrame(topFrame)?.GetMethod();
|
||||
string callerFileName = "Unknown";
|
||||
|
||||
try
|
||||
{
|
||||
if (topMethod?.Name == nameof(IAsyncStateMachine.MoveNext) && typeof(IAsyncStateMachine).IsAssignableFrom(topMethod?.DeclaringType))
|
||||
string fileName = Path.GetFileName(sourceFilePath);
|
||||
if (!string.IsNullOrEmpty(fileName))
|
||||
{
|
||||
// Async method; return actual method as determined by heuristic:
|
||||
// "Nearest method on stack to async state-machine's MoveNext() in same namespace but in a different type".
|
||||
// There are tighter ways of determining the actual method, but this is good enough and probably faster.
|
||||
for (int deepFrame = topFrame + 1; deepFrame < stackTrace.FrameCount; deepFrame++)
|
||||
{
|
||||
var deepMethod = stackTrace.GetFrame(deepFrame)?.GetMethod();
|
||||
|
||||
if (deepMethod?.DeclaringType != topMethod?.DeclaringType && deepMethod?.DeclaringType?.Namespace == topMethod?.DeclaringType?.Namespace)
|
||||
{
|
||||
return deepMethod;
|
||||
}
|
||||
}
|
||||
callerFileName = fileName;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Ignore exceptions in Release. The code above won't throw, but if it does, we don't want to crash the app.
|
||||
callerFileName = "Unknown";
|
||||
#if DEBUG
|
||||
throw;
|
||||
#endif
|
||||
}
|
||||
|
||||
return topMethod;
|
||||
return $"{callerFileName}::{memberName}::{sourceLineNumber}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Look at Directory.Build.props in root for common stuff as well -->
|
||||
<Import Project="..\..\Common.Dotnet.CsWinRT.props" />
|
||||
<Import Project="..\..\Common.Dotnet.AotCompatibility.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<Description>PowerToys ManagedCommon</Description>
|
||||
|
||||
@@ -53,7 +53,7 @@ namespace ManagedCommon
|
||||
|
||||
internal static int Size
|
||||
{
|
||||
get { return Marshal.SizeOf(typeof(INPUT)); }
|
||||
get { return Marshal.SizeOf<INPUT>(); }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,12 +14,11 @@ namespace ManagedCommon
|
||||
{
|
||||
public static class RunnerHelper
|
||||
{
|
||||
public static void WaitForPowerToysRunner(int powerToysPID, Action act)
|
||||
public static void WaitForPowerToysRunner(int powerToysPID, Action act, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
|
||||
{
|
||||
var stackTrace = new StackTrace();
|
||||
var assembly = Assembly.GetCallingAssembly().GetName();
|
||||
var callingMethod = stackTrace.GetFrame(1).GetMethod().Name;
|
||||
PowerToysTelemetry.Log.WriteEvent(new DebugEvent() { Message = $"[{assembly}][{callingMethod}]WaitForPowerToysRunner waiting for Event powerToysPID={powerToysPID}" });
|
||||
PowerToysTelemetry.Log.WriteEvent(new DebugEvent() { Message = $"[{assembly}][{memberName}]WaitForPowerToysRunner waiting for Event powerToysPID={powerToysPID}" });
|
||||
Task.Run(() =>
|
||||
{
|
||||
const uint INFINITE = 0xFFFFFFFF;
|
||||
@@ -29,7 +28,7 @@ namespace ManagedCommon
|
||||
IntPtr powerToysProcHandle = NativeMethods.OpenProcess(SYNCHRONIZE, false, powerToysPID);
|
||||
if (NativeMethods.WaitForSingleObject(powerToysProcHandle, INFINITE) == WAIT_OBJECT_0)
|
||||
{
|
||||
PowerToysTelemetry.Log.WriteEvent(new DebugEvent() { Message = $"[{assembly}][{callingMethod}]WaitForPowerToysRunner Event Notified powerToysPID={powerToysPID}" });
|
||||
PowerToysTelemetry.Log.WriteEvent(new DebugEvent() { Message = $"[{assembly}][{memberName}]WaitForPowerToysRunner Event Notified powerToysPID={powerToysPID}" });
|
||||
act.Invoke();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
using static ManagedCommon.LanguageHelper;
|
||||
|
||||
namespace ManagedCommon.Serialization;
|
||||
|
||||
[JsonSerializable(typeof(OutGoingLanguageSettings))]
|
||||
internal sealed partial class SourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace ManagedCommon
|
||||
/// <param name="sender">Sender ThemeListener</param>
|
||||
public delegate void ThemeChangedEvent(ThemeListener sender);
|
||||
|
||||
public class ThemeListener : IDisposable
|
||||
public partial class ThemeListener : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the App Theme.
|
||||
|
||||
13
src/common/UITestAutomation/Element/Button.cs
Normal file
13
src/common/UITestAutomation/Element/Button.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a button in the UI test environment.
|
||||
/// </summary>
|
||||
public class Button : Element
|
||||
{
|
||||
}
|
||||
}
|
||||
75
src/common/UITestAutomation/Element/By.cs
Normal file
75
src/common/UITestAutomation/Element/By.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using static OpenQA.Selenium.By;
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// This class represents a By selector.
|
||||
/// </summary>
|
||||
public class By
|
||||
{
|
||||
private readonly OpenQA.Selenium.By by;
|
||||
|
||||
private By(OpenQA.Selenium.By by)
|
||||
{
|
||||
this.by = by;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
// override ToString to return detailed debugging content provided by OpenQA.Selenium.By
|
||||
return this.by.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a By object using the name attribute.
|
||||
/// </summary>
|
||||
/// <param name="name">The name attribute to search for.</param>
|
||||
/// <returns>A By object.</returns>
|
||||
public static By Name(string name) => new By(OpenQA.Selenium.By.Name(name));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a By object using the ID attribute.
|
||||
/// </summary>
|
||||
/// <param name="id">The ID attribute to search for.</param>
|
||||
/// <returns>A By object.</returns>
|
||||
public static By Id(string id) => new By(OpenQA.Selenium.By.Id(id));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a By object using the XPath expression.
|
||||
/// </summary>
|
||||
/// <param name="xpath">The XPath expression to search for.</param>
|
||||
/// <returns>A By object.</returns>
|
||||
public static By XPath(string xpath) => new By(OpenQA.Selenium.By.XPath(xpath));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a By object using the CSS selector.
|
||||
/// </summary>
|
||||
/// <param name="cssSelector">The CSS selector to search for.</param>
|
||||
/// <returns>A By object.</returns>
|
||||
public static By CssSelector(string cssSelector) => new By(OpenQA.Selenium.By.CssSelector(cssSelector));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a By object using the link text.
|
||||
/// </summary>
|
||||
/// <param name="linkText">The link text to search for.</param>
|
||||
/// <returns>A By object.</returns>
|
||||
public static By LinkText(string linkText) => new By(OpenQA.Selenium.By.LinkText(linkText));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a By object using the tag name.
|
||||
/// </summary>
|
||||
/// <param name="tagName">The tag name to search for.</param>
|
||||
/// <returns>A By object.</returns>
|
||||
public static By TagName(string tagName) => new By(OpenQA.Selenium.By.TagName(tagName));
|
||||
|
||||
/// <summary>
|
||||
/// Converts the By object to an OpenQA.Selenium.By object.
|
||||
/// </summary>
|
||||
/// <returns>An OpenQA.Selenium.By object.</returns>
|
||||
internal OpenQA.Selenium.By ToSeleniumBy() => by;
|
||||
}
|
||||
}
|
||||
217
src/common/UITestAutomation/Element/Element.cs
Normal file
217
src/common/UITestAutomation/Element/Element.cs
Normal file
@@ -0,0 +1,217 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenQA.Selenium.Appium;
|
||||
using OpenQA.Selenium.Appium.Windows;
|
||||
using OpenQA.Selenium.Interactions;
|
||||
|
||||
[assembly: InternalsVisibleTo("Session")]
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a basic UI element in the application.
|
||||
/// </summary>
|
||||
public class Element
|
||||
{
|
||||
private WindowsElement? windowsElement;
|
||||
|
||||
private WindowsDriver<WindowsElement>? driver;
|
||||
|
||||
internal void SetWindowsElement(WindowsElement windowsElement) => this.windowsElement = windowsElement;
|
||||
|
||||
internal void SetSession(WindowsDriver<WindowsElement> driver) => this.driver = driver;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the UI element.
|
||||
/// </summary>
|
||||
public string Name
|
||||
{
|
||||
get { return GetAttribute("Name"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the text of the UI element.
|
||||
/// </summary>
|
||||
public string Text
|
||||
{
|
||||
get { return this.windowsElement?.Text ?? string.Empty; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the UI element is Enabled or not.
|
||||
/// </summary>
|
||||
public bool Enabled
|
||||
{
|
||||
get { return this.windowsElement?.Enabled ?? false; }
|
||||
}
|
||||
|
||||
public bool Selected
|
||||
{
|
||||
get { return this.windowsElement?.Selected ?? false; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the AutomationID of the UI element.
|
||||
/// </summary>
|
||||
public string AutomationId
|
||||
{
|
||||
get { return GetAttribute("AutomationId"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the class name of the UI element.
|
||||
/// </summary>
|
||||
public string ClassName
|
||||
{
|
||||
get { return GetAttribute("ClassName"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the help text of the UI element.
|
||||
/// </summary>
|
||||
public string HelpText
|
||||
{
|
||||
get { return GetAttribute("HelpText"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the control type of the UI element.
|
||||
/// </summary>
|
||||
public string ControlType
|
||||
{
|
||||
get { return GetAttribute("ControlType"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Click the UI element.
|
||||
/// </summary>
|
||||
/// <param name="rightClick">If true, performs a right-click; otherwise, performs a left-click. Default value is false</param>
|
||||
public void Click(bool rightClick = false)
|
||||
{
|
||||
PerformAction((actions, windowElement) =>
|
||||
{
|
||||
actions.MoveToElement(windowElement);
|
||||
|
||||
// Move 2by2 offset to make click more stable instead of click on the border of the element
|
||||
actions.MoveByOffset(2, 2);
|
||||
|
||||
if (rightClick)
|
||||
{
|
||||
actions.ContextClick();
|
||||
}
|
||||
else
|
||||
{
|
||||
actions.Click();
|
||||
}
|
||||
|
||||
actions.Build().Perform();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Double Click the UI element.
|
||||
/// </summary>
|
||||
public void DoubleClick()
|
||||
{
|
||||
PerformAction((actions, windowElement) =>
|
||||
{
|
||||
actions.MoveToElement(windowElement);
|
||||
|
||||
// Move 2by2 offset to make click more stable instead of click on the border of the element
|
||||
actions.MoveByOffset(2, 2);
|
||||
|
||||
actions.DoubleClick();
|
||||
actions.Build().Perform();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the attribute value of the UI element.
|
||||
/// </summary>
|
||||
/// <param name="attributeName">The name of the attribute to get.</param>
|
||||
/// <returns>The value of the attribute.</returns>
|
||||
public string GetAttribute(string attributeName)
|
||||
{
|
||||
Assert.IsNotNull(this.windowsElement, $"WindowsElement is null in method GetAttribute with parameter: attributeName = {attributeName}");
|
||||
var attributeValue = this.windowsElement.GetAttribute(attributeName);
|
||||
Assert.IsNotNull(attributeValue, $"Attribute '{attributeName}' is null.");
|
||||
return attributeValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds an element by the selector.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The class type of the element to find.</typeparam>
|
||||
/// <param name="by">The selector to use for finding the element.</param>
|
||||
/// <param name="timeoutMS">The timeout in milliseconds.</param>
|
||||
/// <returns>The found element.</returns>
|
||||
public T Find<T>(By by, int timeoutMS = 3000)
|
||||
where T : Element, new()
|
||||
{
|
||||
Assert.IsNotNull(this.windowsElement, $"WindowsElement is null in method Find<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
|
||||
var foundElement = FindHelper.Find<T, AppiumWebElement>(
|
||||
() =>
|
||||
{
|
||||
var element = this.windowsElement.FindElement(by.ToSeleniumBy());
|
||||
Assert.IsNotNull(element, $"Element not found using selector: {by}");
|
||||
return element;
|
||||
},
|
||||
this.driver,
|
||||
timeoutMS);
|
||||
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds all elements by the selector.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The class type of the elements to find.</typeparam>
|
||||
/// <param name="by">The selector to use for finding the elements.</param>
|
||||
/// <param name="timeoutMS">The timeout in milliseconds.</param>
|
||||
/// <returns>A read-only collection of the found elements.</returns>
|
||||
public ReadOnlyCollection<T>? FindAll<T>(By by, int timeoutMS = 3000)
|
||||
where T : Element, new()
|
||||
{
|
||||
Assert.IsNotNull(this.windowsElement, $"WindowsElement is null in method FindAll<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
|
||||
var foundElements = FindHelper.FindAll<T, AppiumWebElement>(
|
||||
() =>
|
||||
{
|
||||
var elements = this.windowsElement.FindElements(by.ToSeleniumBy());
|
||||
Assert.IsTrue(elements.Count > 0, $"Elements not found using selector: {by}");
|
||||
return elements;
|
||||
},
|
||||
this.driver,
|
||||
timeoutMS);
|
||||
|
||||
return foundElements;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Simulates a manual operation on the element.
|
||||
/// </summary>
|
||||
/// <param name="action">The action to perform on the element.</param>
|
||||
/// <param name="msPreAction">The number of milliseconds to wait before the action. Default value is 100 ms</param>
|
||||
/// <param name="msPostAction">The number of milliseconds to wait after the action. Default value is 100 ms</param>
|
||||
protected void PerformAction(Action<Actions, WindowsElement> action, int msPreAction = 100, int msPostAction = 100)
|
||||
{
|
||||
if (msPreAction > 0)
|
||||
{
|
||||
Task.Delay(msPreAction).Wait();
|
||||
}
|
||||
|
||||
var windowElement = this.windowsElement!;
|
||||
Actions actions = new Actions(this.driver);
|
||||
action(actions, windowElement);
|
||||
|
||||
if (msPostAction > 0)
|
||||
{
|
||||
Task.Delay(msPostAction).Wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
40
src/common/UITestAutomation/Element/TextBox.cs
Normal file
40
src/common/UITestAutomation/Element/TextBox.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using OpenQA.Selenium;
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a textbox in the UI test environment.
|
||||
/// </summary>
|
||||
public class TextBox : Element
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets the text of the textbox.
|
||||
/// </summary>
|
||||
/// <param name="value">The text to set.</param>
|
||||
/// <param name="clearText">A value indicating whether to clear the text before setting it. Default value is true</param>
|
||||
/// <returns>The current TextBox instance.</returns>
|
||||
public TextBox SetText(string value, bool clearText = true)
|
||||
{
|
||||
if (clearText)
|
||||
{
|
||||
PerformAction((actions, windowElement) =>
|
||||
{
|
||||
// select all text and delete it
|
||||
windowElement.SendKeys(Keys.Control + "a");
|
||||
windowElement.SendKeys(Keys.Delete);
|
||||
});
|
||||
}
|
||||
|
||||
PerformAction((actions, windowElement) =>
|
||||
{
|
||||
windowElement.SendKeys(value);
|
||||
});
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/common/UITestAutomation/Element/ToggleSwitch.cs
Normal file
41
src/common/UITestAutomation/Element/ToggleSwitch.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a ToggleSwitch in the UI test environment.
|
||||
/// </summary>
|
||||
public class ToggleSwitch : Button
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the ToggleSwitch is on.
|
||||
/// </summary>
|
||||
public bool IsOn
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.Selected;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the ToggleSwitch to the specified value.
|
||||
/// </summary>
|
||||
/// <param name="value">A value indicating whether the ToggleSwitch should be active. Default is true</param>
|
||||
/// <returns>The current ToggleSwitch instance.</returns>
|
||||
public ToggleSwitch Toggle(bool value = true)
|
||||
{
|
||||
if (this.IsOn != value)
|
||||
{
|
||||
// Toggle the switch
|
||||
this.Click();
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
85
src/common/UITestAutomation/Element/Window.cs
Normal file
85
src/common/UITestAutomation/Element/Window.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a window in the UI test environment.
|
||||
/// </summary>
|
||||
public class Window : Element
|
||||
{
|
||||
/// <summary>
|
||||
/// Maximizes the window.
|
||||
/// </summary>
|
||||
/// <param name="byClickButton">If true, clicks the Maximize button; otherwise, sets the window state.</param>
|
||||
/// <returns>The current Window instance.</returns>
|
||||
public Window Maximize(bool byClickButton = true)
|
||||
{
|
||||
if (byClickButton)
|
||||
{
|
||||
Find<Button>(By.Name("Maximize")).Click();
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Implement maximizing the window using an alternative method
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores the window.
|
||||
/// </summary>
|
||||
/// <param name="byClickButton">If true, clicks the Restore button; otherwise, sets the window state.</param>
|
||||
/// <returns>The current Window instance.</returns>
|
||||
public Window Restore(bool byClickButton = true)
|
||||
{
|
||||
if (byClickButton)
|
||||
{
|
||||
Find<Button>(By.Name("Restore")).Click();
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Implement restoring the window using an alternative method
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimizes the window.
|
||||
/// </summary>
|
||||
/// <param name="byClickButton">If true, clicks the Minimize button; otherwise, sets the window state.</param>
|
||||
/// <returns>The current Window instance.</returns>
|
||||
public Window Minimize(bool byClickButton = true)
|
||||
{
|
||||
if (byClickButton)
|
||||
{
|
||||
Find<Button>(By.Name("Minimize")).Click();
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Implement minimizing the window using an alternative method
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the window.
|
||||
/// </summary>
|
||||
/// <param name="byClickButton">If true, clicks the Close button; otherwise, closes the window using an alternative method.</param>
|
||||
public void Close(bool byClickButton = true)
|
||||
{
|
||||
if (byClickButton)
|
||||
{
|
||||
Find<Button>(By.Name("Close")).Click();
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Implement closing the window using an alternative method
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
58
src/common/UITestAutomation/FindHelper.cs
Normal file
58
src/common/UITestAutomation/FindHelper.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenQA.Selenium.Appium.Windows;
|
||||
|
||||
[assembly: InternalsVisibleTo("Element")]
|
||||
[assembly: InternalsVisibleTo("Session")]
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper class for finding elements.
|
||||
/// </summary>
|
||||
internal static class FindHelper
|
||||
{
|
||||
public static T Find<T, TW>(Func<TW> findElementFunc, WindowsDriver<WindowsElement>? driver, int timeoutMS)
|
||||
where T : Element, new()
|
||||
{
|
||||
var item = findElementFunc() as WindowsElement;
|
||||
return NewElement<T>(item, driver, timeoutMS);
|
||||
}
|
||||
|
||||
public static ReadOnlyCollection<T>? FindAll<T, TW>(Func<ReadOnlyCollection<TW>> findElementsFunc, WindowsDriver<WindowsElement>? driver, int timeoutMS)
|
||||
where T : Element, new()
|
||||
{
|
||||
var items = findElementsFunc();
|
||||
var res = items.Select(item =>
|
||||
{
|
||||
var element = item as WindowsElement;
|
||||
return NewElement<T>(element, driver, timeoutMS);
|
||||
}).ToList();
|
||||
|
||||
return new ReadOnlyCollection<T>(res);
|
||||
}
|
||||
|
||||
public static T NewElement<T>(WindowsElement? element, WindowsDriver<WindowsElement>? driver, int timeoutMS)
|
||||
where T : Element, new()
|
||||
{
|
||||
Assert.IsNotNull(driver, $"New Element {typeof(T).Name} error: driver is null.");
|
||||
Assert.IsNotNull(element, $"New Element {typeof(T).Name} error: element is null.");
|
||||
|
||||
T newElement = new T();
|
||||
if (timeoutMS > 0)
|
||||
{
|
||||
// Only set timeout if it is positive value
|
||||
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(timeoutMS);
|
||||
}
|
||||
|
||||
newElement.SetSession(driver);
|
||||
newElement.SetWindowsElement(element);
|
||||
return newElement;
|
||||
}
|
||||
}
|
||||
}
|
||||
72
src/common/UITestAutomation/ModuleConfigData.cs
Normal file
72
src/common/UITestAutomation/ModuleConfigData.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("UITestBase")]
|
||||
[assembly: InternalsVisibleTo("Session")]
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// This file manages the configuration of modules for UI tests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// How to add a new module:
|
||||
/// 1. Define the new module in the PowerToysModule enum.
|
||||
/// 2. Add the exe window name to the ModuleWindowName dictionary in the ModuleConfigData constructor.
|
||||
/// 3. Add the exe path to the ModulePath dictionary in the ModuleConfigData constructor.
|
||||
/// </remarks>
|
||||
|
||||
/// <summary>
|
||||
/// Represents the modules in PowerToys.
|
||||
/// </summary>
|
||||
public enum PowerToysModule
|
||||
{
|
||||
PowerToysSettings,
|
||||
FancyZone,
|
||||
Hosts,
|
||||
}
|
||||
|
||||
internal class ModuleConfigData
|
||||
{
|
||||
private Dictionary<PowerToysModule, string> ModulePath { get; }
|
||||
|
||||
// Singleton instance of ModuleConfigData.
|
||||
private static readonly Lazy<ModuleConfigData> SingletonInstance = new Lazy<ModuleConfigData>(() => new ModuleConfigData());
|
||||
|
||||
public static ModuleConfigData Instance => SingletonInstance.Value;
|
||||
|
||||
public const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
|
||||
|
||||
public Dictionary<PowerToysModule, string> ModuleWindowName { get; }
|
||||
|
||||
private ModuleConfigData()
|
||||
{
|
||||
// The exe window name for each module.
|
||||
ModuleWindowName = new Dictionary<PowerToysModule, string>
|
||||
{
|
||||
[PowerToysModule.PowerToysSettings] = "PowerToys Settings",
|
||||
[PowerToysModule.FancyZone] = "FancyZones Layout",
|
||||
[PowerToysModule.Hosts] = "Hosts File Editor",
|
||||
};
|
||||
|
||||
// Exe start path for the module if it exists.
|
||||
ModulePath = new Dictionary<PowerToysModule, string>
|
||||
{
|
||||
[PowerToysModule.PowerToysSettings] = @"\..\..\..\WinUI3Apps\PowerToys.Settings.exe",
|
||||
[PowerToysModule.FancyZone] = @"\..\..\..\PowerToys.FancyZonesEditor.exe",
|
||||
[PowerToysModule.Hosts] = @"\..\..\..\WinUI3Apps\PowerToys.Hosts.exe",
|
||||
};
|
||||
}
|
||||
|
||||
public string GetModulePath(PowerToysModule scope) => ModulePath[scope];
|
||||
|
||||
public string GetWindowsApplicationDriverUrl() => WindowsApplicationDriverUrl;
|
||||
|
||||
public string GetModuleWindowName(PowerToysModule scope) => ModuleWindowName[scope];
|
||||
}
|
||||
}
|
||||
123
src/common/UITestAutomation/Session.cs
Normal file
123
src/common/UITestAutomation/Session.cs
Normal file
@@ -0,0 +1,123 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenQA.Selenium.Appium;
|
||||
using OpenQA.Selenium.Appium.Windows;
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides interfaces for interacting with UI elements.
|
||||
/// </summary>
|
||||
public class Session
|
||||
{
|
||||
private WindowsDriver<WindowsElement> Root { get; set; }
|
||||
|
||||
private WindowsDriver<WindowsElement> WindowsDriver { get; set; }
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(nint hWnd);
|
||||
|
||||
public Session(WindowsDriver<WindowsElement> root, WindowsDriver<WindowsElement> windowsDriver)
|
||||
{
|
||||
this.Root = root;
|
||||
this.WindowsDriver = windowsDriver;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds an element by selector.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
|
||||
/// <param name="by">The selector to find the element.</param>
|
||||
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
|
||||
/// <returns>The found element.</returns>
|
||||
public T Find<T>(By by, int timeoutMS = 3000)
|
||||
where T : Element, new()
|
||||
{
|
||||
Assert.IsNotNull(this.WindowsDriver, $"WindowsElement is null in method Find<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
|
||||
var foundElement = FindHelper.Find<T, WindowsElement>(
|
||||
() =>
|
||||
{
|
||||
var element = this.WindowsDriver.FindElement(by.ToSeleniumBy());
|
||||
Assert.IsNotNull(element, $"Element not found using selector: {by}");
|
||||
return element;
|
||||
},
|
||||
this.WindowsDriver,
|
||||
timeoutMS);
|
||||
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds all elements by selector.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The class of the elements, should be Element or its derived class.</typeparam>
|
||||
/// <param name="by">The selector to find the elements.</param>
|
||||
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
|
||||
/// <returns>A read-only collection of the found elements.</returns>
|
||||
public ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 3000)
|
||||
where T : Element, new()
|
||||
{
|
||||
Assert.IsNotNull(this.WindowsDriver, $"WindowsElement is null in method FindAll<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
|
||||
var foundElements = FindHelper.FindAll<T, WindowsElement>(
|
||||
() =>
|
||||
{
|
||||
var elements = this.WindowsDriver.FindElements(by.ToSeleniumBy());
|
||||
return elements;
|
||||
},
|
||||
this.WindowsDriver,
|
||||
timeoutMS);
|
||||
|
||||
return foundElements ?? new ReadOnlyCollection<T>(new List<T>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches to an existing PowerToys module.
|
||||
/// </summary>
|
||||
/// <param name="module">The PowerToys module to attach to.</param>
|
||||
/// <returns>The attached session.</returns>
|
||||
public Session Attach(PowerToysModule module)
|
||||
{
|
||||
string windowName = ModuleConfigData.Instance.GetModuleWindowName(module);
|
||||
return this.Attach(windowName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches to an existing exe by string window name.
|
||||
/// The session should be attached when a new app is started.
|
||||
/// </summary>
|
||||
/// <param name="windowName">The window name to attach to.</param>
|
||||
/// <returns>The attached session.</returns>
|
||||
public Session Attach(string windowName)
|
||||
{
|
||||
if (this.Root != null)
|
||||
{
|
||||
var window = this.Root.FindElementByName(windowName);
|
||||
Assert.IsNotNull(window, $"Failed to attach. Window '{windowName}' not found");
|
||||
|
||||
var windowHandle = new nint(int.Parse(window.GetAttribute("NativeWindowHandle")));
|
||||
SetForegroundWindow(windowHandle);
|
||||
var hexWindowHandle = windowHandle.ToString("x");
|
||||
var appCapabilities = new AppiumOptions();
|
||||
|
||||
appCapabilities.AddAdditionalCapability("appTopLevelWindow", hexWindowHandle);
|
||||
appCapabilities.AddAdditionalCapability("deviceName", "WindowsPC");
|
||||
this.WindowsDriver = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), appCapabilities);
|
||||
Assert.IsNotNull(this.WindowsDriver, "Attach WindowsDriver is null");
|
||||
|
||||
// Set implicit timeout to make element search retry every 500 ms
|
||||
this.WindowsDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.IsNotNull(this.Root, $"Failed to attach to the window '{windowName}'. Root driver is null");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
19
src/common/UITestAutomation/UITestAutomation.csproj
Normal file
19
src/common/UITestAutomation/UITestAutomation.csproj
Normal file
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Look at Directory.Build.props in root for common stuff as well -->
|
||||
<Import Project="..\..\Common.Dotnet.CsWinRT.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Appium.WebDriver" />
|
||||
<PackageReference Include="MSTest" />
|
||||
<PackageReference Include="System.IO.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
154
src/common/UITestAutomation/UITestBase.cs
Normal file
154
src/common/UITestAutomation/UITestBase.cs
Normal file
@@ -0,0 +1,154 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenQA.Selenium.Appium;
|
||||
using OpenQA.Selenium.Appium.Windows;
|
||||
|
||||
namespace Microsoft.PowerToys.UITest
|
||||
{
|
||||
/// <summary>
|
||||
/// Base class that should be inherited by all Test Classes.
|
||||
/// </summary>
|
||||
public class UITestBase
|
||||
{
|
||||
public Session Session { get; set; }
|
||||
|
||||
private readonly TestInit testInit = new TestInit();
|
||||
|
||||
public UITestBase(PowerToysModule scope = PowerToysModule.PowerToysSettings)
|
||||
{
|
||||
this.testInit.SetScope(scope);
|
||||
this.testInit.Init();
|
||||
this.Session = new Session(this.testInit.GetRoot(), this.testInit.GetDriver());
|
||||
}
|
||||
|
||||
~UITestBase()
|
||||
{
|
||||
this.testInit.Cleanup();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds an element by selector.
|
||||
/// Shortcut for this.Session.Find<T>(by, timeoutMS)
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
|
||||
/// <param name="by">The selector to find the element.</param>
|
||||
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
|
||||
/// <returns>The found element.</returns>
|
||||
protected T Find<T>(By by, int timeoutMS = 3000)
|
||||
where T : Element, new()
|
||||
{
|
||||
return this.Session.Find<T>(by, timeoutMS);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds all elements by selector.
|
||||
/// Shortcut for this.Session.FindAll<T>(by, timeoutMS)
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The class of the elements, should be Element or its derived class.</typeparam>
|
||||
/// <param name="by">The selector to find the elements.</param>
|
||||
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
|
||||
/// <returns>A read-only collection of the found elements.</returns>
|
||||
protected ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 3000)
|
||||
where T : Element, new()
|
||||
{
|
||||
return this.Session.FindAll<T>(by, timeoutMS);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Nested class for test initialization.
|
||||
/// </summary>
|
||||
private sealed class TestInit
|
||||
{
|
||||
private WindowsDriver<WindowsElement> Root { get; set; }
|
||||
|
||||
private WindowsDriver<WindowsElement>? Driver { get; set; }
|
||||
|
||||
private static Process? appDriver;
|
||||
|
||||
// Default session path is PowerToys settings dashboard
|
||||
private static string sessionPath = ModuleConfigData.Instance.GetModulePath(PowerToysModule.PowerToysSettings);
|
||||
|
||||
public TestInit()
|
||||
{
|
||||
appDriver = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe",
|
||||
Verb = "runas",
|
||||
});
|
||||
|
||||
var desktopCapabilities = new AppiumOptions();
|
||||
desktopCapabilities.AddAdditionalCapability("app", "Root");
|
||||
this.Root = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), desktopCapabilities);
|
||||
|
||||
// Set default timeout to 5 seconds
|
||||
this.Root.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the test environment.
|
||||
/// </summary>
|
||||
[UnconditionalSuppressMessage("SingleFile", "IL3000:Avoid accessing Assembly file path when publishing as a single file", Justification = "<Pending>")]
|
||||
public void Init()
|
||||
{
|
||||
string? path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
this.StartExe(path + sessionPath);
|
||||
|
||||
Assert.IsNotNull(this.Driver, $"Failed to initialize the test environment. Driver is null.");
|
||||
|
||||
// Set default timeout to 5 seconds
|
||||
this.Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up the test environment.
|
||||
/// </summary>
|
||||
public void Cleanup()
|
||||
{
|
||||
try
|
||||
{
|
||||
appDriver?.Kill();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handle exceptions if needed
|
||||
Debug.WriteLine($"Exception during Cleanup: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a new exe and takes control of it.
|
||||
/// </summary>
|
||||
/// <param name="appPath">The path to the application executable.</param>
|
||||
public void StartExe(string appPath)
|
||||
{
|
||||
var opts = new AppiumOptions();
|
||||
opts.AddAdditionalCapability("app", appPath);
|
||||
this.Driver = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), opts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets scope to the Test Class.
|
||||
/// </summary>
|
||||
/// <param name="scope">The PowerToys module to start.</param>
|
||||
public void SetScope(PowerToysModule scope)
|
||||
{
|
||||
sessionPath = ModuleConfigData.Instance.GetModulePath(scope);
|
||||
}
|
||||
|
||||
public WindowsDriver<WindowsElement> GetRoot() => this.Root;
|
||||
|
||||
public WindowsDriver<WindowsElement> GetDriver()
|
||||
{
|
||||
Assert.IsNotNull(this.Driver, $"Failed to get driver. Driver is null.");
|
||||
return this.Driver;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,9 @@ namespace CommonSharedConstants
|
||||
const wchar_t ZOOMIT_REFRESH_SETTINGS_EVENT[] = L"Local\\PowerToysZoomIt-RefreshSettingsEvent-f053a563-d519-4b0d-8152-a54489c13324";
|
||||
const wchar_t ZOOMIT_EXIT_EVENT[] = L"Local\\PowerToysZoomIt-ExitEvent-36641ce6-df02-4eac-abea-a3fbf9138220";
|
||||
|
||||
// Path to the events used by CharacterMap
|
||||
const wchar_t CHARACTER_MAP_TRIGGER_EVENT[] = L"Local\\PowerToysCharacterMap-TriggerEvent-4c45960f-1b0f-40b9-85a6-789cf45efde1";
|
||||
|
||||
// Max DWORD for key code to disable keys.
|
||||
const DWORD VK_DISABLED = 0x100;
|
||||
}
|
||||
|
||||
@@ -77,6 +77,7 @@ struct LogSettings
|
||||
inline const static std::string workspacesSnapshotToolLoggerName = "workspaces-snapshot-tool";
|
||||
inline const static std::wstring workspacesSnapshotToolLogPath = L"workspaces-snapshot-tool-log.txt";
|
||||
inline const static std::string zoomItLoggerName = "zoom-it";
|
||||
inline const static std::string characterMapLoggerName = "CharacterMap";
|
||||
inline const static int retention = 30;
|
||||
std::wstring logLevel;
|
||||
LogSettings();
|
||||
|
||||
@@ -62,6 +62,7 @@ namespace powertoys_gpo {
|
||||
const std::wstring POLICY_CONFIGURE_ENABLED_QOI_THUMBNAILS = L"ConfigureEnabledUtilityFileExplorerQOIThumbnails";
|
||||
const std::wstring POLICY_CONFIGURE_ENABLED_NEWPLUS = L"ConfigureEnabledUtilityNewPlus";
|
||||
const std::wstring POLICY_CONFIGURE_ENABLED_WORKSPACES = L"ConfigureEnabledUtilityWorkspaces";
|
||||
const std::wstring POLICY_CONFIGURE_ENABLED_CHARACTERMAP = L"ConfigureEnabledUtilityCharacterMap";
|
||||
|
||||
// The registry value names for PowerToys installer and update policies.
|
||||
const std::wstring POLICY_DISABLE_PER_USER_INSTALLATION = L"PerUserInstallationDisabled";
|
||||
@@ -455,6 +456,11 @@ namespace powertoys_gpo {
|
||||
{
|
||||
return getUtilityEnabledValue(POLICY_CONFIGURE_ENABLED_NEWPLUS);
|
||||
}
|
||||
|
||||
inline gpo_rule_configured_t getConfiguredCharacterMapEnabledValue()
|
||||
{
|
||||
return getUtilityEnabledValue(POLICY_CONFIGURE_ENABLED_CHARACTERMAP);
|
||||
}
|
||||
#pragma endregion UtilityEnabledStatePolicies
|
||||
|
||||
// Individual module setting policies
|
||||
|
||||
@@ -465,6 +465,16 @@
|
||||
<disabledValue>
|
||||
<decimal value="0" />
|
||||
</disabledValue>
|
||||
</policy>
|
||||
<policy name="ConfigureEnabledUtilityCharacterMap" class="Both" displayName="$(string.ConfigureEnabledUtilityCharacterMap)" explainText="$(string.ConfigureEnabledUtilityDescription)" key="Software\Policies\PowerToys" valueName="ConfigureEnabledUtilityCharacterMap">
|
||||
<parentCategory ref="PowerToys" />
|
||||
<supportedOn ref="SUPPORTED_POWERTOYS_0_88_0" />
|
||||
<enabledValue>
|
||||
<decimal value="1" />
|
||||
</enabledValue>
|
||||
<disabledValue>
|
||||
<decimal value="0" />
|
||||
</disabledValue>
|
||||
</policy>
|
||||
<policy name="DisablePerUserInstallation" class="Machine" displayName="$(string.DisablePerUserInstallation)" explainText="$(string.DisablePerUserInstallationDescription)" key="Software\Policies\PowerToys" valueName="PerUserInstallationDisabled">
|
||||
<parentCategory ref="InstallerUpdates" />
|
||||
|
||||
@@ -267,6 +267,7 @@ If you don't configure this policy, the user takes control over the setting and
|
||||
<string id="ConfigureEnabledUtilityTextExtractor">Text Extractor: Configure enabled state</string>
|
||||
<string id="ConfigureEnabledUtilityVideoConferenceMute">Video Conference Mute: Configure enabled state</string>
|
||||
<string id="ConfigureEnabledUtilityZoomIt">Zoom It: Configure enabled state</string>
|
||||
<string id="ConfigureEnabledUtilityCharacterMap">Character Map: Configure enabled state</string>
|
||||
<string id="DisablePerUserInstallation">Disable per-user installation</string>
|
||||
<string id="DisableAutomaticUpdateDownload">Disable automatic downloads</string>
|
||||
<string id="DoNotShowWhatsNewAfterUpdates">Do not show the release notes after updates</string>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Models.KernelQueryCache;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
|
||||
namespace AdvancedPaste.UnitTests.Mocks;
|
||||
|
||||
internal sealed class NoOpProgress : IProgress<double>
|
||||
{
|
||||
public void Report(double value)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -131,17 +132,18 @@ public sealed class AIServiceBatchIntegrationTests
|
||||
{
|
||||
VaultCredentialsProvider credentialsProvider = new();
|
||||
PromptModerationService promptModerationService = new(credentialsProvider);
|
||||
NoOpProgress progress = new();
|
||||
CustomTextTransformService customTextTransformService = new(credentialsProvider, promptModerationService);
|
||||
|
||||
switch (format)
|
||||
{
|
||||
case PasteFormats.CustomTextTransformation:
|
||||
return DataPackageHelpers.CreateFromText(await customTextTransformService.TransformTextAsync(batchTestInput.Prompt, batchTestInput.Clipboard));
|
||||
return DataPackageHelpers.CreateFromText(await customTextTransformService.TransformTextAsync(batchTestInput.Prompt, batchTestInput.Clipboard, CancellationToken.None, progress));
|
||||
|
||||
case PasteFormats.KernelQuery:
|
||||
var clipboardData = DataPackageHelpers.CreateFromText(batchTestInput.Clipboard).GetView();
|
||||
KernelService kernelService = new(new NoOpKernelQueryCacheService(), credentialsProvider, promptModerationService, customTextTransformService);
|
||||
return await kernelService.TransformClipboardAsync(batchTestInput.Prompt, clipboardData, isSavedQuery: false);
|
||||
return await kernelService.TransformClipboardAsync(batchTestInput.Prompt, clipboardData, isSavedQuery: false, CancellationToken.None, progress);
|
||||
|
||||
default:
|
||||
throw new InvalidOperationException($"Unexpected format {format}");
|
||||
|
||||
@@ -6,6 +6,7 @@ using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -130,7 +131,7 @@ public sealed class KernelServiceIntegrationTests : IDisposable
|
||||
|
||||
private async Task<DataPackageView> GetKernelOutputAsync(string prompt, DataPackage input)
|
||||
{
|
||||
var output = await _kernelService.TransformClipboardAsync(prompt, input.GetView(), isSavedQuery: false);
|
||||
var output = await _kernelService.TransformClipboardAsync(prompt, input.GetView(), isSavedQuery: false, CancellationToken.None, new NoOpProgress());
|
||||
|
||||
Assert.AreEqual(1, _eventListener.SemanticKernelEvents.Count);
|
||||
Assert.IsTrue(_eventListener.SemanticKernelTokens > 0);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
using AdvancedPaste.Models;
|
||||
using AdvancedPaste.UnitTests.Mocks;
|
||||
using ManagedCommon;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Windows.Storage;
|
||||
using Windows.Storage.FileProperties;
|
||||
|
||||
namespace AdvancedPaste.UnitTests.ServicesTests;
|
||||
|
||||
[TestClass]
|
||||
public sealed class TranscodeHelperIntegrationTests
|
||||
{
|
||||
private sealed record class MediaProperties(BasicProperties Basic, MusicProperties Music, VideoProperties Video);
|
||||
|
||||
private const string InputRootFolder = @"%USERPROFILE%\AdvancedPasteTranscodeMediaTestData";
|
||||
|
||||
/// <summary> Tests transforming a folder of media files.
|
||||
/// - Verifies that the output file has the same basic properties (e.g. duration) as the input file.
|
||||
/// - Copies the output file to a subfolder of the input folder for manual inspection.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[DataRow(@"audio", PasteFormats.TranscodeToMp3)]
|
||||
[DataRow(@"video", PasteFormats.TranscodeToMp4)]
|
||||
public async Task TestTransformFolder(string inputSubfolder, PasteFormats format)
|
||||
{
|
||||
var inputFolder = Environment.ExpandEnvironmentVariables(Path.Combine(InputRootFolder, inputSubfolder));
|
||||
|
||||
if (!Directory.Exists(inputFolder))
|
||||
{
|
||||
Assert.Inconclusive($"Skipping tests for {inputFolder} as it does not exist");
|
||||
}
|
||||
|
||||
var outputPath = Path.Combine(inputFolder, $"test_output_{format}");
|
||||
|
||||
foreach (var inputPath in Directory.EnumerateFiles(inputFolder))
|
||||
{
|
||||
await RunTestTransformFileAsync(inputPath, outputPath, format);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunTestTransformFileAsync(string inputPath, string finalOutputPath, PasteFormats format)
|
||||
{
|
||||
Logger.LogDebug($"Running {nameof(RunTestTransformFileAsync)} for {inputPath}/{format}");
|
||||
|
||||
Directory.CreateDirectory(finalOutputPath);
|
||||
|
||||
var inputPackage = await DataPackageHelpers.CreateFromFileAsync(inputPath);
|
||||
var inputProperties = await GetPropertiesAsync(await StorageFile.GetFileFromPathAsync(inputPath));
|
||||
|
||||
var outputPackage = await TransformHelpers.TransformAsync(format, inputPackage.GetView(), CancellationToken.None, new NoOpProgress());
|
||||
|
||||
var outputItems = await outputPackage.GetView().GetStorageItemsAsync();
|
||||
Assert.AreEqual(1, outputItems.Count);
|
||||
var outputFile = outputItems.Single() as StorageFile;
|
||||
Assert.IsNotNull(outputFile);
|
||||
var outputProperties = await GetPropertiesAsync(outputFile);
|
||||
AssertPropertiesMatch(format, inputProperties, outputProperties);
|
||||
|
||||
await outputFile.CopyAsync(await StorageFolder.GetFolderFromPathAsync(finalOutputPath), outputFile.Name, NameCollisionOption.ReplaceExisting);
|
||||
await outputPackage.GetView().TryCleanupAfterDelayAsync(TimeSpan.Zero);
|
||||
}
|
||||
|
||||
private static void AssertPropertiesMatch(PasteFormats format, MediaProperties inputProperties, MediaProperties outputProperties)
|
||||
{
|
||||
Assert.IsTrue(outputProperties.Basic.Size > 0);
|
||||
|
||||
Assert.AreEqual(inputProperties.Music.Title, outputProperties.Music.Title);
|
||||
Assert.AreEqual(inputProperties.Music.Album, outputProperties.Music.Album);
|
||||
Assert.AreEqual(inputProperties.Music.Artist, outputProperties.Music.Artist);
|
||||
AssertDurationsApproxEqual(inputProperties.Music.Duration, outputProperties.Music.Duration);
|
||||
|
||||
if (format == PasteFormats.TranscodeToMp4)
|
||||
{
|
||||
Assert.AreEqual(inputProperties.Video.Title, outputProperties.Video.Title);
|
||||
AssertDurationsApproxEqual(inputProperties.Video.Duration, outputProperties.Video.Duration);
|
||||
|
||||
var inputVideoDimensions = GetNormalizedDimensions(inputProperties.Video);
|
||||
if (inputVideoDimensions != null)
|
||||
{
|
||||
Assert.AreEqual(inputVideoDimensions, GetNormalizedDimensions(outputProperties.Video));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<MediaProperties> GetPropertiesAsync(StorageFile file) =>
|
||||
new(await file.GetBasicPropertiesAsync(), await file.Properties.GetMusicPropertiesAsync(), await file.Properties.GetVideoPropertiesAsync());
|
||||
|
||||
private static void AssertDurationsApproxEqual(TimeSpan expected, TimeSpan actual) =>
|
||||
Assert.AreEqual(expected.Ticks, actual.Ticks, delta: TimeSpan.FromSeconds(1).Ticks);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the dimensions of a video, if available. Accounts for the fact that the dimensions may sometimes be swapped.
|
||||
/// </summary>
|
||||
private static (uint Width, uint Height)? GetNormalizedDimensions(VideoProperties properties) =>
|
||||
properties.Width == 0 || properties.Height == 0
|
||||
? null
|
||||
: (Math.Max(properties.Width, properties.Height), Math.Min(properties.Width, properties.Height));
|
||||
}
|
||||
@@ -28,6 +28,7 @@
|
||||
Background="Transparent"
|
||||
BorderThickness="4"
|
||||
CornerRadius="{TemplateBinding CornerRadius}"
|
||||
IsHitTestVisible="False"
|
||||
Visibility="Collapsed">
|
||||
<!-- CornerRadius needs to be > 0 -->
|
||||
<Grid.BorderBrush>
|
||||
|
||||
@@ -178,17 +178,36 @@
|
||||
Padding="0"
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch">
|
||||
<Image
|
||||
x:Name="AIGlyphImage"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Source="/Assets/AdvancedPaste/SemanticKernel.svg"
|
||||
Visibility="{Binding DataContext.IsAdvancedAIEnabled, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource BoolToVisibilityConverter}}" />
|
||||
<PathIcon
|
||||
x:Name="AIGlyph"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Data="M128 766q0-42 24-77t65-48l178-57q32-11 61-30t52-42q50-50 71-114l58-179q13-40 48-65t78-26q42 0 77 24t50 65l58 177q21 66 72 117 49 50 117 72l176 58q43 14 69 48t26 80q0 41-25 76t-64 49l-178 58q-66 21-117 72-32 32-51 73t-33 84-26 83-30 73-45 51-71 20q-42 0-77-24t-49-65l-58-178q-8-25-19-47t-28-43q-34-43-77-68t-89-41-89-27-78-29-55-45-21-75zm1149 7q-76-29-145-53t-129-60-104-88-73-138l-57-176-67 176q-18 48-42 89t-60 78q-34 34-76 61t-89 43l-177 57q75 29 144 53t127 60 103 89 73 137l57 176 67-176q37-97 103-168t168-103l177-57zm-125 759q0-31 20-57t49-36l99-32q34-11 53-34t30-51 20-59 20-54 33-41 58-16q32 0 59 19t38 50q6 20 11 40t13 40 17 38 25 34q16 17 39 26t48 18 49 16 44 20 31 32 12 50q0 33-18 60t-51 38q-19 6-39 11t-41 13-39 17-34 25q-24 25-35 62t-24 73-35 61-68 25q-32 0-59-19t-38-50q-6-18-11-39t-13-41-17-40-24-33q-18-17-41-27t-47-17-49-15-43-20-30-33-12-54zm583 4q-43-13-74-30t-55-41-40-55-32-74q-12 41-29 72t-42 55-55 42-71 31q81 23 128 71t71 129q15-43 31-74t40-54 53-40 75-32z"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
Visibility="{Binding DataContext.IsAdvancedAIEnabled, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource BoolToInvertedVisibilityConverter}}" />
|
||||
<ProgressRing
|
||||
Width="30"
|
||||
Height="30"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center"
|
||||
IsActive="{Binding DataContext.IsBusy, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
IsIndeterminate="{Binding DataContext.HasIndeterminateTransformProgress, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
Maximum="100"
|
||||
Minimum="0"
|
||||
Visibility="{Binding DataContext.IsBusy, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource BoolToVisibilityConverter}}"
|
||||
Value="{Binding DataContext.TransformProgress, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
|
||||
|
||||
<StackPanel
|
||||
Margin="0"
|
||||
Padding="0"
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch"
|
||||
Visibility="{Binding DataContext.IsBusy, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource BoolToInvertedVisibilityConverter}}">
|
||||
<Image
|
||||
x:Name="AIGlyphImage"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Source="/Assets/AdvancedPaste/SemanticKernel.svg"
|
||||
Visibility="{Binding DataContext.IsAdvancedAIEnabled, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource BoolToVisibilityConverter}}" />
|
||||
<PathIcon
|
||||
x:Name="AIGlyph"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Data="M128 766q0-42 24-77t65-48l178-57q32-11 61-30t52-42q50-50 71-114l58-179q13-40 48-65t78-26q42 0 77 24t50 65l58 177q21 66 72 117 49 50 117 72l176 58q43 14 69 48t26 80q0 41-25 76t-64 49l-178 58q-66 21-117 72-32 32-51 73t-33 84-26 83-30 73-45 51-71 20q-42 0-77-24t-49-65l-58-178q-8-25-19-47t-28-43q-34-43-77-68t-89-41-89-27-78-29-55-45-21-75zm1149 7q-76-29-145-53t-129-60-104-88-73-138l-57-176-67 176q-18 48-42 89t-60 78q-34 34-76 61t-89 43l-177 57q75 29 144 53t127 60 103 89 73 137l57 176 67-176q37-97 103-168t168-103l177-57zm-125 759q0-31 20-57t49-36l99-32q34-11 53-34t30-51 20-59 20-54 33-41 58-16q32 0 59 19t38 50q6 20 11 40t13 40 17 38 25 34q16 17 39 26t48 18 49 16 44 20 31 32 12 50q0 33-18 60t-51 38q-19 6-39 11t-41 13-39 17-34 25q-24 25-35 62t-24 73-35 61-68 25q-32 0-59-19t-38-50q-6-18-11-39t-13-41-17-40-24-33q-18-17-41-27t-47-17-49-15-43-20-30-33-12-54zm583 4q-43-13-74-30t-55-41-40-55-32-74q-12 41-29 72t-42 55-55 42-71 31q81 23 128 71t71 129q15-43 31-74t40-54 53-40 75-32z"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
Visibility="{Binding DataContext.IsAdvancedAIEnabled, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource BoolToInvertedVisibilityConverter}}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Viewbox>
|
||||
<ScrollViewer
|
||||
@@ -572,6 +591,24 @@
|
||||
Duration="0:0:0.167" />
|
||||
</animations:Implicit.HideAnimations>
|
||||
</Button>
|
||||
<Button
|
||||
x:Name="CancelBtn"
|
||||
x:Uid="CancelBtnAutomation"
|
||||
Padding="0"
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch"
|
||||
ui:VisualExtensions.NormalizedCenterPoint="0.5,0.5"
|
||||
Command="{x:Bind CancelPasteActionCommand}"
|
||||
Content="{ui:FontIcon Glyph=,
|
||||
FontSize=16}"
|
||||
Foreground="{ThemeResource AccentTextFillColorPrimaryBrush}"
|
||||
IsEnabled="False"
|
||||
Style="{StaticResource SubtleButtonStyle}"
|
||||
Visibility="Collapsed">
|
||||
<ToolTipService.ToolTip>
|
||||
<TextBlock x:Uid="CancelBtnToolTip" TextWrapping="WrapWholeWords" />
|
||||
</ToolTipService.ToolTip>
|
||||
</Button>
|
||||
<!-- Transparent overlay to show tooltip -->
|
||||
<Grid
|
||||
x:Name="SendBtnOverlay"
|
||||
@@ -679,6 +716,10 @@
|
||||
<Setter Target="Loader.IsLoading" Value="True" />
|
||||
<Setter Target="InputTxtBox.IsEnabled" Value="False" />
|
||||
<Setter Target="SendBtn.IsEnabled" Value="False" />
|
||||
<Setter Target="SendBtn.Visibility" Value="Collapsed" />
|
||||
<Setter Target="SendBtnOverlay.Visibility" Value="Collapsed" />
|
||||
<Setter Target="CancelBtn.IsEnabled" Value="True" />
|
||||
<Setter Target="CancelBtn.Visibility" Value="Visible" />
|
||||
<Setter Target="DisclaimerPresenter.Visibility" Value="Collapsed" />
|
||||
<Setter Target="LoadingText.Visibility" Value="Visible" />
|
||||
</VisualState.Setters>
|
||||
|
||||
@@ -55,9 +55,9 @@ namespace AdvancedPaste.Controls
|
||||
|
||||
private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(ViewModel.Busy) || e.PropertyName == nameof(ViewModel.PasteActionError))
|
||||
if (e.PropertyName is nameof(ViewModel.IsBusy) or nameof(ViewModel.PasteActionError))
|
||||
{
|
||||
var state = ViewModel.Busy ? "LoadingState" : ViewModel.PasteActionError.HasText ? "ErrorState" : "DefaultState";
|
||||
var state = ViewModel.IsBusy ? "LoadingState" : ViewModel.PasteActionError.HasText ? "ErrorState" : "DefaultState";
|
||||
VisualStateManager.GoToState(this, state, true);
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,9 @@ namespace AdvancedPaste.Controls
|
||||
[RelayCommand]
|
||||
private async Task GenerateCustomAIAsync() => await ViewModel.ExecuteCustomAIFormatFromCurrentQueryAsync(PasteActionSource.PromptBox);
|
||||
|
||||
[RelayCommand]
|
||||
private async Task CancelPasteActionAsync() => await ViewModel.CancelPasteActionAsync();
|
||||
|
||||
private async void InputTxtBox_KeyDown(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e)
|
||||
{
|
||||
if (e.Key == Windows.System.VirtualKey.Enter && InputTxtBox.Text.Length > 0 && ViewModel.IsCustomAIAvailable)
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace AdvancedPaste
|
||||
{
|
||||
private readonly WindowMessageMonitor _msgMonitor;
|
||||
private readonly IUserSettings _userSettings;
|
||||
private readonly OptionsViewModel _optionsViewModel;
|
||||
|
||||
private bool _disposedValue;
|
||||
|
||||
@@ -32,8 +33,7 @@ namespace AdvancedPaste
|
||||
InitializeComponent();
|
||||
|
||||
_userSettings = App.GetService<IUserSettings>();
|
||||
|
||||
var optionsViewModel = App.GetService<OptionsViewModel>();
|
||||
_optionsViewModel = App.GetService<OptionsViewModel>();
|
||||
|
||||
var baseHeight = MinHeight;
|
||||
var coreActionCount = PasteFormat.MetadataDict.Values.Count(metadata => metadata.IsCoreAction);
|
||||
@@ -43,7 +43,7 @@ namespace AdvancedPaste
|
||||
double GetHeight(int maxCustomActionCount) =>
|
||||
baseHeight +
|
||||
new PasteFormatsToHeightConverter().GetHeight(coreActionCount + _userSettings.AdditionalActions.Count) +
|
||||
new PasteFormatsToHeightConverter() { MaxItems = maxCustomActionCount }.GetHeight(optionsViewModel.IsCustomAIServiceEnabled ? _userSettings.CustomActions.Count : 0);
|
||||
new PasteFormatsToHeightConverter() { MaxItems = maxCustomActionCount }.GetHeight(_optionsViewModel.IsCustomAIServiceEnabled ? _userSettings.CustomActions.Count : 0);
|
||||
|
||||
MinHeight = GetHeight(1);
|
||||
Height = GetHeight(5);
|
||||
@@ -52,9 +52,9 @@ namespace AdvancedPaste
|
||||
UpdateHeight();
|
||||
|
||||
_userSettings.Changed += (_, _) => UpdateHeight();
|
||||
optionsViewModel.PropertyChanged += (_, e) =>
|
||||
_optionsViewModel.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(optionsViewModel.IsCustomAIServiceEnabled))
|
||||
if (e.PropertyName == nameof(_optionsViewModel.IsCustomAIServiceEnabled))
|
||||
{
|
||||
UpdateHeight();
|
||||
}
|
||||
@@ -111,8 +111,9 @@ namespace AdvancedPaste
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private void WindowEx_Closed(object sender, Microsoft.UI.Xaml.WindowEventArgs args)
|
||||
private async void WindowEx_Closed(object sender, Microsoft.UI.Xaml.WindowEventArgs args)
|
||||
{
|
||||
await _optionsViewModel.CancelPasteActionAsync();
|
||||
Hide();
|
||||
args.Handled = true;
|
||||
}
|
||||
|
||||
@@ -4,10 +4,14 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Models;
|
||||
using ManagedCommon;
|
||||
using Microsoft.Win32;
|
||||
using Windows.ApplicationModel.DataTransfer;
|
||||
using Windows.Data.Html;
|
||||
using Windows.Graphics.Imaging;
|
||||
@@ -18,8 +22,6 @@ namespace AdvancedPaste.Helpers;
|
||||
|
||||
internal static class DataPackageHelpers
|
||||
{
|
||||
private static readonly Lazy<HashSet<string>> ImageFileTypes = new(GetImageFileTypes());
|
||||
|
||||
private static readonly (string DataFormat, ClipboardFormat ClipboardFormat)[] DataFormats =
|
||||
[
|
||||
(StandardDataFormats.Text, ClipboardFormat.Text),
|
||||
@@ -27,6 +29,14 @@ internal static class DataPackageHelpers
|
||||
(StandardDataFormats.Bitmap, ClipboardFormat.Image),
|
||||
];
|
||||
|
||||
private static readonly Lazy<(ClipboardFormat Format, HashSet<string> FileTypes)[]> SupportedFileTypes =
|
||||
new(() =>
|
||||
[
|
||||
(ClipboardFormat.Image, GetImageFileTypes()),
|
||||
(ClipboardFormat.Audio, GetMediaFileTypes("audio")),
|
||||
(ClipboardFormat.Video, GetMediaFileTypes("video")),
|
||||
]);
|
||||
|
||||
internal static DataPackage CreateFromText(string text)
|
||||
{
|
||||
DataPackage dataPackage = new();
|
||||
@@ -57,9 +67,12 @@ internal static class DataPackageHelpers
|
||||
{
|
||||
availableFormats |= ClipboardFormat.File;
|
||||
|
||||
if (ImageFileTypes.Value.Contains(file.FileType))
|
||||
foreach (var (format, fileTypes) in SupportedFileTypes.Value)
|
||||
{
|
||||
availableFormats |= ClipboardFormat.Image;
|
||||
if (fileTypes.Contains(file.FileType))
|
||||
{
|
||||
availableFormats |= format;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +106,60 @@ internal static class DataPackageHelpers
|
||||
return availableFormats == ClipboardFormat.Text ? !string.IsNullOrEmpty(await dataPackageView.GetTextAsync()) : availableFormats != ClipboardFormat.None;
|
||||
}
|
||||
|
||||
internal static async Task TryCleanupAfterDelayAsync(this DataPackageView dataPackageView, TimeSpan delay)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tempFile = await GetSingleTempFileOrNullAsync(dataPackageView);
|
||||
|
||||
if (tempFile != null)
|
||||
{
|
||||
await Task.Delay(delay);
|
||||
|
||||
Logger.LogDebug($"Cleaning up temporary file with extension [{tempFile.Extension}] from data package after delay");
|
||||
|
||||
tempFile.Delete();
|
||||
if (NormalizeDirectoryPath(tempFile.Directory?.Parent?.FullName) == NormalizeDirectoryPath(Path.GetTempPath()))
|
||||
{
|
||||
tempFile.Directory?.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError("Failed to clean up temporary files", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<FileInfo> GetSingleTempFileOrNullAsync(this DataPackageView dataPackageView)
|
||||
{
|
||||
if (!dataPackageView.Contains(StandardDataFormats.StorageItems))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var storageItems = await dataPackageView.GetStorageItemsAsync();
|
||||
|
||||
if (storageItems.Count != 1 || storageItems.Single() is not StorageFile file)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
FileInfo fileInfo = new(file.Path);
|
||||
var tempPathDirectory = NormalizeDirectoryPath(Path.GetTempPath());
|
||||
|
||||
var directoryPaths = new[] { fileInfo.Directory, fileInfo.Directory?.Parent }
|
||||
.Where(directory => directory != null)
|
||||
.Select(directory => NormalizeDirectoryPath(directory.FullName));
|
||||
|
||||
return directoryPaths.Contains(NormalizeDirectoryPath(Path.GetTempPath())) ? fileInfo : null;
|
||||
}
|
||||
|
||||
private static string NormalizeDirectoryPath(string path) =>
|
||||
Path.GetFullPath(new Uri(path).LocalPath)
|
||||
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
|
||||
.ToUpperInvariant();
|
||||
|
||||
internal static async Task<string> GetTextOrEmptyAsync(this DataPackageView dataPackageView) =>
|
||||
dataPackageView.Contains(StandardDataFormats.Text) ? await dataPackageView.GetTextAsync() : string.Empty;
|
||||
|
||||
@@ -153,4 +220,27 @@ internal static class DataPackageHelpers
|
||||
BitmapDecoder.GetDecoderInformationEnumerator()
|
||||
.SelectMany(di => di.FileExtensions)
|
||||
.ToHashSet(StringComparer.InvariantCultureIgnoreCase);
|
||||
|
||||
private static HashSet<string> GetMediaFileTypes(string mediaKind)
|
||||
{
|
||||
static string AssocQueryString(NativeMethods.AssocStr assocStr, string extension)
|
||||
{
|
||||
uint pcchOut = 0;
|
||||
|
||||
NativeMethods.AssocQueryString(NativeMethods.AssocF.None, assocStr, extension, null, null, ref pcchOut);
|
||||
|
||||
StringBuilder pszOut = new((int)pcchOut);
|
||||
var hResult = NativeMethods.AssocQueryString(NativeMethods.AssocF.None, assocStr, extension, null, pszOut, ref pcchOut);
|
||||
return hResult == NativeMethods.HResult.Ok ? pszOut.ToString() : string.Empty;
|
||||
}
|
||||
|
||||
var comparison = StringComparison.OrdinalIgnoreCase;
|
||||
var extensions = from extension in Registry.ClassesRoot.GetSubKeyNames()
|
||||
where extension.StartsWith('.')
|
||||
where AssocQueryString(NativeMethods.AssocStr.PerceivedType, extension).Equals(mediaKind, comparison) ||
|
||||
AssocQueryString(NativeMethods.AssocStr.ContentType, extension).StartsWith($"{mediaKind}/", comparison)
|
||||
select extension;
|
||||
|
||||
return extensions.ToHashSet(StringComparer.InvariantCultureIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Models;
|
||||
@@ -17,6 +18,8 @@ internal static class KernelExtensions
|
||||
private const string DataPackageKey = "DataPackage";
|
||||
private const string LastErrorKey = "LastError";
|
||||
private const string ActionChainKey = "ActionChain";
|
||||
private const string CancellationTokenKey = "CancellationToken";
|
||||
private const string ProgressKey = "Progress";
|
||||
|
||||
internal static DataPackageView GetDataPackageView(this Kernel kernel)
|
||||
{
|
||||
@@ -40,6 +43,14 @@ internal static class KernelExtensions
|
||||
|
||||
internal static void SetDataPackageView(this Kernel kernel, DataPackageView dataPackageView) => kernel.Data[DataPackageKey] = dataPackageView;
|
||||
|
||||
internal static CancellationToken GetCancellationToken(this Kernel kernel) => kernel.Data.TryGetValue(CancellationTokenKey, out object value) ? (CancellationToken)value : CancellationToken.None;
|
||||
|
||||
internal static void SetCancellationToken(this Kernel kernel, CancellationToken cancellationToken) => kernel.Data[CancellationTokenKey] = cancellationToken;
|
||||
|
||||
internal static IProgress<double> GetProgress(this Kernel kernel) => kernel.Data.TryGetValue(ProgressKey, out object obj) ? obj as IProgress<double> : null;
|
||||
|
||||
internal static void SetProgress(this Kernel kernel, IProgress<double> progress) => kernel.Data[ProgressKey] = progress;
|
||||
|
||||
internal static Exception GetLastError(this Kernel kernel) => kernel.Data.TryGetValue(LastErrorKey, out object obj) ? obj as Exception : null;
|
||||
|
||||
internal static void SetLastError(this Kernel kernel, Exception error) => kernel.Data[LastErrorKey] = error;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace AdvancedPaste.Helpers
|
||||
{
|
||||
@@ -83,6 +84,68 @@ namespace AdvancedPaste.Helpers
|
||||
Scancode = 0x0008,
|
||||
}
|
||||
|
||||
public enum HResult
|
||||
{
|
||||
Ok = 0x0000,
|
||||
False = 0x0001,
|
||||
InvalidArguments = unchecked((int)0x80070057),
|
||||
OutOfMemory = unchecked((int)0x8007000E),
|
||||
NoInterface = unchecked((int)0x80004002),
|
||||
Fail = unchecked((int)0x80004005),
|
||||
ExtractionFailed = unchecked((int)0x8004B200),
|
||||
ElementNotFound = unchecked((int)0x80070490),
|
||||
TypeElementNotFound = unchecked((int)0x8002802B),
|
||||
NoObject = unchecked((int)0x800401E5),
|
||||
Win32ErrorCanceled = 1223,
|
||||
Canceled = unchecked((int)0x800704C7),
|
||||
ResourceInUse = unchecked((int)0x800700AA),
|
||||
AccessDenied = unchecked((int)0x80030005),
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum AssocF
|
||||
{
|
||||
None = 0,
|
||||
Init_NoRemapCLSID = 0x1,
|
||||
Init_ByExeName = 0x2,
|
||||
Open_ByExeName = 0x3,
|
||||
Init_DefaultToStar = 0x4,
|
||||
Init_DefaultToFolder = 0x8,
|
||||
NoUserSettings = 0x10,
|
||||
NoTruncate = 0x20,
|
||||
Verify = 0x40,
|
||||
RemapRunDll = 0x80,
|
||||
NoFixUps = 0x100,
|
||||
IgnoreBaseClass = 0x200,
|
||||
}
|
||||
|
||||
public enum AssocStr
|
||||
{
|
||||
Command = 1,
|
||||
Executable,
|
||||
FriendlyDocName,
|
||||
FriendlyAppName,
|
||||
NoOpen,
|
||||
ShellNewValue,
|
||||
DDECommand,
|
||||
DDEIfExec,
|
||||
DDEApplication,
|
||||
DDETopic,
|
||||
InfoTip,
|
||||
QuickTip,
|
||||
TileInfo,
|
||||
ContentType,
|
||||
DefaultIcon,
|
||||
ShellExtension,
|
||||
PerceivedType,
|
||||
DelegateExecute,
|
||||
SupportedUriProtocols,
|
||||
ProgId,
|
||||
AppId,
|
||||
AppPublisher,
|
||||
AppIconReference,
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
|
||||
|
||||
@@ -100,5 +163,8 @@ namespace AdvancedPaste.Helpers
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern bool GetCursorPos(out PointInter lpPoint);
|
||||
|
||||
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
internal static extern HResult AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, [In][Out] ref uint pcchOut);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Windows.Globalization;
|
||||
@@ -15,11 +16,14 @@ namespace AdvancedPaste.Helpers;
|
||||
|
||||
public static class OcrHelpers
|
||||
{
|
||||
public static async Task<string> ExtractTextAsync(SoftwareBitmap bitmap)
|
||||
public static async Task<string> ExtractTextAsync(SoftwareBitmap bitmap, CancellationToken cancellationToken)
|
||||
{
|
||||
var ocrLanguage = GetOCRLanguage() ?? throw new InvalidOperationException("Unable to determine OCR language");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var ocrEngine = OcrEngine.TryCreateFromLanguage(ocrLanguage) ?? throw new InvalidOperationException("Unable to create OCR engine");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var ocrResult = await ocrEngine.RecognizeAsync(bitmap);
|
||||
|
||||
return string.IsNullOrWhiteSpace(ocrResult.Text)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Models;
|
||||
using ManagedCommon;
|
||||
using Windows.ApplicationModel.DataTransfer;
|
||||
using Windows.Media.MediaProperties;
|
||||
using Windows.Media.Transcoding;
|
||||
using Windows.Storage;
|
||||
|
||||
namespace AdvancedPaste.Helpers;
|
||||
|
||||
internal static class TranscodeHelpers
|
||||
{
|
||||
public static async Task<DataPackage> TranscodeToMp3Async(DataPackageView clipboardData, CancellationToken cancellationToken, IProgress<double> progress) =>
|
||||
await TranscodeMediaAsync(clipboardData, MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High), ".mp3", cancellationToken, progress);
|
||||
|
||||
public static async Task<DataPackage> TranscodeToMp4Async(DataPackageView clipboardData, CancellationToken cancellationToken, IProgress<double> progress) =>
|
||||
await TranscodeMediaAsync(clipboardData, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p), ".mp4", cancellationToken, progress);
|
||||
|
||||
private static async Task<DataPackage> TranscodeMediaAsync(DataPackageView clipboardData, MediaEncodingProfile baseOutputProfile, string extension, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
Logger.LogTrace();
|
||||
|
||||
var inputFiles = await clipboardData.GetStorageItemsAsync();
|
||||
|
||||
if (inputFiles.Count != 1)
|
||||
{
|
||||
throw new InvalidOperationException($"{nameof(TranscodeMediaAsync)} does not support multiple files");
|
||||
}
|
||||
|
||||
var inputFile = inputFiles.Single() as StorageFile ?? throw new InvalidOperationException($"{nameof(TranscodeMediaAsync)} only supports files");
|
||||
var inputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFile.Path);
|
||||
|
||||
var inputProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
|
||||
var outputProfile = CreateOutputProfile(inputProfile, baseOutputProfile);
|
||||
|
||||
#if DEBUG
|
||||
static string ProfileToString(MediaEncodingProfile profile) => System.Text.Json.JsonSerializer.Serialize(profile, options: new() { WriteIndented = true });
|
||||
Logger.LogDebug($"{nameof(inputProfile)}: {ProfileToString(inputProfile)}");
|
||||
Logger.LogDebug($"{nameof(outputProfile)}: {ProfileToString(outputProfile)}");
|
||||
#endif
|
||||
|
||||
var outputFolder = await Task.Run(() => Directory.CreateTempSubdirectory("PowerToys_AdvancedPaste_"), cancellationToken);
|
||||
var outputFileName = StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(inputFile.Path), extension) ? inputFileNameWithoutExtension + "_1" : inputFileNameWithoutExtension;
|
||||
var outputFilePath = Path.Combine(outputFolder.FullName, Path.ChangeExtension(outputFileName, extension));
|
||||
await File.WriteAllBytesAsync(outputFilePath, [], cancellationToken); // TranscodeAsync seems to require the output file to exist
|
||||
|
||||
await TranscodeMediaAsync(inputFile, await StorageFile.GetFileFromPathAsync(outputFilePath), outputProfile, cancellationToken, progress);
|
||||
|
||||
return await DataPackageHelpers.CreateFromFileAsync(outputFilePath);
|
||||
}
|
||||
|
||||
private static MediaEncodingProfile CreateOutputProfile(MediaEncodingProfile inputProfile, MediaEncodingProfile baseOutputProfile)
|
||||
{
|
||||
MediaEncodingProfile outputProfile = new()
|
||||
{
|
||||
Video = null,
|
||||
Audio = null,
|
||||
};
|
||||
|
||||
outputProfile.Container = baseOutputProfile.Container.Copy();
|
||||
|
||||
if (inputProfile.Video != null && baseOutputProfile.Video != null)
|
||||
{
|
||||
outputProfile.Video = baseOutputProfile.Video.Copy();
|
||||
|
||||
if (inputProfile.Video.Bitrate != 0)
|
||||
{
|
||||
outputProfile.Video.Bitrate = inputProfile.Video.Bitrate;
|
||||
}
|
||||
|
||||
if (inputProfile.Video.FrameRate.Numerator != 0)
|
||||
{
|
||||
outputProfile.Video.FrameRate.Numerator = inputProfile.Video.FrameRate.Numerator;
|
||||
}
|
||||
|
||||
if (inputProfile.Video.FrameRate.Denominator != 0)
|
||||
{
|
||||
outputProfile.Video.FrameRate.Denominator = inputProfile.Video.FrameRate.Denominator;
|
||||
}
|
||||
|
||||
if (inputProfile.Video.PixelAspectRatio.Numerator != 0)
|
||||
{
|
||||
outputProfile.Video.PixelAspectRatio.Numerator = inputProfile.Video.PixelAspectRatio.Numerator;
|
||||
}
|
||||
|
||||
if (inputProfile.Video.PixelAspectRatio.Denominator != 0)
|
||||
{
|
||||
outputProfile.Video.PixelAspectRatio.Denominator = inputProfile.Video.PixelAspectRatio.Denominator;
|
||||
}
|
||||
|
||||
outputProfile.Video.Width = inputProfile.Video.Width;
|
||||
outputProfile.Video.Height = inputProfile.Video.Height;
|
||||
}
|
||||
|
||||
if (inputProfile.Audio != null && baseOutputProfile.Audio != null)
|
||||
{
|
||||
outputProfile.Audio = baseOutputProfile.Audio.Copy();
|
||||
|
||||
if (inputProfile.Audio.Bitrate != 0)
|
||||
{
|
||||
outputProfile.Audio.Bitrate = inputProfile.Audio.Bitrate;
|
||||
}
|
||||
|
||||
if (inputProfile.Audio.BitsPerSample != 0)
|
||||
{
|
||||
outputProfile.Audio.BitsPerSample = inputProfile.Audio.BitsPerSample;
|
||||
}
|
||||
|
||||
if (inputProfile.Audio.ChannelCount != 0)
|
||||
{
|
||||
outputProfile.Audio.ChannelCount = inputProfile.Audio.ChannelCount;
|
||||
}
|
||||
|
||||
if (inputProfile.Audio.SampleRate != 0)
|
||||
{
|
||||
outputProfile.Audio.SampleRate = inputProfile.Audio.SampleRate;
|
||||
}
|
||||
}
|
||||
|
||||
return outputProfile;
|
||||
}
|
||||
|
||||
private static async Task TranscodeMediaAsync(StorageFile inputFile, StorageFile outputFile, MediaEncodingProfile outputProfile, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
if (outputProfile.Video == null && outputProfile.Audio == null)
|
||||
{
|
||||
throw new InvalidOperationException("Target profile does not contain media");
|
||||
}
|
||||
|
||||
async Task<PrepareTranscodeResult> GetPrepareResult(bool hardwareAccelerationEnabled)
|
||||
{
|
||||
MediaTranscoder transcoder = new()
|
||||
{
|
||||
AlwaysReencode = false,
|
||||
HardwareAccelerationEnabled = hardwareAccelerationEnabled,
|
||||
};
|
||||
|
||||
return await transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, outputProfile);
|
||||
}
|
||||
|
||||
var prepareResult = await GetPrepareResult(hardwareAccelerationEnabled: true);
|
||||
|
||||
if (!prepareResult.CanTranscode)
|
||||
{
|
||||
Logger.LogWarning($"Unable to transcode with hardware acceleration enabled, falling back to software; {nameof(prepareResult.FailureReason)}={prepareResult.FailureReason}");
|
||||
|
||||
prepareResult = await GetPrepareResult(hardwareAccelerationEnabled: false);
|
||||
}
|
||||
|
||||
if (!prepareResult.CanTranscode)
|
||||
{
|
||||
var message = ResourceLoaderInstance.ResourceLoader.GetString(prepareResult.FailureReason == TranscodeFailureReason.CodecNotFound ? "TranscodeErrorUnsupportedCodec" : "TranscodeErrorGeneral");
|
||||
throw new PasteActionException(message, new InvalidOperationException($"Error transcoding; {nameof(prepareResult.FailureReason)}={prepareResult.FailureReason}"));
|
||||
}
|
||||
|
||||
await prepareResult.TranscodeAsync().AsTask(cancellationToken, progress);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Models;
|
||||
@@ -17,17 +18,19 @@ namespace AdvancedPaste.Helpers;
|
||||
|
||||
public static class TransformHelpers
|
||||
{
|
||||
public static async Task<DataPackage> TransformAsync(PasteFormats format, DataPackageView clipboardData)
|
||||
public static async Task<DataPackage> TransformAsync(PasteFormats format, DataPackageView clipboardData, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
return format switch
|
||||
{
|
||||
PasteFormats.PlainText => await ToPlainTextAsync(clipboardData),
|
||||
PasteFormats.Markdown => await ToMarkdownAsync(clipboardData),
|
||||
PasteFormats.Json => await ToJsonAsync(clipboardData),
|
||||
PasteFormats.ImageToText => await ImageToTextAsync(clipboardData),
|
||||
PasteFormats.PasteAsTxtFile => await ToTxtFileAsync(clipboardData),
|
||||
PasteFormats.PasteAsPngFile => await ToPngFileAsync(clipboardData),
|
||||
PasteFormats.PasteAsHtmlFile => await ToHtmlFileAsync(clipboardData),
|
||||
PasteFormats.ImageToText => await ImageToTextAsync(clipboardData, cancellationToken),
|
||||
PasteFormats.PasteAsTxtFile => await ToTxtFileAsync(clipboardData, cancellationToken),
|
||||
PasteFormats.PasteAsPngFile => await ToPngFileAsync(clipboardData, cancellationToken),
|
||||
PasteFormats.PasteAsHtmlFile => await ToHtmlFileAsync(clipboardData, cancellationToken),
|
||||
PasteFormats.TranscodeToMp3 => await TranscodeHelpers.TranscodeToMp3Async(clipboardData, cancellationToken, progress),
|
||||
PasteFormats.TranscodeToMp4 => await TranscodeHelpers.TranscodeToMp4Async(clipboardData, cancellationToken, progress),
|
||||
PasteFormats.KernelQuery => throw new ArgumentException($"Unsupported format {format}", nameof(format)),
|
||||
PasteFormats.CustomTextTransformation => throw new ArgumentException($"Unsupported format {format}", nameof(format)),
|
||||
_ => throw new ArgumentException($"Unknown value {format}", nameof(format)),
|
||||
@@ -52,16 +55,16 @@ public static class TransformHelpers
|
||||
return CreateDataPackageFromText(await JsonHelper.ToJsonFromXmlOrCsvAsync(clipboardData));
|
||||
}
|
||||
|
||||
private static async Task<DataPackage> ImageToTextAsync(DataPackageView clipboardData)
|
||||
private static async Task<DataPackage> ImageToTextAsync(DataPackageView clipboardData, CancellationToken cancellationToken)
|
||||
{
|
||||
Logger.LogTrace();
|
||||
|
||||
var bitmap = await clipboardData.GetImageContentAsync() ?? throw new ArgumentException("No image content found in clipboard", nameof(clipboardData));
|
||||
var text = await OcrHelpers.ExtractTextAsync(bitmap);
|
||||
var text = await OcrHelpers.ExtractTextAsync(bitmap, cancellationToken);
|
||||
return CreateDataPackageFromText(text);
|
||||
}
|
||||
|
||||
private static async Task<DataPackage> ToPngFileAsync(DataPackageView clipboardData)
|
||||
private static async Task<DataPackage> ToPngFileAsync(DataPackageView clipboardData, CancellationToken cancellationToken)
|
||||
{
|
||||
Logger.LogTrace();
|
||||
|
||||
@@ -72,25 +75,25 @@ public static class TransformHelpers
|
||||
encoder.SetSoftwareBitmap(clipboardBitmap);
|
||||
await encoder.FlushAsync();
|
||||
|
||||
return await CreateDataPackageFromFileContentAsync(pngStream.AsStreamForRead(), "png");
|
||||
return await CreateDataPackageFromFileContentAsync(pngStream.AsStreamForRead(), "png", cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task<DataPackage> ToTxtFileAsync(DataPackageView clipboardData)
|
||||
private static async Task<DataPackage> ToTxtFileAsync(DataPackageView clipboardData, CancellationToken cancellationToken)
|
||||
{
|
||||
Logger.LogTrace();
|
||||
|
||||
var text = await clipboardData.GetTextOrHtmlTextAsync();
|
||||
return await CreateDataPackageFromFileContentAsync(text, "txt");
|
||||
return await CreateDataPackageFromFileContentAsync(text, "txt", cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task<DataPackage> ToHtmlFileAsync(DataPackageView clipboardData)
|
||||
private static async Task<DataPackage> ToHtmlFileAsync(DataPackageView clipboardData, CancellationToken cancellationToken)
|
||||
{
|
||||
Logger.LogTrace();
|
||||
|
||||
var cfHtml = await clipboardData.GetHtmlContentAsync();
|
||||
var html = RemoveHtmlMetadata(cfHtml);
|
||||
|
||||
return await CreateDataPackageFromFileContentAsync(html, "html");
|
||||
return await CreateDataPackageFromFileContentAsync(html, "html", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -114,7 +117,7 @@ public static class TransformHelpers
|
||||
return (startFragmentIndex == null || endFragmentIndex == null) ? cfHtml : cfHtml[startFragmentIndex.Value..endFragmentIndex.Value];
|
||||
}
|
||||
|
||||
private static async Task<DataPackage> CreateDataPackageFromFileContentAsync(string data, string fileExtension)
|
||||
private static async Task<DataPackage> CreateDataPackageFromFileContentAsync(string data, string fileExtension, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
@@ -123,16 +126,16 @@ public static class TransformHelpers
|
||||
|
||||
var path = GetPasteAsFileTempFilePath(fileExtension);
|
||||
|
||||
await File.WriteAllTextAsync(path, data);
|
||||
await File.WriteAllTextAsync(path, data, cancellationToken);
|
||||
return await DataPackageHelpers.CreateFromFileAsync(path);
|
||||
}
|
||||
|
||||
private static async Task<DataPackage> CreateDataPackageFromFileContentAsync(Stream stream, string fileExtension)
|
||||
private static async Task<DataPackage> CreateDataPackageFromFileContentAsync(Stream stream, string fileExtension, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = GetPasteAsFileTempFilePath(fileExtension);
|
||||
|
||||
using var fileStream = File.Create(path);
|
||||
await stream.CopyToAsync(fileStream);
|
||||
await stream.CopyToAsync(fileStream, cancellationToken);
|
||||
|
||||
return await DataPackageHelpers.CreateFromFileAsync(path);
|
||||
}
|
||||
|
||||
@@ -108,7 +108,9 @@ namespace AdvancedPaste.Settings
|
||||
(PasteFormats.ImageToText, [sourceAdditionalActions.ImageToText]),
|
||||
(PasteFormats.PasteAsTxtFile, [sourceAdditionalActions.PasteAsFile, sourceAdditionalActions.PasteAsFile.PasteAsTxtFile]),
|
||||
(PasteFormats.PasteAsPngFile, [sourceAdditionalActions.PasteAsFile, sourceAdditionalActions.PasteAsFile.PasteAsPngFile]),
|
||||
(PasteFormats.PasteAsHtmlFile, [sourceAdditionalActions.PasteAsFile, sourceAdditionalActions.PasteAsFile.PasteAsHtmlFile])
|
||||
(PasteFormats.PasteAsHtmlFile, [sourceAdditionalActions.PasteAsFile, sourceAdditionalActions.PasteAsFile.PasteAsHtmlFile]),
|
||||
(PasteFormats.TranscodeToMp3, [sourceAdditionalActions.Transcode, sourceAdditionalActions.Transcode.TranscodeToMp3]),
|
||||
(PasteFormats.TranscodeToMp4, [sourceAdditionalActions.Transcode, sourceAdditionalActions.Transcode.TranscodeToMp4]),
|
||||
];
|
||||
|
||||
_additionalActions.Clear();
|
||||
|
||||
@@ -13,6 +13,7 @@ public enum ClipboardFormat
|
||||
Text = 1 << 0,
|
||||
Html = 1 << 1,
|
||||
Audio = 1 << 2,
|
||||
Image = 1 << 3,
|
||||
File = 1 << 4, // output only for now
|
||||
Video = 1 << 3,
|
||||
Image = 1 << 4,
|
||||
File = 1 << 5, // output only for now
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ public sealed class PasteActionError
|
||||
public static PasteActionError FromException(Exception ex) =>
|
||||
new()
|
||||
{
|
||||
Text = ex is PasteActionException ? ex.Message : ResourceLoaderInstance.ResourceLoader.GetString("PasteError"),
|
||||
Text = ex is PasteActionException ? ex.Message : ResourceLoaderInstance.ResourceLoader.GetString(ex is OperationCanceledException ? "PasteActionCanceled" : "PasteError"),
|
||||
Details = (ex as PasteActionException)?.AIServiceMessage ?? string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -82,12 +82,34 @@ public enum PasteFormats
|
||||
KernelFunctionDescription = "Takes HTML data in the clipboard and transforms it to an HTML file.")]
|
||||
PasteAsHtmlFile,
|
||||
|
||||
[PasteFormatMetadata(
|
||||
IsCoreAction = false,
|
||||
ResourceId = "TranscodeToMp3",
|
||||
IconGlyph = "\uE8D6",
|
||||
RequiresAIService = false,
|
||||
CanPreview = false,
|
||||
SupportedClipboardFormats = ClipboardFormat.Audio | ClipboardFormat.Video,
|
||||
IPCKey = AdvancedPasteTranscodeAction.PropertyNames.TranscodeToMp3,
|
||||
KernelFunctionDescription = "Takes an audio or video file in the clipboard and transcodes it to MP3.")]
|
||||
TranscodeToMp3,
|
||||
|
||||
[PasteFormatMetadata(
|
||||
IsCoreAction = false,
|
||||
ResourceId = "TranscodeToMp4",
|
||||
IconGlyph = "\uE714",
|
||||
RequiresAIService = false,
|
||||
CanPreview = false,
|
||||
SupportedClipboardFormats = ClipboardFormat.Video,
|
||||
IPCKey = AdvancedPasteTranscodeAction.PropertyNames.TranscodeToMp4,
|
||||
KernelFunctionDescription = "Takes a video file in the clipboard and transcodes it to MP4 (H.264/AAC).")]
|
||||
TranscodeToMp4,
|
||||
|
||||
[PasteFormatMetadata(
|
||||
IsCoreAction = false,
|
||||
IconGlyph = "\uE945",
|
||||
RequiresAIService = true,
|
||||
CanPreview = true,
|
||||
SupportedClipboardFormats = ClipboardFormat.Text | ClipboardFormat.Html | ClipboardFormat.Audio | ClipboardFormat.Image,
|
||||
SupportedClipboardFormats = ClipboardFormat.Text | ClipboardFormat.Html | ClipboardFormat.Audio | ClipboardFormat.Video | ClipboardFormat.Image,
|
||||
RequiresPrompt = true)]
|
||||
KernelQuery,
|
||||
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AdvancedPaste.Services;
|
||||
|
||||
public interface ICustomTextTransformService
|
||||
{
|
||||
Task<string> TransformTextAsync(string prompt, string inputText);
|
||||
Task<string> TransformTextAsync(string prompt, string inputText, CancellationToken cancellationToken, IProgress<double> progress);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Windows.ApplicationModel.DataTransfer;
|
||||
@@ -10,5 +12,5 @@ namespace AdvancedPaste.Services;
|
||||
|
||||
public interface IKernelService
|
||||
{
|
||||
Task<DataPackage> TransformClipboardAsync(string prompt, DataPackageView clipboardData, bool isSavedQuery);
|
||||
Task<DataPackage> TransformClipboardAsync(string prompt, DataPackageView clipboardData, bool isSavedQuery, CancellationToken cancellationToken, IProgress<double> progress);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Models;
|
||||
@@ -11,5 +13,5 @@ namespace AdvancedPaste.Services;
|
||||
|
||||
public interface IPasteFormatExecutor
|
||||
{
|
||||
Task<DataPackage> ExecutePasteFormatAsync(PasteFormat pasteFormat, PasteActionSource source);
|
||||
Task<DataPackage> ExecutePasteFormatAsync(PasteFormat pasteFormat, PasteActionSource source, CancellationToken cancellationToken, IProgress<double> progress);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AdvancedPaste.Services;
|
||||
|
||||
public interface IPromptModerationService
|
||||
{
|
||||
Task ValidateAsync(string fullPrompt);
|
||||
Task ValidateAsync(string fullPrompt, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -36,12 +37,14 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
|
||||
protected abstract AIServiceUsage GetAIServiceUsage(ChatMessageContent chatMessage);
|
||||
|
||||
public async Task<DataPackage> TransformClipboardAsync(string prompt, DataPackageView clipboardData, bool isSavedQuery)
|
||||
public async Task<DataPackage> TransformClipboardAsync(string prompt, DataPackageView clipboardData, bool isSavedQuery, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
Logger.LogTrace();
|
||||
|
||||
var kernel = CreateKernel();
|
||||
kernel.SetDataPackageView(clipboardData);
|
||||
kernel.SetCancellationToken(cancellationToken);
|
||||
kernel.SetProgress(progress);
|
||||
|
||||
CacheKey cacheKey = new() { Prompt = prompt, AvailableFormats = await clipboardData.GetAvailableFormatsAsync() };
|
||||
var maybeCacheValue = _queryCacheService.ReadOrNull(cacheKey);
|
||||
@@ -51,7 +54,7 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
|
||||
try
|
||||
{
|
||||
(chatHistory, var usage) = cacheUsed ? await ExecuteCachedActionChain(kernel, maybeCacheValue.ActionChain) : await ExecuteAICompletion(kernel, prompt);
|
||||
(chatHistory, var usage) = cacheUsed ? await ExecuteCachedActionChain(kernel, maybeCacheValue.ActionChain) : await ExecuteAICompletion(kernel, prompt, cancellationToken);
|
||||
|
||||
LogResult(cacheUsed, isSavedQuery, kernel.GetOrAddActionChain(), usage);
|
||||
|
||||
@@ -84,7 +87,7 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
AdvancedPasteSemanticKernelErrorEvent errorEvent = new(ex is PasteActionModeratedException ? PasteActionModeratedException.ErrorDescription : ex.Message);
|
||||
PowerToysTelemetry.Log.WriteEvent(errorEvent);
|
||||
|
||||
if (ex is PasteActionException)
|
||||
if (ex is PasteActionException or OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
@@ -127,7 +130,7 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
return $"{combinedSystemMessage}{newLine}{newLine}User instructions:{newLine}{userPromptMessage.Content}";
|
||||
}
|
||||
|
||||
private async Task<(ChatHistory ChatHistory, AIServiceUsage Usage)> ExecuteAICompletion(Kernel kernel, string prompt)
|
||||
private async Task<(ChatHistory ChatHistory, AIServiceUsage Usage)> ExecuteAICompletion(Kernel kernel, string prompt, CancellationToken cancellationToken)
|
||||
{
|
||||
ChatHistory chatHistory = [];
|
||||
|
||||
@@ -141,10 +144,10 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
chatHistory.AddSystemMessage($"Available clipboard formats: {await kernel.GetDataFormatsAsync()}");
|
||||
chatHistory.AddUserMessage(prompt);
|
||||
|
||||
await _promptModerationService.ValidateAsync(GetFullPrompt(chatHistory));
|
||||
await _promptModerationService.ValidateAsync(GetFullPrompt(chatHistory), cancellationToken);
|
||||
|
||||
var chatResult = await kernel.GetRequiredService<IChatCompletionService>()
|
||||
.GetChatMessageContentAsync(chatHistory, PromptExecutionSettings, kernel);
|
||||
.GetChatMessageContentAsync(chatHistory, PromptExecutionSettings, kernel, cancellationToken);
|
||||
chatHistory.Add(chatResult);
|
||||
|
||||
var totalUsage = chatHistory.Select(GetAIServiceUsage)
|
||||
@@ -157,6 +160,8 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
{
|
||||
foreach (var item in actionChain)
|
||||
{
|
||||
kernel.GetCancellationToken().ThrowIfCancellationRequested();
|
||||
|
||||
if (item.Arguments.Count > 0)
|
||||
{
|
||||
await ExecutePromptTransformAsync(kernel, item.Format, item.Arguments[PromptParameterName]);
|
||||
@@ -208,14 +213,14 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
async dataPackageView =>
|
||||
{
|
||||
var input = await dataPackageView.GetTextAsync();
|
||||
string output = await GetPromptBasedOutput(format, prompt, input);
|
||||
string output = await GetPromptBasedOutput(format, prompt, input, kernel.GetCancellationToken(), kernel.GetProgress());
|
||||
return DataPackageHelpers.CreateFromText(output);
|
||||
});
|
||||
|
||||
private async Task<string> GetPromptBasedOutput(PasteFormats format, string prompt, string input) =>
|
||||
private async Task<string> GetPromptBasedOutput(PasteFormats format, string prompt, string input, CancellationToken cancellationToken, IProgress<double> progress) =>
|
||||
format switch
|
||||
{
|
||||
PasteFormats.CustomTextTransformation => await _customTextTransformService.TransformTextAsync(prompt, input),
|
||||
PasteFormats.CustomTextTransformation => await _customTextTransformService.TransformTextAsync(prompt, input, cancellationToken, progress),
|
||||
_ => throw new ArgumentException($"Unsupported format {format} for prompt transform", nameof(format)),
|
||||
};
|
||||
|
||||
@@ -223,7 +228,7 @@ public abstract class KernelServiceBase(IKernelQueryCacheService queryCacheServi
|
||||
ExecuteTransformAsync(
|
||||
kernel,
|
||||
new ActionChainItem(format, Arguments: []),
|
||||
async dataPackageView => await TransformHelpers.TransformAsync(format, dataPackageView));
|
||||
async dataPackageView => await TransformHelpers.TransformAsync(format, dataPackageView, kernel.GetCancellationToken(), kernel.GetProgress()));
|
||||
|
||||
private static async Task<string> ExecuteTransformAsync(Kernel kernel, ActionChainItem actionChainItem, Func<DataPackageView, Task<DataPackage>> transformFunc)
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -23,11 +24,11 @@ public sealed class CustomTextTransformService(IAICredentialsProvider aiCredenti
|
||||
private readonly IAICredentialsProvider _aiCredentialsProvider = aiCredentialsProvider;
|
||||
private readonly IPromptModerationService _promptModerationService = promptModerationService;
|
||||
|
||||
private async Task<Completions> GetAICompletionAsync(string systemInstructions, string userMessage)
|
||||
private async Task<Completions> GetAICompletionAsync(string systemInstructions, string userMessage, CancellationToken cancellationToken)
|
||||
{
|
||||
var fullPrompt = systemInstructions + "\n\n" + userMessage;
|
||||
|
||||
await _promptModerationService.ValidateAsync(fullPrompt);
|
||||
await _promptModerationService.ValidateAsync(fullPrompt, cancellationToken);
|
||||
|
||||
OpenAIClient azureAIClient = new(_aiCredentialsProvider.Key);
|
||||
|
||||
@@ -41,7 +42,8 @@ public sealed class CustomTextTransformService(IAICredentialsProvider aiCredenti
|
||||
},
|
||||
Temperature = 0.01F,
|
||||
MaxTokens = 2000,
|
||||
});
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
if (response.Value.Choices[0].FinishReason == "length")
|
||||
{
|
||||
@@ -51,7 +53,7 @@ public sealed class CustomTextTransformService(IAICredentialsProvider aiCredenti
|
||||
return response;
|
||||
}
|
||||
|
||||
public async Task<string> TransformTextAsync(string prompt, string inputText)
|
||||
public async Task<string> TransformTextAsync(string prompt, string inputText, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(prompt))
|
||||
{
|
||||
@@ -80,7 +82,7 @@ Output:
|
||||
|
||||
try
|
||||
{
|
||||
var response = await GetAICompletionAsync(systemInstructions, userMessage);
|
||||
var response = await GetAICompletionAsync(systemInstructions, userMessage, cancellationToken);
|
||||
|
||||
var usage = response.Usage;
|
||||
AdvancedPasteGenerateCustomFormatEvent telemetryEvent = new(usage.PromptTokens, usage.CompletionTokens, ModelName);
|
||||
@@ -98,7 +100,7 @@ Output:
|
||||
AdvancedPasteGenerateCustomErrorEvent errorEvent = new(ex is PasteActionModeratedException ? PasteActionModeratedException.ErrorDescription : ex.Message);
|
||||
PowerToysTelemetry.Log.WriteEvent(errorEvent);
|
||||
|
||||
if (ex is PasteActionException)
|
||||
if (ex is PasteActionException or OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.ClientModel;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -18,12 +19,12 @@ public sealed class PromptModerationService(IAICredentialsProvider aiCredentials
|
||||
|
||||
private readonly IAICredentialsProvider _aiCredentialsProvider = aiCredentialsProvider;
|
||||
|
||||
public async Task ValidateAsync(string fullPrompt)
|
||||
public async Task ValidateAsync(string fullPrompt, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
ModerationClient moderationClient = new(ModelName, _aiCredentialsProvider.Key);
|
||||
var moderationClientResult = await moderationClient.ClassifyTextAsync(fullPrompt);
|
||||
var moderationClientResult = await moderationClient.ClassifyTextAsync(fullPrompt, cancellationToken);
|
||||
var moderationResult = moderationClientResult.Value;
|
||||
|
||||
Logger.LogDebug($"{nameof(PromptModerationService)}.{nameof(ValidateAsync)} complete; {nameof(moderationResult.Flagged)}={moderationResult.Flagged}");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -17,7 +18,7 @@ public sealed class PasteFormatExecutor(IKernelService kernelService, ICustomTex
|
||||
private readonly IKernelService _kernelService = kernelService;
|
||||
private readonly ICustomTextTransformService _customTextTransformService = customTextTransformService;
|
||||
|
||||
public async Task<DataPackage> ExecutePasteFormatAsync(PasteFormat pasteFormat, PasteActionSource source)
|
||||
public async Task<DataPackage> ExecutePasteFormatAsync(PasteFormat pasteFormat, PasteActionSource source, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
if (!pasteFormat.IsEnabled)
|
||||
{
|
||||
@@ -34,9 +35,9 @@ public sealed class PasteFormatExecutor(IKernelService kernelService, ICustomTex
|
||||
return await Task.Run(async () =>
|
||||
pasteFormat.Format switch
|
||||
{
|
||||
PasteFormats.KernelQuery => await _kernelService.TransformClipboardAsync(pasteFormat.Prompt, clipboardData, pasteFormat.IsSavedQuery),
|
||||
PasteFormats.CustomTextTransformation => DataPackageHelpers.CreateFromText(await _customTextTransformService.TransformTextAsync(pasteFormat.Prompt, await clipboardData.GetTextAsync())),
|
||||
_ => await TransformHelpers.TransformAsync(format, clipboardData),
|
||||
PasteFormats.KernelQuery => await _kernelService.TransformClipboardAsync(pasteFormat.Prompt, clipboardData, pasteFormat.IsSavedQuery, cancellationToken, progress),
|
||||
PasteFormats.CustomTextTransformation => DataPackageHelpers.CreateFromText(await _customTextTransformService.TransformTextAsync(pasteFormat.Prompt, await clipboardData.GetTextAsync(), cancellationToken, progress)),
|
||||
_ => await TransformHelpers.TransformAsync(format, clipboardData, cancellationToken, progress),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -135,6 +135,9 @@
|
||||
<data name="OpenAIApiKeyError" xml:space="preserve">
|
||||
<value>OpenAI request failed with status code: </value>
|
||||
</data>
|
||||
<data name="PasteActionCanceled" xml:space="preserve">
|
||||
<value>The paste operation was canceled</value>
|
||||
</data>
|
||||
<data name="PasteError" xml:space="preserve">
|
||||
<value>An error occurred during the paste operation</value>
|
||||
</data>
|
||||
@@ -188,7 +191,19 @@
|
||||
</data>
|
||||
<data name="PasteAsHtmlFile" xml:space="preserve">
|
||||
<value>Paste as .html file</value>
|
||||
</data>
|
||||
<data name="TranscodeToMp3" xml:space="preserve">
|
||||
<value>Transcode to .mp3</value>
|
||||
</data>
|
||||
<data name="TranscodeToMp4" xml:space="preserve">
|
||||
<value>Transcode to .mp4 (H.264/AAC)</value>
|
||||
</data>
|
||||
<data name="TranscodeErrorGeneral" xml:space="preserve">
|
||||
<value>An error occurred while transcoding media file</value>
|
||||
</data>
|
||||
<data name="TranscodeErrorUnsupportedCodec" xml:space="preserve">
|
||||
<value>The media file contains an unsupported codec</value>
|
||||
</data>
|
||||
<data name="PasteButtonAutomation.[using:Microsoft.UI.Xaml.Automation]AutomationProperties.Name" xml:space="preserve">
|
||||
<value>Paste</value>
|
||||
</data>
|
||||
@@ -207,6 +222,9 @@
|
||||
<data name="SendBtnToolTip.Text" xml:space="preserve">
|
||||
<value>Generate and paste data</value>
|
||||
</data>
|
||||
<data name="CancelBtnToolTip.Text" xml:space="preserve">
|
||||
<value>Cancel paste operation</value>
|
||||
</data>
|
||||
<data name="RegenerateBtnToolTip.Text" xml:space="preserve">
|
||||
<value>Regenerate</value>
|
||||
</data>
|
||||
@@ -216,6 +234,9 @@
|
||||
<data name="SendButtonAutomation.[using:Microsoft.UI.Xaml.Automation]AutomationProperties.Name" xml:space="preserve">
|
||||
<value>Generate and paste data</value>
|
||||
</data>
|
||||
<data name="CancelBtnAutomation.[using:Microsoft.UI.Xaml.Automation]AutomationProperties.Name" xml:space="preserve">
|
||||
<value>Cancel paste operation</value>
|
||||
</data>
|
||||
<data name="SettingsBtn.Content" xml:space="preserve">
|
||||
<value>Open settings</value>
|
||||
</data>
|
||||
|
||||
@@ -8,6 +8,8 @@ using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using AdvancedPaste.Helpers;
|
||||
@@ -29,7 +31,7 @@ using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue;
|
||||
|
||||
namespace AdvancedPaste.ViewModels
|
||||
{
|
||||
public sealed partial class OptionsViewModel : ObservableObject, IDisposable
|
||||
public sealed partial class OptionsViewModel : ObservableObject, IProgress<double>, IDisposable
|
||||
{
|
||||
private readonly DispatcherQueue _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
|
||||
private readonly DispatcherTimer _clipboardTimer;
|
||||
@@ -37,6 +39,8 @@ namespace AdvancedPaste.ViewModels
|
||||
private readonly IPasteFormatExecutor _pasteFormatExecutor;
|
||||
private readonly IAICredentialsProvider _aiCredentialsProvider;
|
||||
|
||||
private CancellationTokenSource _pasteActionCancellationTokenSource;
|
||||
|
||||
public DataPackageView ClipboardData { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
@@ -65,7 +69,11 @@ namespace AdvancedPaste.ViewModels
|
||||
private bool _pasteFormatsDirty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _busy;
|
||||
private bool _isBusy;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasIndeterminateTransformProgress))]
|
||||
private double _transformProgress = double.NaN;
|
||||
|
||||
public ObservableCollection<PasteFormat> StandardPasteFormats { get; } = [];
|
||||
|
||||
@@ -81,9 +89,24 @@ namespace AdvancedPaste.ViewModels
|
||||
|
||||
public bool ClipboardHasDataForCustomAI => PasteFormat.SupportsClipboardFormats(CustomAIFormat, AvailableClipboardFormats);
|
||||
|
||||
public bool HasIndeterminateTransformProgress => double.IsNaN(TransformProgress);
|
||||
|
||||
private PasteFormats CustomAIFormat => _userSettings.IsAdvancedAIEnabled ? PasteFormats.KernelQuery : PasteFormats.CustomTextTransformation;
|
||||
|
||||
private bool Visible => GetMainWindow()?.Visible is true;
|
||||
private bool Visible
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
return GetMainWindow()?.Visible is true;
|
||||
}
|
||||
catch (COMException)
|
||||
{
|
||||
return false; // window is closed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event EventHandler PreviewRequested;
|
||||
|
||||
@@ -189,7 +212,12 @@ namespace AdvancedPaste.ViewModels
|
||||
|
||||
void UpdateFormats(ObservableCollection<PasteFormat> collection, IEnumerable<PasteFormat> pasteFormats)
|
||||
{
|
||||
collection.Clear();
|
||||
// Hack: Clear collection via repeated RemoveAt to avoid this crash, which seems to occasionally occur when using Clear:
|
||||
// https://github.com/microsoft/microsoft-ui-xaml/issues/8684
|
||||
while (collection.Count > 0)
|
||||
{
|
||||
collection.RemoveAt(collection.Count - 1);
|
||||
}
|
||||
|
||||
foreach (var format in FilterAndSort(pasteFormats))
|
||||
{
|
||||
@@ -214,12 +242,13 @@ namespace AdvancedPaste.ViewModels
|
||||
public void Dispose()
|
||||
{
|
||||
_clipboardTimer.Stop();
|
||||
_pasteActionCancellationTokenSource?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public async Task ReadClipboardAsync()
|
||||
{
|
||||
if (Busy)
|
||||
if (IsBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -324,6 +353,10 @@ namespace AdvancedPaste.ViewModels
|
||||
{
|
||||
await ClipboardHelper.TryCopyPasteAsync(package, HideWindow);
|
||||
Query = string.Empty;
|
||||
|
||||
// Delete any temp files created. A delay is needed to ensure the file is not in use by the target application -
|
||||
// for example, when pasting onto File Explorer, the paste operation will trigger a file copy.
|
||||
_ = Task.Run(() => package.GetView().TryCleanupAfterDelayAsync(TimeSpan.FromSeconds(30)));
|
||||
}
|
||||
|
||||
// Command to select the previous custom format
|
||||
@@ -362,7 +395,7 @@ namespace AdvancedPaste.ViewModels
|
||||
|
||||
internal async Task ExecutePasteFormatAsync(PasteFormat pasteFormat, PasteActionSource source)
|
||||
{
|
||||
if (Busy)
|
||||
if (IsBusy)
|
||||
{
|
||||
Logger.LogWarning($"Execution of {pasteFormat.Format} from {source} suppressed as busy");
|
||||
return;
|
||||
@@ -377,16 +410,18 @@ namespace AdvancedPaste.ViewModels
|
||||
var elapsedWatch = Stopwatch.StartNew();
|
||||
Logger.LogDebug($"Started executing {pasteFormat.Format} from source {source}");
|
||||
|
||||
Busy = true;
|
||||
IsBusy = true;
|
||||
_pasteActionCancellationTokenSource = new();
|
||||
TransformProgress = double.NaN;
|
||||
PasteActionError = PasteActionError.None;
|
||||
Query = pasteFormat.Query;
|
||||
|
||||
try
|
||||
{
|
||||
// Minimum time to show busy spinner for AI actions when triggered by global keyboard shortcut.
|
||||
var aiActionMinTaskTime = TimeSpan.FromSeconds(2);
|
||||
var aiActionMinTaskTime = TimeSpan.FromSeconds(1.5);
|
||||
var delayTask = (Visible && source == PasteActionSource.GlobalKeyboardShortcut) ? Task.Delay(aiActionMinTaskTime) : Task.CompletedTask;
|
||||
var dataPackage = await _pasteFormatExecutor.ExecutePasteFormatAsync(pasteFormat, source);
|
||||
var dataPackage = await _pasteFormatExecutor.ExecutePasteFormatAsync(pasteFormat, source, _pasteActionCancellationTokenSource.Token, this);
|
||||
|
||||
await delayTask;
|
||||
|
||||
@@ -410,7 +445,9 @@ namespace AdvancedPaste.ViewModels
|
||||
PasteActionError = PasteActionError.FromException(ex);
|
||||
}
|
||||
|
||||
Busy = false;
|
||||
IsBusy = false;
|
||||
_pasteActionCancellationTokenSource?.Dispose();
|
||||
_pasteActionCancellationTokenSource = null;
|
||||
elapsedWatch.Stop();
|
||||
Logger.LogDebug($"Finished executing {pasteFormat.Format} from source {source}; timeTakenMs={elapsedWatch.ElapsedMilliseconds}");
|
||||
}
|
||||
@@ -484,5 +521,26 @@ namespace AdvancedPaste.ViewModels
|
||||
|
||||
return IsAllowedByGPO && _aiCredentialsProvider.Refresh();
|
||||
}
|
||||
|
||||
public async Task CancelPasteActionAsync()
|
||||
{
|
||||
if (_pasteActionCancellationTokenSource != null)
|
||||
{
|
||||
await _pasteActionCancellationTokenSource.CancelAsync();
|
||||
}
|
||||
}
|
||||
|
||||
void IProgress<double>.Report(double value)
|
||||
{
|
||||
ReportProgress(value);
|
||||
}
|
||||
|
||||
private void ReportProgress(double value)
|
||||
{
|
||||
_dispatcherQueue.TryEnqueue(() =>
|
||||
{
|
||||
TransformProgress = value;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,8 @@ void Trace::AdvancedPaste_SettingsTelemetry(const PowertoyModuleIface::Hotkey& p
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"ImageToText"), "ImageToTextHotkey"),
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"PasteAsTxtFile"), "PasteAsTxtFileHotkey"),
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"PasteAsPngFile"), "PasteAsPngFileHotkey"),
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"PasteAsHtmlFile"), "PasteAsHtmlFileHotkey")
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"PasteAsHtmlFile"), "PasteAsHtmlFileHotkey"),
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"TranscodeToMp3"), "TranscodeToMp3Hotkey"),
|
||||
TraceLoggingWideString(getAdditionalActionHotkeyCStr(L"TranscodeToMp4"), "TranscodeToMp4Hotkey")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#include <windows.h>
|
||||
#include "resource.h"
|
||||
#include "../../../common/version/version.h"
|
||||
|
||||
#define APSTUDIO_READONLY_SYMBOLS
|
||||
#include "winres.h"
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
|
||||
1 VERSIONINFO
|
||||
FILEVERSION FILE_VERSION
|
||||
PRODUCTVERSION PRODUCT_VERSION
|
||||
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
|
||||
#ifdef _DEBUG
|
||||
FILEFLAGS VS_FF_DEBUG
|
||||
#else
|
||||
FILEFLAGS 0x0L
|
||||
#endif
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_DLL
|
||||
FILESUBTYPE VFT2_UNKNOWN
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904b0" // US English (0x0409), Unicode (0x04B0) charset
|
||||
BEGIN
|
||||
VALUE "CompanyName", COMPANY_NAME
|
||||
VALUE "FileDescription", FILE_DESCRIPTION
|
||||
VALUE "FileVersion", FILE_VERSION_STRING
|
||||
VALUE "InternalName", INTERNAL_NAME
|
||||
VALUE "LegalCopyright", COPYRIGHT_NOTE
|
||||
VALUE "OriginalFilename", ORIGINAL_FILENAME
|
||||
VALUE "ProductName", PRODUCT_NAME
|
||||
VALUE "ProductVersion", PRODUCT_VERSION_STRING
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1200 // US English (0x0409), Unicode (1200) charset
|
||||
END
|
||||
END
|
||||
@@ -0,0 +1,111 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.240111.5\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.240111.5\build\native\Microsoft.Windows.CppWinRT.props')" />
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>17.0</VCProjectVersion>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<ProjectGuid>{4D6155E2-055B-4B0F-85E8-C3A1AAA54C82}</ProjectGuid>
|
||||
<RootNamespace>CharacterMapModuleInterface</RootNamespace>
|
||||
<ProjectName>CharacterMapModuleInterface</ProjectName>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="Shared">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets">
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<OutDir>..\..\..\..\$(Platform)\$(Configuration)\</OutDir>
|
||||
<TargetName>PowerToys.CharacterMapModuleInterface</TargetName>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>..\;$(SolutionDir)src\common\Telemetry;$(SolutionDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
|
||||
<ClCompile>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableUAC>false</EnableUAC>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
|
||||
<ClCompile>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableUAC>false</EnableUAC>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="pch.h" />
|
||||
<ClInclude Include="resource.h" />
|
||||
<ClInclude Include="trace.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="CharacterMapModuleInterface.rc" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="dllmain.cpp" />
|
||||
<ClCompile Include="pch.cpp">
|
||||
<PrecompiledHeader Condition="'$(UsePrecompiledHeaders)' != 'false'">Create</PrecompiledHeader>
|
||||
</ClCompile>
|
||||
<ClCompile Include="trace.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
|
||||
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\common\SettingsAPI\SettingsAPI.vcxproj">
|
||||
<Project>{6955446d-23f7-4023-9bb3-8657f904af99}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.240111.5\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.240111.5\build\native\Microsoft.Windows.CppWinRT.targets')" />
|
||||
</ImportGroup>
|
||||
<Import Project="..\..\..\..\deps\spdlog.props" />
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
|
||||
</PropertyGroup>
|
||||
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.240111.5\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.240111.5\build\native\Microsoft.Windows.CppWinRT.props'))" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="Source Files">
|
||||
<UniqueIdentifier>{f5f15d18-c8fd-4f95-9bdd-d7229f26bcfe}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Header Files">
|
||||
<UniqueIdentifier>{cf528697-5153-4e00-802d-18b371bbe659}</UniqueIdentifier>
|
||||
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Resource Files">
|
||||
<UniqueIdentifier>{88e6c746-6a4b-47a4-b5da-a78a9b3e92f6}</UniqueIdentifier>
|
||||
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="resource.h">
|
||||
<Filter>Resource Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="pch.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="trace.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="CharacterMapModuleInterface.rc">
|
||||
<Filter>Resource Files</Filter>
|
||||
</ResourceCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="dllmain.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="pch.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="trace.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
270
src/modules/CharacterMap/CharacterMapModuleInterface/dllmain.cpp
Normal file
270
src/modules/CharacterMap/CharacterMapModuleInterface/dllmain.cpp
Normal file
@@ -0,0 +1,270 @@
|
||||
#include "pch.h"
|
||||
|
||||
#include <modules/interface/powertoy_module_interface.h>
|
||||
#include <common/SettingsAPI/settings_objects.h>
|
||||
|
||||
#include "trace.h"
|
||||
#include <common/logger/logger.h>
|
||||
#include <common/utils/logger_helper.h>
|
||||
#include <common/utils/EventWaiter.h>
|
||||
#include <common/utils/resources.h>
|
||||
#include <common/utils/winapi_error.h>
|
||||
|
||||
#include <shellapi.h>
|
||||
#include <common/interop/shared_constants.h>
|
||||
|
||||
namespace NonLocalizable
|
||||
{
|
||||
//const wchar_t ModulePath[] = L"PowerToys.CharacterMap.exe";
|
||||
const inline wchar_t ModuleKey[] = L"CharacterMap";
|
||||
}
|
||||
|
||||
BOOL APIENTRY DllMain( HMODULE /*hModule*/,
|
||||
DWORD ul_reason_for_call,
|
||||
LPVOID /*lpReserved*/
|
||||
)
|
||||
{
|
||||
switch (ul_reason_for_call)
|
||||
{
|
||||
case DLL_PROCESS_ATTACH:
|
||||
Trace::RegisterProvider();
|
||||
break;
|
||||
case DLL_THREAD_ATTACH:
|
||||
case DLL_THREAD_DETACH:
|
||||
break;
|
||||
case DLL_PROCESS_DETACH:
|
||||
Trace::UnregisterProvider();
|
||||
break;
|
||||
}
|
||||
return TRUE;
|
||||
|
||||
}
|
||||
|
||||
class CharacterMapModuleInterface : public PowertoyModuleIface
|
||||
{
|
||||
public:
|
||||
// Return the localized display name of the powertoy
|
||||
virtual PCWSTR get_name() override
|
||||
{
|
||||
return app_name.c_str();
|
||||
}
|
||||
|
||||
// Return the non localized key of the powertoy, this will be cached by the runner
|
||||
virtual const wchar_t* get_key() override
|
||||
{
|
||||
return app_key.c_str();
|
||||
}
|
||||
|
||||
// Return the configured status for the gpo policy for the module
|
||||
virtual powertoys_gpo::gpo_rule_configured_t gpo_policy_enabled_configuration() override
|
||||
{
|
||||
return powertoys_gpo::getConfiguredCharacterMapEnabledValue();
|
||||
}
|
||||
|
||||
// Return JSON with the configuration options.
|
||||
// These are the settings shown on the settings page along with their current values.
|
||||
virtual bool get_config(wchar_t* buffer, int* buffer_size) override
|
||||
{
|
||||
HINSTANCE hinstance = reinterpret_cast<HINSTANCE>(&__ImageBase);
|
||||
|
||||
// TODO: Read settings from Registry.
|
||||
|
||||
// Create a Settings object.
|
||||
PowerToysSettings::Settings settings(hinstance, get_name());
|
||||
|
||||
return settings.serialize_to_buffer(buffer, buffer_size);
|
||||
}
|
||||
|
||||
// Passes JSON with the configuration settings for the powertoy.
|
||||
// This is called when the user hits Save on the settings page.
|
||||
virtual void set_config(const wchar_t*) override
|
||||
{
|
||||
try
|
||||
{
|
||||
// Parse the input JSON string.
|
||||
// TODO: Save settings to registry.
|
||||
}
|
||||
catch (std::exception&)
|
||||
{
|
||||
// Improper JSON.
|
||||
}
|
||||
}
|
||||
|
||||
// Enable the powertoy
|
||||
virtual void enable()
|
||||
{
|
||||
Logger::info("CharacterMap enabling");
|
||||
Enable();
|
||||
}
|
||||
|
||||
// Disable the powertoy
|
||||
virtual void disable()
|
||||
{
|
||||
Logger::info("CharacterMap disabling");
|
||||
Disable(true);
|
||||
}
|
||||
|
||||
// Returns if the powertoy is enabled
|
||||
virtual bool is_enabled() override
|
||||
{
|
||||
return m_enabled;
|
||||
}
|
||||
|
||||
// Destroy the powertoy and free memory
|
||||
virtual void destroy() override
|
||||
{
|
||||
Disable(false);
|
||||
delete this;
|
||||
}
|
||||
|
||||
CharacterMapModuleInterface()
|
||||
{
|
||||
app_name = L"CharacterMap";
|
||||
app_key = NonLocalizable::ModuleKey;
|
||||
LoggerHelpers::init_logger(app_key, L"ModuleInterface", LogSettings::characterMapLoggerName);
|
||||
//m_reload_settings_event_handle = CreateDefaultEvent(CommonSharedConstants::ZOOMIT_REFRESH_SETTINGS_EVENT);
|
||||
//m_exit_event_handle = CreateDefaultEvent(CommonSharedConstants::ZOOMIT_EXIT_EVENT);
|
||||
triggerEvent = CreateEvent(nullptr, false, false, CommonSharedConstants::CHARACTER_MAP_TRIGGER_EVENT);
|
||||
triggerEventWaiter = EventWaiter(CommonSharedConstants::CHARACTER_MAP_TRIGGER_EVENT, [this](int) {
|
||||
on_hotkey(0);
|
||||
});
|
||||
}
|
||||
~CharacterMapModuleInterface()
|
||||
{
|
||||
if (m_enabled)
|
||||
{
|
||||
terminate_process();
|
||||
}
|
||||
m_enabled = false;
|
||||
}
|
||||
|
||||
private:
|
||||
bool is_process_running()
|
||||
{
|
||||
return WaitForSingleObject(m_hProcess, 0) == WAIT_TIMEOUT;
|
||||
}
|
||||
void launch_process()
|
||||
{
|
||||
if (m_enabled)
|
||||
{
|
||||
Logger::trace(L"Starting Character Map process");
|
||||
//Get current process id
|
||||
unsigned long powertoys_pid = GetCurrentProcessId();
|
||||
std::wstring executable_args = std::to_wstring(powertoys_pid);
|
||||
|
||||
// Initiate SHELLEXECUTEINFOW structure
|
||||
SHELLEXECUTEINFOW sei{ sizeof(sei) };
|
||||
sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
|
||||
sei.lpFile = L"shell:AppsFolder\\PowerToys.CharacterMap_8wekyb3d8bbwe!App"; // UWP App ID
|
||||
sei.nShow = SW_SHOWNORMAL;
|
||||
sei.lpParameters = executable_args.c_str();
|
||||
|
||||
// start the app
|
||||
if (ShellExecuteExW(&sei) == FALSE)
|
||||
{
|
||||
|
||||
Logger::error(L"Character Map failed to start. {}", get_last_error_or_default(GetLastError()));
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::trace("PowerToys.CharacterMap started successfully!");
|
||||
m_hProcess = sei.hProcess;
|
||||
}
|
||||
}
|
||||
}
|
||||
virtual void call_custom_action(const wchar_t* action) override
|
||||
{
|
||||
try
|
||||
{
|
||||
PowerToysSettings::CustomActionObject action_object =
|
||||
PowerToysSettings::CustomActionObject::from_json_string(action);
|
||||
|
||||
if (action_object.get_name() == L"Launch")
|
||||
{
|
||||
launch_process();
|
||||
Trace::ActivateEditor();
|
||||
}
|
||||
}
|
||||
catch (std::exception&)
|
||||
{
|
||||
Logger::error(L"Failed to parse action. {}", action);
|
||||
}
|
||||
}
|
||||
void terminate_process()
|
||||
{
|
||||
TerminateProcess(m_hProcess, 1);
|
||||
}
|
||||
|
||||
|
||||
bool is_enabled_by_default() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void Enable()
|
||||
{
|
||||
m_enabled = true;
|
||||
|
||||
// Log telemetry
|
||||
Trace::EnableCharacterMap(true);
|
||||
}
|
||||
|
||||
void Disable(bool const traceEvent)
|
||||
{
|
||||
m_enabled = false;
|
||||
// Log telemetry
|
||||
if (traceEvent)
|
||||
{
|
||||
Trace::EnableCharacterMap(false);
|
||||
}
|
||||
if (m_enabled)
|
||||
{
|
||||
// let the DLL disable the app
|
||||
terminate_process();
|
||||
|
||||
Logger::trace(L"Disabling Registry Preview...");
|
||||
}
|
||||
|
||||
m_enabled = false;
|
||||
|
||||
}
|
||||
|
||||
virtual bool on_hotkey(size_t /*hotkeyId*/) override
|
||||
{
|
||||
if (m_enabled)
|
||||
{
|
||||
Logger::trace(L"Character Map hotkey pressed");
|
||||
if (is_process_running())
|
||||
{
|
||||
terminate_process();
|
||||
}
|
||||
else
|
||||
{
|
||||
launch_process();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
std::wstring app_name;
|
||||
std::wstring app_key; //contains the non localized key of the powertoy
|
||||
|
||||
bool m_enabled = false;
|
||||
HANDLE m_hProcess = nullptr;
|
||||
|
||||
HANDLE triggerEvent;
|
||||
EventWaiter triggerEventWaiter;
|
||||
|
||||
//HANDLE m_reload_settings_event_handle = NULL;
|
||||
//HANDLE m_exit_event_handle = NULL;
|
||||
};
|
||||
|
||||
extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create()
|
||||
{
|
||||
return new CharacterMapModuleInterface();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.Windows.CppWinRT" version="2.0.240111.5" targetFramework="native" />
|
||||
</packages>
|
||||
@@ -0,0 +1,5 @@
|
||||
// pch.cpp: source file corresponding to the pre-compiled header
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
// When you are using pre-compiled headers, this source file is necessary for compilation to succeed.
|
||||
10
src/modules/CharacterMap/CharacterMapModuleInterface/pch.h
Normal file
10
src/modules/CharacterMap/CharacterMapModuleInterface/pch.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
|
||||
#include <windows.h>
|
||||
#include <Unknwn.h>
|
||||
#include <winrt/base.h>
|
||||
#include <winrt/Windows.Foundation.h>
|
||||
#include <winrt/Windows.Foundation.Collections.h>
|
||||
#include <ProjectTelemetry.h>
|
||||
#include <TraceLoggingActivity.h>
|
||||
@@ -0,0 +1,13 @@
|
||||
//{{NO_DEPENDENCIES}}
|
||||
// Microsoft Visual C++ generated include file.
|
||||
// Used by ZoomItModuleInterface.rc
|
||||
|
||||
//////////////////////////////
|
||||
// Non-localizable
|
||||
|
||||
#define FILE_DESCRIPTION "PowerToys CharacterMapModuleInterface"
|
||||
#define INTERNAL_NAME "PowerToys.CharacterMapModuleInterface"
|
||||
#define ORIGINAL_FILENAME "PowerToys.CharacterMapModuleInterface.dll"
|
||||
|
||||
// Non-localizable
|
||||
//////////////////////////////
|
||||
@@ -0,0 +1,40 @@
|
||||
#include "pch.h"
|
||||
#include "trace.h"
|
||||
|
||||
TRACELOGGING_DEFINE_PROVIDER(
|
||||
g_hProvider,
|
||||
"Microsoft.PowerToys",
|
||||
// {38e8889b-9731-53f5-e901-e8a7c1753074}
|
||||
(0x38e8889b, 0x9731, 0x53f5, 0xe9, 0x01, 0xe8, 0xa7, 0xc1, 0x75, 0x30, 0x74),
|
||||
TraceLoggingOptionProjectTelemetry());
|
||||
|
||||
void Trace::RegisterProvider()
|
||||
{
|
||||
TraceLoggingRegister(g_hProvider);
|
||||
}
|
||||
|
||||
void Trace::UnregisterProvider()
|
||||
{
|
||||
TraceLoggingUnregister(g_hProvider);
|
||||
}
|
||||
|
||||
// Log if the user has ZoomIt enabled or disabled
|
||||
void Trace::EnableCharacterMap(const bool enabled) noexcept
|
||||
{
|
||||
TraceLoggingWrite(
|
||||
g_hProvider,
|
||||
"EnableCharacterMap_EnableZoomIt",
|
||||
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
|
||||
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE),
|
||||
TraceLoggingBoolean(enabled, "Enabled"));
|
||||
}
|
||||
|
||||
// Log that the user tried to activate the app
|
||||
void Trace::ActivateEditor() noexcept
|
||||
{
|
||||
TraceLoggingWrite(
|
||||
g_hProvider,
|
||||
"EnableCharacterMap_Activate",
|
||||
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
|
||||
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE));
|
||||
}
|
||||
13
src/modules/CharacterMap/CharacterMapModuleInterface/trace.h
Normal file
13
src/modules/CharacterMap/CharacterMapModuleInterface/trace.h
Normal file
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
class Trace
|
||||
{
|
||||
public:
|
||||
static void RegisterProvider();
|
||||
static void UnregisterProvider();
|
||||
|
||||
// Log if the user has ZoomIt enabled or disabled
|
||||
static void EnableCharacterMap(const bool enabled) noexcept;
|
||||
// Log that the user tried to activate the app
|
||||
static void ActivateEditor() noexcept;
|
||||
};
|
||||
35
src/modules/Hosts/Hosts.FuzzTests/Fuzz.md
Normal file
35
src/modules/Hosts/Hosts.FuzzTests/Fuzz.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Create Fuzzing Tests in your .NET Code Project
|
||||
|
||||
This document provides a step-by-step guide for integrating fuzzing tests into your .NET project.
|
||||
|
||||
### Step1: Add a Fuzzing Test Project
|
||||
Create a new test project within your module folder. Ensure the project name follows the format *.FuzzTests*.
|
||||
|
||||
### step2: Add FuzzTests and OneFuzzConfig.json to your fuzzing test project
|
||||
Follow the instructions in [Fuzz.md](https://github.com/microsoft/PowerToys/blob/main/src/modules/AdvancedPaste/AdvancedPaste.FuzzTests/Fuzz.md) from AdvancedPaste.FuzzTests to properly integrate fuzzing tests into your project.
|
||||
|
||||
Configuring **OneFuzzConfig.json**:
|
||||
1. Update the dll, class, method, and FuzzingTargetBinaries field in the fuzzers list.
|
||||
2. Modify the AssignedTo field in the adoTemplate list.
|
||||
3. Set the jobNotificationEmail to your Microsoft email account.
|
||||
4. Update the projectName and targetName fields in the oneFuzzJobs list.
|
||||
5. Define job dependencies in the following directory:
|
||||
Example:
|
||||
```PowerToys\x64\Debug\tests\Hosts.FuzzTests\net8.0-windows10.0.19041.0```
|
||||
|
||||
|
||||
# step3: Configure the OneFuzz Pipeline
|
||||
Modify the patterns in the job steps within [job-fuzz.yml](https://github.com/microsoft/PowerToys/blob/main/.pipelines/v2/templates/job-fuzz.yml) to match your fuzzing project name.
|
||||
|
||||
Example:
|
||||
```
|
||||
- download: current
|
||||
displayName: Download artifacts
|
||||
artifact: $(ArtifactName)
|
||||
patterns: |-
|
||||
**/tests/Hosts.FuzzTests/**
|
||||
```
|
||||
|
||||
|
||||
# step4: Submit OneFuzz Pipeline and Verify Results on the OneFuzz Platform
|
||||
After executing the tests, check your email for the job link. Click the link to review the fuzzing test results.
|
||||
101
src/modules/Hosts/Hosts.FuzzTests/FuzzTests.cs
Normal file
101
src/modules/Hosts/Hosts.FuzzTests/FuzzTests.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions.TestingHelpers;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Hosts.Tests.Mocks;
|
||||
using HostsUILib.Helpers;
|
||||
using HostsUILib.Models;
|
||||
using HostsUILib.Settings;
|
||||
using Moq;
|
||||
|
||||
namespace Hosts.FuzzTests
|
||||
{
|
||||
public class FuzzTests
|
||||
{
|
||||
private static Mock<IUserSettings> _userSettings;
|
||||
private static Mock<IElevationHelper> _elevationHelper;
|
||||
|
||||
// Case1: Fuzzing method for ValidIPv4
|
||||
public static void FuzzValidIPv4(ReadOnlySpan<byte> input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string address = System.Text.Encoding.UTF8.GetString(input);
|
||||
bool isValid = ValidationHelper.ValidIPv4(address);
|
||||
}
|
||||
catch (Exception ex) when (ex is RegexMatchTimeoutException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Case2: fuzzing method for ValidIPv6
|
||||
public static void FuzzValidIPv6(ReadOnlySpan<byte> input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string address = System.Text.Encoding.UTF8.GetString(input);
|
||||
bool isValid = ValidationHelper.ValidIPv6(address);
|
||||
}
|
||||
catch (Exception ex) when (ex is RegexMatchTimeoutException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Case3: fuzzing method for ValidHosts
|
||||
public static void FuzzValidHosts(ReadOnlySpan<byte> input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string hosts = System.Text.Encoding.UTF8.GetString(input);
|
||||
bool isValid = ValidationHelper.ValidHosts(hosts, true);
|
||||
}
|
||||
catch (Exception ex) when (ex is RegexMatchTimeoutException)
|
||||
{
|
||||
// It's important to filter out any *expected* exceptions from our code here.
|
||||
// However, catching all exceptions is considered an anti-pattern because it may suppress legitimate
|
||||
// issues, such as a NullReferenceException thrown by our code. In this case, we still re-throw
|
||||
// the exception, as the ToJsonFromXmlOrCsvAsync method is not expected to throw any exceptions.
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static void FuzzWriteAsync(ReadOnlySpan<byte> data)
|
||||
{
|
||||
try
|
||||
{
|
||||
_userSettings = new Mock<IUserSettings>();
|
||||
_elevationHelper = new Mock<IElevationHelper>();
|
||||
_elevationHelper.Setup(m => m.IsElevated).Returns(true);
|
||||
|
||||
var fileSystem = new CustomMockFileSystem();
|
||||
var service = new HostsService(fileSystem, _userSettings.Object, _elevationHelper.Object);
|
||||
|
||||
string input = System.Text.Encoding.UTF8.GetString(data);
|
||||
|
||||
// Since the WriteAsync method does not involve content parsing, we won't fuzz the additionalLines in the hosts file.
|
||||
string additionalLines = " ";
|
||||
string hosts = input;
|
||||
string address = input;
|
||||
string comments = input;
|
||||
var entries = new List<Entry>
|
||||
{
|
||||
new Entry(1, hosts, address, comments, true),
|
||||
};
|
||||
|
||||
// fuzzing WriteAsync
|
||||
_ = Task.Run(async () => await service.WriteAsync(additionalLines, entries));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
51
src/modules/Hosts/Hosts.FuzzTests/Hosts.FuzzTests.csproj
Normal file
51
src/modules/Hosts/Hosts.FuzzTests/Hosts.FuzzTests.csproj
Normal file
@@ -0,0 +1,51 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.19041.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputPath>..\..\..\..\$(Platform)\$(Configuration)\tests\Hosts.FuzzTests\</OutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\Hosts.Tests\Mocks\CustomMockFileSystem.cs" Link="CustomMockFileSystem.cs" />
|
||||
<Compile Include="..\Hosts.Tests\Mocks\MockFileSystemWatcher.cs" Link="MockFileSystemWatcher.cs" />
|
||||
<Compile Include="..\Hosts.Tests\Mocks\MockFileSystemWatcherFactory.cs" Link="MockFileSystemWatcherFactory.cs" />
|
||||
<Compile Include="..\HostsUILib\Consts.cs" Link="Consts.cs" />
|
||||
<Compile Include="..\HostsUILib\Helpers\ValidationHelper.cs" Link="ValidationHelper.cs" />
|
||||
<Compile Include="..\HostsUILib\Exceptions\NotRunningElevatedException.cs" Link="NotRunningElevatedException.cs" />
|
||||
<Compile Include="..\HostsUILib\Exceptions\ReadOnlyHostsException.cs" Link="ReadOnlyHostsException.cs" />
|
||||
<Compile Include="..\HostsUILib\Helpers\HostsService.cs" Link="HostsService.cs" />
|
||||
<Compile Include="..\HostsUILib\Helpers\IElevationHelper.cs" Link="IElevationHelper.cs" />
|
||||
<Compile Include="..\HostsUILib\Helpers\IHostsService.cs" Link="IHostsService.cs" />
|
||||
<Compile Include="..\HostsUILib\Helpers\ILogger.cs" Link="ILogger.cs" />
|
||||
<Compile Include="..\HostsUILib\Helpers\LoggerInstance.cs" Link="LoggerInstance.cs" />
|
||||
<Compile Include="..\HostsUILib\Models\AddressType.cs" Link="AddressType.cs" />
|
||||
<Compile Include="..\HostsUILib\Models\Entry.cs" Link="Entry.cs" />
|
||||
<Compile Include="..\HostsUILib\Models\HostsData.cs" Link="HostsData.cs" />
|
||||
<Compile Include="..\HostsUILib\Settings\HostsAdditionalLinesPosition.cs" Link="HostsAdditionalLinesPosition.cs" />
|
||||
<Compile Include="..\HostsUILib\Settings\HostsEncoding.cs" Link="HostsEncoding.cs" />
|
||||
<Compile Include="..\HostsUILib\Settings\IUserSettings.cs" Link="IUserSettings.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Moq" />
|
||||
<PackageReference Include="MSTest" />
|
||||
<PackageReference Include="System.IO.Abstractions" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||
<PackageReference Include="System.IO.Abstractions.TestingHelpers" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="OneFuzzConfig.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
5
src/modules/Hosts/Hosts.FuzzTests/MSTestSettings.cs
Normal file
5
src/modules/Hosts/Hosts.FuzzTests/MSTestSettings.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
[assembly: Parallelize(Scope = ExecutionScope.MethodLevel)]
|
||||
178
src/modules/Hosts/Hosts.FuzzTests/OneFuzzConfig.json
Normal file
178
src/modules/Hosts/Hosts.FuzzTests/OneFuzzConfig.json
Normal file
@@ -0,0 +1,178 @@
|
||||
{
|
||||
"configVersion": 3,
|
||||
"entries": [
|
||||
{
|
||||
"fuzzer": {
|
||||
"$type": "libfuzzerDotNet",
|
||||
"dll": "Hosts.FuzzTests.dll",
|
||||
"class": "Hosts.FuzzTests.FuzzTests",
|
||||
"method": "FuzzValidIPv4",
|
||||
"FuzzingTargetBinaries": [
|
||||
"PowerToys.Hosts.dll"
|
||||
]
|
||||
},
|
||||
"adoTemplate": {
|
||||
// supply the values appropriate to your
|
||||
// project, where bugs will be filed
|
||||
"org": "microsoft",
|
||||
"project": "OS",
|
||||
"AssignedTo": "mengyuanchen@microsoft.com",
|
||||
"AreaPath": "OS\\Windows Client and Services\\WinPD\\DEEP-Developer Experience, Ecosystem and Partnerships\\SHINE\\PowerToys",
|
||||
"IterationPath": "OS\\Future"
|
||||
},
|
||||
"jobNotificationEmail": "mengyuanchen@microsoft.com",
|
||||
"skip": false,
|
||||
"rebootAfterSetup": false,
|
||||
"oneFuzzJobs": [
|
||||
// at least one job is required
|
||||
{
|
||||
"projectName": "Hosts",
|
||||
"targetName": "Hosts-dotnet-fuzzer-Ipv4"
|
||||
}
|
||||
],
|
||||
"jobDependencies": [
|
||||
// this should contain, at minimum,
|
||||
// the DLL and PDB files
|
||||
// you will need to add any other files required
|
||||
// (globs are supported)
|
||||
"Hosts.FuzzTests.dll",
|
||||
"Hosts.FuzzTests.pdb",
|
||||
"Microsoft.Windows.SDK.NET.dll",
|
||||
"WinRT.Runtime.dll"
|
||||
],
|
||||
"SdlWorkItemId": 49911822
|
||||
},
|
||||
{
|
||||
"fuzzer": {
|
||||
"$type": "libfuzzerDotNet",
|
||||
"dll": "Hosts.FuzzTests.dll",
|
||||
"class": "Hosts.FuzzTests.FuzzTests",
|
||||
"method": "FuzzValidIPv6",
|
||||
"FuzzingTargetBinaries": [
|
||||
"PowerToys.Hosts.dll"
|
||||
]
|
||||
},
|
||||
"adoTemplate": {
|
||||
// supply the values appropriate to your
|
||||
// project, where bugs will be filed
|
||||
"org": "microsoft",
|
||||
"project": "OS",
|
||||
"AssignedTo": "mengyuanchen@microsoft.com",
|
||||
"AreaPath": "OS\\Windows Client and Services\\WinPD\\DEEP-Developer Experience, Ecosystem and Partnerships\\SHINE\\PowerToys",
|
||||
"IterationPath": "OS\\Future"
|
||||
},
|
||||
"jobNotificationEmail": "mengyuanchen@microsoft.com",
|
||||
"skip": false,
|
||||
"rebootAfterSetup": false,
|
||||
"oneFuzzJobs": [
|
||||
// at least one job is required
|
||||
{
|
||||
"projectName": "Hosts",
|
||||
"targetName": "Hosts-dotnet-fuzzer-Ipv6"
|
||||
}
|
||||
],
|
||||
"jobDependencies": [
|
||||
// this should contain, at minimum,
|
||||
// the DLL and PDB files
|
||||
// you will need to add any other files required
|
||||
// (globs are supported)
|
||||
"Hosts.FuzzTests.dll",
|
||||
"Hosts.FuzzTests.pdb",
|
||||
"Microsoft.Windows.SDK.NET.dll",
|
||||
"WinRT.Runtime.dll"
|
||||
],
|
||||
"SdlWorkItemId": 49911822
|
||||
},
|
||||
{
|
||||
"fuzzer": {
|
||||
"$type": "libfuzzerDotNet",
|
||||
"dll": "Hosts.FuzzTests.dll",
|
||||
"class": "Hosts.FuzzTests.FuzzTests",
|
||||
"method": "FuzzValidHosts",
|
||||
"FuzzingTargetBinaries": [
|
||||
"PowerToys.Hosts.dll"
|
||||
]
|
||||
},
|
||||
"adoTemplate": {
|
||||
// supply the values appropriate to your
|
||||
// project, where bugs will be filed
|
||||
"org": "microsoft",
|
||||
"project": "OS",
|
||||
"AssignedTo": "mengyuanchen@microsoft.com",
|
||||
"AreaPath": "OS\\Windows Client and Services\\WinPD\\DEEP-Developer Experience, Ecosystem and Partnerships\\SHINE\\PowerToys",
|
||||
"IterationPath": "OS\\Future"
|
||||
},
|
||||
"jobNotificationEmail": "mengyuanchen@microsoft.com",
|
||||
"skip": false,
|
||||
"rebootAfterSetup": false,
|
||||
"oneFuzzJobs": [
|
||||
// at least one job is required
|
||||
{
|
||||
"projectName": "Hosts",
|
||||
"targetName": "Hosts-dotnet-fuzzer-hosts"
|
||||
}
|
||||
],
|
||||
"jobDependencies": [
|
||||
// this should contain, at minimum,
|
||||
// the DLL and PDB files
|
||||
// you will need to add any other files required
|
||||
// (globs are supported)
|
||||
"Hosts.FuzzTests.dll",
|
||||
"Hosts.FuzzTests.pdb",
|
||||
"Microsoft.Windows.SDK.NET.dll",
|
||||
"WinRT.Runtime.dll"
|
||||
],
|
||||
"SdlWorkItemId": 49911822
|
||||
},
|
||||
{
|
||||
"fuzzer": {
|
||||
"$type": "libfuzzerDotNet",
|
||||
"dll": "Hosts.FuzzTests.dll",
|
||||
"class": "Hosts.FuzzTests.FuzzTests",
|
||||
"method": "FuzzWriteAsync",
|
||||
"FuzzingTargetBinaries": [
|
||||
"PowerToys.Hosts.dll"
|
||||
]
|
||||
},
|
||||
"adoTemplate": {
|
||||
// supply the values appropriate to your
|
||||
// project, where bugs will be filed
|
||||
"org": "microsoft",
|
||||
"project": "OS",
|
||||
"AssignedTo": "mengyuanchen@microsoft.com",
|
||||
"AreaPath": "OS\\Windows Client and Services\\WinPD\\DEEP-Developer Experience, Ecosystem and Partnerships\\SHINE\\PowerToys",
|
||||
"IterationPath": "OS\\Future"
|
||||
},
|
||||
"jobNotificationEmail": "mengyuanchen@microsoft.com",
|
||||
"skip": false,
|
||||
"rebootAfterSetup": false,
|
||||
"oneFuzzJobs": [
|
||||
// at least one job is required
|
||||
{
|
||||
"projectName": "Hosts",
|
||||
"targetName": "Hosts-dotnet-fuzzer-WriteAsync"
|
||||
}
|
||||
],
|
||||
"jobDependencies": [
|
||||
// this should contain, at minimum,
|
||||
// the DLL and PDB files
|
||||
// you will need to add any other files required
|
||||
// (globs are supported)
|
||||
"Hosts.FuzzTests.dll",
|
||||
"Hosts.FuzzTests.pdb",
|
||||
"Microsoft.Windows.SDK.NET.dll",
|
||||
"WinRT.Runtime.dll",
|
||||
"Moq.dll",
|
||||
"testhost.dll",
|
||||
"Castle.Core.dll",
|
||||
"System.IO.Abstractions.dll",
|
||||
"CommunityToolkit.Mvvm.dll",
|
||||
"System.IO.Abstractions.TestingHelpers.dll",
|
||||
"TestableIO.System.IO.Abstractions.dll",
|
||||
"TestableIO.System.IO.Abstractions.TestingHelpers.dll",
|
||||
"TestableIO.System.IO.Abstractions.Wrappers.dll"
|
||||
],
|
||||
"SdlWorkItemId": 49911822
|
||||
}
|
||||
]
|
||||
}
|
||||
108
src/modules/Hosts/Hosts.UITests/HostModuleTests.cs
Normal file
108
src/modules/Hosts/Hosts.UITests/HostModuleTests.cs
Normal file
@@ -0,0 +1,108 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.PowerToys.UITest;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace Hosts.UITests
|
||||
{
|
||||
[TestClass]
|
||||
public class HostModuleTests : UITestBase
|
||||
{
|
||||
public HostModuleTests()
|
||||
: base(PowerToysModule.Hosts)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test if Empty-view is shown when no entries are present.
|
||||
/// And 'Add an entry' button from Empty-view is functional.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void TestEmptyView()
|
||||
{
|
||||
this.CloseWarningDialog();
|
||||
this.RemoveAllEntries();
|
||||
|
||||
// 'Add an entry' button (only show-up when list is empty) should be visible
|
||||
Assert.IsTrue(this.FindAll<Button>(By.Name("Add an entry")).Count == 1, "'Add an entry' button should be visible in the empty view");
|
||||
|
||||
// Click 'Add an entry' from empty-view for adding Host override rule
|
||||
this.Find<Button>(By.Name("Add an entry")).Click();
|
||||
|
||||
this.AddEntry("192.168.0.1", "localhost", false, false);
|
||||
|
||||
// Should have one row now and not more empty view
|
||||
Assert.IsTrue(this.FindAll<Button>(By.Name("Delete")).Count == 1, "Should have one row now");
|
||||
Assert.IsTrue(this.FindAll<Button>(By.Name("Add an entry")).Count == 0, "'Add an entry' button should be invisible if not empty view");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test if 'New entry' button is functional
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void TestAddingEntry()
|
||||
{
|
||||
this.CloseWarningDialog();
|
||||
this.RemoveAllEntries();
|
||||
|
||||
Assert.IsTrue(this.FindAll<Button>(By.Name("Delete")).Count == 0, "Should have no row after removing all");
|
||||
|
||||
this.AddEntry("192.168.0.1", "localhost", true);
|
||||
|
||||
Assert.IsTrue(this.FindAll<Button>(By.Name("Delete")).Count == 1, "Should have one row now");
|
||||
}
|
||||
|
||||
private void AddEntry(string ip, string host, bool active = true, bool clickAddEntryButton = true)
|
||||
{
|
||||
if (clickAddEntryButton)
|
||||
{
|
||||
// Click 'Add an entry' for adding Host override rule
|
||||
this.Find<Button>(By.Name("New entry")).Click();
|
||||
}
|
||||
|
||||
// Adding a new host override localhost -> 192.168.0.1
|
||||
Assert.IsFalse(this.Find<Button>(By.Name("Add")).Enabled, "Add button should be Disabled by default");
|
||||
|
||||
Assert.IsTrue(this.Find<TextBox>(By.Name("Address")).SetText(ip, false).Text == ip);
|
||||
Assert.IsTrue(this.Find<TextBox>(By.Name("Hosts")).SetText(host, false).Text == host);
|
||||
|
||||
this.Find<ToggleSwitch>(By.Name("Active")).Toggle(active);
|
||||
|
||||
Assert.IsTrue(this.Find<Button>(By.Name("Add")).Enabled, "Add button should be Enabled after providing valid inputs");
|
||||
|
||||
// Add the entry
|
||||
this.Find<Button>(By.Name("Add")).Click();
|
||||
|
||||
// 0.5 second delay after adding an entry
|
||||
Task.Delay(500).Wait();
|
||||
}
|
||||
|
||||
private void CloseWarningDialog()
|
||||
{
|
||||
// Find 'Accept' button which come in 'Warning' dialog
|
||||
if (this.FindAll<Window>(By.Name("Warning")).Count > 0 &&
|
||||
this.FindAll<Button>(By.Name("Accept")).Count > 0)
|
||||
{
|
||||
// Hide Warning dialog if any
|
||||
this.Find<Button>(By.Name("Accept")).Click();
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveAllEntries()
|
||||
{
|
||||
// Delete all existing host-override rules
|
||||
foreach (var deleteBtn in this.FindAll<Button>(By.Name("Delete")))
|
||||
{
|
||||
deleteBtn.Click();
|
||||
this.Find<Button>(By.Name("Yes")).Click();
|
||||
}
|
||||
|
||||
// Should have no row left, and no more delete button
|
||||
Assert.IsTrue(this.FindAll<Button>(By.Name("Delete")).Count == 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
25
src/modules/Hosts/Hosts.UITests/Hosts.UITests.csproj
Normal file
25
src/modules/Hosts/Hosts.UITests/Hosts.UITests.csproj
Normal file
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Look at Directory.Build.props in root for common stuff as well -->
|
||||
<Import Project="..\..\..\Common.Dotnet.CsWinRT.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<ProjectGuid>{4E0AE3A4-2EE0-44D7-A2D0-8769977254A0}</ProjectGuid>
|
||||
<RootNamespace>PowerToys.Hosts.UITests</RootNamespace>
|
||||
<AssemblyName>PowerToys.Hosts.UITests</AssemblyName>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<Nullable>enable</Nullable>
|
||||
<OutputType>Library</OutputType>
|
||||
|
||||
<!-- This is a UI test, so don't run as part of MSBuild -->
|
||||
<RunVSTest>false</RunVSTest>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<OutputPath>$(SolutionDir)$(Platform)\$(Configuration)\tests\Hosts.UITests\</OutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest" />
|
||||
<ProjectReference Include="..\..\..\common\UITestAutomation\UITestAutomation.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -233,6 +233,12 @@ void Highlighter::ClearDrawingPoint(MouseButton _button)
|
||||
{
|
||||
winrt::Windows::UI::Composition::CompositionSpriteShape circleShape{ nullptr };
|
||||
|
||||
if (nullptr == m_alwaysPointer)
|
||||
{
|
||||
// Guard against alwaysPointer not being initialized.
|
||||
return;
|
||||
}
|
||||
|
||||
// always
|
||||
circleShape = m_alwaysPointer;
|
||||
|
||||
@@ -265,6 +271,11 @@ LRESULT CALLBACK Highlighter::MouseHookProc(int nCode, WPARAM wParam, LPARAM lPa
|
||||
// Clear AlwaysPointer only when it's enabled and RightPointer is not active
|
||||
instance->ClearDrawingPoint(MouseButton::None);
|
||||
}
|
||||
if (instance->m_leftButtonPressed)
|
||||
{
|
||||
// There might be a stray point from the user releasing the mouse button on an elevated window, which wasn't caught by us.
|
||||
instance->StartDrawingPointFading(MouseButton::Left);
|
||||
}
|
||||
instance->AddDrawingPoint(MouseButton::Left);
|
||||
instance->m_leftButtonPressed = true;
|
||||
// start a timer for the scenario, when the user clicks a pinned window which has no focus.
|
||||
@@ -284,6 +295,11 @@ LRESULT CALLBACK Highlighter::MouseHookProc(int nCode, WPARAM wParam, LPARAM lPa
|
||||
// Clear AlwaysPointer only when it's enabled and LeftPointer is not active
|
||||
instance->ClearDrawingPoint(MouseButton::None);
|
||||
}
|
||||
if (instance->m_rightButtonPressed)
|
||||
{
|
||||
// There might be a stray point from the user releasing the mouse button on an elevated window, which wasn't caught by us.
|
||||
instance->StartDrawingPointFading(MouseButton::Right);
|
||||
}
|
||||
instance->AddDrawingPoint(MouseButton::Right);
|
||||
instance->m_rightButtonPressed = true;
|
||||
// same as for the left button, start a timer for reposition ourselves to topmost position
|
||||
|
||||
@@ -431,7 +431,7 @@ namespace MouseWithoutBorders
|
||||
if (!IsConnectedByAClientSocketTo(remoteMachine))
|
||||
{
|
||||
Logger.Log($"No potential inbound connection from {MachineName} to {remoteMachine}, ask for a push back instead.");
|
||||
ID machineId = MachinePool.ResolveID(remoteMachine);
|
||||
ID machineId = MachineStuff.MachinePool.ResolveID(remoteMachine);
|
||||
|
||||
if (machineId != ID.NONE)
|
||||
{
|
||||
@@ -840,7 +840,7 @@ namespace MouseWithoutBorders
|
||||
|
||||
Logger.LogDebug($"{nameof(ShakeHand)}: Connection from {name}:{package.Src}");
|
||||
|
||||
if (Common.MachinePool.ResolveID(name) == package.Src && Common.IsConnectedTo(package.Src))
|
||||
if (MachineStuff.MachinePool.ResolveID(name) == package.Src && Common.IsConnectedTo(package.Src))
|
||||
{
|
||||
clientPushData = package.Type == PackageType.ClipboardPush;
|
||||
postAction = package.PostAction;
|
||||
|
||||
@@ -1,409 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
|
||||
using Microsoft.PowerToys.Telemetry;
|
||||
|
||||
// <summary>
|
||||
// Drag/Drop implementation.
|
||||
// </summary>
|
||||
// <history>
|
||||
// 2008 created by Truong Do (ductdo).
|
||||
// 2009-... modified by Truong Do (TruongDo).
|
||||
// 2023- Included in PowerToys.
|
||||
// </history>
|
||||
using MouseWithoutBorders.Class;
|
||||
using MouseWithoutBorders.Core;
|
||||
|
||||
using Thread = MouseWithoutBorders.Core.Thread;
|
||||
|
||||
namespace MouseWithoutBorders
|
||||
{
|
||||
/* Common.DragDrop.cs
|
||||
* Drag&Drop is one complicated implementation of the tool with some tricks.
|
||||
*
|
||||
* SEQUENCE OF EVENTS:
|
||||
* DragDropStep01: MachineX: Remember mouse down state since it could be a start of a dragging
|
||||
* DragDropStep02: MachineY: Send an message to the MachineX to ask it to check if it is
|
||||
* doing drag/drop
|
||||
* DragDropStep03: MachineX: Got explorerDragDrop, send WM_CHECK_EXPLORER_DRAG_DROP to its mainForm
|
||||
* DragDropStep04: MachineX: Show Mouse Without Borders Helper form at mouse cursor to get DragEnter event.
|
||||
* DragDropStepXX: MachineX: Mouse Without Borders Helper: Called by DragEnter, check if dragging a single file,
|
||||
* remember the file (set as its window caption)
|
||||
* DragDropStep05: MachineX: Get the file name from Mouse Without Borders Helper, hide Mouse Without Borders Helper window
|
||||
* DragDropStep06: MachineX: Broadcast a message saying that it has some drag file.
|
||||
* DragDropStep08: MachineY: Got ClipboardDragDrop, isDropping set, get the MachineX name from the package.
|
||||
* DragDropStep09: MachineY: Since isDropping is true, show up the drop form (looks like an icon).
|
||||
* DragDropStep10: MachineY: MouseUp, set isDropping to false, hide the drop "icon" and get data.
|
||||
* DragDropStep11: MachineX: Mouse move back without drop event, cancelling drag/dop
|
||||
* SendClipboardBeatDragDropEnd
|
||||
* DragDropStep12: MachineY: Hide the drop "icon" when received ClipboardDragDropEnd.
|
||||
*
|
||||
* FROM VERSION 1.6.3: Drag/Drop is temporary removed, Drop action cannot be done from a lower integrity app to a higher one.
|
||||
* We have to run a helper process...
|
||||
* http://forums.microsoft.com/MSDN/ShowPost.aspx?PageIndex=1&SiteID=1&PageID=1&PostID=736086
|
||||
*
|
||||
* 2008.10.28: Trying to restore the Drag/Drop feature by adding the drag/drop helper process. Coming in version
|
||||
* 1.6.5
|
||||
* */
|
||||
|
||||
internal partial class Common
|
||||
{
|
||||
private static bool isDragging;
|
||||
|
||||
internal static bool IsDragging
|
||||
{
|
||||
get => Common.isDragging;
|
||||
set => Common.isDragging = value;
|
||||
}
|
||||
|
||||
internal static void DragDropStep01(int wParam)
|
||||
{
|
||||
if (!Setting.Values.TransferFile)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (wParam == WM_LBUTTONDOWN)
|
||||
{
|
||||
MouseDown = true;
|
||||
DragMachine = desMachineID;
|
||||
dropMachineID = ID.NONE;
|
||||
Logger.LogDebug("DragDropStep01: MouseDown");
|
||||
}
|
||||
else if (wParam == WM_LBUTTONUP)
|
||||
{
|
||||
MouseDown = false;
|
||||
Logger.LogDebug("DragDropStep01: MouseUp");
|
||||
}
|
||||
|
||||
if (wParam == WM_RBUTTONUP && IsDropping)
|
||||
{
|
||||
IsDropping = false;
|
||||
LastIDWithClipboardData = ID.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DragDropStep02()
|
||||
{
|
||||
if (desMachineID == MachineID)
|
||||
{
|
||||
Logger.LogDebug("DragDropStep02: SendCheckExplorerDragDrop sent to myself");
|
||||
DoSomethingInUIThread(() =>
|
||||
{
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP, (IntPtr)0, (IntPtr)0);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
SendCheckExplorerDragDrop();
|
||||
Logger.LogDebug("DragDropStep02: SendCheckExplorerDragDrop sent");
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DragDropStep03(DATA package)
|
||||
{
|
||||
if (RunOnLogonDesktop || RunOnScrSaverDesktop)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (package.Des == MachineID || package.Des == ID.ALL)
|
||||
{
|
||||
Logger.LogDebug("DragDropStep03: ExplorerDragDrop Received.");
|
||||
dropMachineID = package.Src; // Drop machine is the machine that sent ExplorerDragDrop
|
||||
if (MouseDown || IsDropping)
|
||||
{
|
||||
Logger.LogDebug("DragDropStep03: Mouse is down, check if dragging...sending WM_CHECK_EXPLORER_DRAG_DROP to myself...");
|
||||
DoSomethingInUIThread(() =>
|
||||
{
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP, (IntPtr)0, (IntPtr)0);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int dragDropStep05ExCalledByIpc;
|
||||
|
||||
internal static void DragDropStep04()
|
||||
{
|
||||
if (!IsDropping)
|
||||
{
|
||||
IntPtr h = (IntPtr)NativeMethods.FindWindow(null, Common.HELPER_FORM_TEXT);
|
||||
if (h.ToInt32() > 0)
|
||||
{
|
||||
_ = Interlocked.Exchange(ref dragDropStep05ExCalledByIpc, 0);
|
||||
|
||||
MainForm.Hide();
|
||||
MainFormVisible = false;
|
||||
|
||||
Point p = default;
|
||||
|
||||
// NativeMethods.SetWindowText(h, "");
|
||||
_ = NativeMethods.SetWindowPos(h, NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, NativeMethods.SWP_SHOWWINDOW);
|
||||
|
||||
for (int i = -10; i < 10; i++)
|
||||
{
|
||||
if (dragDropStep05ExCalledByIpc > 0)
|
||||
{
|
||||
Logger.LogDebug("DragDropStep04: DragDropStep05ExCalledByIpc.");
|
||||
break;
|
||||
}
|
||||
|
||||
_ = NativeMethods.GetCursorPos(ref p);
|
||||
Logger.LogDebug("DragDropStep04: Moving Mouse Without Borders Helper to (" + p.X.ToString(CultureInfo.CurrentCulture) + ", " + p.Y.ToString(CultureInfo.CurrentCulture) + ")");
|
||||
_ = NativeMethods.SetWindowPos(h, NativeMethods.HWND_TOPMOST, p.X - 100 + i, p.Y - 100 + i, 200, 200, 0);
|
||||
_ = NativeMethods.SendMessage(h, 0x000F, IntPtr.Zero, IntPtr.Zero); // WM_PAINT
|
||||
Thread.Sleep(20);
|
||||
Application.DoEvents();
|
||||
|
||||
// if (GetText(h).Length > 1) break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogDebug("DragDropStep04: Mouse without Borders Helper not found!");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogDebug("DragDropStep04: IsDropping == true, skip checking");
|
||||
}
|
||||
|
||||
Logger.LogDebug("DragDropStep04: Got WM_CHECK_EXPLORER_DRAG_DROP, done with processing jump to DragDropStep05...");
|
||||
}
|
||||
|
||||
internal static void DragDropStep05Ex(string dragFileName)
|
||||
{
|
||||
Logger.LogDebug("DragDropStep05 called.");
|
||||
|
||||
_ = Interlocked.Exchange(ref dragDropStep05ExCalledByIpc, 1);
|
||||
|
||||
if (RunOnLogonDesktop || RunOnScrSaverDesktop)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsDropping)
|
||||
{
|
||||
_ = Common.ImpersonateLoggedOnUserAndDoSomething(() =>
|
||||
{
|
||||
if (!string.IsNullOrEmpty(dragFileName) && (File.Exists(dragFileName) || Directory.Exists(dragFileName)))
|
||||
{
|
||||
Common.LastDragDropFile = dragFileName;
|
||||
/*
|
||||
* possibleDropMachineID is used as desID sent in DragDropStep06();
|
||||
* */
|
||||
if (dropMachineID == ID.NONE)
|
||||
{
|
||||
dropMachineID = newDesMachineID;
|
||||
}
|
||||
|
||||
DragDropStep06();
|
||||
Logger.LogDebug("DragDropStep05: File dragging: " + dragFileName);
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DD_HELPER, (IntPtr)1, (IntPtr)0);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogDebug("DragDropStep05: File not found: [" + dragFileName + "]");
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DD_HELPER, (IntPtr)0, (IntPtr)0);
|
||||
}
|
||||
|
||||
Logger.LogDebug("DragDropStep05: WM_HIDE_DDHelper sent");
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogDebug("DragDropStep05: IsDropping == true, change drop machine...");
|
||||
IsDropping = false;
|
||||
MainFormVisible = true; // WM_HIDE_DRAG_DROP
|
||||
SendDropBegin(); // To dropMachineID set in DragDropStep03
|
||||
}
|
||||
|
||||
MouseDown = false;
|
||||
}
|
||||
|
||||
internal static void DragDropStep06()
|
||||
{
|
||||
IsDragging = true;
|
||||
Logger.LogDebug("DragDropStep06: SendClipboardBeatDragDrop");
|
||||
SendClipboardBeatDragDrop();
|
||||
SendDropBegin();
|
||||
}
|
||||
|
||||
internal static void DragDropStep08(DATA package)
|
||||
{
|
||||
Receiver.GetNameOfMachineWithClipboardData(package);
|
||||
Logger.LogDebug("DragDropStep08: ClipboardDragDrop Received. machine with drag file was set");
|
||||
}
|
||||
|
||||
internal static void DragDropStep08_2(DATA package)
|
||||
{
|
||||
if (package.Des == MachineID && !RunOnLogonDesktop && !RunOnScrSaverDesktop)
|
||||
{
|
||||
IsDropping = true;
|
||||
dropMachineID = MachineID;
|
||||
Logger.LogDebug("DragDropStep08_2: ClipboardDragDropOperation Received. IsDropping set");
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DragDropStep09(int wParam)
|
||||
{
|
||||
if (wParam == WM_MOUSEMOVE && IsDropping)
|
||||
{
|
||||
// Show/Move form
|
||||
DoSomethingInUIThread(() =>
|
||||
{
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_SHOW_DRAG_DROP, (IntPtr)0, (IntPtr)0);
|
||||
});
|
||||
}
|
||||
else if (wParam == WM_LBUTTONUP && (IsDropping || IsDragging))
|
||||
{
|
||||
if (IsDropping)
|
||||
{
|
||||
// Hide form, get data
|
||||
DragDropStep10();
|
||||
}
|
||||
else
|
||||
{
|
||||
IsDragging = false;
|
||||
LastIDWithClipboardData = ID.NONE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DragDropStep10()
|
||||
{
|
||||
Logger.LogDebug("DragDropStep10: Hide the form and get data...");
|
||||
IsDropping = false;
|
||||
IsDragging = false;
|
||||
LastIDWithClipboardData = ID.NONE;
|
||||
|
||||
DoSomethingInUIThread(() =>
|
||||
{
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DRAG_DROP, (IntPtr)0, (IntPtr)0);
|
||||
});
|
||||
|
||||
PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersDragAndDropEvent());
|
||||
GetRemoteClipboard("desktop");
|
||||
}
|
||||
|
||||
internal static void DragDropStep11()
|
||||
{
|
||||
Logger.LogDebug("DragDropStep11: Mouse drag coming back, canceling drag/drop");
|
||||
SendClipboardBeatDragDropEnd();
|
||||
IsDropping = false;
|
||||
IsDragging = false;
|
||||
DragMachine = (ID)1;
|
||||
LastIDWithClipboardData = ID.NONE;
|
||||
LastDragDropFile = null;
|
||||
MouseDown = false;
|
||||
}
|
||||
|
||||
internal static void DragDropStep12()
|
||||
{
|
||||
Logger.LogDebug("DragDropStep12: ClipboardDragDropEnd received");
|
||||
IsDropping = false;
|
||||
LastIDWithClipboardData = ID.NONE;
|
||||
|
||||
DoSomethingInUIThread(() =>
|
||||
{
|
||||
_ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DRAG_DROP, (IntPtr)0, (IntPtr)0);
|
||||
});
|
||||
}
|
||||
|
||||
internal static void SendCheckExplorerDragDrop()
|
||||
{
|
||||
DATA package = new();
|
||||
package.Type = PackageType.ExplorerDragDrop;
|
||||
|
||||
/*
|
||||
* package.src = newDesMachineID:
|
||||
* sent from the master machine but the src must be the
|
||||
* new des machine since the previous des machine will get this and set
|
||||
* to possibleDropMachineID in DragDropStep3()
|
||||
* */
|
||||
package.Src = newDesMachineID;
|
||||
|
||||
package.Des = desMachineID;
|
||||
package.MachineName = MachineName;
|
||||
|
||||
SkSend(package, null, false);
|
||||
}
|
||||
|
||||
private static void ChangeDropMachine()
|
||||
{
|
||||
// desMachineID = current drop machine
|
||||
// newDesMachineID = new drop machine
|
||||
|
||||
// 1. Cancelling dropping in current drop machine
|
||||
if (dropMachineID == MachineID)
|
||||
{
|
||||
// Drag/Drop coming through me
|
||||
IsDropping = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Drag/Drop coming back
|
||||
SendClipboardBeatDragDropEnd();
|
||||
}
|
||||
|
||||
// 2. SendClipboardBeatDragDrop to new drop machine
|
||||
// new drop machine is not me
|
||||
if (newDesMachineID != MachineID)
|
||||
{
|
||||
dropMachineID = newDesMachineID;
|
||||
SendDropBegin();
|
||||
}
|
||||
|
||||
// New drop machine is me
|
||||
else
|
||||
{
|
||||
IsDropping = true;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void SendClipboardBeatDragDrop()
|
||||
{
|
||||
SendPackage(ID.ALL, PackageType.ClipboardDragDrop);
|
||||
}
|
||||
|
||||
internal static void SendDropBegin()
|
||||
{
|
||||
Logger.LogDebug("SendDropBegin...");
|
||||
SendPackage(dropMachineID, PackageType.ClipboardDragDropOperation);
|
||||
}
|
||||
|
||||
internal static void SendClipboardBeatDragDropEnd()
|
||||
{
|
||||
if (desMachineID != MachineID)
|
||||
{
|
||||
SendPackage(desMachineID, PackageType.ClipboardDragDropEnd);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool isDropping;
|
||||
private static ID dragMachine;
|
||||
|
||||
internal static ID DragMachine
|
||||
{
|
||||
get => Common.dragMachine;
|
||||
set => Common.dragMachine = value;
|
||||
}
|
||||
|
||||
internal static bool IsDropping
|
||||
{
|
||||
get => Common.isDropping;
|
||||
set => Common.isDropping = value;
|
||||
}
|
||||
|
||||
internal static bool MouseDown { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ namespace MouseWithoutBorders
|
||||
|
||||
if (switchByMouseEnabled && Sk != null && (DesMachineID == MachineID || !Setting.Values.MoveMouseRelatively) && e.dwFlags == WM_MOUSEMOVE)
|
||||
{
|
||||
Point p = MoveToMyNeighbourIfNeeded(e.X, e.Y, desMachineID);
|
||||
Point p = MachineStuff.MoveToMyNeighbourIfNeeded(e.X, e.Y, MachineStuff.desMachineID);
|
||||
|
||||
if (!p.IsEmpty)
|
||||
{
|
||||
@@ -81,20 +81,20 @@ namespace MouseWithoutBorders
|
||||
Logger.LogDebug(string.Format(
|
||||
CultureInfo.CurrentCulture,
|
||||
"***** Host Machine: newDesMachineIdEx set = [{0}]. Mouse is now at ({1},{2})",
|
||||
newDesMachineIdEx,
|
||||
MachineStuff.newDesMachineIdEx,
|
||||
e.X,
|
||||
e.Y));
|
||||
|
||||
myLastX = e.X;
|
||||
myLastY = e.Y;
|
||||
|
||||
PrepareToSwitchToMachine(newDesMachineIdEx, p);
|
||||
PrepareToSwitchToMachine(MachineStuff.newDesMachineIdEx, p);
|
||||
}
|
||||
}
|
||||
|
||||
if (desMachineID != MachineID && SwitchLocation.Count <= 0)
|
||||
if (MachineStuff.desMachineID != MachineID && MachineStuff.SwitchLocation.Count <= 0)
|
||||
{
|
||||
MousePackage.Des = desMachineID;
|
||||
MousePackage.Des = MachineStuff.desMachineID;
|
||||
MousePackage.Type = PackageType.Mouse;
|
||||
MousePackage.Md.dwFlags = e.dwFlags;
|
||||
MousePackage.Md.WheelDelta = e.WheelDelta;
|
||||
@@ -107,8 +107,8 @@ namespace MouseWithoutBorders
|
||||
}
|
||||
else
|
||||
{
|
||||
MousePackage.Md.X = (e.X - primaryScreenBounds.Left) * 65535 / screenWidth;
|
||||
MousePackage.Md.Y = (e.Y - primaryScreenBounds.Top) * 65535 / screenHeight;
|
||||
MousePackage.Md.X = (e.X - MachineStuff.primaryScreenBounds.Left) * 65535 / screenWidth;
|
||||
MousePackage.Md.Y = (e.Y - MachineStuff.primaryScreenBounds.Top) * 65535 / screenHeight;
|
||||
}
|
||||
|
||||
SkSend(MousePackage, null, false);
|
||||
@@ -156,15 +156,15 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
Logger.LogDebug($"PrepareToSwitchToMachine: newDesMachineID = {newDesMachineID}, desMachineXY = {desMachineXY}");
|
||||
|
||||
if (((GetTick() - lastJump < 100) && (GetTick() - lastJump > 0)) || desMachineID == ID.ALL)
|
||||
if (((GetTick() - MachineStuff.lastJump < 100) && (GetTick() - MachineStuff.lastJump > 0)) || MachineStuff.desMachineID == ID.ALL)
|
||||
{
|
||||
Logger.LogDebug("PrepareToSwitchToMachine: lastJump");
|
||||
return;
|
||||
}
|
||||
|
||||
lastJump = GetTick();
|
||||
MachineStuff.lastJump = GetTick();
|
||||
|
||||
string newDesMachineName = NameFromID(newDesMachineID);
|
||||
string newDesMachineName = MachineStuff.NameFromID(newDesMachineID);
|
||||
|
||||
if (!IsConnectedTo(newDesMachineID))
|
||||
{// Connection lost, cancel switching
|
||||
@@ -174,46 +174,46 @@ namespace MouseWithoutBorders
|
||||
}
|
||||
else
|
||||
{
|
||||
Common.newDesMachineID = newDesMachineID;
|
||||
SwitchLocation.X = desMachineXY.X;
|
||||
SwitchLocation.Y = desMachineXY.Y;
|
||||
SwitchLocation.ResetCount();
|
||||
MachineStuff.newDesMachineID = newDesMachineID;
|
||||
MachineStuff.SwitchLocation.X = desMachineXY.X;
|
||||
MachineStuff.SwitchLocation.Y = desMachineXY.Y;
|
||||
MachineStuff.SwitchLocation.ResetCount();
|
||||
_ = EvSwitch.Set();
|
||||
|
||||
// PostMessage(mainForm.Handle, WM_SWITCH, IntPtr.Zero, IntPtr.Zero);
|
||||
if (newDesMachineID != DragMachine)
|
||||
if (newDesMachineID != DragDrop.DragMachine)
|
||||
{
|
||||
if (!IsDragging && !IsDropping)
|
||||
if (!DragDrop.IsDragging && !DragDrop.IsDropping)
|
||||
{
|
||||
if (MouseDown && !RunOnLogonDesktop && !RunOnScrSaverDesktop)
|
||||
if (DragDrop.MouseDown && !RunOnLogonDesktop && !RunOnScrSaverDesktop)
|
||||
{
|
||||
DragDropStep02();
|
||||
DragDrop.DragDropStep02();
|
||||
}
|
||||
}
|
||||
else if (DragMachine != (ID)1)
|
||||
else if (DragDrop.DragMachine != (ID)1)
|
||||
{
|
||||
ChangeDropMachine();
|
||||
DragDrop.ChangeDropMachine();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
DragDropStep11();
|
||||
DragDrop.DragDropStep11();
|
||||
}
|
||||
|
||||
// Change des machine
|
||||
if (desMachineID != newDesMachineID)
|
||||
if (MachineStuff.desMachineID != newDesMachineID)
|
||||
{
|
||||
Logger.LogDebug("MouseEvent: Switching to new machine:" + newDesMachineName);
|
||||
|
||||
// Ask current machine to hide the Mouse cursor
|
||||
if (newDesMachineID != ID.ALL && desMachineID != MachineID)
|
||||
if (newDesMachineID != ID.ALL && MachineStuff.desMachineID != MachineID)
|
||||
{
|
||||
SendPackage(desMachineID, PackageType.HideMouse);
|
||||
SendPackage(MachineStuff.desMachineID, PackageType.HideMouse);
|
||||
}
|
||||
|
||||
DesMachineID = newDesMachineID;
|
||||
|
||||
if (desMachineID == MachineID)
|
||||
if (MachineStuff.desMachineID == MachineID)
|
||||
{
|
||||
if (GetTick() - clipboardCopiedTime < BIG_CLIPBOARD_DATA_TIMEOUT)
|
||||
{
|
||||
@@ -224,7 +224,7 @@ namespace MouseWithoutBorders
|
||||
else
|
||||
{
|
||||
// Ask the new active machine to get clipboard data (if the data is too big)
|
||||
SendPackage(desMachineID, PackageType.MachineSwitched);
|
||||
SendPackage(MachineStuff.desMachineID, PackageType.MachineSwitched);
|
||||
}
|
||||
|
||||
_ = Interlocked.Increment(ref switchCount);
|
||||
@@ -249,15 +249,15 @@ namespace MouseWithoutBorders
|
||||
try
|
||||
{
|
||||
PaintCount = 0;
|
||||
if (desMachineID != newDesMachineID)
|
||||
if (MachineStuff.desMachineID != MachineStuff.newDesMachineID)
|
||||
{
|
||||
Logger.LogDebug("KeybdEvent: Switching to new machine...");
|
||||
DesMachineID = newDesMachineID;
|
||||
DesMachineID = MachineStuff.newDesMachineID;
|
||||
}
|
||||
|
||||
if (desMachineID != MachineID)
|
||||
if (MachineStuff.desMachineID != MachineID)
|
||||
{
|
||||
KeybdPackage.Des = desMachineID;
|
||||
KeybdPackage.Des = MachineStuff.desMachineID;
|
||||
KeybdPackage.Type = PackageType.Keyboard;
|
||||
KeybdPackage.Kd = e;
|
||||
KeybdPackage.DateTime = GetTick();
|
||||
|
||||
@@ -9,6 +9,7 @@ using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
using System.Windows.Forms;
|
||||
|
||||
@@ -87,35 +88,35 @@ namespace MouseWithoutBorders
|
||||
break;
|
||||
}
|
||||
|
||||
if (Common.NewDesMachineID != Common.MachineID && Common.NewDesMachineID != ID.ALL)
|
||||
if (MachineStuff.NewDesMachineID != Common.MachineID && MachineStuff.NewDesMachineID != ID.ALL)
|
||||
{
|
||||
HideMouseCursor(false);
|
||||
Common.MainFormDotEx(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Common.SwitchLocation.Count > 0)
|
||||
if (MachineStuff.SwitchLocation.Count > 0)
|
||||
{
|
||||
Common.SwitchLocation.Count--;
|
||||
MachineStuff.SwitchLocation.Count--;
|
||||
|
||||
// When we want to move mouse by pixels, we add 300k to x and y (search for XY_BY_PIXEL for other related code).
|
||||
Logger.LogDebug($"+++++ Moving mouse to {Common.SwitchLocation.X}, {Common.SwitchLocation.Y}");
|
||||
Logger.LogDebug($"+++++ Moving mouse to {MachineStuff.SwitchLocation.X}, {MachineStuff.SwitchLocation.Y}");
|
||||
|
||||
// MaxXY = 65535 so 100k is safe.
|
||||
if (Common.SwitchLocation.X > XY_BY_PIXEL - 100000 || Common.SwitchLocation.Y > XY_BY_PIXEL - 100000)
|
||||
if (MachineStuff.SwitchLocation.X > XY_BY_PIXEL - 100000 || MachineStuff.SwitchLocation.Y > XY_BY_PIXEL - 100000)
|
||||
{
|
||||
InputSimulation.MoveMouse(Common.SwitchLocation.X - XY_BY_PIXEL, Common.SwitchLocation.Y - XY_BY_PIXEL);
|
||||
InputSimulation.MoveMouse(MachineStuff.SwitchLocation.X - XY_BY_PIXEL, MachineStuff.SwitchLocation.Y - XY_BY_PIXEL);
|
||||
}
|
||||
else
|
||||
{
|
||||
InputSimulation.MoveMouseEx(Common.SwitchLocation.X, Common.SwitchLocation.Y);
|
||||
InputSimulation.MoveMouseEx(MachineStuff.SwitchLocation.X, MachineStuff.SwitchLocation.Y);
|
||||
}
|
||||
|
||||
Common.MainFormDot();
|
||||
}
|
||||
}
|
||||
|
||||
if (Common.NewDesMachineID == Common.MachineID)
|
||||
if (MachineStuff.NewDesMachineID == Common.MachineID)
|
||||
{
|
||||
ReleaseAllKeys();
|
||||
}
|
||||
@@ -136,8 +137,8 @@ namespace MouseWithoutBorders
|
||||
|
||||
if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop)
|
||||
{
|
||||
int left = Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2) - 1;
|
||||
int top = Setting.Values.HideMouse ? 3 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2);
|
||||
int left = MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2) - 1;
|
||||
int top = Setting.Values.HideMouse ? 3 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2);
|
||||
|
||||
Common.MainFormVisible = true;
|
||||
|
||||
@@ -197,8 +198,8 @@ namespace MouseWithoutBorders
|
||||
DoSomethingInUIThread(
|
||||
() =>
|
||||
{
|
||||
MainForm.Left = Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2) - 2;
|
||||
MainForm.Top = Setting.Values.HideMouse ? 3 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2) - 1;
|
||||
MainForm.Left = MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2) - 2;
|
||||
MainForm.Top = Setting.Values.HideMouse ? 3 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2) - 1;
|
||||
MainForm.Width = 3;
|
||||
MainForm.Height = 3;
|
||||
MainForm.Opacity = 0.11D;
|
||||
@@ -229,8 +230,8 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
_ = Common.SendMessageToHelper(0x408, IntPtr.Zero, IntPtr.Zero, false);
|
||||
|
||||
MainForm.Left = Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2) - 1;
|
||||
MainForm.Top = Setting.Values.HideMouse ? 3 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2);
|
||||
MainForm.Left = MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2) - 1;
|
||||
MainForm.Top = Setting.Values.HideMouse ? 3 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2);
|
||||
MainForm.Width = 1;
|
||||
MainForm.Height = 1;
|
||||
MainForm.Opacity = 0.15;
|
||||
@@ -380,7 +381,7 @@ namespace MouseWithoutBorders
|
||||
log += $"{Setting.Values.Username}/{GetDebugInfo(MyKey)}\r\n";
|
||||
log += $"{MachineName}/{MachineID}/{DesMachineID}\r\n";
|
||||
log += $"Id: {Setting.Values.DeviceId}\r\n";
|
||||
log += $"Matrix: {string.Join(",", MachineMatrix)}\r\n";
|
||||
log += $"Matrix: {string.Join(",", MachineStuff.MachineMatrix)}\r\n";
|
||||
log += $"McPool: {Setting.Values.MachinePoolString}\r\n";
|
||||
|
||||
log += "\r\nOPTIONS:\r\n";
|
||||
@@ -443,7 +444,31 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
_ = Common.ImpersonateLoggedOnUserAndDoSomething(() =>
|
||||
{
|
||||
Setting.Values.Username = WindowsIdentity.GetCurrent(true).Name;
|
||||
// See: https://stackoverflow.com/questions/19487541/how-to-get-windows-user-name-from-sessionid
|
||||
static string GetUsernameBySessionId(int sessionId)
|
||||
{
|
||||
string username = "SYSTEM";
|
||||
if (NativeMethods.WTSQuerySessionInformation(IntPtr.Zero, sessionId, NativeMethods.WTSInfoClass.WTSUserName, out nint buffer, out int strLen) && strLen > 1)
|
||||
{
|
||||
username = Marshal.PtrToStringAnsi(buffer);
|
||||
NativeMethods.WTSFreeMemory(buffer);
|
||||
|
||||
if (NativeMethods.WTSQuerySessionInformation(IntPtr.Zero, sessionId, NativeMethods.WTSInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1)
|
||||
{
|
||||
username = @$"{Marshal.PtrToStringAnsi(buffer)}\{username}";
|
||||
NativeMethods.WTSFreeMemory(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
return username;
|
||||
}
|
||||
|
||||
// The most direct way to fetch the username is WindowsIdentity.GetCurrent(true).Name
|
||||
// but GetUserName can run within an ExecutionContext.SuppressFlow block, which creates issues
|
||||
// with WindowsIdentity.GetCurrent.
|
||||
// See: https://stackoverflow.com/questions/76998988/exception-when-using-executioncontext-suppressflow-in-net-7
|
||||
// So we use WTSQuerySessionInformation as a workaround.
|
||||
Setting.Values.Username = GetUsernameBySessionId(Process.GetCurrentProcess().SessionId);
|
||||
});
|
||||
}
|
||||
else
|
||||
|
||||
@@ -46,7 +46,7 @@ namespace MouseWithoutBorders
|
||||
internal static void UpdateMachineTimeAndID()
|
||||
{
|
||||
Common.MachineName = Common.MachineName.Trim();
|
||||
_ = Common.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
|
||||
_ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
|
||||
}
|
||||
|
||||
private static void InitializeMachinePoolFromSettings()
|
||||
@@ -59,13 +59,13 @@ namespace MouseWithoutBorders
|
||||
info[i].Name = info[i].Name.Trim();
|
||||
}
|
||||
|
||||
Common.MachinePool.Initialize(info);
|
||||
Common.MachinePool.ResetIPAddressesForDeadMachines(true);
|
||||
MachineStuff.MachinePool.Initialize(info);
|
||||
MachineStuff.MachinePool.ResetIPAddressesForDeadMachines(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Log(ex);
|
||||
Common.MachinePool.Clear();
|
||||
MachineStuff.MachinePool.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,16 +74,16 @@ namespace MouseWithoutBorders
|
||||
try
|
||||
{
|
||||
GetMachineName();
|
||||
DesMachineID = NewDesMachineID = MachineID;
|
||||
DesMachineID = MachineStuff.NewDesMachineID = MachineID;
|
||||
|
||||
// MessageBox.Show(machineID.ToString(CultureInfo.CurrentCulture)); // For test
|
||||
InitializeMachinePoolFromSettings();
|
||||
|
||||
Common.MachineName = Common.MachineName.Trim();
|
||||
_ = Common.MachinePool.LearnMachine(Common.MachineName);
|
||||
_ = Common.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
|
||||
_ = MachineStuff.MachinePool.LearnMachine(Common.MachineName);
|
||||
_ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
|
||||
|
||||
Common.UpdateMachinePoolStringSetting();
|
||||
MachineStuff.UpdateMachinePoolStringSetting();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -154,7 +154,7 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
Logger.TelemetryLogTrace($"{nameof(SystemEvents_PowerModeChanged)}: {e.Mode}", SeverityLevel.Information);
|
||||
LastResumeSuspendTime = DateTime.UtcNow;
|
||||
SwitchToMultipleMode(false, true);
|
||||
MachineStuff.SwitchToMultipleMode(false, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
@@ -39,23 +38,31 @@ namespace MouseWithoutBorders
|
||||
}
|
||||
else
|
||||
{
|
||||
// SuppressFlow fixes an issue on service mode, where WTSQueryUserToken runs successfully once and then fails
|
||||
// on subsequent calls. The reason appears to be an unknown issue with reverting the impersonation,
|
||||
// meaning that subsequent impersonation attempts run as the logged-on user and fail.
|
||||
// This is a workaround.
|
||||
using var asyncFlowControl = System.Threading.ExecutionContext.SuppressFlow();
|
||||
|
||||
uint dwSessionId;
|
||||
IntPtr hUserToken = IntPtr.Zero, hUserTokenDup = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
dwSessionId = (uint)Process.GetCurrentProcess().SessionId;
|
||||
uint rv = NativeMethods.WTSQueryUserToken(dwSessionId, ref hUserToken);
|
||||
Logger.LogDebug("WTSQueryUserToken returned " + rv.ToString(CultureInfo.CurrentCulture));
|
||||
var lastError = rv == 0 ? Marshal.GetLastWin32Error() : 0;
|
||||
|
||||
Logger.LogDebug($"{nameof(NativeMethods.WTSQueryUserToken)} returned {rv.ToString(CultureInfo.CurrentCulture)}");
|
||||
|
||||
if (rv == 0)
|
||||
{
|
||||
Logger.LogDebug($"WTSQueryUserToken failed with: {Marshal.GetLastWin32Error()}.");
|
||||
Logger.Log($"{nameof(NativeMethods.WTSQueryUserToken)} failed with: {lastError}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!NativeMethods.DuplicateToken(hUserToken, (int)NativeMethods.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref hUserTokenDup))
|
||||
{
|
||||
Logger.TelemetryLogTrace($"DuplicateToken Failed! {Logger.GetStackTrace(new StackTrace())}", SeverityLevel.Warning);
|
||||
Logger.TelemetryLogTrace($"{nameof(NativeMethods.DuplicateToken)} Failed! {Logger.GetStackTrace(new StackTrace())}", SeverityLevel.Warning);
|
||||
_ = NativeMethods.CloseHandle(hUserToken);
|
||||
_ = NativeMethods.CloseHandle(hUserTokenDup);
|
||||
return false;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -41,7 +41,7 @@ namespace MouseWithoutBorders
|
||||
GetScreenConfig();
|
||||
}
|
||||
|
||||
private static readonly List<Point> SensitivePoints = new();
|
||||
internal static readonly List<Point> SensitivePoints = new();
|
||||
|
||||
private static bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref NativeMethods.RECT lprcMonitor, IntPtr dwData)
|
||||
{
|
||||
@@ -162,21 +162,21 @@ namespace MouseWithoutBorders
|
||||
|
||||
// 1000 calls to EnumDisplayMonitors cost a dozen of milliseconds
|
||||
#endif
|
||||
Interlocked.Exchange(ref desktopBounds, newDesktopBounds);
|
||||
Interlocked.Exchange(ref primaryScreenBounds, newPrimaryScreenBounds);
|
||||
Interlocked.Exchange(ref MachineStuff.desktopBounds, newDesktopBounds);
|
||||
Interlocked.Exchange(ref MachineStuff.primaryScreenBounds, newPrimaryScreenBounds);
|
||||
|
||||
Logger.Log(string.Format(
|
||||
CultureInfo.CurrentCulture,
|
||||
"logon = {0} PrimaryScreenBounds = {1},{2},{3},{4} desktopBounds = {5},{6},{7},{8}",
|
||||
Common.RunOnLogonDesktop,
|
||||
Common.PrimaryScreenBounds.Left,
|
||||
Common.PrimaryScreenBounds.Top,
|
||||
Common.PrimaryScreenBounds.Right,
|
||||
Common.PrimaryScreenBounds.Bottom,
|
||||
Common.DesktopBounds.Left,
|
||||
Common.DesktopBounds.Top,
|
||||
Common.DesktopBounds.Right,
|
||||
Common.DesktopBounds.Bottom));
|
||||
MachineStuff.PrimaryScreenBounds.Left,
|
||||
MachineStuff.PrimaryScreenBounds.Top,
|
||||
MachineStuff.PrimaryScreenBounds.Right,
|
||||
MachineStuff.PrimaryScreenBounds.Bottom,
|
||||
MachineStuff.DesktopBounds.Left,
|
||||
MachineStuff.DesktopBounds.Top,
|
||||
MachineStuff.DesktopBounds.Right,
|
||||
MachineStuff.DesktopBounds.Bottom));
|
||||
|
||||
Logger.Log("==================== GetScreenConfig ended");
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ namespace MouseWithoutBorders
|
||||
internal const int JUST_GOT_BACK_FROM_SCREEN_SAVER = 9999;
|
||||
|
||||
internal const int NETWORK_STREAM_BUF_SIZE = 1024 * 1024;
|
||||
private static readonly EventWaitHandle EvSwitch = new(false, EventResetMode.AutoReset);
|
||||
internal static readonly EventWaitHandle EvSwitch = new(false, EventResetMode.AutoReset);
|
||||
private static Point lastPos;
|
||||
private static int switchCount;
|
||||
private static long lastReconnectByHotKeyTime;
|
||||
@@ -236,12 +236,12 @@ namespace MouseWithoutBorders
|
||||
|
||||
internal static ID DesMachineID
|
||||
{
|
||||
get => Common.desMachineID;
|
||||
get => MachineStuff.desMachineID;
|
||||
|
||||
set
|
||||
{
|
||||
Common.desMachineID = value;
|
||||
Common.DesMachineName = Common.NameFromID(Common.desMachineID);
|
||||
MachineStuff.desMachineID = value;
|
||||
MachineStuff.DesMachineName = MachineStuff.NameFromID(MachineStuff.desMachineID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,7 +351,7 @@ namespace MouseWithoutBorders
|
||||
Logger.TelemetryLogTrace($"[{actionName}] took more than {(long)timeout.TotalSeconds}, restarting the process.", SeverityLevel.Warning, true);
|
||||
|
||||
string desktop = Common.GetMyDesktop();
|
||||
oneInstanceCheck?.Close();
|
||||
MachineStuff.oneInstanceCheck?.Close();
|
||||
_ = Process.Start(Application.ExecutablePath, desktop);
|
||||
Logger.LogDebug($"Started on desktop {desktop}");
|
||||
|
||||
@@ -619,12 +619,12 @@ namespace MouseWithoutBorders
|
||||
|
||||
internal static void ProcessByeByeMessage(DATA package)
|
||||
{
|
||||
if (package.Src == desMachineID)
|
||||
if (package.Src == MachineStuff.desMachineID)
|
||||
{
|
||||
SwitchToMachine(MachineName.Trim());
|
||||
MachineStuff.SwitchToMachine(MachineName.Trim());
|
||||
}
|
||||
|
||||
_ = RemoveDeadMachines(package.Src);
|
||||
_ = MachineStuff.RemoveDeadMachines(package.Src);
|
||||
}
|
||||
|
||||
internal static long GetTick() // ms
|
||||
@@ -644,12 +644,12 @@ namespace MouseWithoutBorders
|
||||
try
|
||||
{
|
||||
string fileName = GetMyStorageDir() + @"ScreenCaptureByMouseWithoutBorders.png";
|
||||
int w = desktopBounds.Right - desktopBounds.Left;
|
||||
int h = desktopBounds.Bottom - desktopBounds.Top;
|
||||
int w = MachineStuff.desktopBounds.Right - MachineStuff.desktopBounds.Left;
|
||||
int h = MachineStuff.desktopBounds.Bottom - MachineStuff.desktopBounds.Top;
|
||||
Bitmap bm = new(w, h);
|
||||
Graphics g = Graphics.FromImage(bm);
|
||||
Size s = new(w, h);
|
||||
g.CopyFromScreen(desktopBounds.Left, desktopBounds.Top, 0, 0, s);
|
||||
g.CopyFromScreen(MachineStuff.desktopBounds.Left, MachineStuff.desktopBounds.Top, 0, 0, s);
|
||||
bm.Save(fileName, ImageFormat.Png);
|
||||
bm.Dispose();
|
||||
return fileName;
|
||||
@@ -665,7 +665,7 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
Common.DoSomethingInUIThread(() =>
|
||||
{
|
||||
if (!MouseDown && Common.SendMessageToHelper(0x401, IntPtr.Zero, IntPtr.Zero) > 0)
|
||||
if (!DragDrop.MouseDown && Common.SendMessageToHelper(0x401, IntPtr.Zero, IntPtr.Zero) > 0)
|
||||
{
|
||||
Common.MMSleep(0.2);
|
||||
InputSimulation.SendKey(new KEYBDDATA() { wVk = (int)VK.SNAPSHOT });
|
||||
@@ -675,10 +675,10 @@ namespace MouseWithoutBorders
|
||||
|
||||
_ = NativeMethods.MoveWindow(
|
||||
(IntPtr)NativeMethods.FindWindow(null, Common.HELPER_FORM_TEXT),
|
||||
Common.DesktopBounds.Left,
|
||||
Common.DesktopBounds.Top,
|
||||
Common.DesktopBounds.Right - Common.DesktopBounds.Left,
|
||||
Common.DesktopBounds.Bottom - Common.DesktopBounds.Top,
|
||||
MachineStuff.DesktopBounds.Left,
|
||||
MachineStuff.DesktopBounds.Top,
|
||||
MachineStuff.DesktopBounds.Right - MachineStuff.DesktopBounds.Left,
|
||||
MachineStuff.DesktopBounds.Bottom - MachineStuff.DesktopBounds.Top,
|
||||
false);
|
||||
|
||||
_ = Common.SendMessageToHelper(0x406, IntPtr.Zero, IntPtr.Zero, false);
|
||||
@@ -729,7 +729,7 @@ namespace MouseWithoutBorders
|
||||
}
|
||||
else
|
||||
{
|
||||
ID id = Common.MachinePool.ResolveID(machine);
|
||||
ID id = MachineStuff.MachinePool.ResolveID(machine);
|
||||
if (id != ID.NONE)
|
||||
{
|
||||
SendPackage(id, PackageType.ClipboardCapture);
|
||||
@@ -753,7 +753,7 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
if (Setting.Values.FirstRun)
|
||||
{
|
||||
Common.Settings?.ShowTip(icon, tip, timeOutInMilliseconds);
|
||||
MachineStuff.Settings?.ShowTip(icon, tip, timeOutInMilliseconds);
|
||||
}
|
||||
|
||||
Common.MatrixForm?.ShowTip(icon, tip, timeOutInMilliseconds);
|
||||
@@ -882,7 +882,7 @@ namespace MouseWithoutBorders
|
||||
|
||||
if (updateClientSockets)
|
||||
{
|
||||
UpdateClientSockets(nameof(IsConnectedTo));
|
||||
MachineStuff.UpdateClientSockets(nameof(IsConnectedTo));
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -921,7 +921,7 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
if (t != null && t.BackingSocket != null && (t.Status == SocketStatus.Connected || (t.Status == SocketStatus.Handshaking && includeHandShakingSockets)))
|
||||
{
|
||||
if (t.MachineId == (uint)data.Des || (data.Des == ID.ALL && t.MachineId != exceptDes && InMachineMatrix(t.MachineName)))
|
||||
if (t.MachineId == (uint)data.Des || (data.Des == ID.ALL && t.MachineId != exceptDes && MachineStuff.InMachineMatrix(t.MachineName)))
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -952,20 +952,20 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
Logger.LogDebug("********** No active connection found for the remote machine! **********" + data.Des.ToString());
|
||||
|
||||
if (data.Des == ID.NONE || RemoveDeadMachines(data.Des))
|
||||
if (data.Des == ID.NONE || MachineStuff.RemoveDeadMachines(data.Des))
|
||||
{
|
||||
// SwitchToMachine(MachineName.Trim());
|
||||
NewDesMachineID = DesMachineID = MachineID;
|
||||
SwitchLocation.X = XY_BY_PIXEL + myLastX;
|
||||
SwitchLocation.Y = XY_BY_PIXEL + myLastY;
|
||||
SwitchLocation.ResetCount();
|
||||
MachineStuff.NewDesMachineID = DesMachineID = MachineID;
|
||||
MachineStuff.SwitchLocation.X = XY_BY_PIXEL + myLastX;
|
||||
MachineStuff.SwitchLocation.Y = XY_BY_PIXEL + myLastY;
|
||||
MachineStuff.SwitchLocation.ResetCount();
|
||||
EvSwitch.Set();
|
||||
}
|
||||
}
|
||||
|
||||
if (updateClientSockets)
|
||||
{
|
||||
UpdateClientSockets("SkSend");
|
||||
MachineStuff.UpdateClientSockets("SkSend");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -1203,7 +1203,7 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
int machineCt = 0;
|
||||
|
||||
foreach (string m in Common.MachineMatrix)
|
||||
foreach (string m in MachineStuff.MachineMatrix)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(m.Trim()))
|
||||
{
|
||||
@@ -1211,15 +1211,15 @@ namespace MouseWithoutBorders
|
||||
}
|
||||
}
|
||||
|
||||
if (machineCt < 2 && Common.Settings != null && (Common.Settings.GetCurrentPage() is SetupPage1 || Common.Settings.GetCurrentPage() is SetupPage2b))
|
||||
if (machineCt < 2 && MachineStuff.Settings != null && (MachineStuff.Settings.GetCurrentPage() is SetupPage1 || MachineStuff.Settings.GetCurrentPage() is SetupPage2b))
|
||||
{
|
||||
Common.MachineMatrix = new string[Common.MAX_MACHINE] { Common.MachineName.Trim(), desMachine, string.Empty, string.Empty };
|
||||
Logger.LogDebug("UpdateSetupMachineMatrix: " + string.Join(",", Common.MachineMatrix));
|
||||
MachineStuff.MachineMatrix = new string[MachineStuff.MAX_MACHINE] { Common.MachineName.Trim(), desMachine, string.Empty, string.Empty };
|
||||
Logger.LogDebug("UpdateSetupMachineMatrix: " + string.Join(",", MachineStuff.MachineMatrix));
|
||||
|
||||
Common.DoSomethingInUIThread(
|
||||
() =>
|
||||
{
|
||||
Common.Settings.SetControlPage(new SetupPage4());
|
||||
MachineStuff.Settings.SetControlPage(new SetupPage4());
|
||||
},
|
||||
true);
|
||||
}
|
||||
@@ -1255,7 +1255,7 @@ namespace MouseWithoutBorders
|
||||
SocketStuff.ClearBadIPs();
|
||||
}
|
||||
|
||||
UpdateClientSockets("ReopenSockets");
|
||||
MachineStuff.UpdateClientSockets("ReopenSockets");
|
||||
}
|
||||
},
|
||||
true);
|
||||
@@ -1473,17 +1473,17 @@ namespace MouseWithoutBorders
|
||||
{
|
||||
Logger.LogDebug("+++++ MoveMouseToCenter");
|
||||
InputSimulation.MoveMouse(
|
||||
Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2),
|
||||
Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2));
|
||||
MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2),
|
||||
MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2));
|
||||
}
|
||||
|
||||
internal static void HideMouseCursor(bool byHideMouseMessage)
|
||||
{
|
||||
Common.LastPos = new Point(
|
||||
Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2),
|
||||
Setting.Values.HideMouse ? 4 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2));
|
||||
MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2),
|
||||
Setting.Values.HideMouse ? 4 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2));
|
||||
|
||||
if ((desMachineID != MachineID && desMachineID != ID.ALL) || byHideMouseMessage)
|
||||
if ((MachineStuff.desMachineID != MachineID && MachineStuff.desMachineID != ID.ALL) || byHideMouseMessage)
|
||||
{
|
||||
_ = NativeMethods.SetCursorPos(Common.LastPos.X, Common.LastPos.Y);
|
||||
_ = NativeMethods.GetCursorPos(ref Common.lastPos);
|
||||
|
||||
@@ -154,7 +154,7 @@ namespace MouseWithoutBorders
|
||||
|
||||
public void SendDragFile(string fileName)
|
||||
{
|
||||
Common.DragDropStep05Ex(fileName);
|
||||
DragDrop.DragDropStep05Ex(fileName);
|
||||
}
|
||||
|
||||
public void SendClipboardData(ByteArrayOrString data, bool isFilePath)
|
||||
|
||||
@@ -222,10 +222,10 @@ namespace MouseWithoutBorders.Class
|
||||
{
|
||||
Common.RealInputEventCount++;
|
||||
|
||||
if (Common.NewDesMachineID == Common.MachineID || Common.NewDesMachineID == ID.ALL)
|
||||
if (MachineStuff.NewDesMachineID == Common.MachineID || MachineStuff.NewDesMachineID == ID.ALL)
|
||||
{
|
||||
local = true;
|
||||
if (Common.MainFormVisible && !Common.IsDropping)
|
||||
if (Common.MainFormVisible && !DragDrop.IsDropping)
|
||||
{
|
||||
Common.MainFormDot();
|
||||
}
|
||||
@@ -265,19 +265,19 @@ namespace MouseWithoutBorders.Class
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Common.SwitchLocation.Count > 0 && Common.NewDesMachineID != Common.MachineID && Common.NewDesMachineID != ID.ALL)
|
||||
if (MachineStuff.SwitchLocation.Count > 0 && MachineStuff.NewDesMachineID != Common.MachineID && MachineStuff.NewDesMachineID != ID.ALL)
|
||||
{
|
||||
Common.SwitchLocation.Count--;
|
||||
MachineStuff.SwitchLocation.Count--;
|
||||
|
||||
if (Common.SwitchLocation.X > Common.XY_BY_PIXEL - 100000 || Common.SwitchLocation.Y > Common.XY_BY_PIXEL - 100000)
|
||||
if (MachineStuff.SwitchLocation.X > Common.XY_BY_PIXEL - 100000 || MachineStuff.SwitchLocation.Y > Common.XY_BY_PIXEL - 100000)
|
||||
{
|
||||
hookCallbackMouseData.X = Common.SwitchLocation.X - Common.XY_BY_PIXEL;
|
||||
hookCallbackMouseData.Y = Common.SwitchLocation.Y - Common.XY_BY_PIXEL;
|
||||
hookCallbackMouseData.X = MachineStuff.SwitchLocation.X - Common.XY_BY_PIXEL;
|
||||
hookCallbackMouseData.Y = MachineStuff.SwitchLocation.Y - Common.XY_BY_PIXEL;
|
||||
}
|
||||
else
|
||||
{
|
||||
hookCallbackMouseData.X = (Common.SwitchLocation.X * Common.ScreenWidth / 65535) + Common.PrimaryScreenBounds.Left;
|
||||
hookCallbackMouseData.Y = (Common.SwitchLocation.Y * Common.ScreenHeight / 65535) + Common.PrimaryScreenBounds.Top;
|
||||
hookCallbackMouseData.X = (MachineStuff.SwitchLocation.X * Common.ScreenWidth / 65535) + MachineStuff.PrimaryScreenBounds.Left;
|
||||
hookCallbackMouseData.Y = (MachineStuff.SwitchLocation.Y * Common.ScreenHeight / 65535) + MachineStuff.PrimaryScreenBounds.Top;
|
||||
}
|
||||
|
||||
Common.HideMouseCursor(false);
|
||||
@@ -290,22 +290,22 @@ namespace MouseWithoutBorders.Class
|
||||
hookCallbackMouseData.X += dx;
|
||||
hookCallbackMouseData.Y += dy;
|
||||
|
||||
if (hookCallbackMouseData.X < Common.PrimaryScreenBounds.Left)
|
||||
if (hookCallbackMouseData.X < MachineStuff.PrimaryScreenBounds.Left)
|
||||
{
|
||||
hookCallbackMouseData.X = Common.PrimaryScreenBounds.Left - 1;
|
||||
hookCallbackMouseData.X = MachineStuff.PrimaryScreenBounds.Left - 1;
|
||||
}
|
||||
else if (hookCallbackMouseData.X > Common.PrimaryScreenBounds.Right)
|
||||
else if (hookCallbackMouseData.X > MachineStuff.PrimaryScreenBounds.Right)
|
||||
{
|
||||
hookCallbackMouseData.X = Common.PrimaryScreenBounds.Right + 1;
|
||||
hookCallbackMouseData.X = MachineStuff.PrimaryScreenBounds.Right + 1;
|
||||
}
|
||||
|
||||
if (hookCallbackMouseData.Y < Common.PrimaryScreenBounds.Top)
|
||||
if (hookCallbackMouseData.Y < MachineStuff.PrimaryScreenBounds.Top)
|
||||
{
|
||||
hookCallbackMouseData.Y = Common.PrimaryScreenBounds.Top - 1;
|
||||
hookCallbackMouseData.Y = MachineStuff.PrimaryScreenBounds.Top - 1;
|
||||
}
|
||||
else if (hookCallbackMouseData.Y > Common.PrimaryScreenBounds.Bottom)
|
||||
else if (hookCallbackMouseData.Y > MachineStuff.PrimaryScreenBounds.Bottom)
|
||||
{
|
||||
hookCallbackMouseData.Y = Common.PrimaryScreenBounds.Bottom + 1;
|
||||
hookCallbackMouseData.Y = MachineStuff.PrimaryScreenBounds.Bottom + 1;
|
||||
}
|
||||
|
||||
dx += dx < 0 ? -Common.MOVE_MOUSE_RELATIVE : Common.MOVE_MOUSE_RELATIVE;
|
||||
@@ -315,8 +315,8 @@ namespace MouseWithoutBorders.Class
|
||||
|
||||
MouseEvent(hookCallbackMouseData, dx, dy);
|
||||
|
||||
Common.DragDropStep01(wParam);
|
||||
Common.DragDropStep09(wParam);
|
||||
DragDrop.DragDropStep01(wParam);
|
||||
DragDrop.DragDropStep09(wParam);
|
||||
}
|
||||
|
||||
if (local)
|
||||
@@ -432,7 +432,7 @@ namespace MouseWithoutBorders.Class
|
||||
|
||||
if (Common.DesMachineID != ID.ALL)
|
||||
{
|
||||
Common.SwitchToMachine(Common.MachineName.Trim());
|
||||
MachineStuff.SwitchToMachine(Common.MachineName.Trim());
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -518,7 +518,7 @@ namespace MouseWithoutBorders.Class
|
||||
if (Common.HotkeyMatched(vkCode, winDown, CtrlDown, altDown, shiftDown, Setting.Values.HotKeySwitch2AllPC))
|
||||
{
|
||||
ResetLastSwitchKeys();
|
||||
Common.SwitchToMultipleMode(Common.DesMachineID != ID.ALL, true);
|
||||
MachineStuff.SwitchToMultipleMode(Common.DesMachineID != ID.ALL, true);
|
||||
}
|
||||
|
||||
if (Common.HotkeyMatched(vkCode, winDown, CtrlDown, altDown, shiftDown, Setting.Values.HotKeyToggleEasyMouse))
|
||||
@@ -543,7 +543,7 @@ namespace MouseWithoutBorders.Class
|
||||
{
|
||||
if (Common.GetTick() - lastHotKeyLockMachine < 500)
|
||||
{
|
||||
Common.SwitchToMultipleMode(true, true);
|
||||
MachineStuff.SwitchToMultipleMode(true, true);
|
||||
|
||||
var codes = GetVkCodesList(Setting.Values.HotKeyLockMachine);
|
||||
|
||||
@@ -561,7 +561,7 @@ namespace MouseWithoutBorders.Class
|
||||
KeyboardEvent(hookCallbackKeybdData);
|
||||
}
|
||||
|
||||
Common.SwitchToMultipleMode(false, true);
|
||||
MachineStuff.SwitchToMultipleMode(false, true);
|
||||
|
||||
_ = NativeMethods.LockWorkStation();
|
||||
}
|
||||
@@ -625,9 +625,9 @@ namespace MouseWithoutBorders.Class
|
||||
|
||||
private static bool Switch2(int index)
|
||||
{
|
||||
if (Common.MachineMatrix != null && Common.MachineMatrix.Length > index)
|
||||
if (MachineStuff.MachineMatrix != null && MachineStuff.MachineMatrix.Length > index)
|
||||
{
|
||||
string mcName = Common.MachineMatrix[index].Trim();
|
||||
string mcName = MachineStuff.MachineMatrix[index].Trim();
|
||||
if (!string.IsNullOrEmpty(mcName))
|
||||
{
|
||||
// Common.DoSomethingInUIThread(delegate()
|
||||
@@ -636,7 +636,7 @@ namespace MouseWithoutBorders.Class
|
||||
}
|
||||
|
||||
// );
|
||||
Common.SwitchToMachine(mcName);
|
||||
MachineStuff.SwitchToMachine(mcName);
|
||||
|
||||
if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop)
|
||||
{
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user