Compare commits

...

15 Commits

Author SHA1 Message Date
Laszlo Nemeth
8a2d4745fa [PTRun]Fix locking link files for MSI installers. Warning 1946 (#37654)
* [Runner] fix MSI installer issue. Warning 1946

* Fix catching exceptions

* Better error handling

* Revert "Better error handling"

This reverts commit 0f3ec2a3ef.
2025-02-27 19:17:43 +00:00
leileizhang
bf2685757a [CI] Use Download Task for X64 and Bypass ARM Testing for Forked Repositories (#37617)
* use x64

* add conditation for arm tests

* check repo

* use System.PullRequest.IsFork

* remove print

* remove condition
2025-02-27 16:39:25 +08:00
Laszlo Nemeth
b8cef42776 [Workspaces] Fix regression when capturing minimized apps (#37599) 2025-02-26 12:51:46 +01:00
Jerry Xu
959a54bcd9 Revert "[Hosts] Add UITest Cases for Hosts Module" (#37619)
* Revert "[Hosts] Add UITest Cases for Hosts Module (#37600)"

This reverts commit c656dcc9c5.

* Matching all UITest projects and UITestAutomation project

* Add back Hosts UITests

---------

Co-authored-by: Jerry Xu <nxu@microsoft.com>
2025-02-26 07:55:15 +08:00
Smeagol
491d51afaf [QuickAccent]Add final sigma ( ς ) to the Greek character set (#37611) 2025-02-25 22:35:22 +00:00
Ani
f263042aeb [AdvancedPaste]Add paste actions to allow transcoding of media files (#37188)
* [AdvancedPaste] Additional actions, including Image to text

* Spellcheck issue

* [AdvancedPaste] Paste as file and many other improvements

* Fixed typo

* Fixed typo

* [AdvancedPaste] Improved paste window menu layout

* [AdvancedPaste] Improved settings window layout

* [AdvancedPaste] Removed AudioToText for the moment

* Code cleanup

* Minor fixes

* [AdvancedPaste] Semantic Kernel support

* Changed log-line with potentially sensitive info

* Spellcheck issues

* Various improvements for Semantic Kernel

* Spellcheck issue

* Refactored Clipboard routines

* Added integration tests for KernelService

* Extra telemetry for AdvancedPaste

* Added 'Hotkey' suffix to AdvancedPaste_Settings telemetry event

* Added IsSavedQuery

* Added KernelQueryCache

* Refactoring

* Added KernelQueryCache to BugReportTool delete list

* Added opt-n for Semantic Kernel

* Fixed bug with KernelQueryCache

* Ability to view last AI chat message on error

* Improved kernel query cache

* Used System.IO.Abstractions and improved tests

* Fixed under-count of token usage

* Used Semantic Kernel icon

* Cleanup

* Add missing EndProject line

* Fix dependency version conflicts

* Fix NOTICE.md

* Correct place of SemanticKernel in NOTICE.md

* Unlinked CustomPreview toggle from AI

* Added Microsoft.Bcl.AsyncInterfaces dependency to AdvancedPaste

* Fixed NOTICE.md order

* Moved Custom Preview to behaviour section

* Made Image to Text raise error on empty output

* Added AIServiceBatchIntegrationTests

* Updated AIServiceBatchIntegrationTests

* Added prompt moderation

* [AdvancedPaste] Media Transcoding support

* Spellcheck issue

* Improved transcoding output profile and added tests

* Moved GPO Infobar to better location

* Added cancel button and minor bug fixes

* Fixed crash

* Minor cleanups

* Improved transcoding error messages

* Used software back when transcoding fails with hardware accerlation

* Added Reencode to spellcheck

* Spellcheck issue

---------

Co-authored-by: Jaime Bernardo <jaime@janeasystems.com>
Co-authored-by: Dustin L. Howett <dustin@howett.net>
Co-authored-by: Jeremy Sinclair <4016293+snickler@users.noreply.github.com>
2025-02-25 21:33:39 +00:00
moooyo
c09a5337c4 [AOT] Refactor Logger function to improve performance and mark managedCommon as AOT compatible (#36327)
* Use function to init static value

* Replace GetFileName with GetFileNameWithoutExtension

* Add exception catch for GetCallerInfo

* Remove sourceLineNumber

* Add kernal to allow list

* Remove unused commit

* Add new folder to place source generation context

* update

* fix build issue

* Move line number back

* Use fileName to replace full path

---------

Co-authored-by: Yu Leng (from Dev Box) <yuleng@microsoft.com>
2025-02-26 00:12:38 +08:00
Ionuț Manța
9a658eb884 [PTRun] Disable CETCompat in Launcher (#37550)
* Disable CETCompat in Launcher

* Added comment

* Improved comment
2025-02-25 11:34:30 +00:00
Kai Tao
4eb11d6f9b [Workspaces][ARM64] Bring icon to packaged apps (#37625)
Bring icon to packaged apps
2025-02-25 19:17:41 +08:00
Dave Rayment
a5a354a70f [ImageResizer] Fix issues with blank Width and Height controls (#37373)
* Allow custom preset's dimensions to be blank in the UI while still persisted as 0.

* XAML formatting - reorder namespaces.

* Add "(auto)" text to zero-value Width/Height in Settings. Ensure Width and Height fields in flyout are formatted to empty when their value is 0.
2025-02-25 16:23:30 +08:00
Ionuț Manța
744316c400 [Settings]Fix ColorPicker dashboard shortcut (#37547)
* Fix color picker dashboard shortcut

* remove not needed code

* Remove comment
2025-02-24 23:14:45 +00:00
Jaime Bernardo
f2370912f3 [ci]Sign and fix KeyboardManagerEditorLibraryWrapper.dll (#37601)
* [ci]Sign KeyboardManagerEditorLibraryWrapper.dll

* Fix dll metadata
2025-02-24 21:12:42 +00:00
moooyo
5cc30df4db [AOT] Clean up AOT build issue in Common.UI (#36376)
* init commit

* Use path.combine

* Add useWPF and useWindowsForms back

---------

Co-authored-by: Yu Leng (from Dev Box) <yuleng@microsoft.com>
2025-02-25 02:56:04 +08:00
moooyo
f81f65db3d [AOT] clean up AOT issue in Settings.UI (#36559)
* Rename source generation context file

* fix build issue

* fix path bug

---------

Co-authored-by: Yu Leng (from Dev Box) <yuleng@microsoft.com>
2025-02-25 02:48:54 +08:00
leileizhang
9f008a65d6 [Build] Revert "[Hosts] Add UITest Cases for Hosts Module (#37600)" to fix CI issue (#37606)
Revert "[Hosts] Add UITest Cases for Hosts Module (#37600)"

This reverts commit c656dcc9c5.
2025-02-24 16:30:33 +00:00
121 changed files with 1524 additions and 308 deletions

View File

@@ -1283,7 +1283,7 @@ rectp
RECTSOURCE
recyclebin
Redist
reencode
Reencode
reencoded
REFCLSID
REFGUID

View File

@@ -128,6 +128,7 @@
"PowerToys.KeyboardManager.dll",
"KeyboardManagerEditor\\PowerToys.KeyboardManagerEditor.exe",
"KeyboardManagerEngine\\PowerToys.KeyboardManagerEngine.exe",
"PowerToys.KeyboardManagerEditorLibraryWrapper.dll",
"PowerToys.Launcher.dll",
"PowerToys.PowerLauncher.dll",

View File

@@ -61,9 +61,18 @@ jobs:
reg add "HKLM\Software\Policies\Microsoft\Edge\WebView2\ReleaseChannels" /v PowerToys.exe /t REG_SZ /d "3"
displayName: "Enable WebView2 Canary Channel"
- template: steps-download-artifacts-with-azure-cli.yml
parameters:
artifactName: $(TestArtifactsName)
- ${{ if ne(parameters.platform, 'arm64') }}:
- download: current
displayName: Download artifacts
artifact: $(TestArtifactsName)
patterns: |-
**
!**\*.pdb
!**\*.lib
- ${{ else }}:
- template: steps-download-artifacts-with-azure-cli.yml
parameters:
artifactName: $(TestArtifactsName)
- template: steps-ensure-dotnet-version.yml
parameters:

View File

@@ -72,7 +72,7 @@ stages:
winAppSDKVersionNumber: ${{ parameters.winAppSDKVersionNumber }}
useExperimentalVersion: ${{ parameters.useExperimentalVersion }}
- ${{ if eq(parameters.runTests, true) }}:
- ${{ if and(eq(parameters.runTests, true), not(and(eq(platform, 'arm64'), eq(variables['System.PullRequest.IsFork'], true)))) }}:
- stage: Test_${{ platform }}
displayName: Test ${{ platform }}
dependsOn:

View File

@@ -15,7 +15,7 @@ Param(
$referencedFileVersionsPerDll = @{}
$totalFailures = 0
Get-ChildItem $targetDir -Recurse -Filter *.deps.json -Exclude *UITests*,MouseJump.Common.UnitTests*,*.FuzzTests* | ForEach-Object {
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

View File

@@ -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>

View File

@@ -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
{

View File

@@ -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";

View File

@@ -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)
{

View File

@@ -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}";
}
}
}

View File

@@ -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>

View File

@@ -53,7 +53,7 @@ namespace ManagedCommon
internal static int Size
{
get { return Marshal.SizeOf(typeof(INPUT)); }
get { return Marshal.SizeOf<INPUT>(); }
}
}

View File

@@ -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();
}
});

View 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.
using System.Text.Json.Serialization;
using static ManagedCommon.LanguageHelper;
namespace ManagedCommon.Serialization;
[JsonSerializable(typeof(OutGoingLanguageSettings))]
internal sealed partial class SourceGenerationContext : JsonSerializerContext
{
}

View File

@@ -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.

View File

@@ -16,7 +16,7 @@ namespace Microsoft.PowerToys.UITest
/// <summary>
/// Represents a basic UI element in the application.
/// </summary>
public abstract class Element
public class Element
{
private WindowsElement? windowsElement;

View File

@@ -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;

View File

@@ -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)
{
}
}

View File

@@ -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}");

View File

@@ -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);

View File

@@ -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));
}

View File

@@ -28,6 +28,7 @@
Background="Transparent"
BorderThickness="4"
CornerRadius="{TemplateBinding CornerRadius}"
IsHitTestVisible="False"
Visibility="Collapsed">
<!-- CornerRadius needs to be > 0 -->
<Grid.BorderBrush>

View File

@@ -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=&#xE711;,
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>

View File

@@ -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)

View File

@@ -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;
}

View File

@@ -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);
}
}

