Manage global shortcuts (#635)
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
Build and Release / Read metadata (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-01-24 20:05:34 +01:00
1 parent c9f037bb2c
commit 127778df42
34 files changed
+1654 -35

No files matched your search

@@ -0,0 +1,111 @@
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Rust;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Tools.Services;
public sealed class GlobalShortcutService : BackgroundService, IMessageBusReceiver
{
private static bool IS_INITIALIZED;
private readonly ILogger<GlobalShortcutService> logger;
private readonly SettingsManager settingsManager;
private readonly MessageBus messageBus;
private readonly RustService rustService;
public GlobalShortcutService(
ILogger<GlobalShortcutService> logger,
SettingsManager settingsManager,
MessageBus messageBus,
RustService rustService)
{
this.logger = logger;
this.settingsManager = settingsManager;
this.messageBus = messageBus;
this.rustService = rustService;
this.messageBus.RegisterComponent(this);
this.ApplyFilters([], [Event.CONFIGURATION_CHANGED]);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Wait until the app is fully initialized:
while (!stoppingToken.IsCancellationRequested && !IS_INITIALIZED)
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
// Register shortcuts on startup:
await this.RegisterAllShortcuts();
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
this.messageBus.Unregister(this);
await base.StopAsync(cancellationToken);
}
#region IMessageBusReceiver
public async Task ProcessMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data)
{
switch (triggeredEvent)
{
case Event.CONFIGURATION_CHANGED:
await this.RegisterAllShortcuts();
break;
}
}
public Task<TResult?> ProcessMessageWithResult<TPayload, TResult>(ComponentBase? sendingComponent, Event triggeredEvent, TPayload? data) => Task.FromResult<TResult?>(default);
#endregion
private async Task RegisterAllShortcuts()
{
this.logger.LogInformation("Registering global shortcuts.");
foreach (var shortcutId in Enum.GetValues<Shortcut>())
{
if(shortcutId is Shortcut.NONE)
continue;
var shortcut = this.GetShortcutValue(shortcutId);
var isEnabled = this.IsShortcutAllowed(shortcutId);
if (isEnabled && !string.IsNullOrWhiteSpace(shortcut))
{
var success = await this.rustService.UpdateGlobalShortcut(shortcutId, shortcut);
if (success)
this.logger.LogInformation("Global shortcut '{ShortcutId}' ({Shortcut}) registered.", shortcutId, shortcut);
else
this.logger.LogWarning("Failed to register global shortcut '{ShortcutId}' ({Shortcut}).", shortcutId, shortcut);
}
else
{
// Disable the shortcut when empty or feature is disabled:
await this.rustService.UpdateGlobalShortcut(shortcutId, string.Empty);
}
}
this.logger.LogInformation("Global shortcuts registration completed.");
}
private string GetShortcutValue(Shortcut name) => name switch
{
Shortcut.VOICE_RECORDING_TOGGLE => this.settingsManager.ConfigurationData.App.ShortcutVoiceRecording,
_ => string.Empty,
};
private bool IsShortcutAllowed(Shortcut name) => name switch
{
// Voice recording is a preview feature:
Shortcut.VOICE_RECORDING_TOGGLE => PreviewFeatures.PRE_SPEECH_TO_TEXT_2026.IsEnabled(this.settingsManager),
// Other shortcuts are always allowed:
_ => true,
};
public static void Initialize() => IS_INITIALIZED = true;
}
@@ -0,0 +1,112 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace AIStudio.Tools.Services;
/// <summary>
/// Converts enum values for Rust communication.
/// </summary>
/// <remarks>
/// Rust expects PascalCase enum values (e.g., "VoiceRecordingToggle"),
/// while .NET uses UPPER_SNAKE_CASE (e.g., "VOICE_RECORDING_TOGGLE").
/// This converter handles the bidirectional conversion.
/// </remarks>
public sealed class RustEnumConverter : JsonConverter<object>
{
private static readonly ILogger<RustEnumConverter> LOG = Program.LOGGER_FACTORY.CreateLogger<RustEnumConverter>();
public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;
public override object? Read(ref Utf8JsonReader reader, Type enumType, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
var text = reader.GetString();
text = ConvertToUpperSnakeCase(text);
if (Enum.TryParse(enumType, text, out var result))
return result;
}
LOG.LogWarning($"Cannot read '{reader.GetString()}' as '{enumType.Name}' enum; token type: {reader.TokenType}");
return Activator.CreateInstance(enumType);
}
public override object ReadAsPropertyName(ref Utf8JsonReader reader, Type enumType, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.PropertyName)
{
var text = reader.GetString();
text = ConvertToUpperSnakeCase(text);
if (Enum.TryParse(enumType, text, out var result))
return result;
}
LOG.LogWarning($"Cannot read '{reader.GetString()}' as '{enumType.Name}' enum; token type: {reader.TokenType}");
return Activator.CreateInstance(enumType)!;
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WriteStringValue(ConvertToPascalCase(value.ToString()));
}
public override void WriteAsPropertyName(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WritePropertyName(ConvertToPascalCase(value.ToString()));
}
/// <summary>
/// Converts UPPER_SNAKE_CASE to PascalCase.
/// </summary>
/// <param name="text">The text to convert (e.g., "VOICE_RECORDING_TOGGLE").</param>
/// <returns>The converted text as PascalCase (e.g., "VoiceRecordingToggle").</returns>
private static string ConvertToPascalCase(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
var parts = text.Split('_', StringSplitOptions.RemoveEmptyEntries);
var sb = new StringBuilder();
foreach (var part in parts)
{
if (part.Length == 0)
continue;
// First character uppercase, rest lowercase:
sb.Append(char.ToUpperInvariant(part[0]));
if (part.Length > 1)
sb.Append(part[1..].ToLowerInvariant());
}
return sb.ToString();
}
/// <summary>
/// Converts a string to UPPER_SNAKE_CASE.
/// </summary>
/// <param name="text">The text to convert.</param>
/// <returns>The converted text as UPPER_SNAKE_CASE.</returns>
private static string ConvertToUpperSnakeCase(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
var sb = new StringBuilder(text.Length);
var lastCharWasLowerCase = false;
foreach (var c in text)
{
if (char.IsUpper(c) && lastCharWasLowerCase)
sb.Append('_');
sb.Append(char.ToUpperInvariant(c));
lastCharWasLowerCase = char.IsLower(c);
}
return sb.ToString();
}
}
@@ -0,0 +1,140 @@
// ReSharper disable NotAccessedPositionalProperty.Local
using AIStudio.Tools.Rust;
namespace AIStudio.Tools.Services;
public sealed partial class RustService
{
/// <summary>
/// Registers or updates a global keyboard shortcut.
/// </summary>
/// <param name="shortcutId">The identifier for the shortcut.</param>
/// <param name="shortcut">The shortcut string in Tauri format (e.g., "CmdOrControl+1"). Use empty string to disable.</param>
/// <returns>True if the shortcut was registered successfully, false otherwise.</returns>
public async Task<bool> UpdateGlobalShortcut(Shortcut shortcutId, string shortcut)
{
try
{
var request = new RegisterShortcutRequest(shortcutId, shortcut);
var response = await this.http.PostAsJsonAsync("/shortcuts/register", request, this.jsonRustSerializerOptions);
if (!response.IsSuccessStatusCode)
{
this.logger?.LogError("Failed to register global shortcut '{ShortcutId}' due to network error: {StatusCode}", shortcutId, response.StatusCode);
return false;
}
var result = await response.Content.ReadFromJsonAsync<ShortcutResponse>(this.jsonRustSerializerOptions);
if (result is null || !result.Success)
{
this.logger?.LogError("Failed to register global shortcut '{ShortcutId}': {Error}", shortcutId, result?.ErrorMessage ?? "Unknown error");
return false;
}
this.logger?.LogInformation("Global shortcut '{ShortcutId}' registered successfully with key '{Shortcut}'.", shortcutId, shortcut);
return true;
}
catch (Exception ex)
{
this.logger?.LogError(ex, "Exception while registering global shortcut '{ShortcutId}'.", shortcutId);
return false;
}
}
/// <summary>
/// Validates a shortcut string without registering it.
/// </summary>
/// <param name="shortcut">The shortcut string to validate.</param>
/// <returns>A validation result indicating if the shortcut is valid and any conflicts.</returns>
public async Task<ShortcutValidationResult> ValidateShortcut(string shortcut)
{
try
{
var request = new ValidateShortcutRequest(shortcut);
var response = await this.http.PostAsJsonAsync("/shortcuts/validate", request, this.jsonRustSerializerOptions);
if (!response.IsSuccessStatusCode)
{
this.logger?.LogError("Failed to validate shortcut due to network error: {StatusCode}", response.StatusCode);
return new ShortcutValidationResult(false, "Network error during validation", false, string.Empty);
}
var result = await response.Content.ReadFromJsonAsync<ShortcutValidationResponse>(this.jsonRustSerializerOptions);
if (result is null)
return new ShortcutValidationResult(false, "Invalid response from server", false, string.Empty);
return new ShortcutValidationResult(result.IsValid, result.ErrorMessage, result.HasConflict, result.ConflictDescription);
}
catch (Exception ex)
{
this.logger?.LogError(ex, "Exception while validating shortcut.");
return new ShortcutValidationResult(false, ex.Message, false, string.Empty);
}
}
/// <summary>
/// Suspends shortcut processing. The shortcuts remain registered, but events are not sent.
/// This is useful when opening a dialog to configure shortcuts, so the user can
/// press the current shortcut to re-enter it without triggering the action.
/// </summary>
/// <returns>True if successful, false otherwise.</returns>
public async Task<bool> SuspendShortcutProcessing()
{
try
{
var response = await this.http.PostAsync("/shortcuts/suspend", null);
if (!response.IsSuccessStatusCode)
{
this.logger?.LogError("Failed to suspend the shortcut processing due to network error: {StatusCode}.", response.StatusCode);
return false;
}
var result = await response.Content.ReadFromJsonAsync<ShortcutResponse>(this.jsonRustSerializerOptions);
if (result is null || !result.Success)
{
this.logger?.LogError("Failed to suspend shortcut processing: {Error}", result?.ErrorMessage ?? "Unknown error");
return false;
}
this.logger?.LogDebug("Shortcut processing suspended.");
return true;
}
catch (Exception ex)
{
this.logger?.LogError(ex, "Exception while suspending shortcut processing.");
return false;
}
}
/// <summary>
/// Resumes the shortcut processing after it was suspended.
/// </summary>
/// <returns>True if successful, false otherwise.</returns>
public async Task<bool> ResumeShortcutProcessing()
{
try
{
var response = await this.http.PostAsync("/shortcuts/resume", null);
if (!response.IsSuccessStatusCode)
{
this.logger?.LogError("Failed to resume shortcut processing due to network error: {StatusCode}.", response.StatusCode);
return false;
}
var result = await response.Content.ReadFromJsonAsync<ShortcutResponse>(this.jsonRustSerializerOptions);
if (result is null || !result.Success)
{
this.logger?.LogError("Failed to resume shortcut processing: {Error}", result?.ErrorMessage ?? "Unknown error");
return false;
}
this.logger?.LogDebug("Shortcut processing resumed.");
return true;
}
catch (Exception ex)
{
this.logger?.LogError(ex, "Exception while resuming shortcut processing.");
return false;
}
}
}
@@ -1,7 +1,6 @@
using System.Security.Cryptography;
using System.Text.Json;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
using Version = System.Version;
@@ -22,7 +21,10 @@ public sealed partial class RustService : BackgroundService
private readonly JsonSerializerOptions jsonRustSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
Converters = { new TolerantEnumConverter() },
Converters =
{
new RustEnumConverter(),
},
};
private ILogger<RustService>? logger;