Compare commits
7 Commits
4f6e817a76
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30da1680f2 | ||
|
|
ad9a9021cc | ||
|
|
4f6c1e2060 | ||
|
|
cbbadd547d | ||
|
|
32ef8fb1ac | ||
|
|
0611966be9 | ||
|
|
4caa21c4d2 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,6 @@
|
||||
bin/
|
||||
obj/
|
||||
publish/
|
||||
.vs/
|
||||
.vscode/
|
||||
*.user
|
||||
|
||||
22
README.md
22
README.md
@@ -18,3 +18,25 @@ dotnet run --project .\WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csp
|
||||
|
||||
The initial server listens on `ws://0.0.0.0:8181`.
|
||||
|
||||
## Release Build
|
||||
|
||||
Build a Windows x64 single-file executable:
|
||||
|
||||
```powershell
|
||||
dotnet publish .\WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csproj `
|
||||
-c Release `
|
||||
-r win-x64 `
|
||||
--self-contained true `
|
||||
-p:PublishSingleFile=true `
|
||||
-p:EnableCompressionInSingleFile=true `
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||
-o .\publish\win-x64-single
|
||||
```
|
||||
|
||||
The runnable app is written to:
|
||||
|
||||
```text
|
||||
publish\win-x64-single\WirelessTextSyncer.Windows.exe
|
||||
```
|
||||
|
||||
This build includes the .NET runtime, so the target Windows machine does not need .NET installed. The generated `.pdb` file is only for debugging and is not required to run the app.
|
||||
|
||||
@@ -46,7 +46,7 @@ public sealed class SyncMessageTests
|
||||
public void ReplaceAllAppendsSubmittedText()
|
||||
{
|
||||
var keyboard = new RecordingKeyboardInjectionService();
|
||||
var handler = new SyncMessageHandler(keyboard);
|
||||
var handler = new SyncMessageHandler(keyboard, new RecordingAudioControlService());
|
||||
|
||||
handler.Handle(new SyncMessage
|
||||
{
|
||||
@@ -59,6 +59,62 @@ public sealed class SyncMessageTests
|
||||
keyboard.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeserializeAndroidSetMuteMessage()
|
||||
{
|
||||
var message = JsonSerializer.Deserialize<SyncMessage>(
|
||||
"""{"action":"setMute","muted":true}""",
|
||||
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||
|
||||
Assert.IsNotNull(message);
|
||||
Assert.AreEqual(SyncAction.SetMute, message.Action);
|
||||
Assert.AreEqual(true, message.Muted);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SetMuteForwardsToAudioService()
|
||||
{
|
||||
var audio = new RecordingAudioControlService();
|
||||
var handler = new SyncMessageHandler(new RecordingKeyboardInjectionService(), audio);
|
||||
|
||||
handler.Handle(new SyncMessage
|
||||
{
|
||||
Action = SyncAction.SetMute,
|
||||
Muted = true
|
||||
});
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "mute:True" }, audio.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DiscoveryResponseContainsServiceEndpoint()
|
||||
{
|
||||
using var discovery = new DiscoveryResponderService(() => "192.168.1.10", () => 8181, "Desktop-WIN11");
|
||||
|
||||
using var document = JsonDocument.Parse(discovery.BuildResponseJson());
|
||||
var root = document.RootElement;
|
||||
|
||||
Assert.AreEqual("wirelessTextSyncer.service", root.GetProperty("type").GetString());
|
||||
Assert.AreEqual(1, root.GetProperty("version").GetInt32());
|
||||
Assert.AreEqual("Desktop-WIN11", root.GetProperty("name").GetString());
|
||||
Assert.AreEqual("192.168.1.10", root.GetProperty("host").GetString());
|
||||
Assert.AreEqual(8181, root.GetProperty("port").GetInt32());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WebSocketServiceInfoContainsDeviceName()
|
||||
{
|
||||
using var server = new WebSocketServerService(new SyncMessageHandler(new RecordingKeyboardInjectionService(), new RecordingAudioControlService()), "Desktop-WIN11");
|
||||
|
||||
using var document = JsonDocument.Parse(server.BuildServiceInfoJson());
|
||||
var root = document.RootElement;
|
||||
|
||||
Assert.AreEqual("wirelessTextSyncer.service", root.GetProperty("type").GetString());
|
||||
Assert.AreEqual(1, root.GetProperty("version").GetInt32());
|
||||
Assert.AreEqual("Desktop-WIN11", root.GetProperty("name").GetString());
|
||||
Assert.AreEqual(8181, root.GetProperty("port").GetInt32());
|
||||
}
|
||||
|
||||
private sealed class RecordingKeyboardInjectionService : IKeyboardInjectionService
|
||||
{
|
||||
public List<string> Calls { get; } = [];
|
||||
@@ -83,4 +139,16 @@ public sealed class SyncMessageTests
|
||||
Calls.Add("enter");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingAudioControlService : IAudioControlService
|
||||
{
|
||||
public List<string> Calls { get; } = [];
|
||||
|
||||
public bool IsMuted => Calls.Count > 0 && Calls[^1] == "mute:True";
|
||||
|
||||
public void SetMute(bool muted)
|
||||
{
|
||||
Calls.Add($"mute:{muted}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,5 +9,6 @@ public enum SyncAction
|
||||
ReplaceAll,
|
||||
Backspace,
|
||||
Enter,
|
||||
Ping
|
||||
Ping,
|
||||
SetMute
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ public sealed class SyncActionJsonConverter : JsonConverter<SyncAction>
|
||||
"backspace" => SyncAction.Backspace,
|
||||
"enter" => SyncAction.Enter,
|
||||
"ping" => SyncAction.Ping,
|
||||
"setMute" => SyncAction.SetMute,
|
||||
_ => throw new JsonException($"Unsupported sync action: {value}")
|
||||
};
|
||||
}
|
||||
@@ -35,6 +36,7 @@ public sealed class SyncActionJsonConverter : JsonConverter<SyncAction>
|
||||
SyncAction.Backspace => "backspace",
|
||||
SyncAction.Enter => "enter",
|
||||
SyncAction.Ping => "ping",
|
||||
SyncAction.SetMute => "setMute",
|
||||
_ => throw new JsonException($"Unsupported sync action: {value}")
|
||||
};
|
||||
|
||||
|
||||
@@ -9,4 +9,7 @@ public sealed record SyncMessage
|
||||
|
||||
[JsonPropertyName("text")]
|
||||
public string? Text { get; init; }
|
||||
|
||||
[JsonPropertyName("muted")]
|
||||
public bool? Muted { get; init; }
|
||||
}
|
||||
|
||||
BIN
WirelessTextSyncer.Windows/Resources/Icons/app-icon.png
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/app-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 106 KiB |
BIN
WirelessTextSyncer.Windows/Resources/Icons/app.ico
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/app.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-connected.png
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-connected.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-wait.png
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-wait.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.7 KiB |
52
WirelessTextSyncer.Windows/Services/AudioControlService.cs
Normal file
52
WirelessTextSyncer.Windows/Services/AudioControlService.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using NAudio.CoreAudioApi;
|
||||
|
||||
namespace WirelessTextSyncer.Windows.Services;
|
||||
|
||||
public sealed class AudioControlService : IAudioControlService, IDisposable
|
||||
{
|
||||
private readonly MMDeviceEnumerator enumerator = new();
|
||||
private bool disposed;
|
||||
|
||||
public bool IsMuted
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
|
||||
return device.AudioEndpointVolume.Mute;
|
||||
}
|
||||
catch (COMException exception)
|
||||
{
|
||||
AppLogger.Error("Failed to read audio mute state.", exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void SetMute(bool muted)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
|
||||
device.AudioEndpointVolume.Mute = muted;
|
||||
AppLogger.Info($"Audio mute set to {muted}.");
|
||||
}
|
||||
catch (COMException exception)
|
||||
{
|
||||
AppLogger.Error($"Failed to set audio mute to {muted}.", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
enumerator.Dispose();
|
||||
}
|
||||
}
|
||||
115
WirelessTextSyncer.Windows/Services/DiscoveryResponderService.cs
Normal file
115
WirelessTextSyncer.Windows/Services/DiscoveryResponderService.cs
Normal file
@@ -0,0 +1,115 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WirelessTextSyncer.Windows.Services;
|
||||
|
||||
public sealed class DiscoveryResponderService : IDisposable
|
||||
{
|
||||
public const int DiscoveryPort = 8182;
|
||||
public const string DiscoveryRequestType = "wirelessTextSyncer.discovery";
|
||||
public const string ServiceResponseType = "wirelessTextSyncer.service";
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
private readonly Func<string> hostProvider;
|
||||
private readonly Func<int> portProvider;
|
||||
private readonly string deviceName;
|
||||
private readonly CancellationTokenSource cancellation = new();
|
||||
private UdpClient? udpClient;
|
||||
private Task? listenTask;
|
||||
|
||||
public DiscoveryResponderService(Func<string> hostProvider, Func<int> portProvider, string? deviceName = null)
|
||||
{
|
||||
this.hostProvider = hostProvider;
|
||||
this.portProvider = portProvider;
|
||||
this.deviceName = string.IsNullOrWhiteSpace(deviceName) ? Environment.MachineName : deviceName;
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (udpClient is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
udpClient = new UdpClient(AddressFamily.InterNetwork);
|
||||
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
udpClient.EnableBroadcast = true;
|
||||
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryPort));
|
||||
listenTask = Task.Run(ListenAsync);
|
||||
AppLogger.Info($"Discovery responder listening on UDP {DiscoveryPort}.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
cancellation.Cancel();
|
||||
udpClient?.Dispose();
|
||||
|
||||
try
|
||||
{
|
||||
listenTask?.Wait(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
catch (AggregateException)
|
||||
{
|
||||
}
|
||||
|
||||
cancellation.Dispose();
|
||||
}
|
||||
|
||||
public string BuildResponseJson()
|
||||
{
|
||||
return JsonSerializer.Serialize(
|
||||
new DiscoveryResponse(ServiceResponseType, 1, deviceName, hostProvider(), portProvider()),
|
||||
JsonOptions);
|
||||
}
|
||||
|
||||
private async Task ListenAsync()
|
||||
{
|
||||
var token = cancellation.Token;
|
||||
while (!token.IsCancellationRequested && udpClient is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await udpClient.ReceiveAsync(token);
|
||||
if (!IsDiscoveryRequest(result.Buffer))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var responseBytes = Encoding.UTF8.GetBytes(BuildResponseJson());
|
||||
await udpClient.SendAsync(responseBytes, result.RemoteEndPoint, token);
|
||||
AppLogger.Info($"Answered discovery request from {result.RemoteEndPoint}.");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppLogger.Error("Discovery responder failed to process a packet.", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsDiscoveryRequest(byte[] bytes)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = JsonSerializer.Deserialize<DiscoveryRequest>(bytes, JsonOptions);
|
||||
return request?.Type == DiscoveryRequestType && request.Version == 1;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record DiscoveryRequest(string Type, int Version);
|
||||
|
||||
private sealed record DiscoveryResponse(string Type, int Version, string Name, string Host, int Port);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace WirelessTextSyncer.Windows.Services;
|
||||
|
||||
public interface IAudioControlService
|
||||
{
|
||||
bool IsMuted { get; }
|
||||
|
||||
void SetMute(bool muted);
|
||||
}
|
||||
@@ -5,11 +5,13 @@ namespace WirelessTextSyncer.Windows.Services;
|
||||
public sealed class SyncMessageHandler
|
||||
{
|
||||
private readonly IKeyboardInjectionService keyboard;
|
||||
private readonly IAudioControlService audio;
|
||||
private string remoteText = string.Empty;
|
||||
|
||||
public SyncMessageHandler(IKeyboardInjectionService keyboard)
|
||||
public SyncMessageHandler(IKeyboardInjectionService keyboard, IAudioControlService audio)
|
||||
{
|
||||
this.keyboard = keyboard;
|
||||
this.audio = audio;
|
||||
}
|
||||
|
||||
public void Handle(SyncMessage message)
|
||||
@@ -38,11 +40,21 @@ public sealed class SyncMessageHandler
|
||||
break;
|
||||
case SyncAction.Ping:
|
||||
break;
|
||||
case SyncAction.SetMute:
|
||||
HandleSetMute(message);
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException($"Unsupported sync action: {message.Action}");
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleSetMute(SyncMessage message)
|
||||
{
|
||||
var muted = message.Muted ?? false;
|
||||
AppLogger.Info($"SetMute received muted={muted}.");
|
||||
audio.SetMute(muted);
|
||||
}
|
||||
|
||||
private void AppendSubmittedText(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
|
||||
@@ -9,19 +9,24 @@ namespace WirelessTextSyncer.Windows.Services;
|
||||
|
||||
public sealed class WebSocketServerService : IDisposable
|
||||
{
|
||||
private static readonly byte[] HeartbeatPayload = "wts-heartbeat"u8.ToArray();
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
private readonly TimeSpan heartbeatInterval = TimeSpan.FromSeconds(5);
|
||||
private readonly SyncMessageHandler messageHandler;
|
||||
private readonly string deviceName;
|
||||
private readonly List<IWebSocketConnection> clients = [];
|
||||
private readonly object clientsLock = new();
|
||||
private WebSocketServer? server;
|
||||
private System.Threading.Timer? heartbeatTimer;
|
||||
|
||||
public WebSocketServerService(SyncMessageHandler messageHandler)
|
||||
public WebSocketServerService(SyncMessageHandler messageHandler, string? deviceName = null)
|
||||
{
|
||||
this.messageHandler = messageHandler;
|
||||
this.deviceName = string.IsNullOrWhiteSpace(deviceName) ? Environment.MachineName : deviceName;
|
||||
}
|
||||
|
||||
public int Port { get; private set; } = 8181;
|
||||
@@ -34,6 +39,7 @@ public sealed class WebSocketServerService : IDisposable
|
||||
{
|
||||
lock (clientsLock)
|
||||
{
|
||||
clients.RemoveAll(client => !client.IsAvailable);
|
||||
return clients.Count > 0;
|
||||
}
|
||||
}
|
||||
@@ -41,6 +47,18 @@ public sealed class WebSocketServerService : IDisposable
|
||||
|
||||
public event EventHandler? StatusChanged;
|
||||
|
||||
public string BuildServiceInfoJson()
|
||||
{
|
||||
return JsonSerializer.Serialize(
|
||||
new ServiceInfoMessage(
|
||||
DiscoveryResponderService.ServiceResponseType,
|
||||
1,
|
||||
deviceName,
|
||||
LocalIpAddress,
|
||||
Port),
|
||||
JsonOptions);
|
||||
}
|
||||
|
||||
public void Start(int port)
|
||||
{
|
||||
Port = port;
|
||||
@@ -52,12 +70,23 @@ public sealed class WebSocketServerService : IDisposable
|
||||
{
|
||||
socket.OnOpen = () =>
|
||||
{
|
||||
IWebSocketConnection[] replacedClients;
|
||||
lock (clientsLock)
|
||||
{
|
||||
replacedClients = clients
|
||||
.Where(client => client.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress)
|
||||
.ToArray();
|
||||
clients.RemoveAll(client => !client.IsAvailable || replacedClients.Contains(client));
|
||||
clients.Add(socket);
|
||||
}
|
||||
|
||||
foreach (var replacedClient in replacedClients)
|
||||
{
|
||||
replacedClient.Close();
|
||||
}
|
||||
|
||||
AppLogger.Info($"Client connected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
|
||||
_ = SendServiceInfoAsync(socket);
|
||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||
};
|
||||
socket.OnClose = () =>
|
||||
@@ -73,14 +102,16 @@ public sealed class WebSocketServerService : IDisposable
|
||||
socket.OnError = exception =>
|
||||
{
|
||||
AppLogger.Error("WebSocket connection error.", exception);
|
||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||
RemoveClient(socket, "connection error");
|
||||
};
|
||||
socket.OnMessage = HandleRawMessage;
|
||||
});
|
||||
heartbeatTimer = new System.Threading.Timer(_ => ProbeClients(), null, heartbeatInterval, heartbeatInterval);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
heartbeatTimer?.Dispose();
|
||||
IWebSocketConnection[] currentClients;
|
||||
lock (clientsLock)
|
||||
{
|
||||
@@ -96,6 +127,79 @@ public sealed class WebSocketServerService : IDisposable
|
||||
server?.Dispose();
|
||||
}
|
||||
|
||||
private void ProbeClients()
|
||||
{
|
||||
IWebSocketConnection[] currentClients;
|
||||
var removedUnavailableClients = false;
|
||||
lock (clientsLock)
|
||||
{
|
||||
var countBefore = clients.Count;
|
||||
clients.RemoveAll(client => !client.IsAvailable);
|
||||
removedUnavailableClients = clients.Count != countBefore;
|
||||
currentClients = clients.ToArray();
|
||||
}
|
||||
|
||||
if (removedUnavailableClients)
|
||||
{
|
||||
AppLogger.Info("Removed unavailable WebSocket clients during heartbeat.");
|
||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
foreach (var client in currentClients)
|
||||
{
|
||||
_ = SendHeartbeatAsync(client);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendHeartbeatAsync(IWebSocketConnection client)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!client.IsAvailable)
|
||||
{
|
||||
RemoveClient(client, "heartbeat unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
await client.SendPing(HeartbeatPayload);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppLogger.Error("WebSocket heartbeat failed.", exception);
|
||||
RemoveClient(client, "heartbeat failure");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendServiceInfoAsync(IWebSocketConnection client)
|
||||
{
|
||||
try
|
||||
{
|
||||
await client.Send(BuildServiceInfoJson());
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppLogger.Error("Failed to send WebSocket service info.", exception);
|
||||
RemoveClient(client, "service info failure");
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveClient(IWebSocketConnection client, string reason)
|
||||
{
|
||||
var removed = false;
|
||||
lock (clientsLock)
|
||||
{
|
||||
removed = clients.Remove(client);
|
||||
}
|
||||
|
||||
if (!removed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
AppLogger.Info($"Removed WebSocket client after {reason}: {client.ConnectionInfo.ClientIpAddress}:{client.ConnectionInfo.ClientPort}");
|
||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private void HandleRawMessage(string rawMessage)
|
||||
{
|
||||
try
|
||||
@@ -139,4 +243,6 @@ public sealed class WebSocketServerService : IDisposable
|
||||
|
||||
return address?.ToString() ?? "127.0.0.1";
|
||||
}
|
||||
|
||||
private sealed record ServiceInfoMessage(string Type, int Version, string Name, string Host, int Port);
|
||||
}
|
||||
|
||||
@@ -5,23 +5,35 @@ namespace WirelessTextSyncer.Windows.Tray;
|
||||
public sealed class TrayApplicationContext : ApplicationContext
|
||||
{
|
||||
private readonly KeyboardInjectionService keyboard;
|
||||
private readonly AudioControlService audio;
|
||||
private readonly WebSocketServerService server;
|
||||
private readonly DiscoveryResponderService discovery;
|
||||
private readonly NotifyIcon notifyIcon;
|
||||
private readonly Icon connectedIcon;
|
||||
private readonly Icon waitIcon;
|
||||
private readonly SynchronizationContext uiContext;
|
||||
private ToolStripMenuItem? clipboardPasteMenuItem;
|
||||
private ToolStripMenuItem? sendInputTypingMenuItem;
|
||||
private bool? lastConnectionState;
|
||||
private bool disposed;
|
||||
|
||||
public TrayApplicationContext()
|
||||
{
|
||||
AppLogger.Info("Tray application starting.");
|
||||
uiContext = SynchronizationContext.Current ?? new WindowsFormsSynchronizationContext();
|
||||
keyboard = new KeyboardInjectionService();
|
||||
var handler = new SyncMessageHandler(keyboard);
|
||||
audio = new AudioControlService();
|
||||
var handler = new SyncMessageHandler(keyboard, audio);
|
||||
|
||||
server = new WebSocketServerService(handler);
|
||||
server.StatusChanged += (_, _) => UpdateTrayText();
|
||||
server.StatusChanged += (_, _) => uiContext.Post(_ => UpdateTrayStatus(), null);
|
||||
discovery = new DiscoveryResponderService(() => server.LocalIpAddress, () => server.Port);
|
||||
connectedIcon = TrayIconFactory.CreateConnectedIcon();
|
||||
waitIcon = TrayIconFactory.CreateWaitIcon();
|
||||
|
||||
notifyIcon = new NotifyIcon
|
||||
{
|
||||
Icon = SystemIcons.Application,
|
||||
Icon = waitIcon,
|
||||
Text = "WirelessTextSyncer starting...",
|
||||
Visible = true,
|
||||
ContextMenuStrip = BuildMenu()
|
||||
@@ -31,7 +43,8 @@ public sealed class TrayApplicationContext : ApplicationContext
|
||||
try
|
||||
{
|
||||
server.Start(8181);
|
||||
UpdateTrayText();
|
||||
discovery.Start();
|
||||
UpdateTrayStatus();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -46,7 +59,12 @@ public sealed class TrayApplicationContext : ApplicationContext
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
disposed = true;
|
||||
notifyIcon.Dispose();
|
||||
connectedIcon.Dispose();
|
||||
waitIcon.Dispose();
|
||||
discovery.Dispose();
|
||||
audio.Dispose();
|
||||
server.Dispose();
|
||||
}
|
||||
|
||||
@@ -127,10 +145,34 @@ public sealed class TrayApplicationContext : ApplicationContext
|
||||
notifyIcon.ShowBalloonTip(1500);
|
||||
}
|
||||
|
||||
private void UpdateTrayText()
|
||||
private void UpdateTrayStatus()
|
||||
{
|
||||
var status = server.HasClient ? "connected" : "waiting";
|
||||
if (disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var connected = server.HasClient;
|
||||
var status = connected ? "connected" : "waiting";
|
||||
var text = $"WirelessTextSyncer {server.LocalIpAddress}:{server.Port} ({status})";
|
||||
notifyIcon.Icon = connected ? connectedIcon : waitIcon;
|
||||
notifyIcon.Text = text.Length > 63 ? text[..63] : text;
|
||||
|
||||
if (lastConnectionState is not null && lastConnectionState != connected)
|
||||
{
|
||||
ShowConnectionToast(connected);
|
||||
}
|
||||
|
||||
lastConnectionState = connected;
|
||||
}
|
||||
|
||||
private void ShowConnectionToast(bool connected)
|
||||
{
|
||||
notifyIcon.BalloonTipTitle = "WirelessTextSyncer";
|
||||
notifyIcon.BalloonTipText = connected
|
||||
? $"Device connected to {server.LocalIpAddress}:{server.Port}."
|
||||
: "Device disconnected. Waiting for connection.";
|
||||
notifyIcon.BalloonTipIcon = connected ? ToolTipIcon.Info : ToolTipIcon.Warning;
|
||||
notifyIcon.ShowBalloonTip(3000);
|
||||
}
|
||||
}
|
||||
|
||||
50
WirelessTextSyncer.Windows/Tray/TrayIconFactory.cs
Normal file
50
WirelessTextSyncer.Windows/Tray/TrayIconFactory.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System.Drawing.Imaging;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WirelessTextSyncer.Windows.Tray;
|
||||
|
||||
internal static class TrayIconFactory
|
||||
{
|
||||
private const string ConnectedResourceName = "WirelessTextSyncer.TrayConnected.png";
|
||||
private const string WaitResourceName = "WirelessTextSyncer.TrayWait.png";
|
||||
|
||||
public static Icon CreateConnectedIcon()
|
||||
{
|
||||
return CreateIconFromResource(ConnectedResourceName);
|
||||
}
|
||||
|
||||
public static Icon CreateWaitIcon()
|
||||
{
|
||||
return CreateIconFromResource(WaitResourceName);
|
||||
}
|
||||
|
||||
private static Icon CreateIconFromResource(string resourceName)
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
using var stream = assembly.GetManifestResourceStream(resourceName)
|
||||
?? throw new InvalidOperationException($"Tray icon resource not found: {resourceName}");
|
||||
using var source = new Bitmap(stream);
|
||||
using var bitmap = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb);
|
||||
using (var graphics = Graphics.FromImage(bitmap))
|
||||
{
|
||||
graphics.Clear(Color.Transparent);
|
||||
graphics.DrawImage(source, 0, 0, source.Width, source.Height);
|
||||
}
|
||||
|
||||
var handle = bitmap.GetHicon();
|
||||
try
|
||||
{
|
||||
using var icon = Icon.FromHandle(handle);
|
||||
return (Icon)icon.Clone();
|
||||
}
|
||||
finally
|
||||
{
|
||||
DestroyIcon(handle);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool DestroyIcon(IntPtr handle);
|
||||
}
|
||||
@@ -6,11 +6,18 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<ApplicationIcon>Resources\Icons\app.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Fleck" Version="1.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.8" />
|
||||
<PackageReference Include="NAudio" Version="2.2.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\Icons\tray-connected.png" LogicalName="WirelessTextSyncer.TrayConnected.png" />
|
||||
<EmbeddedResource Include="Resources\Icons\tray-wait.png" LogicalName="WirelessTextSyncer.TrayWait.png" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user