View File

@@ -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;

View File

@@ -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);
}
}

View File

@@ -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)

View File

@@ -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);
}
}

View File

@@ -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);
}

View File

@@ -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();

View File

@@ -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
}

View File

@@ -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,
};
}

View File

@@ -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,

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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)
{

View File

@@ -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;
}

View File

@@ -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}");

View File

@@ -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),
});
}

View File

@@ -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>

View File

@@ -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;
});
}
}
}

View File

@@ -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")
);
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -22,4 +22,4 @@
<PackageReference Include="MSTest" />
<ProjectReference Include="..\..\..\common\UITestAutomation\UITestAutomation.csproj" />
</ItemGroup>
</Project>
</Project>

View File

@@ -192,7 +192,7 @@ namespace WorkspacesCsharpLibrary.Models
else
{
string appPath = AppPath.Replace("C:\\Program Files\\WindowsApps\\", string.Empty);
Regex packagedAppPathRegex = new Regex(@"(?<APPID>[^_]*)_\d+.\d+.\d+.\d+_x64__(?<PublisherID>[^\\]*)", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
Regex packagedAppPathRegex = new Regex(@"(?<APPID>[^_]*)_\d+.\d+.\d+.\d+_(:?x64|arm64)__(?<PublisherID>[^\\]*)", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
Match match = packagedAppPathRegex.Match(appPath);
_isPackagedApp = match.Success;
if (match.Success)

View File

@@ -62,10 +62,10 @@ namespace PlacementHelper
else
{
placement.showCmd = SW_RESTORE;
ScreenToWorkAreaCoords(window, monitor, rect);
placement.rcNormalPosition = rect;
}
ScreenToWorkAreaCoords(window, monitor, rect);
placement.rcNormalPosition = rect;
placement.flags |= WPF_ASYNCWINDOWPLACEMENT;
auto result = ::SetWindowPlacement(window, &placement);

View File

@@ -21,6 +21,8 @@
<v:VisibilityBoolConverter x:Key="VisibilityBoolConverter" />
<v:EnumToIntConverter x:Key="EnumToIntConverter" />
<v:AccessTextToTextConverter x:Key="AccessTextToTextConverter" />
<v:NumberBoxValueConverter x:Key="NumberBoxValueConverter" />
<v:ZeroToEmptyStringNumberFormatter x:Key="ZeroToEmptyStringNumberFormatter" />
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@@ -10,29 +10,55 @@ using System.Windows.Data;
using ImageResizer.Properties;
namespace ImageResizer.Views
namespace ImageResizer.Views;
/// <summary>
/// Converts between double and string for text-based controls bound to Width or Height fields.
/// Optionally returns localized "Auto" text when the underlying value is 0, letting the UI show,
/// for example "(auto) x 1024 pixels".
/// </summary>
[ValueConversion(typeof(double), typeof(string))]
internal class AutoDoubleConverter : IValueConverter
{
[ValueConversion(typeof(double), typeof(string))]
internal class AutoDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
/// <summary>
/// Converts a double to a string, optionally showing "Auto" for 0 values. NaN values are
/// converted to empty strings.
/// </summary>
/// <param name="value">The value to convert from <see cref="double"/> to
/// <see cref="string"/>.</param>
/// <param name="targetType">The conversion target type. <see cref="string"/> here.</param>
/// <param name="parameter">Set to "Auto" to return the localized "Auto" string if the
/// value is 0.</param>
/// <param name="culture">The <see cref="CultureInfo"/> to use for the number formatting.
/// </param>
/// <returns>The string representation of the passed-in value.</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value switch
{
var d = (double)value;
double d => d switch
{
double.NaN => "0",
0 => (string)parameter == "Auto" ? Resources.Input_Auto : "0",
_ => d.ToString(culture),
},
return d != 0
? d.ToString(culture)
: (string)parameter == "Auto"
? Resources.Input_Auto
: string.Empty;
}
_ => "0",
};
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
/// <summary>
/// Converts the string representation back to a double, returning 0 if the string is empty,
/// null or not a valid number in the specified culture.
/// </summary>
/// <param name="value">The string value to convert.</param>
/// <param name="targetType">The conversion target type. <see cref="double"/> here.</param>
/// <param name="parameter">Converter parameter. Unused.</param>
/// <param name="culture">The <see cref="CultureInfo"/> to use for the text parsing.</param>
/// <returns>The corresponding double value.</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
value switch
{
var text = (string)value;
return !string.IsNullOrEmpty(text)
? double.Parse(text, culture)
: 0;
}
}
null or "" => 0,
string text when double.TryParse(text, NumberStyles.Any, culture, out double result) => result,
_ => 0,
};
}

