Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only allow a single instance of UX #2828

Merged
merged 1 commit into from Aug 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 45 additions & 1 deletion OpenTabletDriver.UX/App.cs
@@ -1,9 +1,11 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO.Pipes;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Eto.Drawing;
using Eto.Forms;
using OpenTabletDriver.Desktop;
Expand All @@ -26,6 +28,23 @@ private App()
}

public static void Run(string platform, string[] args)
{
using (var mutex = new Mutex(true, @$"Global\{APPNAME}.Mutex", out var firstInstance))
{
if (firstInstance)
{
RunInternal(platform, args);
}
else
{
using var client = new NamedPipeClientStream(".", APPNAME + ".Singleton", PipeDirection.InOut);
client.Connect();
return;
}
}
}

private static void RunInternal(string platform, string[] args)
{
var root = new RootCommand("OpenTabletDriver UX")
{
Expand Down Expand Up @@ -63,6 +82,30 @@ public static void Run(string platform, string[] args)
app.NotificationActivated += Current.HandleNotification;
app.UnhandledException += ShowUnhandledException;

Task.Run(async () =>
{
while (true)
{
using var ipcServer = new NamedPipeServerStream(
APPNAME + ".Singleton",
PipeDirection.InOut,
1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);

// if something connects to the pipe, it means another instance is trying to start
// no need for any actual communication
await ipcServer.WaitForConnectionAsync();

app.AsyncInvoke(() =>
{
mainForm.Show();
mainForm.BringToFront();
});
ipcServer.Disconnect();
}
});

app.Run(mainForm);
}

Expand Down Expand Up @@ -99,6 +142,7 @@ public Settings Settings
Logo = Logo.WithSize(256, 256)
};

private const string APPNAME = "OpenTabletDriver.UX";
public readonly static bool EnableTrayIcon = (PluginPlatform.Windows | PluginPlatform.MacOS).HasFlag(DesktopInterop.CurrentPlatform);
public readonly static bool EnableDaemonWatchdog = (PluginPlatform.Windows | PluginPlatform.MacOS).HasFlag(DesktopInterop.CurrentPlatform);
public static DaemonWatchdog DaemonWatchdog;
Expand Down