Skip to content

A Swiss Army knife for developers.

Added Smart Detection & partially Clipboard API (#771)

Etienne Baudoux9235d0dce61b
diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props
index 419162c24..fb8d1517e 100644
--- a/src/Directory.Packages.props
+++ b/src/Directory.Packages.props
@@ -46,6 +46,7 @@
<PackageVersion Include="Moq" Version="4.18.2" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.1" />
<PackageVersion Include="Nuke.Common" Version="6.2.1" />
+ <PackageVersion Include="SixLabors.ImageSharp" Version="3.0.0"/>
<PackageVersion Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
<PackageVersion Include="System.ComponentModel.Composition" Version="$(DotNetVersion)" />
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
diff --git a/src/app/dev/DevToys.Api/Core/IClipboard.cs b/src/app/dev/DevToys.Api/Core/IClipboard.cs
new file mode 100644
index 000000000..b8824ea81
--- /dev/null
+++ b/src/app/dev/DevToys.Api/Core/IClipboard.cs
@@ -0,0 +1,43 @@
+namespace DevToys.Api.Core;
+
+/// <summary>
+/// Provides a platform agnostic way to interact with the clipboard of the operating system the app is running on.
+/// </summary>
+public interface IClipboard
+{
+ /// <summary>
+ /// Retrieves data from the system clipboard.
+ /// </summary>
+ /// <remarks>
+ /// This method may try to access to the UI thread.
+ /// </remarks>
+ /// <returns>The data currently stored in the system clipboard.</returns>
+ Task<object?> GetClipboardDataAsync();
+
+ /// <summary>
+ /// Sets text to the system clipboard.
+ /// </summary>
+ /// <remarks>
+ /// This method may try to access to the UI thread.
+ /// </remarks>
+ /// <param name="data">The data to be stored in the system clipboard.</param>
+ Task SetClipboardTextAsync(string? data);
+
+ /// <summary>
+ /// Sets files to the system clipboard.
+ /// </summary>
+ /// <remarks>
+ /// This method may try to access to the UI thread.
+ /// </remarks>
+ /// <param name="data">The data to be stored in the system clipboard.</param>
+ Task SetClipboardFilesAsync(string? data);
+
+ /// <summary>
+ /// Sets bitmap to the system clipboard.
+ /// </summary>
+ /// <remarks>
+ /// This method may try to access to the UI thread.
+ /// </remarks>
+ /// <param name="data">The data to be stored in the system clipboard.</param>
+ Task SetClipboardBitmapAsync(string? data);
+}
diff --git a/src/app/dev/DevToys.UI.Framework/Threading/TaskSchedulerAwaiter.cs b/src/app/dev/DevToys.Api/Core/Threading/TaskSchedulerAwaiter.cs
similarity index 98%
rename from src/app/dev/DevToys.UI.Framework/Threading/TaskSchedulerAwaiter.cs
rename to src/app/dev/DevToys.Api/Core/Threading/TaskSchedulerAwaiter.cs
index 8fc8ae471..f837584c4 100644
--- a/src/app/dev/DevToys.UI.Framework/Threading/TaskSchedulerAwaiter.cs
+++ b/src/app/dev/DevToys.Api/Core/Threading/TaskSchedulerAwaiter.cs
@@ -1,6 +1,6 @@
using System.Runtime.CompilerServices;
-namespace DevToys.UI.Framework.Threading;
+namespace DevToys.Api;
/// <summary>
/// An awaiter returned from <see cref="GetAwaiter(TaskScheduler)"/>.
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/DataDetectionResult.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/DataDetectionResult.cs
index 9059e3f35..58ae41262 100644
--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/DataDetectionResult.cs
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/DataDetectionResult.cs
@@ -2,5 +2,7 @@
public record DataDetectionResult(bool Success, object? Data)
{
- public readonly DataDetectionResult Unsuccessful = new(false, null);
+ public static readonly DataDetectionResult Unsuccessful = new(false, null);
+
+ public Type? DataType => Data?.GetType();
}
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/IDataTypeDetector.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/IDataTypeDetector.cs
index d67e59020..7b1cd148c 100644
--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/IDataTypeDetector.cs
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/IDataTypeDetector.cs
@@ -7,7 +7,7 @@
/// <example>
/// <code>
/// [Export(typeof(IDataTypeDetector))]
-/// [DataTypeName("jwt-header", baseName: "json")] // jwt-header type inheriting from json type.
+/// [DataTypeName("jwt-header", baseName: "json" /* optional */)] // jwt-header type inheriting from json type.
/// [TargetPlatform(Platform.Windows)] // Optional
/// [TargetPlatform(Platform.WASM)] // Optional
/// internal sealed class JwtDetector : IDataTypeDetector
@@ -31,11 +31,13 @@ public interface IDataTypeDetector
/// passed to <see cref="IGuiTool.OnDataReceived(string, object?)"/>.
/// </para>
/// </remarks>
- /// <param name="data">The data to analyze, often coming from the OS's clipboard.</param>
+ /// <param name="rawData">The data to analyze, often coming from the OS's clipboard.</param>
+ /// <param name="resultFromBaseDetector">The result coming from the <see cref="IDataTypeDetector"/> corresponding to the given <see cref="DataTypeNameAttribute.DataTypeBaseName"/>.
+ /// Since, the <see cref="DataTypeNameAttribute.DataTypeBaseName"/> is optional, this parameter can be null.</param>
/// <returns>
/// Returns a <see cref="DataDetectionResult"/> that indicates whether the data could be analyzed / parsed / read
/// correctly, along with the parsed data, if any change has been made to it during parsing (for example, string to
/// integer conversion).
/// </returns>
- ValueTask<DataDetectionResult> TryDetectDataAsync(object data);
+ ValueTask<DataDetectionResult> TryDetectDataAsync(object rawData, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken);
}
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
new file mode 100644
index 000000000..73f583310
--- /dev/null
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
@@ -0,0 +1,9 @@
+namespace DevToys.Api;
+
+public static class PredefinedCommonDataTypeNames
+{
+ public const string Text = "text";
+ public const string Json = "json";
+ public const string Image = "image";
+ public const string File = "file";
+}
diff --git a/src/app/dev/DevToys.Business/Models/ChangeSelectedMenuItemMessage.cs b/src/app/dev/DevToys.Business/Models/ChangeSelectedMenuItemMessage.cs
index c3afe5f65..c519b2c0a 100644
--- a/src/app/dev/DevToys.Business/Models/ChangeSelectedMenuItemMessage.cs
+++ b/src/app/dev/DevToys.Business/Models/ChangeSelectedMenuItemMessage.cs
@@ -1,11 +1,23 @@
using CommunityToolkit.Mvvm.Messaging.Messages;
+using DevToys.Core.Tools;
namespace DevToys.Business.Models;
-internal sealed class ChangeSelectedMenuItemMessage : ValueChangedMessage<object>
+internal sealed class ChangeSelectedMenuItemMessage : ValueChangedMessage<GuiToolInstance>
{
- internal ChangeSelectedMenuItemMessage(object value)
- : base(value)
+ internal ChangeSelectedMenuItemMessage(GuiToolInstance tool)
+ : base(tool)
{
+ Guard.IsNotNull(tool);
+ SmartDetectionInfo = null;
}
+
+ internal ChangeSelectedMenuItemMessage(SmartDetectedTool smartDetectionInfo)
+ : base(smartDetectionInfo.ToolInstance)
+ {
+ Guard.IsNotNull(smartDetectionInfo);
+ SmartDetectionInfo = smartDetectionInfo;
+ }
+
+ internal SmartDetectedTool? SmartDetectionInfo { get; }
}
diff --git a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs
index 9b218e1e2..fda8b1d69 100644
--- a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs
+++ b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs
@@ -2,26 +2,44 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
+using DevToys.Api;
+using DevToys.Api.Core;
+using DevToys.Business.Models;
using DevToys.Core.Tools;
using DevToys.Core.Tools.ViewItems;
-using DevToys.Business.Models;
using DevToys.Localization.Strings.MainWindow;
+using Microsoft.Extensions.Logging;
+using Uno.Extensions;
namespace DevToys.Business.ViewModels;
[Export]
internal sealed partial class MainWindowViewModel : ObservableRecipient
{
+ private readonly ILogger _logger;
private readonly GuiToolProvider _guiToolProvider;
+ private readonly SmartDetectionService _smartDetectionService;
+ private readonly IClipboard _clipboard;
+ private readonly ISettingsProvider _settingsProvider;
private readonly Stack<INotifyPropertyChanged> _navigationHistory = new();
+ private IReadOnlyList<SmartDetectedTool>? _oldSmartDetectedTools;
+ private object? _oldRawClipboardData;
private INotifyPropertyChanged? _selectedMenuItem;
private bool _isGoingBack;
[ImportingConstructor]
- public MainWindowViewModel(GuiToolProvider guiToolProvider)
+ public MainWindowViewModel(
+ GuiToolProvider guiToolProvider,
+ SmartDetectionService smartDetectionService,
+ IClipboard clipboard,
+ ISettingsProvider settingsProvider)
{
+ _logger = this.Log();
_guiToolProvider = guiToolProvider;
+ _smartDetectionService = smartDetectionService;
+ _clipboard = clipboard;
+ _settingsProvider = settingsProvider;
Messenger.Register<MainWindowViewModel, ChangeSelectedMenuItemMessage>(this, OnChangeSelectedMenuItemMessageReceived);
}
@@ -154,6 +172,79 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient
}
}
+ /// <summary>
+ /// Get the data from the clipboard and try to detect tools that can accept the clipboard data as an input.
+ /// </summary>
+ internal async Task RunSmartDetectionAsync(bool isInCompactOverlayMode)
+ {
+ if (isInCompactOverlayMode || !_settingsProvider.GetSetting(DevToys.Core.Settings.PredefinedSettings.SmartDetection))
+ {
+ return;
+ }
+
+ Guard.IsNotEmpty((IReadOnlyList<INotifyPropertyChanged>)HeaderAndBodyToolViewItems);
+
+ try
+ {
+ var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
+ INotifyPropertyChanged? selectedMenuBeforeSmartDetection = SelectedMenuItem;
+ Guard.IsNotNull(selectedMenuBeforeSmartDetection);
+
+ // Retrieve clipboard content.
+ object? rawClipboardData = await _clipboard.GetClipboardDataAsync();
+
+ // If the clipboard content has changed since the last time
+ if (!cancellationTokenSource.Token.IsCancellationRequested && !object.Equals(_oldRawClipboardData, rawClipboardData))
+ {
+ // Reset recommended tools.
+ _guiToolProvider.ForEachToolViewItem(toolViewItem => toolViewItem.IsRecommended = false);
+
+ // Detect tools to recommend.
+ IReadOnlyList<SmartDetectedTool> detectedTools
+ = await _smartDetectionService.DetectAsync(rawClipboardData, strict: true, cancellationTokenSource.Token)
+ .ConfigureAwait(true);
+
+ GuiToolViewItem? firstToolViewItem = null;
+
+ // For each recommended tool, set IsRecommended.
+ for (int i = 0; i < detectedTools.Count; i++)
+ {
+ SmartDetectedTool detectedTool = detectedTools[i];
+ IEnumerable<GuiToolViewItem> toolViewItems = _guiToolProvider.GetViewItemFromTool(detectedTool.ToolInstance);
+ GuiToolViewItem? toolViewItem = toolViewItems.FirstOrDefault();
+ if (toolViewItem != null)
+ {
+ if (i == 0)
+ {
+ firstToolViewItem = toolViewItem;
+ }
+ toolViewItem.IsRecommended = true;
+ }
+ }
+
+ // If one unique tool got found
+ // And that the current selected menu item is a group, or that the user didn't selected another menu item since the smart detection started
+ if (detectedTools.Count == 1 && (SelectedMenuItem == selectedMenuBeforeSmartDetection || SelectedMenuItem is GroupViewItem && firstToolViewItem is not null))
+ {
+ // Then let's navigate immeditaly to it and set the detected data as an input.
+ SelectedMenuItem = firstToolViewItem;
+ detectedTools[0].ToolInstance.PassSmartDetectedData(detectedTools[0].DataTypeName, detectedTools[0].ParsedData);
+ }
+
+ _oldSmartDetectedTools = detectedTools;
+ _oldRawClipboardData = rawClipboardData;
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // Ignore
+ }
+ catch (Exception ex)
+ {
+ LogSmartDetectionFailed(ex);
+ }
+ }
+
/// <summary>
/// Command invoked when the search box's text changed.
/// </summary>
@@ -227,5 +318,12 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient
{
// Select the actual menu item in the navigation view. This will trigger the navigation.
SelectedMenuItem = GetBestMenuItemToSelect(message.Value);
+ if (message.SmartDetectionInfo is not null)
+ {
+ message.SmartDetectionInfo.ToolInstance.PassSmartDetectedData(message.SmartDetectionInfo.DataTypeName, message.SmartDetectionInfo.ParsedData);
+ }
}
+
+ [LoggerMessage(1, LogLevel.Warning, "Failed to perform smart detection.")]
+ partial void LogSmartDetectionFailed(Exception ex);
}
diff --git a/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs b/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs
index 5e02c09ee..b715b0e08 100644
--- a/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs
+++ b/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs
@@ -44,4 +44,12 @@ public static class PredefinedSettings
= new(
name: nameof(RecentTool3),
defaultValue: string.Empty);
+
+ /// <summary>
+ /// Whether the application should automatically detect the best tool to use based on the clipboard content.
+ /// </summary>
+ public static readonly SettingDefinition<bool> SmartDetection
+ = new(
+ name: nameof(SmartDetection),
+ defaultValue: true);
}
diff --git a/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs b/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs
index 99dde6d99..5fa9908c6 100644
--- a/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs
+++ b/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs
@@ -1,18 +1,22 @@
using System.Collections;
using System.Globalization;
using DevToys.Api;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
+using Uno.Extensions;
namespace DevToys.Core.Settings;
[Export(typeof(ISettingsProvider))]
-internal sealed class SettingsProvider : ISettingsProvider
+internal sealed partial class SettingsProvider : ISettingsProvider
{
+ private readonly ILogger _logger;
private readonly ISettingsStorage _settingsStorage;
[ImportingConstructor]
public SettingsProvider(ISettingsStorage settingsStorage)
{
+ _logger = this.Log();
_settingsStorage = settingsStorage;
}
@@ -55,6 +59,8 @@ internal sealed class SettingsProvider : ISettingsProvider
_settingsStorage.WriteSetting(settingDefinition.Name, valueToSave);
+ LogSetSetting(settingDefinition.Name, valueToSave?.ToString() ?? "{null}");
+
SettingChanged?.Invoke(this, new SettingChangedEventArgs(settingDefinition.Name, value));
}
@@ -64,4 +70,7 @@ internal sealed class SettingsProvider : ISettingsProvider
SettingChanged?.Invoke(this, new SettingChangedEventArgs(settingDefinition.Name, settingDefinition.DefaultValue));
}
+
+ [LoggerMessage(1, LogLevel.Information, "Setting '{settingName}' changed to '{newValue}'")]
+ partial void LogSetSetting(string settingName, string newValue);
}
diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs
index 14ed181d0..bb5fbbe67 100644
--- a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs
+++ b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs
@@ -78,12 +78,22 @@ public sealed partial class GuiToolInstance : ObservableObject
public bool IsFooterTool => _guiToolDefinition.Metadata.MenuPlacement == MenuPlacement.Footer;
+ public IReadOnlyList<string> AcceptedDataTypeNames => _guiToolDefinition.Metadata.AcceptedDataTypeNames;
+
/// <summary>
/// Gets the view of the tool.
/// Calling this property is expensive the first time as it will create the instance of the tool and the instance of the view.
/// </summary>
public IUIElement View => _view.Value;
+ /// <summary>
+ /// Send data coming from Smart Detection to the tool.
+ /// </summary>
+ public void PassSmartDetectedData(string dataTypeName, object? parsedData)
+ {
+ _instance.Value.OnDataReceived(dataTypeName, parsedData);
+ }
+
private ResourceManager? GetResourceManager(Assembly? resourceManagerAssembly)
{
ResourceManager? resourceManager = null;
diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs
index 62dfcf1c4..c661ba2eb 100644
--- a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs
+++ b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs
@@ -32,7 +32,7 @@ public sealed partial class GuiToolProvider
shortDisplayTitleResourceName: "N/A",
longDisplayTitleResourceName: nameof(MainWindow.SearchNoResultsFound),
resourceManagerAssemblyIdentifier: nameof(DevToysLocalizationResourceManagerAssemblyIdentifier),
- resourceManagerBaseName: "DevToys.Localization.Strings.MainMenu.MainMenu")),
+ resourceManagerBaseName: "DevToys.Localization.Strings.MainWindow.MainWindow")),
typeof(DevToysLocalizationResourceManagerAssemblyIdentifier).Assembly),
showLongDisplayTitle: true);
@@ -273,8 +273,8 @@ public sealed partial class GuiToolProvider
{
for (int j = 0; j < groupViewItem.Children.Count; j++)
{
- INotifyPropertyChanged subItem = groupViewItem.Children[j];
- if (subItem is GuiToolViewItem subGuiToolViewItem && subGuiToolViewItem.ToolInstance == guiToolInstance)
+ GuiToolViewItem subGuiToolViewItem = groupViewItem.Children[j];
+ if (subGuiToolViewItem.ToolInstance == guiToolInstance)
{
yield return subGuiToolViewItem;
}
@@ -283,6 +283,31 @@ public sealed partial class GuiToolProvider
}
}
+ public void ForEachToolViewItem(Action<GuiToolViewItem> action)
+ {
+ for (int i = 0; i < FooterToolViewItems.Count; i++)
+ {
+ action(FooterToolViewItems[i]);
+ }
+
+ for (int i = 0; i < HeaderAndBodyToolViewItems.Count; i++)
+ {
+ INotifyPropertyChanged item = HeaderAndBodyToolViewItems[i];
+ if (item is GuiToolViewItem guiToolViewItem)
+ {
+ action(guiToolViewItem);
+ }
+ else if (item is GroupViewItem groupViewItem && groupViewItem.Children is not null)
+ {
+ for (int j = 0; j < groupViewItem.Children.Count; j++)
+ {
+ GuiToolViewItem subGuiToolViewItem = groupViewItem.Children[j];
+ action(subGuiToolViewItem);
+ }
+ }
+ }
+ }
+
/// <summary>
/// Search the given <paramref name="searchQuery"/> in the list of known tools and update the given <paramref name="searchResultListToUpdate"/>
/// to reflect the result.
diff --git a/src/app/dev/DevToys.Core/Tools/Metadata/DataTypeDetectorMetadata.cs b/src/app/dev/DevToys.Core/Tools/Metadata/DataTypeDetectorMetadata.cs
new file mode 100644
index 000000000..3a0ceaef2
--- /dev/null
+++ b/src/app/dev/DevToys.Core/Tools/Metadata/DataTypeDetectorMetadata.cs
@@ -0,0 +1,21 @@
+using DevToys.Api;
+
+namespace DevToys.Core.Tools.Metadata;
+
+[DebuggerDisplay($"DataTypeName = {{{nameof(DataTypeName)}}}, DataTypeBaseName = {{{nameof(DataTypeBaseName)}}}")]
+public sealed class DataTypeDetectorMetadata
+{
+ public DataTypeDetectorMetadata(IDictionary<string, object> metadata)
+ {
+ DataTypeName = metadata.GetValueOrDefault(nameof(DataTypeNameAttribute.DataTypeName)) as string ?? string.Empty;
+ DataTypeBaseName = metadata.GetValueOrDefault(nameof(DataTypeNameAttribute.DataTypeBaseName)) as string ?? string.Empty;
+ TargetPlatforms = metadata.GetValueOrDefault(nameof(TargetPlatformAttribute.TargetPlatform)) as IReadOnlyList<Platform> ?? Array.Empty<Platform>();
+ Guard.IsNotNullOrWhiteSpace(DataTypeName);
+ }
+
+ public string DataTypeName { get; }
+
+ public string DataTypeBaseName { get; }
+
+ public IReadOnlyList<Platform> TargetPlatforms { get; }
+}
diff --git a/src/app/dev/DevToys.Core/Tools/SmartDetectedTool.cs b/src/app/dev/DevToys.Core/Tools/SmartDetectedTool.cs
new file mode 100644
index 000000000..3ff427bdb
--- /dev/null
+++ b/src/app/dev/DevToys.Core/Tools/SmartDetectedTool.cs
@@ -0,0 +1,19 @@
+namespace DevToys.Core.Tools;
+
+public class SmartDetectedTool
+{
+ public SmartDetectedTool(GuiToolInstance toolInstance, string dataTypeName, object? parsedData)
+ {
+ Guard.IsNotNull(toolInstance);
+ Guard.IsNotNullOrEmpty(dataTypeName);
+ ToolInstance = toolInstance;
+ DataTypeName = dataTypeName;
+ ParsedData = parsedData;
+ }
+
+ public GuiToolInstance ToolInstance { get; }
+
+ public string DataTypeName { get; }
+
+ public object? ParsedData { get; }
+}
diff --git a/src/app/dev/DevToys.Core/Tools/SmartDetectionService.cs b/src/app/dev/DevToys.Core/Tools/SmartDetectionService.cs
new file mode 100644
index 000000000..8e3b637d0
--- /dev/null
+++ b/src/app/dev/DevToys.Core/Tools/SmartDetectionService.cs
@@ -0,0 +1,270 @@
+using System;
+using DevToys.Api;
+using DevToys.Core.Tools.Metadata;
+using Microsoft.Extensions.Logging;
+using Uno.Extensions;
+
+namespace DevToys.Core.Tools;
+
+[Export(typeof(SmartDetectionService))]
+public sealed partial class SmartDetectionService
+{
+ private readonly ILogger _logger;
+ private readonly IReadOnlyList<DetectorNode> _detectorHierarchy;
+ private readonly Dictionary<string, List<GuiToolInstance>> _dataTypeToToolInstanceMap;
+ private readonly GuiToolProvider _guiToolProvider;
+
+ [ImportingConstructor]
+ public SmartDetectionService(
+ [ImportMany] IEnumerable<Lazy<IDataTypeDetector, DataTypeDetectorMetadata>> dataTypeDetectors,
+ ISettingsProvider settingsProvider,
+ GuiToolProvider guiToolProvider)
+ {
+ _logger = this.Log();
+ _guiToolProvider = guiToolProvider;
+
+ // Build a hiearchy of detectors based on their indicated base data type name.
+ _detectorHierarchy = BuildDetectorNodeHierarchy(dataTypeDetectors);
+
+ // Create a map of data types to tools.
+ _dataTypeToToolInstanceMap = BuildDataTypeToToolInstanceMap(guiToolProvider);
+ }
+
+ /// <summary>
+ /// Detects the best tools that could be used with the given <paramref name="rawData"/>.
+ /// </summary>
+ /// <param name="rawData">The raw data to use to detect the tools that could be used.</param>
+ /// <param name="strict">When true, only returns tools that fit the best the given <paramref name="rawData"/>.
+ /// When false, returns in priority the best tools that fit the given <paramref name="rawData"/>, then the first level of data type base that fit the <paramref name="rawData"/>.
+ /// Example: Assuming the following data type dependencies: JWT-Header > JSON > Text. If <paramref name="rawData"/> is a JWT-Header and that <paramref name="strict"/> is true, only tools that stricly support JWT-Header data type will be return.
+ /// if <paramref name="strict"/> is false, tools that support JWT-Header and JSON data types will be return, but tools that support Text won't be returned.</param>
+ /// <returns>
+ /// Assuming the following data type dependencies: JWT-Header > JSON > Text. If <paramref name="rawData"/> is a JWT-Header and that <paramref name="strict"/> is true, only tools that stricly support JWT-Header data type will be return.
+ /// if <paramref name="strict"/> is false, tools that support JWT-Header and JSON data types will be return, but tools that support Text won't be returned.
+ /// </returns>
+ public async Task<IReadOnlyList<SmartDetectedTool>> DetectAsync(object? rawData, bool strict, CancellationToken cancellationToken)
+ {
+ var detectedTools = new List<SmartDetectedTool>();
+
+ if (rawData == null)
+ {
+ return detectedTools;
+ }
+
+ // Make sure to be off the UI thread as this method may take many seconds to run.
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);
+
+ IReadOnlyList<(DetectorNode, DataDetectionResult)> succeededDetectors = await DetectAsync(cancellationToken, _detectorHierarchy, rawData);
+ for (int i = 0; i < succeededDetectors.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ (DetectorNode detectorNode, DataDetectionResult dataDetectionResult) = succeededDetectors[i];
+
+ // Add to the top of the list (high priority tool).
+ if (_dataTypeToToolInstanceMap.TryGetValue(detectorNode.Detector.Metadata.DataTypeName, out List<GuiToolInstance>? toolList))
+ {
+ for (int j = 0; j < toolList.Count; j++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ detectedTools.Insert(0, new(toolList[j], detectorNode.Detector.Metadata.DataTypeName, dataDetectionResult.Data));
+ }
+ }
+
+ if (!strict && !string.IsNullOrWhiteSpace(detectorNode.Detector.Metadata.DataTypeBaseName))
+ {
+ // Add to the end of the list (low priority tool).
+ if (_dataTypeToToolInstanceMap.TryGetValue(detectorNode.Detector.Metadata.DataTypeBaseName, out toolList))
+ {
+ for (int j = 0; j < toolList.Count; j++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ detectedTools.Add(new(toolList[j], detectorNode.Detector.Metadata.DataTypeBaseName, dataDetectionResult.Data));
+ }
+ }
+ }
+ }
+
+ return detectedTools;
+ }
+
+ /// <summary>
+ /// Detects data types from raw data using a hierarchy of detector nodes.
+ /// </summary>
+ /// <param name="detectorHierarchy">The hierarchy of detector nodes.</param>
+ /// <param name="rawData">The raw data to detect data types from.</param>
+ /// <param name="resultFromBaseDetector">The result from the base detector, if any.</param>
+ /// <returns>A list of tuples containing a detector node and its corresponding detection result.</returns>
+ private async Task<IReadOnlyList<(DetectorNode, DataDetectionResult)>> DetectAsync(
+ CancellationToken cancellationToken,
+ IReadOnlyList<DetectorNode> detectorHierarchy,
+ object rawData,
+ DataDetectionResult? resultFromBaseDetector = null)
+ {
+ var results = new List<(DetectorNode, DataDetectionResult)>();
+
+ for (int i = 0; i < detectorHierarchy.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ DetectorNode detectorNode = detectorHierarchy[i];
+
+ // Detect data types from raw data using the current detector.
+ DataDetectionResult resultFromDetector = await DetectAsync(cancellationToken, detectorNode.Detector.Value, rawData, resultFromBaseDetector);
+
+ // If the detection was successful
+ if (resultFromDetector.Success)
+ {
+ // If the current node has child detectors
+ if (detectorNode.ChildrenDetectors?.Count > 0)
+ {
+ // Recursively detect data types using child detectors
+ IReadOnlyList<(DetectorNode, DataDetectionResult)> resultFromDetectors
+ = await DetectAsync(
+ cancellationToken,
+ detectorNode.ChildrenDetectors,
+ rawData,
+ resultFromDetector);
+
+ // If no results were returned by child detectors
+ if (resultFromDetectors.Count == 0)
+ {
+ // Add the current detection result to the list of results
+ results.Add(new(detectorNode, resultFromDetector));
+ }
+ else
+ {
+ // Otherwise add all results returned by child detectors to the list of results
+ results.AddRange(resultFromDetectors);
+ }
+ }
+ else
+ {
+ // If the current node does not have child detectors,
+ // add its detection result to the list of results
+ results.Add(new(detectorNode, resultFromDetector));
+ }
+ }
+ }
+
+ return results;
+ }
+
+ private async ValueTask<DataDetectionResult> DetectAsync(
+ CancellationToken cancellationToken,
+ IDataTypeDetector detector,
+ object rawData,
+ DataDetectionResult? resultFromBaseDetector)
+ {
+ try
+ {
+ return await detector.TryDetectDataAsync(rawData, resultFromBaseDetector, cancellationToken) ?? DataDetectionResult.Unsuccessful;
+ }
+ catch (Exception ex) when (!(ex is OperationCanceledException))
+ {
+ LogDetectAsyncError(ex);
+ }
+
+ return DataDetectionResult.Unsuccessful;
+ }
+
+ /// <summary>
+ /// Builds a hierarchy of detector nodes from a collection of detectors.
+ /// </summary>
+ /// <param name="detectors">The collection of detectors.</param>
+ /// <returns>A list of root detector nodes.</returns>
+ private static List<DetectorNode> BuildDetectorNodeHierarchy(IEnumerable<Lazy<IDataTypeDetector, DataTypeDetectorMetadata>> detectors)
+ {
+ // Create a dictionary that maps data type names to detector nodes
+ var lookup
+ = detectors.ToDictionary(
+ node => node.Metadata.DataTypeName,
+ node => new DetectorNode(node));
+ var result = new List<DetectorNode>();
+
+ foreach (KeyValuePair<string, DetectorNode> node in lookup)
+ {
+ // Check if the current detector is supported by the current operating system
+ if (!OSHelper.IsOsSupported(node.Value.Detector.Metadata.TargetPlatforms))
+ {
+ // If not supported, ignore it.
+ Debug.WriteLine($"Ignoring '{node.Value.Detector.Metadata.DataTypeName}' data type detector as it isn't supported by the current OS.");
+ }
+ else if (string.IsNullOrEmpty(node.Value.Detector.Metadata.DataTypeBaseName))
+ {
+ // If the current detector does not have a base data type name, add it to the result list as a root node
+ result.Add(node.Value);
+ }
+ else if (lookup.TryGetValue(node.Value.Detector.Metadata.DataTypeBaseName, out DetectorNode? parentNode))
+ {
+ // If the current detector has a base data type name and its parent node exists in the dictionary,
+ // add it as a child to its parent node
+ if (parentNode.ChildrenDetectors is null)
+ {
+ parentNode.ChildrenDetectors = new();
+ }
+
+ parentNode.ChildrenDetectors.Add(node.Value);
+ }
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Builds a dictionary that maps data types to a list of GUI tool instances that accept them.
+ /// </summary>
+ /// <param name="guiToolProvider">The GUI tool provider.</param>
+ /// <returns>A dictionary that maps data types to a list of GUI tool instances that accept them.</returns>
+ private static Dictionary<string, List<GuiToolInstance>> BuildDataTypeToToolInstanceMap(GuiToolProvider guiToolProvider)
+ {
+ // Create a new dictionary with case-insensitive string keys
+ var dataTypeToToolInstanceMap = new Dictionary<string, List<GuiToolInstance>>(StringComparer.OrdinalIgnoreCase);
+
+ // Iterate over all tools provided by the GUI tool provider
+ for (int i = 0; i < guiToolProvider.AllTools.Count; i++)
+ {
+ GuiToolInstance tool = guiToolProvider.AllTools[i];
+
+ // Iterate over all data types accepted by the current tool
+ for (int j = 0; j < tool.AcceptedDataTypeNames.Count; j++)
+ {
+ string dataType = tool.AcceptedDataTypeNames[j];
+ if (!dataTypeToToolInstanceMap.TryGetValue(dataType, out List<GuiToolInstance>? toolList))
+ {
+ toolList = new();
+ dataTypeToToolInstanceMap[dataType] = toolList;
+ }
+
+ toolList.Add(tool);
+ }
+ }
+
+ return dataTypeToToolInstanceMap;
+ }
+
+ [LoggerMessage(0, LogLevel.Error, $"Error in {nameof(DetectAsync)}.")]
+ partial void LogDetectAsyncError(Exception ex);
+
+ private sealed class DetectorNode
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DetectorNode"/> class with the specified detector.
+ /// </summary>
+ /// <param name="detector">The detector associated with this node.</param>
+ internal DetectorNode(Lazy<IDataTypeDetector, DataTypeDetectorMetadata> detector)
+ {
+ Guard.IsNotNull(detector);
+ Detector = detector;
+ }
+
+ /// <summary>
+ /// Gets the detector associated with this node.
+ /// </summary>
+ internal Lazy<IDataTypeDetector, DataTypeDetectorMetadata> Detector { get; }
+
+ /// <summary>
+ /// Gets the list of child detectors for this node.
+ /// </summary>
+ internal List<DetectorNode>? ChildrenDetectors { get; set; }
+ }
+}
diff --git a/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.cs b/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.cs
index 86abf884f..06f0ab9c9 100644
--- a/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.cs
+++ b/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.cs
@@ -102,12 +102,9 @@ public sealed class GroupViewItem : ObservableObject
{
get
{
- if (Children is not null)
+ if (IsAnyChildrenRecommended())
{
- if (Children.Any(item => item.IsRecommended))
- {
- return true;
- }
+ return true;
}
if (_childItemJustGotSelected)
@@ -153,7 +150,7 @@ public sealed class GroupViewItem : ObservableObject
private void Child_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
- if (e.PropertyName == nameof(GuiToolViewItem.IsRecommended))
+ if (e.PropertyName == nameof(GuiToolViewItem.IsRecommended) && IsAnyChildrenRecommended())
{
OnPropertyChanged(nameof(MenuItemShouldBeExpanded));
}
@@ -164,4 +161,17 @@ public sealed class GroupViewItem : ObservableObject
_childItemJustGotSelected = true;
OnPropertyChanged(nameof(MenuItemShouldBeExpanded));
}
+
+ private bool IsAnyChildrenRecommended()
+ {
+ if (Children is not null)
+ {
+ if (Children.Any(item => item.IsRecommended))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
}
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
index 29142d607..a28cc61e3 100644
--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
@@ -20,25 +20,30 @@
-->
</ItemGroup>
<ItemGroup>
- <Compile Update="Sample\Sample.Designer.cs">
+ <Compile Update="Tools\Sample\Sample.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Sample.resx</DependentUpon>
</Compile>
- <Compile Update="Settings\Settings.Designer.cs">
+ <Compile Update="Tools\Settings\Settings.Designer.cs">
<DependentUpon>Settings.resx</DependentUpon>
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
</Compile>
</ItemGroup>
<ItemGroup>
- <EmbeddedResource Update="Sample\Sample.resx">
+ <EmbeddedResource Update="Tools\Sample\Sample.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Sample.Designer.cs</LastGenOutput>
</EmbeddedResource>
- <EmbeddedResource Update="Settings\Settings.resx">
+ <EmbeddedResource Update="Tools\Settings\Settings.resx">
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
</ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Uno.Core.Extensions.Logging.Singleton" />
+ <PackageReference Include="Newtonsoft.Json" />
+ </ItemGroup>
</Project>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs
new file mode 100644
index 000000000..6f0e12f15
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs
@@ -0,0 +1,49 @@
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using Uno.Extensions;
+
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Json, baseName: PredefinedCommonDataTypeNames.Text)]
+internal sealed partial class JsonDataTypeDetector : IDataTypeDetector
+{
+ private readonly ILogger _logger;
+
+ [ImportingConstructor]
+ public JsonDataTypeDetector()
+ {
+ _logger = this.Log();
+ }
+
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (resultFromBaseDetector is not null
+ && resultFromBaseDetector.Data is string dataString
+ && !long.TryParse(dataString, out _))
+ {
+ try
+ {
+ var jtoken = JToken.Parse(dataString);
+ if (jtoken is not null)
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: new Tuple<JToken, string>(jtoken, dataString)));
+ }
+ }
+ catch (JsonReaderException)
+ {
+ // Exception in parsing json. It likely mean the text isn't a JSON.
+ }
+ catch (Exception ex) //some other exception
+ {
+ LogError(ex);
+ }
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+
+ [LoggerMessage(1, LogLevel.Error, "An unexpected exception happened while trying to detect some JSON data.")]
+ partial void LogError(Exception ex);
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/TextDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/TextDataTypeDetector.cs
new file mode 100644
index 000000000..84dbdf982
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/TextDataTypeDetector.cs
@@ -0,0 +1,16 @@
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Text)]
+internal sealed partial class TextDataTypeDetector : IDataTypeDetector
+{
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (data is string dataString && !string.IsNullOrEmpty(dataString))
+ {
+ return ValueTask.FromResult(new DataDetectionResult(true, dataString));
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Sample/Sample.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Sample/Sample.Designer.cs
similarity index 98%
rename from src/app/dev/DevToys.Tools/Sample/Sample.Designer.cs
rename to src/app/dev/DevToys.Tools/Tools/Sample/Sample.Designer.cs
index c35b7cb10..f1c1ce35c 100644
--- a/src/app/dev/DevToys.Tools/Sample/Sample.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Sample/Sample.Designer.cs
@@ -8,7 +8,7 @@
// </auto-generated>
//------------------------------------------------------------------------------
-namespace DevToys.Tools.Sample {
+namespace DevToys.Tools.Tools.Sample {
using System;
@@ -39,7 +39,7 @@ namespace DevToys.Tools.Sample {
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Sample.Sample", typeof(Sample).Assembly);
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Sample.Sample", typeof(Sample).Assembly);
resourceMan = temp;
}
return resourceMan;
diff --git a/src/app/dev/DevToys.Tools/Sample/Sample.resx b/src/app/dev/DevToys.Tools/Tools/Sample/Sample.resx
similarity index 100%
rename from src/app/dev/DevToys.Tools/Sample/Sample.resx
rename to src/app/dev/DevToys.Tools/Tools/Sample/Sample.resx
diff --git a/src/app/dev/DevToys.Tools/Sample/SampleToolFactory.cs b/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs
similarity index 93%
rename from src/app/dev/DevToys.Tools/Sample/SampleToolFactory.cs
rename to src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs
index bf1053fb9..b763377bc 100644
--- a/src/app/dev/DevToys.Tools/Sample/SampleToolFactory.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs
@@ -1,14 +1,13 @@
-using DevToys.Api;
-using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging;
-namespace DevToys.Tools.Sample;
+namespace DevToys.Tools.Tools.Sample;
[Export(typeof(ICommandLineTool))]
[Name("Sample tool")]
[CommandName(
Name = "base64",
Alias = "b64",
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
DescriptionResourceName = nameof(Sample.CommandDescription))]
[TargetPlatform(Platform.Windows)] // Optional. Not putting any attribute means every platforms are supported.
[TargetPlatform(Platform.Linux)]
@@ -42,12 +41,13 @@ internal sealed class SampleCommandLineTool : ICommandLineTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.LongTitle),
DescriptionResourceName = nameof(Sample.Description),
AccessibleNameResourceName = nameof(Sample.CommandDescription),
SearchKeywordsResourceName = nameof(Sample.CommandDescription))]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]
[TargetPlatform(Platform.Windows)] // Optional. Not putting any attribute means every platforms are supported.
[TargetPlatform(Platform.Linux)]
[TargetPlatform(Platform.MacCatalyst)]
@@ -66,7 +66,7 @@ internal sealed class SampleGuiTool : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -90,7 +90,7 @@ internal sealed class SampleGuiTool2 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -114,7 +114,7 @@ internal sealed class SampleGuiTool3 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -138,7 +138,7 @@ internal sealed class SampleGuiTool4 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -162,7 +162,7 @@ internal sealed class SampleGuiTool5 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -186,7 +186,7 @@ internal sealed class SampleGuiTool6 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -210,7 +210,7 @@ internal sealed class SampleGuiTool7 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -234,7 +234,7 @@ internal sealed class SampleGuiTool8 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -258,7 +258,7 @@ internal sealed class SampleGuiTool9 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -282,7 +282,7 @@ internal sealed class SampleGuiTool10 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -306,7 +306,7 @@ internal sealed class SampleGuiTool11 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -330,7 +330,7 @@ internal sealed class SampleGuiTool12 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -354,7 +354,7 @@ internal sealed class SampleGuiTool13 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -378,7 +378,7 @@ internal sealed class SampleGuiTool14 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -402,7 +402,7 @@ internal sealed class SampleGuiTool15 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
@@ -426,7 +426,7 @@ internal sealed class SampleGuiTool16 : IGuiTool
IconGlyph = "\uE670",
GroupName = "Encoders / Decoders",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
DescriptionResourceName = nameof(Sample.CommandDescription),
diff --git a/src/app/dev/DevToys.Tools/Settings/Settings.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Settings/Settings.Designer.cs
similarity index 97%
rename from src/app/dev/DevToys.Tools/Settings/Settings.Designer.cs
rename to src/app/dev/DevToys.Tools/Tools/Settings/Settings.Designer.cs
index d6d7ee501..5bd73da95 100644
--- a/src/app/dev/DevToys.Tools/Settings/Settings.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Settings/Settings.Designer.cs
@@ -8,7 +8,7 @@
// </auto-generated>
//------------------------------------------------------------------------------
-namespace DevToys.Tools.Settings {
+namespace DevToys.Tools.Tools.Settings {
using System;
@@ -39,7 +39,7 @@ namespace DevToys.Tools.Settings {
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Settings.Settings", typeof(Settings).Assembly);
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Settings.Settings", typeof(Settings).Assembly);
resourceMan = temp;
}
return resourceMan;
diff --git a/src/app/dev/DevToys.Tools/Settings/Settings.resx b/src/app/dev/DevToys.Tools/Tools/Settings/Settings.resx
similarity index 100%
rename from src/app/dev/DevToys.Tools/Settings/Settings.resx
rename to src/app/dev/DevToys.Tools/Tools/Settings/Settings.resx
diff --git a/src/app/dev/DevToys.Tools/Settings/SettingsGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.cs
similarity index 97%
rename from src/app/dev/DevToys.Tools/Settings/SettingsGuiTool.cs
rename to src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.cs
index 82c37f45a..ab942fdcd 100644
--- a/src/app/dev/DevToys.Tools/Settings/SettingsGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.cs
@@ -1,6 +1,6 @@
using DevToys.Api.Core.Theme;
-namespace DevToys.Tools.Settings;
+namespace DevToys.Tools.Tools.Settings;
[Export(typeof(IGuiTool))]
[Name("Settings")]
@@ -8,7 +8,7 @@ namespace DevToys.Tools.Settings;
IconFontName = "FluentSystemIcons",
IconGlyph = "\uF6A9",
ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Settings.Settings",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Settings.Settings",
ShortDisplayTitleResourceName = nameof(Settings.ShortDisplayTitle),
DescriptionResourceName = nameof(Settings.Description),
AccessibleNameResourceName = nameof(Settings.AccessibleName))]
diff --git a/src/app/dev/DevToys.UI/Assets/Icons/Idea.svg b/src/app/dev/DevToys.UI/Assets/Icons/Idea.svg
new file mode 100644
index 000000000..4ab8b7011
--- /dev/null
+++ b/src/app/dev/DevToys.UI/Assets/Icons/Idea.svg
@@ -0,0 +1,12 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
+ <radialGradient id="4Var25g6pDrxGe_QIeTVza" cx="16.106" cy="-171.073" r="23.43" gradientTransform="matrix(1 0 0 -1 0 118)" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="#6e757b"></stop>
+ <stop offset="1" stop-color="#4a4e52"></stop>
+ </radialGradient>
+ <path fill="url(#4Var25g6pDrxGe_QIeTVza)" d="M30,34H18c0,0.855,0,3.95,0,3.95c0,3.314,2.686,6,6,6s6-2.686,6-6C30,37.95,30,34.855,30,34z"></path>
+ <linearGradient id="4Var25g6pDrxGe_QIeTVzb" x1="16.365" x2="28.493" y1="2.837" y2="26.454" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="#ffda1c"></stop>
+ <stop offset="1" stop-color="#feb705"></stop>
+ </linearGradient>
+ <path fill="url(#4Var25g6pDrxGe_QIeTVzb)" d="M36,16c0-6.627-5.373-12-12-12S12,9.373,12,16c0,7,6,12,6,15.8V34h12v-2.2C30,28,36,23,36,16z"></path>
+</svg>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.UI/DevToys.UI.csproj b/src/app/dev/DevToys.UI/DevToys.UI.csproj
index 21bc9a30e..a2d3f215c 100644
--- a/src/app/dev/DevToys.UI/DevToys.UI.csproj
+++ b/src/app/dev/DevToys.UI/DevToys.UI.csproj
@@ -88,6 +88,7 @@
</Page>
<PRIResource Include="**\*.resw" />
<Content Include="Assets\**" />
+ <None Remove="Assets\Icons\Idea.svg" />
<None Remove="Assets\Logo\Square44x44Logo.altform-lightunplated_targetsize-16.png" />
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
diff --git a/src/app/dev/DevToys.UI/Views/MainWindow.xaml b/src/app/dev/DevToys.UI/Views/MainWindow.xaml
index 7cf302bcc..afc8b1f0e 100644
--- a/src/app/dev/DevToys.UI/Views/MainWindow.xaml
+++ b/src/app/dev/DevToys.UI/Views/MainWindow.xaml
@@ -283,7 +283,7 @@
x:Name="NavigationViewItemRecommendedIcon"
x:Load="{x:Bind IsRecommended, Mode=OneWay}"
Grid.Column="1"
- Source="/Assets/Icons/Idea.svg"
+ Source="ms-appx:///DevToys.UI/Assets/Icons/Idea.svg"
Height="16"
Width="16"/>
</Grid>
diff --git a/src/app/dev/DevToys.UI/Views/MainWindow.xaml.cs b/src/app/dev/DevToys.UI/Views/MainWindow.xaml.cs
index 0bc8db766..23b08299b 100644
--- a/src/app/dev/DevToys.UI/Views/MainWindow.xaml.cs
+++ b/src/app/dev/DevToys.UI/Views/MainWindow.xaml.cs
@@ -11,6 +11,10 @@ using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media.Animation;
+#if !__WINDOWS__
+using WindowActivationState = Windows.UI.Core.CoreWindowActivationState;
+#endif
+
namespace DevToys.UI.Views;
/// <summary>
@@ -48,6 +52,7 @@ public sealed partial class MainWindow : BackdropPage
Loaded += MainWindow_Loaded;
SizeChanged += MainWindow_SizeChanged;
CompactOverlayModeChanged += MainWindow_CompactOverlayModeChanged;
+ Activated += MainWindow_Activated;
DataContext = mefProvider.Import<MainWindowViewModel>();
ViewModel.SelectedMenuItemChanged += ViewModel_SelectedMenuItemChanged;
@@ -102,6 +107,9 @@ public sealed partial class MainWindow : BackdropPage
// Explicitly select the first item in the menu.
Guard.IsNotEmpty((IReadOnlyList<INotifyPropertyChanged>)ViewModel.HeaderAndBodyToolViewItems);
ViewModel.SelectedMenuItem = ViewModel.HeaderAndBodyToolViewItems[0];
+
+ // Start Smart Detection
+ ViewModel.RunSmartDetectionAsync(IsInCompactOverlay).Forget();
}
private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
@@ -114,6 +122,14 @@ public sealed partial class MainWindow : BackdropPage
IsInCompactOverlay = IsInCompactOverlayMode();
}
+ private void MainWindow_Activated(BackdropWindow sender, WindowActivatedEventArgs args)
+ {
+ if (args.WindowActivationState == WindowActivationState.CodeActivated && IsLoaded)
+ {
+ ViewModel.RunSmartDetectionAsync(IsInCompactOverlay).Forget();
+ }
+ }
+
private void MenuNavigationView_DisplayModeChanged(NavigationView sender, NavigationViewDisplayModeChangedEventArgs args)
{
_navigationViewDisplayMode = MenuNavigationView.DisplayMode;
diff --git a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/Core/Clipboard/Clipboard.cs b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/Core/Clipboard/Clipboard.cs
new file mode 100644
index 000000000..c9393a240
--- /dev/null
+++ b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/Core/Clipboard/Clipboard.cs
@@ -0,0 +1,97 @@
+using DevToys.Api;
+using Microsoft.Extensions.Logging;
+using Uno.Extensions;
+using Windows.ApplicationModel.DataTransfer;
+using Windows.Storage;
+using Windows.Storage.Streams;
+
+namespace DevToys.MauiBlazor.Core.Clipboard;
+
+[Export(typeof(Api.Core.IClipboard))]
+internal sealed partial class Clipboard : Api.Core.IClipboard
+{
+ private readonly ILogger _logger;
+
+ [ImportingConstructor]
+ public Clipboard()
+ {
+ _logger = this.Log();
+ }
+
+ public async Task<object?> GetClipboardDataAsync()
+ {
+ try
+ {
+ if (Microsoft.Maui.ApplicationModel.DataTransfer.Clipboard.Default.HasText)
+ {
+ return await Microsoft.Maui.ApplicationModel.DataTransfer.Clipboard.Default.GetTextAsync();
+ }
+#if __WINDOWS__
+ else
+ {
+ return await MainThread.InvokeOnMainThreadAsync<object?>(async () =>
+ {
+ try
+ {
+ Windows.ApplicationModel.DataTransfer.DataPackageView package = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
+ if (package.Contains(StandardDataFormats.StorageItems))
+ {
+ IReadOnlyList<IStorageItem> storageitems = await package.GetStorageItemsAsync();
+ var files = new List<FileInfo>();
+ foreach (IStorageItem storageItem in storageitems)
+ {
+ files.Add(new FileInfo(storageItem.Path));
+ }
+ return files;
+ }
+ else if (package.Contains(StandardDataFormats.Bitmap))
+ {
+ RandomAccessStreamReference imageStreamRef = await package.GetBitmapAsync();
+ using IRandomAccessStreamWithContentType streamWithContentType = await imageStreamRef.OpenReadAsync();
+ using Stream stream = streamWithContentType.AsStream();
+ return await SixLabors.ImageSharp.Image.LoadAsync(stream);
+ }
+ }
+ catch (Exception ex)
+ {
+ LogGetClipboardFailed(ex);
+ }
+
+ return null;
+ });
+ }
+#elif __MACCATALYST__
+ else
+ {
+ // TODO: On Mac, use AppKit API to get file and bitmap from clipboard.
+ }
+#endif
+ }
+ catch (Exception ex)
+ {
+ LogGetClipboardFailed(ex);
+ }
+ return null;
+ }
+
+ public Task SetClipboardBitmapAsync(string? data)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public Task SetClipboardFilesAsync(string? data)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public Task SetClipboardTextAsync(string? data)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ [LoggerMessage(1, LogLevel.Warning, "Failed to retrieve the clipboard data.")]
+ partial void LogGetClipboardFailed(Exception ex);
+}
diff --git a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/DevToys.MauiBlazor.csproj b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/DevToys.MauiBlazor.csproj
index 84974aa31..1328e7751 100644
--- a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/DevToys.MauiBlazor.csproj
+++ b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/DevToys.MauiBlazor.csproj
@@ -105,6 +105,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
+ <PackageReference Include="SixLabors.ImageSharp" />
</ItemGroup>
</Project>
\ No newline at end of file
diff --git a/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/Core/Clipboard/Clipboard.cs b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/Core/Clipboard/Clipboard.cs
new file mode 100644
index 000000000..b9a4e017a
--- /dev/null
+++ b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/Core/Clipboard/Clipboard.cs
@@ -0,0 +1,91 @@
+using System.IO;
+using DevToys.Api.Core;
+using DevToys.UI.Framework.Threading;
+using Microsoft.Extensions.Logging;
+using Microsoft.UI.Dispatching;
+using Uno.Extensions;
+using Windows.ApplicationModel.DataTransfer;
+using Windows.Storage;
+using Windows.Storage.Streams;
+
+namespace DevToys.Wasdk.Core.Clipboard;
+
+[Export(typeof(IClipboard))]
+internal sealed partial class Clipboard : IClipboard
+{
+ private readonly ILogger _logger;
+ private readonly Lazy<DispatcherQueue> _dispatcherQueue
+ = new(() =>
+ {
+ UI.Views.MainWindow? mainWindow = ((App)App.Current).MainWindow;
+ Guard.IsNotNull(mainWindow);
+ return mainWindow.DispatcherQueue;
+ });
+
+ [ImportingConstructor]
+ public Clipboard()
+ {
+ _logger = this.Log();
+ }
+
+ public Task<object?> GetClipboardDataAsync()
+ {
+ return _dispatcherQueue.Value.RunOnUIThreadAsync<object?>(async () =>
+ {
+ try
+ {
+ DataPackageView package = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
+ if (package.Contains(StandardDataFormats.Text))
+ {
+ return await package.GetTextAsync();
+ }
+ else if (package.Contains(StandardDataFormats.StorageItems))
+ {
+ IReadOnlyList<IStorageItem> storageitems = await package.GetStorageItemsAsync();
+ var files = new List<FileInfo>();
+ foreach (IStorageItem storageItem in storageitems)
+ {
+ files.Add(new FileInfo(storageItem.Path));
+ }
+ return files;
+ }
+#if !__WASM__
+ else if (package.Contains(StandardDataFormats.Bitmap))
+ {
+ RandomAccessStreamReference imageStreamRef = await package.GetBitmapAsync();
+ using IRandomAccessStreamWithContentType streamWithContentType = await imageStreamRef.OpenReadAsync();
+ using Stream stream = streamWithContentType.AsStream();
+ return await Image.LoadAsync(stream);
+ }
+#endif
+ }
+ catch (Exception ex)
+ {
+ LogGetClipboardFailed(ex);
+ }
+
+ return null;
+ });
+ }
+
+ public Task SetClipboardBitmapAsync(string? data)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public Task SetClipboardFilesAsync(string? data)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public Task SetClipboardTextAsync(string? data)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ [LoggerMessage(1, LogLevel.Warning, "Failed to retrieve the clipboard data.")]
+ partial void LogGetClipboardFailed(Exception ex);
+}
diff --git a/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj
index 73a9b63c4..f19ba3b09 100644
--- a/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj
+++ b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj
@@ -60,6 +60,7 @@
<PackageReference Include="Microsoft.Extensions.Logging.Debug" />
<PackageReference Include="Microsoft.WindowsAppSDK" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
+ <PackageReference Include="SixLabors.ImageSharp" />
<Manifest Include="$(ApplicationManifest)" />
</ItemGroup>
diff --git a/src/app/tests/DevToys.UnitTests/Core/Tools/SmartDetectionServiceTests.cs b/src/app/tests/DevToys.UnitTests/Core/Tools/SmartDetectionServiceTests.cs
new file mode 100644
index 000000000..8ceea9aec
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Core/Tools/SmartDetectionServiceTests.cs
@@ -0,0 +1,26 @@
+using System.Threading;
+using System.Threading.Tasks;
+using DevToys.Core.Tools;
+
+namespace DevToys.UnitTests.Core.Tools;
+
+public class SmartDetectionServiceTests : MefBasedTest
+{
+ [Theory]
+ [InlineData("hello world", true, "MockTool2")]
+ [InlineData("hello world", false, "MockTool2")]
+ [InlineData("{ \"json\": 123 }", true, "MockTool")]
+ [InlineData("{ \"json\": 123 }", false, "MockTool", "MockTool2")]
+ [InlineData(123, false)]
+ public async Task DetectToolsAsync(object rawData, bool isStrict, params string[] toolNames)
+ {
+ SmartDetectionService smartDetectionService = MefProvider.Import<SmartDetectionService>();
+ IReadOnlyList<SmartDetectedTool> detectedTools = await smartDetectionService.DetectAsync(rawData, isStrict, CancellationToken.None);
+
+ Assert.Equal(toolNames.Length, detectedTools.Count);
+ for (int i = 0; i < toolNames.Length; i++)
+ {
+ Assert.Equal(toolNames[i], detectedTools[i].ToolInstance.InternalComponentName);
+ }
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/MefBasedTest.cs b/src/app/tests/DevToys.UnitTests/MefBasedTest.cs
index 315a42faa..278d352c0 100644
--- a/src/app/tests/DevToys.UnitTests/MefBasedTest.cs
+++ b/src/app/tests/DevToys.UnitTests/MefBasedTest.cs
@@ -1,7 +1,6 @@
using System.Globalization;
using System.Reflection;
using DevToys.Core.Mef;
-using DevToys.Core.Settings;
namespace DevToys.UnitTests;
diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs
new file mode 100644
index 000000000..d7cf49ffc
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs
@@ -0,0 +1,48 @@
+using System.ComponentModel.Composition;
+using System.Threading;
+using System.Threading.Tasks;
+using Newtonsoft.Json.Linq;
+
+namespace DevToys.UnitTests.Mocks.Tools;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName("JSON", baseName: "text")]
+internal class MockJsonDataTypeDetector : IDataTypeDetector
+{
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (resultFromBaseDetector is not null
+ && resultFromBaseDetector.Data is string dataString
+ && !long.TryParse(dataString, out _))
+ {
+ try
+ {
+ var jtoken = JToken.Parse(dataString);
+ if (jtoken is not null)
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: new Tuple<JToken, string>(jtoken, dataString)));
+ }
+ }
+ catch
+ {
+ }
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName("text")]
+internal class MockTextDataTypeDetector : IDataTypeDetector
+{
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (data is string dataString && !string.IsNullOrEmpty(dataString))
+ {
+ return ValueTask.FromResult(new DataDetectionResult(true, dataString));
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs
index 44b51eac1..267c5c2cc 100644
--- a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs
+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs
@@ -16,6 +16,7 @@ namespace DevToys.UnitTests.Mocks.Tools;
DescriptionResourceName = nameof(MockToolResource.Title),
AccessibleNameResourceName = nameof(MockToolResource.Title),
SearchKeywordsResourceName = nameof(MockToolResource.Title))]
+[AcceptedDataTypeName("text")]
internal sealed class MockIGuiTool2 : IGuiTool
{
public IUIElement View => null!;
@@ -36,6 +37,7 @@ internal sealed class MockIGuiTool2 : IGuiTool
DescriptionResourceName = nameof(MockToolResource.Title),
AccessibleNameResourceName = nameof(MockToolResource.Title),
SearchKeywordsResourceName = nameof(MockToolResource.Title))]
+[AcceptedDataTypeName("JSON")]
internal sealed class MockIGuiTool : IGuiTool
{
public IUIElement View => null!;