View File

@@ -4,7 +4,8 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:m="clr-namespace:ImageResizer.Models"
xmlns:p="clr-namespace:ImageResizer.Properties"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:v="clr-namespace:ImageResizer.Views">
<Grid>
<Grid.RowDefinitions>
@@ -114,8 +115,12 @@
KeyDown="Button_KeyDown"
Minimum="0"
SpinButtonPlacementMode="Inline">
<ui:NumberBox.NumberFormatter>
<v:ZeroToEmptyStringNumberFormatter />
</ui:NumberBox.NumberFormatter>
<ui:NumberBox.Value>
<Binding
Converter="{StaticResource NumberBoxValueConverter}"
ElementName="SizeComboBox"
Mode="TwoWay"
Path="SelectedValue.Width"
@@ -143,8 +148,12 @@
Minimum="0"
SpinButtonPlacementMode="Inline"
Visibility="{Binding ElementName=SizeComboBox, Path=SelectedValue.ShowHeight, Converter={StaticResource BoolValueConverter}}">
<ui:NumberBox.NumberFormatter>
<v:ZeroToEmptyStringNumberFormatter />
</ui:NumberBox.NumberFormatter>
<ui:NumberBox.Value>
<Binding
Converter="{StaticResource NumberBoxValueConverter}"
ElementName="SizeComboBox"
Mode="TwoWay"
Path="SelectedValue.Height"

View File

@@ -0,0 +1,32 @@
// 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.Globalization;
using System.Windows.Data;
namespace ImageResizer.Views;
public class NumberBoxValueConverter : IValueConverter
{
/// <summary>
/// Converts the underlying double value to a display-friendly format. Ensures that NaN values
/// are not propagated to the UI.
/// </summary>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is double d && double.IsNaN(d) ? 0 : value;
/// <summary>
/// Converts the user input back to the underlying double value. If the input is not a valid
/// number, 0 is returned.
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
value switch
{
null => 0,
double d when double.IsNaN(d) => 0,
string str when !double.TryParse(str, out _) => 0,
_ => value,
};
}

View File

@@ -0,0 +1,37 @@
// 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.Globalization;
using Wpf.Ui.Controls;
namespace ImageResizer.Views;
public class ZeroToEmptyStringNumberFormatter : INumberFormatter, INumberParser
{
public string FormatDouble(double? value) => value switch
{
null => string.Empty,
0 => string.Empty,
_ => value.Value.ToString(CultureInfo.CurrentCulture),
};
public double? ParseDouble(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return 0;
}
return double.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out double result) ? result : 0;
}
public string FormatInt(int? value) => throw new NotImplementedException();
public string FormatUInt(uint? value) => throw new NotImplementedException();
public int? ParseInt(string value) => throw new NotImplementedException();
public uint? ParseUInt(string value) => throw new NotImplementedException();
}

View File

@@ -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

View File

@@ -34,6 +34,9 @@
<RootNamespace>KeyboardManagerEditorLibraryWrapper</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<PropertyGroup>
<TargetName>PowerToys.KeyboardManagerEditorLibraryWrapper</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
@@ -218,6 +221,7 @@
<ClInclude Include="framework.h" />
<ClInclude Include="KeyboardManagerEditorLibraryWrapper.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="resource.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
@@ -231,6 +235,9 @@
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="KeyboardManagerEditorLibraryWrapper.rc" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>

View File

@@ -24,6 +24,9 @@
<ClInclude Include="KeyboardManagerEditorLibraryWrapper.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Resource Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
@@ -39,4 +42,9 @@
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="KeyboardManagerEditorLibraryWrapper.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by AlwaysOnTopModuleInterface.rc
//////////////////////////////
// Non-localizable
#define FILE_DESCRIPTION "PowerToys Keyboard Manager Editor Library Wrapper"
#define INTERNAL_NAME "PowerToys.KeyboardManagerEditorLibraryWrapper"
#define ORIGINAL_FILENAME "PowerToys.KeyboardManagerEditorLibraryWrapper.dll"
// Non-localizable
//////////////////////////////

View File

@@ -7,6 +7,8 @@
<AssemblyTitle>PowerToys.Run</AssemblyTitle>
<OutputType>WinExe</OutputType>
<UseWPF>true</UseWPF>
<!-- For some users, it crashes in ExtractAssociatedIcon https://github.com/microsoft/PowerToys/issues/37254. Workaround suggested here https://github.com/dotnet/wpf/issues/10483 was to disable CETCompat -->
<CETCompat>false</CETCompat>
<UseWindowsForms>False</UseWindowsForms>
<StartupObject>PowerLauncher.App</StartupObject>
<ApplicationIcon>Assets\PowerLauncher\RunResource.ico</ApplicationIcon>

View File

@@ -136,13 +136,25 @@ namespace Wox.Infrastructure
var link = new ShellLink();
const int STGM_READ = 0;
// Make sure not to open exclusive handles.
// See: https://github.com/microsoft/WSL/issues/11276
const int STGM_SHARE_DENY_NONE = 0x00000040;
const int STGM_TRANSACTED = 0x00010000;
try
{
((IPersistFile)link).Load(path, STGM_READ);
((IPersistFile)link).Load(path, STGM_READ | STGM_SHARE_DENY_NONE | STGM_TRANSACTED);
}
catch (System.IO.FileNotFoundException ex)
{
Log.Exception("Path could not be retrieved", ex, GetType(), path);
Log.Exception("Path could not be retrieved " + path, ex, GetType(), path);
Marshal.ReleaseComObject(link);
return string.Empty;
}
catch (System.Exception ex)
{
Log.Exception("Exception loading path " + path, ex, GetType(), path);
Marshal.ReleaseComObject(link);
return string.Empty;
}

View File

@@ -677,7 +677,7 @@ namespace PowerAccent.Core
LetterKey.VK_O => new string[] { "ο", "ό", "ω", "ώ" },
LetterKey.VK_P => new string[] { "π", "φ", "ψ" },
LetterKey.VK_R => new string[] { "ρ" },
LetterKey.VK_S => new string[] { "σ" },
LetterKey.VK_S => new string[] { "σ", "ς" },
LetterKey.VK_T => new string[] { "τ", "θ", "ϑ" },
LetterKey.VK_U => new string[] { "υ", "ύ" },
LetterKey.VK_X => new string[] { "ξ" },

View File

@@ -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.Collections.Generic;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
@@ -36,4 +37,7 @@ public sealed partial class AdvancedPasteAdditionalAction : Observable, IAdvance
get => _isShown;
set => Set(ref _isShown, value);
}
[JsonIgnore]
public IEnumerable<IAdvancedPasteAction> SubActions => [];
}

View File

@@ -14,6 +14,7 @@ public sealed class AdvancedPasteAdditionalActions
{
public const string ImageToText = "image-to-text";
public const string PasteAsFile = "paste-as-file";
public const string Transcode = "transcode";
}
[JsonPropertyName(PropertyNames.ImageToText)]
@@ -22,6 +23,22 @@ public sealed class AdvancedPasteAdditionalActions
[JsonPropertyName(PropertyNames.PasteAsFile)]
public AdvancedPastePasteAsFileAction PasteAsFile { get; init; } = new();
[JsonIgnore]
public IEnumerable<IAdvancedPasteAction> AllActions => new IAdvancedPasteAction[] { ImageToText, PasteAsFile }.Concat(PasteAsFile.SubActions);
[JsonPropertyName(PropertyNames.Transcode)]
public AdvancedPasteTranscodeAction Transcode { get; init; } = new();
public IEnumerable<IAdvancedPasteAction> GetAllActions()
{
Queue<IAdvancedPasteAction> queue = new([ImageToText, PasteAsFile, Transcode]);
while (queue.Count != 0)
{
var action = queue.Dequeue();
yield return action;
foreach (var subAction in action.SubActions)
{
queue.Enqueue(subAction);
}
}
}
}

View File

@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
@@ -98,6 +99,9 @@ public sealed class AdvancedPasteCustomAction : Observable, IAdvancedPasteAction
private set => Set(ref _isValid, value);
}
[JsonIgnore]
public IEnumerable<IAdvancedPasteAction> SubActions => [];
public object Clone()
{
AdvancedPasteCustomAction clone = new();

View File

@@ -52,5 +52,5 @@ public sealed class AdvancedPastePasteAsFileAction : Observable, IAdvancedPasteA
}
[JsonIgnore]
public IEnumerable<AdvancedPasteAdditionalAction> SubActions => [PasteAsTxtFile, PasteAsPngFile, PasteAsHtmlFile];
public IEnumerable<IAdvancedPasteAction> SubActions => [PasteAsTxtFile, PasteAsPngFile, PasteAsHtmlFile];
}

View File

@@ -0,0 +1,47 @@
// 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.Generic;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
namespace Microsoft.PowerToys.Settings.UI.Library;
public sealed class AdvancedPasteTranscodeAction : Observable, IAdvancedPasteAction
{
public static class PropertyNames
{
public const string TranscodeToMp3 = "transcode-to-mp3";
public const string TranscodeToMp4 = "transcode-to-mp4";
}
private AdvancedPasteAdditionalAction _transcodeToMp3 = new();
private AdvancedPasteAdditionalAction _transcodeToMp4 = new();
private bool _isShown = true;
[JsonPropertyName("isShown")]
public bool IsShown
{
get => _isShown;
set => Set(ref _isShown, value);
}
[JsonPropertyName(PropertyNames.TranscodeToMp3)]
public AdvancedPasteAdditionalAction TranscodeToMp3
{
get => _transcodeToMp3;
init => Set(ref _transcodeToMp3, value);
}
[JsonPropertyName(PropertyNames.TranscodeToMp4)]
public AdvancedPasteAdditionalAction TranscodeToMp4
{
get => _transcodeToMp4;
init => Set(ref _transcodeToMp4, value);
}
[JsonIgnore]
public IEnumerable<IAdvancedPasteAction> SubActions => [TranscodeToMp3, TranscodeToMp4];
}

View File

@@ -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.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerToys.Settings.UI.Library;
@@ -9,4 +10,6 @@ namespace Microsoft.PowerToys.Settings.UI.Library;
public interface IAdvancedPasteAction : INotifyPropertyChanged
{
public bool IsShown { get; }
public IEnumerable<IAdvancedPasteAction> SubActions { get; }
}

View File

@@ -0,0 +1,61 @@
// 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.Globalization;
using Microsoft.UI.Xaml.Data;
namespace Microsoft.PowerToys.Settings.UI.Converters;
/// <summary>
/// Converts between double and string for text-based controls bound to Width or Height fields.
/// Optionally returns localized "Auto" text when the underlying value is 0, letting the UI show,
/// for example "(auto) x 1024 pixels".
/// </summary>
public sealed partial class ImageResizerDoubleToAutoConverter : IValueConverter
{
private static readonly string AutoText =
Helpers.ResourceLoaderInstance.ResourceLoader.GetString("ImageResizer_AutoText");
/// <summary>
/// Converts a double to a string, optionally showing "Auto" for 0 values. NaN values are
/// converted to empty strings.
/// </summary>
/// <param name="value">The value to convert from <see cref="double"/> to
/// <see cref="string"/>.</param>
/// <param name="targetType">The conversion target type. <see cref="string"/> here.</param>
/// <param name="parameter">Set to "Auto" to return the localized "Auto" string if the
/// value is 0.</param>
/// <param name="language">Ignored.</param>
/// <returns>The string representation of the passed-in value.</returns>
public object Convert(object value, Type targetType, object parameter, string language) =>
value switch
{
double d => d switch
{
double.NaN => "0",
0 => (string)parameter == "Auto" ? AutoText : "0",
_ => d.ToString(CultureInfo.CurrentCulture),
},
_ => "0",
};
/// <summary>
/// Converts the string representation back to a double, returning 0 if the string is empty,
/// null or not a valid number in the specified culture.
/// </summary>
/// <param name="value">The string value to convert.</param>
/// <param name="targetType">The conversion target type. <see cref="double"/> here.</param>
/// <param name="parameter">Converter parameter. Unused.</param>
/// <param name="language">Ignored.</param>
/// <returns>The corresponding double value.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
value switch
{
null or "" => 0.0,
string text when double.TryParse(text, NumberStyles.Any, CultureInfo.CurrentCulture, out double result) => result,
_ => 0.0,
};
}

View File

@@ -0,0 +1,31 @@
// 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 Microsoft.UI.Xaml.Data;
namespace Microsoft.PowerToys.Settings.UI.Converters;
public partial class ImageResizerNumberBoxValueConverter : IValueConverter
{
/// <summary>
/// Converts the underlying double value to a display-friendly format. Ensures that NaN values
/// are not propagated to the UI.
/// </summary>
public object Convert(object value, Type targetType, object parameter, string language) =>
value is double d && double.IsNaN(d) ? 0.0 : value;
/// <summary>
/// Converts the user input back to the underlying double value. If the input is not a valid
/// number, a double with value 0 is returned.
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
value switch
{
null => 0.0,
double d when double.IsNaN(d) => 0.0,
string str when !double.TryParse(str, out _) => 0.0,
_ => value,
};
}

View File

@@ -0,0 +1,39 @@
// 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.Globalization;
using Microsoft.UI.Xaml.Controls;
namespace Microsoft.PowerToys.Settings.UI.Converters;
public partial class ImageResizerZeroToEmptyStringNumberFormatter
{
public string Format(long value) => throw new NotImplementedException();
public string Format(ulong value) => throw new NotImplementedException();
public string Format(double value) => throw new NotImplementedException();
public string FormatDouble(double? value) => value switch
{
null => string.Empty,
0 => string.Empty,
_ => value.Value.ToString(CultureInfo.CurrentCulture),
};
public double? ParseDouble(string text)
{
if (string.IsNullOrWhiteSpace(text))
{
return 0.0;
}
return double.TryParse(text, NumberStyles.Any, CultureInfo.CurrentCulture, out double result) ? result : 0.0;
}
public long? ParseInt(string text) => throw new NotImplementedException();
public ulong? ParseUInt(string text) => throw new NotImplementedException();
}

View File

@@ -0,0 +1,48 @@
// 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Microsoft.PowerToys.Settings.UI.Helpers
{
public sealed class ActionMessage
{
[JsonPropertyName("action")]
public SettingsAction Action { get; set; }
public static ActionMessage Create(string actionName)
{
return new ActionMessage
{
Action = new SettingsAction
{
PublishedDate = new SettingsGeneral
{
ActionName = actionName,
},
},
};
}
}
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Those are just a define for one simple struct")]
public sealed class SettingsAction
{
[JsonPropertyName("general")]
public SettingsGeneral PublishedDate { get; set; }
}
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Those are just a define for one simple struct")]
public sealed class SettingsGeneral
{
[JsonPropertyName("action_name")]
public string ActionName { get; set; }
}
}

View File

@@ -11,7 +11,7 @@ using System.Windows.Input;
namespace Microsoft.PowerToys.Settings.UI.Helpers
{
internal sealed class AsyncCommand : ICommand
internal sealed partial class AsyncCommand : ICommand
{
private readonly Func<Task> _execute;
private readonly Func<bool> _canExecute;

View File

@@ -27,7 +27,7 @@ namespace Microsoft.PowerToys.Settings.UI.Helpers
}
#pragma warning disable SA1402 // File may only contain a single type
public class IndexedObservableCollection<T> : ObservableCollection<IndexedItem<T>>
public partial class IndexedObservableCollection<T> : ObservableCollection<IndexedItem<T>>
#pragma warning restore SA1402 // File may only contain a single type
{
public IndexedObservableCollection(IEnumerable<T> items)

View File

@@ -18,7 +18,7 @@ namespace Microsoft.PowerToys.Settings.UI.Helpers
internal static int Size
{
get { return Marshal.SizeOf(typeof(INPUT)); }
get { return Marshal.SizeOf<INPUT>(); }
}
}

View File

@@ -0,0 +1,29 @@
// 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.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Microsoft.PowerToys.Settings.UI.Helpers
{
// Contains information for a release. Used to deserialize release JSON info from GitHub.
public sealed class PowerToysReleaseInfo
{
[JsonPropertyName("published_at")]
public DateTimeOffset PublishedDate { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("tag_name")]
public string TagName { get; set; }
[JsonPropertyName("body")]
public string ReleaseNotes { get; set; }
}
}

View File

@@ -7,7 +7,7 @@ using System.Windows.Input;
namespace Microsoft.PowerToys.Settings.UI.Helpers
{
public class RelayCommand : ICommand
public partial class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
@@ -33,7 +33,7 @@ namespace Microsoft.PowerToys.Settings.UI.Helpers
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "abstract T and abstract")]
public class RelayCommand<T> : ICommand
public partial class RelayCommand<T> : ICommand
{
private readonly Action<T> execute;

View File

@@ -6,7 +6,7 @@ using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
using Microsoft.UI.Xaml;
namespace Microsoft.PowerToys.Settings.UI.Helpers
@@ -20,9 +20,9 @@ namespace Microsoft.PowerToys.Settings.UI.Helpers
try
{
var json = File.ReadAllText(_placementPath);
var placement = JsonSerializer.Deserialize<WINDOWPLACEMENT>(json);
var placement = JsonSerializer.Deserialize<WINDOWPLACEMENT>(json, SourceGenerationContextContext.Default.WINDOWPLACEMENT);
placement.Length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
placement.Length = Marshal.SizeOf<WINDOWPLACEMENT>();
placement.Flags = 0;
placement.ShowCmd = (placement.ShowCmd == NativeMethods.SW_SHOWMAXIMIZED) ? NativeMethods.SW_SHOWMAXIMIZED : NativeMethods.SW_SHOWNORMAL;
return placement;
@@ -40,7 +40,7 @@ namespace Microsoft.PowerToys.Settings.UI.Helpers
_ = NativeMethods.GetWindowPlacement(handle, out var placement);
try
{
var json = JsonSerializer.Serialize(placement);
var json = JsonSerializer.Serialize(placement, SourceGenerationContextContext.Default.WINDOWPLACEMENT);
File.WriteAllText(_placementPath, json);
}
catch (Exception)

View File

@@ -0,0 +1,35 @@
// 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.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.PowerToys.Settings.UI.Helpers;
using Microsoft.PowerToys.Settings.UI.Library;
namespace Microsoft.PowerToys.Settings.UI.SerializationContext;
[JsonSerializable(typeof(WINDOWPLACEMENT))]
[JsonSerializable(typeof(AdvancedPasteSettings))]
[JsonSerializable(typeof(Dictionary<string, List<string>>))]
[JsonSerializable(typeof(AlwaysOnTopSettings))]
[JsonSerializable(typeof(ColorPickerSettings))]
[JsonSerializable(typeof(CropAndLockSettings))]
[JsonSerializable(typeof(FileLocksmithSettings))]
[JsonSerializable(typeof(MeasureToolSettings))]
[JsonSerializable(typeof(MouseWithoutBordersSettings))]
[JsonSerializable(typeof(NewPlusSettings))]
[JsonSerializable(typeof(PeekSettings))]
[JsonSerializable(typeof(PowerLauncherSettings))]
[JsonSerializable(typeof(PowerOcrSettings))]
[JsonSerializable(typeof(RegistryPreviewSettings))]
[JsonSerializable(typeof(WorkspacesSettings))]
[JsonSerializable(typeof(IList<PowerToysReleaseInfo>))]
[JsonSerializable(typeof(ActionMessage))]
public sealed partial class SourceGenerationContextContext : JsonSerializerContext
{
}

View File

@@ -14,6 +14,7 @@ using ManagedCommon;
using Microsoft.PowerToys.Settings.UI.Helpers;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Telemetry.Events;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
using Microsoft.PowerToys.Settings.UI.Services;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.PowerToys.Telemetry;
@@ -167,7 +168,7 @@ namespace Microsoft.PowerToys.Settings.UI
try
{
var requestedSettings = JsonSerializer.Deserialize<Dictionary<string, List<string>>>(File.ReadAllText(ipcFileName));
var requestedSettings = JsonSerializer.Deserialize<Dictionary<string, List<string>>>(File.ReadAllText(ipcFileName), SourceGenerationContextContext.Default.DictionaryStringListString);
File.WriteAllText(ipcFileName, GetSettingCommandLineCommand.Execute(requestedSettings));
}
catch (Exception ex)

View File

@@ -0,0 +1,38 @@
// 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 Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace Microsoft.PowerToys.Settings.UI.Controls;
public partial class ImageResizerDimensionsNumberBox : NumberBox
{
public ImageResizerDimensionsNumberBox()
{
this.Loaded += (_, _) => UpdateDisplayText();
this.ValueChanged += (_, _) => UpdateDisplayText();
this.GotFocus += (s, e) =>
{
// Show "0" in the UI when focused on the empty value. This ensures that the spinbutton
// controls are usable.
if (Value is double.NaN)
{
Value = 0.0;
}
};
this.LostFocus += (_, _) => UpdateDisplayText();
}
private void UpdateDisplayText()
{
if (FocusState == FocusState.Unfocused && Value == 0)
{
Text = string.Empty;
}
}
}

View File

@@ -20,6 +20,7 @@ using ManagedCommon;
using Microsoft.PowerToys.Settings.UI.Helpers;
using Microsoft.PowerToys.Settings.UI.OOBE.Enums;
using Microsoft.PowerToys.Settings.UI.OOBE.ViewModel;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.PowerToys.Telemetry;
using Microsoft.UI.Xaml.Controls;
@@ -29,22 +30,6 @@ namespace Microsoft.PowerToys.Settings.UI.OOBE.Views
{
public sealed partial class OobeWhatsNew : Page
{
// Contains information for a release. Used to deserialize release JSON info from GitHub.
private sealed class PowerToysReleaseInfo
{
[JsonPropertyName("published_at")]
public DateTimeOffset PublishedDate { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("tag_name")]
public string TagName { get; set; }
[JsonPropertyName("body")]
public string ReleaseNotes { get; set; }
}
public OobePowerToysModule ViewModel { get; set; }
public bool ShowDataDiagnosticsInfoBar => GetShowDataDiagnosticsInfoBar();
@@ -111,7 +96,7 @@ namespace Microsoft.PowerToys.Settings.UI.OOBE.Views
// https://docs.github.com/rest/overview/resources-in-the-rest-api#user-agent-required
getReleaseInfoClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PowerToys");
releaseNotesJSON = await getReleaseInfoClient.GetStringAsync("https://api.github.com/repos/microsoft/PowerToys/releases");
IList<PowerToysReleaseInfo> releases = JsonSerializer.Deserialize<IList<PowerToysReleaseInfo>>(releaseNotesJSON);
IList<PowerToysReleaseInfo> releases = JsonSerializer.Deserialize<IList<PowerToysReleaseInfo>>(releaseNotesJSON, SourceGenerationContextContext.Default.IListPowerToysReleaseInfo);
// Get the latest releases
var latestReleases = releases.OrderByDescending(release => release.PublishedDate).Take(5);

View File

@@ -276,6 +276,37 @@
</tkcontrols:SettingsExpander.Items>
</tkcontrols:SettingsExpander>
<tkcontrols:SettingsExpander
x:Uid="Transcode"
DataContext="{x:Bind ViewModel.AdditionalActions.Transcode, Mode=OneWay}"
HeaderIcon="{ui:FontIcon Glyph=&#xEA69;}"
IsExpanded="{Binding IsShown, Mode=OneWay}">
<tkcontrols:SettingsExpander.Content>
<ToggleSwitch
IsOn="{Binding IsShown, Mode=TwoWay}"
OffContent=""
OnContent="" />
</tkcontrols:SettingsExpander.Content>
<tkcontrols:SettingsExpander.Items>
<!-- HACK: For some weird reason, a ShortcutControl does not work correctly if it's the first or last item in the expander, so we add an invisible card. -->
<tkcontrols:SettingsCard Visibility="Collapsed" />
<tkcontrols:SettingsCard
x:Uid="TranscodeToMp3"
DataContext="{Binding TranscodeToMp3, Mode=TwoWay}"
IsEnabled="{x:Bind ViewModel.AdditionalActions.Transcode.IsShown, Mode=OneWay}">
<ContentControl ContentTemplate="{StaticResource AdditionalActionTemplate}" />
</tkcontrols:SettingsCard>
<tkcontrols:SettingsCard
x:Uid="TranscodeToMp4"
DataContext="{Binding TranscodeToMp4, Mode=TwoWay}"
IsEnabled="{x:Bind ViewModel.AdditionalActions.Transcode.IsShown, Mode=OneWay}">
<ContentControl ContentTemplate="{StaticResource AdditionalActionTemplate}" />
</tkcontrols:SettingsCard>
<!-- HACK: For some weird reason, a ShortcutControl does not work correctly if it's the first or last item in the expander, so we add an invisible card. -->
<tkcontrols:SettingsCard Visibility="Collapsed" />
</tkcontrols:SettingsExpander.Items>
</tkcontrols:SettingsExpander>
<InfoBar
x:Uid="AdvancedPaste_ShortcutWarning"
IsClosable="False"

View File

@@ -31,7 +31,7 @@ namespace Microsoft.PowerToys.Settings.UI.Views
ViewModel = new ColorPickerViewModel(
settingsUtils,
SettingsRepository<GeneralSettings>.GetInstance(settingsUtils),
null,
SettingsRepository<ColorPickerSettings>.GetInstance(settingsUtils),
ShellPage.SendDefaultIPCMessage);
DataContext = ViewModel;
InitializeComponent();

View File

@@ -19,6 +19,9 @@
<converters:ImageResizerUnitToStringConverter x:Key="ImageResizerUnitToStringConverter" />
<converters:ImageResizerUnitToIntConverter x:Key="ImageResizerUnitToIntConverter" />
<converters:ImageResizerSizeToAccessibleTextConverter x:Key="ImageResizerSizeToAccessibleTextConverter" />
<converters:ImageResizerDoubleToAutoConverter x:Key="ImageResizerDoubleToAutoConverter" />
<converters:ImageResizerNumberBoxValueConverter x:Key="ImageResizerNumberBoxValueConverter" />
<converters:ImageResizerZeroToEmptyStringNumberFormatter x:Key="ImageResizerZeroToEmptyStringNumberFormatter" />
<toolkitconverters:BoolToObjectConverter
x:Key="BoolToComboBoxIndexConverter"
FalseValue="1"
@@ -78,7 +81,7 @@
Margin="0,0,4,0"
FontWeight="SemiBold"
Style="{ThemeResource SecondaryTextStyle}"
Text="{x:Bind Width, Mode=OneWay}" />
Text="{x:Bind Width, Mode=OneWay, Converter={StaticResource ImageResizerDoubleToAutoConverter}, ConverterParameter=Auto}" />
<TextBlock
Margin="0,5,4,0"
AutomationProperties.AccessibilityView="Raw"
@@ -91,7 +94,7 @@
Margin="0,0,4,0"
FontWeight="SemiBold"
Style="{ThemeResource SecondaryTextStyle}"
Text="{x:Bind Height, Mode=OneWay}"
Text="{x:Bind Height, Mode=OneWay, Converter={StaticResource ImageResizerDoubleToAutoConverter}, ConverterParameter=Auto}"
Visibility="{x:Bind IsHeightUsed, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}" />
<TextBlock
Margin="0,0,4,0"
@@ -136,20 +139,20 @@
</ComboBox>
<StackPanel Orientation="Horizontal" Spacing="8">
<NumberBox
<controls:ImageResizerDimensionsNumberBox
x:Uid="ImageResizer_Width"
Width="116"
Minimum="0"
SpinButtonPlacementMode="Compact"
Value="{x:Bind Width, Mode=TwoWay}" />
Value="{x:Bind Width, Mode=TwoWay, Converter={StaticResource ImageResizerNumberBoxValueConverter}}" />
<NumberBox
<controls:ImageResizerDimensionsNumberBox
x:Uid="ImageResizer_Height"
Width="116"
Minimum="0"
SpinButtonPlacementMode="Compact"
Visibility="{x:Bind IsHeightUsed, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}"
Value="{x:Bind Height, Mode=TwoWay}" />
Value="{x:Bind Height, Mode=TwoWay, Converter={StaticResource ImageResizerNumberBoxValueConverter}}" />
</StackPanel>
<ComboBox

View File

@@ -1193,6 +1193,10 @@
<value>TIFF compression</value>
<comment>{Locked="TIFF"}</comment>
</data>
<data name="ImageResizer_AutoText" xml:space="preserve">
<value>(auto)</value>
<comment>Displayed on the preset card when the Width or Height property is zero. The same as "Input_Auto" in the ImageResizerUI project's resources.</comment>
</data>
<data name="File.Header" xml:space="preserve">
<value>File</value>
<comment>as in a computer file</comment>
@@ -1930,6 +1934,15 @@ Made with 💗 by Microsoft and the PowerToys community.</value>
<data name="PasteAsHtmlFile.Header" xml:space="preserve">
<value>Paste as .html file</value>
</data>
<data name="Transcode.Header" xml:space="preserve">
<value>Transcode audio / video</value>
</data>
<data name="TranscodeToMp3.Header" xml:space="preserve">
<value>Transcode to .mp3</value>
</data>
<data name="TranscodeToMp4.Header" xml:space="preserve">
<value>Transcode to .mp4 (H.264/AAC)</value>
</data>
<data name="AdvancedPaste_EnableAIDialogOpenAIApiKey.Text" xml:space="preserve">
<value>OpenAI API key:</value>
</data>

View File

@@ -18,12 +18,13 @@ using global::PowerToys.GPOWrapper;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
using Microsoft.Win32;
using Windows.Security.Credentials;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class AdvancedPasteViewModel : Observable, IDisposable
public partial class AdvancedPasteViewModel : Observable, IDisposable
{
private static readonly HashSet<string> WarnHotkeys = ["Ctrl + V", "Ctrl + Shift + V"];
@@ -83,7 +84,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
_delayedTimer.Elapsed += DelayedTimer_Tick;
_delayedTimer.AutoReset = false;
foreach (var action in _additionalActions.AllActions)
foreach (var action in _additionalActions.GetAllActions())
{
action.PropertyChanged += OnAdditionalActionPropertyChanged;
}
@@ -365,7 +366,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
.Any(hotkey => WarnHotkeys.Contains(hotkey.ToString()));
public bool IsAdditionalActionConflictingCopyShortcut =>
_additionalActions.AllActions
_additionalActions.GetAllActions()
.OfType<AdvancedPasteAdditionalAction>()
.Select(additionalAction => additionalAction.Shortcut)
.Any(hotkey => WarnHotkeys.Contains(hotkey.ToString()));
@@ -387,7 +388,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
AdvancedPasteSettings.ModuleName,
JsonSerializer.Serialize(_advancedPasteSettings)));
JsonSerializer.Serialize(_advancedPasteSettings, SourceGenerationContextContext.Default.AdvancedPasteSettings)));
}
public void RefreshEnabledState()

View File

@@ -12,10 +12,11 @@ using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.Library.Utilities;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class AlwaysOnTopViewModel : Observable
public partial class AlwaysOnTopViewModel : Observable
{
private ISettingsUtils SettingsUtils { get; set; }
@@ -131,7 +132,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
AlwaysOnTopSettings.ModuleName,
JsonSerializer.Serialize(Settings)));
JsonSerializer.Serialize(Settings, SourceGenerationContextContext.Default.AlwaysOnTopSettings)));
}
}
}

View File

@@ -11,7 +11,7 @@ using Microsoft.PowerToys.Settings.UI.Library.Helpers;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class AwakeViewModel : Observable
public partial class AwakeViewModel : Observable
{
public AwakeViewModel()
{

View File

@@ -19,7 +19,7 @@ using Microsoft.PowerToys.Telemetry;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class CmdNotFoundViewModel : Observable
public partial class CmdNotFoundViewModel : Observable
{
public ButtonClickCommand CheckRequirementsEventHandler => new ButtonClickCommand(CheckCommandNotFoundRequirements);
@@ -39,10 +39,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
get
{
string codeBase = Assembly.GetExecutingAssembly().Location;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
return Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
}
}

View File

@@ -16,10 +16,11 @@ using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Enumerations;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class ColorPickerViewModel : Observable, IDisposable
public partial class ColorPickerViewModel : Observable, IDisposable
{
private bool disposedValue;
@@ -56,15 +57,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
_settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
if (colorPickerSettingsRepository == null)
{
// used in release. This method converts the settings stored in the previous form, so we have forwards compatibility
_colorPickerSettings = _settingsUtils.GetSettingsOrDefault<ColorPickerSettings, ColorPickerSettingsVersion1>(ColorPickerSettings.ModuleName, settingsUpgrader: ColorPickerSettings.UpgradeSettings);
}
else
{
_colorPickerSettings = colorPickerSettingsRepository.SettingsConfig; // used in the unit tests
}
_colorPickerSettings = colorPickerSettingsRepository.SettingsConfig;
InitializeEnabledValue();
@@ -362,7 +355,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
ColorPickerSettings.ModuleName,
JsonSerializer.Serialize(_colorPickerSettings)));
JsonSerializer.Serialize(_colorPickerSettings, SourceGenerationContextContext.Default.ColorPickerSettings)));
}
public void RefreshEnabledState()

View File

@@ -7,7 +7,7 @@ using System.Windows.Input;
namespace Microsoft.PowerToys.Settings.UI.ViewModels.Commands
{
public class ButtonClickCommand : ICommand
public partial class ButtonClickCommand : ICommand
{
private readonly Action _execute;

View File

@@ -12,10 +12,11 @@ using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.Library.Utilities;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class CropAndLockViewModel : Observable
public partial class CropAndLockViewModel : Observable
{
private ISettingsUtils SettingsUtils { get; set; }
@@ -122,7 +123,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
CropAndLockSettings.ModuleName,
JsonSerializer.Serialize(Settings)));
JsonSerializer.Serialize(Settings, SourceGenerationContextContext.Default.CropAndLockSettings)));
}
}
}
@@ -153,7 +154,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
CropAndLockSettings.ModuleName,
JsonSerializer.Serialize(Settings)));
JsonSerializer.Serialize(Settings, SourceGenerationContextContext.Default.CropAndLockSettings)));
}
}
}

View File

@@ -13,7 +13,7 @@ using Windows.UI;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class DashboardListItem : INotifyPropertyChanged
public partial class DashboardListItem : INotifyPropertyChanged
{
private bool _visible;
private bool _isEnabled;

View File

@@ -14,11 +14,11 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
#pragma warning disable SA1402 // File may only contain a single type
#pragma warning disable SA1649 // File name should match first type name
public class DashboardModuleTextItem : DashboardModuleItem
public partial class DashboardModuleTextItem : DashboardModuleItem
{
}
public class DashboardModuleButtonItem : DashboardModuleItem
public partial class DashboardModuleButtonItem : DashboardModuleItem
{
public string ButtonTitle { get; set; }
@@ -31,12 +31,12 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
public RoutedEventHandler ButtonClickHandler { get; set; }
}
public class DashboardModuleShortcutItem : DashboardModuleItem
public partial class DashboardModuleShortcutItem : DashboardModuleItem
{
public List<object> Shortcut { get; set; }
}
public class DashboardModuleKBMItem : DashboardModuleItem
public partial class DashboardModuleKBMItem : DashboardModuleItem
{
private List<KeysDataModel> _remapKeys = new List<KeysDataModel>();
@@ -55,7 +55,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
}
}
public class DashboardModuleItem : INotifyPropertyChanged
public partial class DashboardModuleItem : INotifyPropertyChanged
{
public string Label { get; set; }

View File

@@ -22,7 +22,7 @@ using Microsoft.UI.Xaml.Controls;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class DashboardViewModel : Observable
public partial class DashboardViewModel : Observable
{
private const string JsonFileType = ".json";
private IFileSystemWatcher _watcher;
@@ -55,7 +55,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
_allModules = new List<DashboardListItem>();
foreach (ModuleType moduleType in Enum.GetValues(typeof(ModuleType)))
foreach (ModuleType moduleType in Enum.GetValues<ModuleType>())
{
AddDashboardListItem(moduleType);
}

View File

@@ -16,7 +16,7 @@ using Settings.UI.Library.Enumerations;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class EnvironmentVariablesViewModel : Observable
public partial class EnvironmentVariablesViewModel : Observable
{
private bool _isElevated;
private GpoRuleConfigured _enabledGpoRuleConfiguration;

View File

@@ -13,7 +13,7 @@ using Microsoft.PowerToys.Settings.UI.Library.ViewModels.Commands;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class FancyZonesViewModel : Observable
public partial class FancyZonesViewModel : Observable
{
private SettingsUtils SettingsUtils { get; set; }

View File

@@ -10,10 +10,11 @@ using global::PowerToys.GPOWrapper;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class FileLocksmithViewModel : Observable
public partial class FileLocksmithViewModel : Observable
{
private GeneralSettings GeneralSettingsConfig { get; set; }
@@ -134,7 +135,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
FileLocksmithSettings.ModuleName,
JsonSerializer.Serialize(Settings)));
JsonSerializer.Serialize(Settings, SourceGenerationContextContext.Default.FileLocksmithSettings)));
}
private Func<string, int> SendConfigMSG { get; }

View File

@@ -15,7 +15,7 @@ using Microsoft.Windows.ApplicationModel.Resources;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class AllAppsViewModel : Observable
public partial class AllAppsViewModel : Observable
{
public ObservableCollection<FlyoutMenuItem> FlyoutMenuItems { get; set; }
@@ -34,7 +34,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
resourceLoader = Helpers.ResourceLoaderInstance.ResourceLoader;
FlyoutMenuItems = new ObservableCollection<FlyoutMenuItem>();
foreach (ModuleType moduleType in Enum.GetValues(typeof(ModuleType)))
foreach (ModuleType moduleType in Enum.GetValues<ModuleType>())
{
AddFlyoutMenuItem(moduleType);
}

Some files were not shown because too many files have changed in this diff Show More