diff --git a/src/application.cpp b/src/application.cpp index 38a120d..baa77c8 100644 --- a/src/application.cpp +++ b/src/application.cpp @@ -128,6 +128,31 @@ void Application::InvalidateQuitRequest() { quit_state_.reset(); } +void Application::NotifySecondInstance(std::vector arguments, + std::string working_directory) try { + if (IsMainThread()) { + Emit(std::move(arguments), + std::move(working_directory)); + return; + } + struct Payload { + std::vector args; + std::string cwd; + }; + auto payload = std::make_shared( + Payload{std::move(arguments), std::move(working_directory)}); + auto dispatch = CreateGuardedCallback<>(std::function([this, payload] { + try { + Emit(payload->args, payload->cwd); + } catch (...) { + } + })); + if (!RunOnMainThread(std::move(dispatch))) { + EmitAsync(payload->args, payload->cwd); + } +} catch (...) { +} + void detail::ApplicationQuitDispatch::RequestForLoop(int exit_code, std::function stop_loop, std::shared_ptr loop_owner) { diff --git a/src/application.h b/src/application.h index f4942a6..ec6eba8 100644 --- a/src/application.h +++ b/src/application.h @@ -131,6 +131,39 @@ class ApplicationSystemBrightnessChangedEvent : public ApplicationEvent { Brightness brightness_; }; +/** + * @brief Event emitted on the primary instance when a second instance launches. + * + * Dispatched on the main/UI thread when another process calls + * Application::RequestSingleInstanceLock() with the same identifier while + * this process holds the lock. + */ +class ApplicationSecondInstanceEvent : public ApplicationEvent { + public: + ApplicationSecondInstanceEvent(std::vector arguments, + std::string working_directory) + : arguments_(std::move(arguments)), + working_directory_(std::move(working_directory)) {} + + /** + * @brief Gets the command-line arguments forwarded by the second instance. + * @return Vector of UTF-8 argument strings. + */ + std::vector GetArguments() const { return arguments_; } + + /** + * @brief Gets the working directory of the second instance when it launched. + * @return UTF-8 working directory path, or empty string if unavailable. + */ + std::string GetWorkingDirectory() const { return working_directory_; } + + std::string GetTypeName() const override { return "ApplicationSecondInstanceEvent"; } + + private: + std::vector arguments_; + std::string working_directory_; +}; + /** * @brief Application is a singleton class that manages the application lifecycle * @@ -298,6 +331,61 @@ class Application : public EventEmitter { */ bool IsSingleInstance() const; + /** + * @brief Requests the application's single-instance lock for an identifier. + * + * Call early during startup before creating windows. If no other instance + * holds the lock for @p identifier, this process acquires it, begins + * listening for secondary launches, and returns true. Calling again with the + * same @p identifier while already holding the lock returns true. + * + * If another instance already holds the lock for @p identifier, @p arguments + * and this process's current working directory are forwarded to the primary + * instance—which receives ApplicationSecondInstanceEvent on its main/UI + * thread—and this call returns false so the secondary process can exit. + * + * @param identifier Non-empty unique identifier for the application lock + * (e.g. "com.example.myapp"). + * @param arguments Optional command-line arguments to forward if a primary + * instance is already running. + * @return true if this process holds the single-instance lock; false if + * another instance already holds it, @p identifier is empty, this + * process already holds a lock for a different identifier, or the + * platform does not support single-instance locking. + * + * @note Platform availability: + * - macOS: ✅ Fully supported - Exclusive flock lock file and Unix domain socket IPC. + * - Windows: ✅ Fully supported - Per-session named mutex and named pipe IPC; + * secondary instances also grant foreground focus permission to the primary. + * - Linux: ✅ Fully supported - Exclusive flock lock file and Unix domain socket IPC + * (under XDG_RUNTIME_DIR, TMPDIR, or /tmp). + * - Android: ❌ Not applicable - Always returns false. + * - iOS: ❌ Not applicable - Always returns false (iOS apps are single instance). + * - OpenHarmony: ❌ Not applicable - Always returns false (managed by system multiAppMode). + */ + bool RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments = {}); + + /** + * @brief Checks whether this process currently holds the single-instance lock. + * + * @return true if RequestSingleInstanceLock() succeeded and the lock has not + * been released, false otherwise. + * @see RequestSingleInstanceLock() for platform availability. + */ + bool HasSingleInstanceLock() const; + + /** + * @brief Releases the single-instance lock if held by this process. + * + * Stops listening for secondary instances and releases the OS lock so another + * process can become the primary instance. Safe to call when no lock is held; + * also called automatically when Application shuts down. + * + * @see RequestSingleInstanceLock() for platform availability. + */ + void ReleaseSingleInstanceLock(); + /** * @brief Shows the application again after Hide(), and makes it active. * @@ -572,6 +660,8 @@ class Application : public EventEmitter { std::function native_confirmation = nullptr); void PerformQuit(int exit_code); void InvalidateQuitRequest(); + void NotifySecondInstance(std::vector arguments, + std::string working_directory); std::shared_ptr quit_state_; // Prevent copy construction and assignment to maintain singleton property diff --git a/src/capi/application_c.cpp b/src/capi/application_c.cpp index 9c2dc81..f1b1e43 100644 --- a/src/capi/application_c.cpp +++ b/src/capi/application_c.cpp @@ -70,6 +70,38 @@ bool native_application_is_single_instance(void) { } } +bool native_application_request_single_instance_lock(const char* identifier, native_string_list_t arguments) { + try { + std::vector arguments_cpp; + for (long i = 0; i < arguments.count; ++i) { + arguments_cpp.emplace_back(arguments.items[i] ? arguments.items[i] : ""); + } + return nativeapi::Application::GetInstance().RequestSingleInstanceLock(std::string(identifier ? identifier : ""), arguments_cpp); + } catch (...) { + fprintf(stderr, "[nativeapi] %s: unexpected exception\n", "native_application_request_single_instance_lock"); + return false; + } +} + +bool native_application_has_single_instance_lock(void) { + try { + return nativeapi::Application::GetInstance().HasSingleInstanceLock(); + } catch (...) { + fprintf(stderr, "[nativeapi] %s: unexpected exception\n", "native_application_has_single_instance_lock"); + return false; + } +} + +void native_application_release_single_instance_lock(void) { + try { + nativeapi::Application::GetInstance().ReleaseSingleInstanceLock(); + return; + } catch (...) { + fprintf(stderr, "[nativeapi] %s: unexpected exception\n", "native_application_release_single_instance_lock"); + return; + } +} + bool native_application_show(void) { try { return nativeapi::Application::GetInstance().Show(); @@ -297,6 +329,12 @@ bool to_c_application_event(const nativeapi::ApplicationEvent& event, native_app out->data.system_brightness_changed.brightness = to_c_brightness(typed->GetBrightness()); return true; } + if (const auto* typed = dynamic_cast(&event)) { + out->type = NATIVE_APPLICATION_EVENT_TYPE_SECOND_INSTANCE; + out->data.second_instance.arguments = to_c_string_list(typed->GetArguments()); + out->data.second_instance.working_directory = to_c_str(typed->GetWorkingDirectory()); + return true; + } return false; } @@ -308,5 +346,10 @@ void free_c_application_event(native_application_event_t* value) { nativeapi::HandleTable::GetInstance().Release(value->data.quit_requested.request); value->data.quit_requested.request = 0; } + if (value->type == NATIVE_APPLICATION_EVENT_TYPE_SECOND_INSTANCE) { + native_string_list_free(&value->data.second_instance.arguments); + free_c_str(value->data.second_instance.working_directory); + value->data.second_instance.working_directory = nullptr; + } } diff --git a/src/capi/application_c.h b/src/capi/application_c.h index b3c20e4..33b3118 100644 --- a/src/capi/application_c.h +++ b/src/capi/application_c.h @@ -7,6 +7,7 @@ #include #include "common_c.h" +#include "string_utils_c.h" typedef uint64_t native_event_request_t; typedef uint64_t native_menu_t; typedef uint64_t native_window_t; @@ -41,6 +42,7 @@ typedef enum { NATIVE_APPLICATION_EVENT_TYPE_DEACTIVATED = 3, NATIVE_APPLICATION_EVENT_TYPE_QUIT_REQUESTED = 4, NATIVE_APPLICATION_EVENT_TYPE_SYSTEM_BRIGHTNESS_CHANGED = 5, + NATIVE_APPLICATION_EVENT_TYPE_SECOND_INSTANCE = 6, } native_application_event_type_t; /// One ApplicationEvent, tagged by its concrete type. @@ -59,6 +61,10 @@ typedef struct { struct { native_brightness_t brightness; } system_brightness_changed; + struct { + native_string_list_t arguments; + char* working_directory; + } second_instance; } data; } native_application_event_t; @@ -80,6 +86,15 @@ bool native_application_is_running(void); FFI_PLUGIN_EXPORT bool native_application_is_single_instance(void); +FFI_PLUGIN_EXPORT +bool native_application_request_single_instance_lock(const char* identifier, native_string_list_t arguments); + +FFI_PLUGIN_EXPORT +bool native_application_has_single_instance_lock(void); + +FFI_PLUGIN_EXPORT +void native_application_release_single_instance_lock(void); + FFI_PLUGIN_EXPORT bool native_application_show(void); diff --git a/src/platform/android/application_android.cpp b/src/platform/android/application_android.cpp index 9ced4b4..6311f06 100644 --- a/src/platform/android/application_android.cpp +++ b/src/platform/android/application_android.cpp @@ -44,6 +44,17 @@ bool Application::IsSingleInstance() const { return false; } +bool Application::RequestSingleInstanceLock(const std::string&, + const std::vector&) { + return false; +} + +bool Application::HasSingleInstanceLock() const { + return false; +} + +void Application::ReleaseSingleInstanceLock() {} + // No application-level hiding here; see Application::Hide(). bool Application::Show() { return false; diff --git a/src/platform/ios/application_ios.mm b/src/platform/ios/application_ios.mm index 1cbb92f..4a8305f 100644 --- a/src/platform/ios/application_ios.mm +++ b/src/platform/ios/application_ios.mm @@ -46,6 +46,17 @@ return true; // iOS apps are always single instance } +bool Application::RequestSingleInstanceLock(const std::string&, + const std::vector&) { + return false; +} + +bool Application::HasSingleInstanceLock() const { + return false; +} + +void Application::ReleaseSingleInstanceLock() {} + // No application-level hiding here; see Application::Hide(). bool Application::Show() { return false; diff --git a/src/platform/linux/application_linux.cpp b/src/platform/linux/application_linux.cpp index 6104ddf..6d34816 100644 --- a/src/platform/linux/application_linux.cpp +++ b/src/platform/linux/application_linux.cpp @@ -14,12 +14,13 @@ #include "../../foundation/dispatcher.h" #include "../../menu.h" #include "../../window_manager.h" +#include "../single_instance_posix.h" namespace nativeapi { class Application::Impl { public: - Impl(Application* app) : app_(app), gtk_app_(nullptr), lock_file_handle_(-1) {} + Impl(Application* app) : app_(app), gtk_app_(nullptr) {} ~Impl() = default; bool Initialize() { @@ -325,10 +326,7 @@ class Application::Impl { void CleanupEventMonitoring() { StopEventMonitoring(); // Clean up Linux-specific event monitoring - if (lock_file_handle_ != -1) { - close(lock_file_handle_); - lock_file_handle_ = -1; - } + single_instance_.ReleaseLock(); if (gtk_app_) { g_object_unref(gtk_app_); @@ -336,10 +334,23 @@ class Application::Impl { } } + bool RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments) { + return single_instance_.RequestLock( + identifier, arguments, + [this](std::vector args, std::string cwd) { + app_->NotifySecondInstance(std::move(args), std::move(cwd)); + }); + } + + bool HasSingleInstanceLock() const { return single_instance_.HasLock(); } + + void ReleaseSingleInstanceLock() { single_instance_.ReleaseLock(); } + private: Application* app_; GtkApplication* gtk_app_; - int lock_file_handle_; + detail::SingleInstancePosix single_instance_; double launcher_progress_ = 0.0; bool launcher_progress_visible_ = false; long long launcher_count_ = 0; @@ -435,6 +446,7 @@ Application::Application() } Application::~Application() { + ReleaseSingleInstanceLock(); ShutdownEmitter(); InvalidateQuitRequest(); // Clean up platform-specific event monitoring @@ -488,7 +500,20 @@ bool Application::IsRunning() const { } bool Application::IsSingleInstance() const { - return false; + return HasSingleInstanceLock(); +} + +bool Application::RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments) { + return pimpl_->RequestSingleInstanceLock(identifier, arguments); +} + +bool Application::HasSingleInstanceLock() const { + return pimpl_->HasSingleInstanceLock(); +} + +void Application::ReleaseSingleInstanceLock() { + pimpl_->ReleaseSingleInstanceLock(); } // No application-level hiding here; see Application::Hide(). diff --git a/src/platform/macos/application_macos.mm b/src/platform/macos/application_macos.mm index 95187a6..0a1128b 100644 --- a/src/platform/macos/application_macos.mm +++ b/src/platform/macos/application_macos.mm @@ -12,6 +12,7 @@ #include "../../foundation/dispatcher.h" #include "../../menu.h" #include "../../window_manager.h" +#include "../single_instance_posix.h" #include "application_quit_macos.h" @interface NativeApplicationDelegate : NSObject { @@ -480,10 +481,7 @@ void CleanupEventMonitoring() { objc_setAssociatedObject(host, kApplicationQuitObserverKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); // Clean up macOS-specific event monitoring - if (lock_file_handle_ != -1) { - close(lock_file_handle_); - lock_file_handle_ = -1; - } + single_instance_.ReleaseLock(); if (delegate_) { // Do not erase a delegate a host installed after nativeapi initialized. @@ -498,6 +496,19 @@ void CleanupEventMonitoring() { } } + bool RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments) { + return single_instance_.RequestLock( + identifier, arguments, + [this](std::vector args, std::string cwd) { + app_->NotifySecondInstance(std::move(args), std::move(cwd)); + }); + } + + bool HasSingleInstanceLock() const { return single_instance_.HasLock(); } + + void ReleaseSingleInstanceLock() { single_instance_.ReleaseLock(); } + private: Application* app_; NativeApplicationDelegate* delegate_; @@ -506,7 +517,7 @@ void CleanupEventMonitoring() { id theme_observer_ = nil; Brightness last_system_brightness_ = Brightness::System; NSHashTable* delegate_hosts_ = nil; - int lock_file_handle_ = -1; + detail::SingleInstancePosix single_instance_; NSImageView* dock_icon_view_ = nil; NSProgressIndicator* dock_progress_ = nil; }; @@ -527,6 +538,7 @@ void CleanupEventMonitoring() { } Application::~Application() { + ReleaseSingleInstanceLock(); ShutdownEmitter(); InvalidateQuitRequest(); // Clean up platform-specific event monitoring @@ -606,7 +618,20 @@ void CleanupEventMonitoring() { } bool Application::IsSingleInstance() const { - return false; + return HasSingleInstanceLock(); +} + +bool Application::RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments) { + return pimpl_->RequestSingleInstanceLock(identifier, arguments); +} + +bool Application::HasSingleInstanceLock() const { + return pimpl_->HasSingleInstanceLock(); +} + +void Application::ReleaseSingleInstanceLock() { + pimpl_->ReleaseSingleInstanceLock(); } bool Application::Show() { diff --git a/src/platform/ohos/application_ohos.cpp b/src/platform/ohos/application_ohos.cpp index 6e98e17..88a517b 100644 --- a/src/platform/ohos/application_ohos.cpp +++ b/src/platform/ohos/application_ohos.cpp @@ -267,6 +267,14 @@ bool Application::IsSingleInstance() const { }); return result; } +bool Application::RequestSingleInstanceLock(const std::string&, + const std::vector&) { + return false; +} +bool Application::HasSingleInstanceLock() const { + return false; +} +void Application::ReleaseSingleInstanceLock() {} bool Application::Show() { return Visibility(pimpl_->state, true); diff --git a/src/platform/single_instance_posix.h b/src/platform/single_instance_posix.h new file mode 100644 index 0000000..7f4e4eb --- /dev/null +++ b/src/platform/single_instance_posix.h @@ -0,0 +1,388 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../single_instance_internal.h" + +namespace nativeapi::detail { + +class SingleInstancePosix { + public: + using SecondInstanceCallback = + std::function, std::string)>; + + SingleInstancePosix() = default; + ~SingleInstancePosix() { ReleaseLock(); } + + SingleInstancePosix(const SingleInstancePosix&) = delete; + SingleInstancePosix& operator=(const SingleInstancePosix&) = delete; + + bool RequestLock(const std::string& identifier, + const std::vector& arguments, + SecondInstanceCallback callback) { + if (identifier.empty()) { + return false; + } + + { + std::lock_guard lock(mutex_); + if (lock_fd_ >= 0) { + return identifier_ == identifier; + } + } + + std::string lock_path; + std::string sock_path; + BuildPaths(identifier, lock_path, sock_path); + + int lock_fd = ::open(lock_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0600); + if (lock_fd < 0) { + return false; + } + + if (::flock(lock_fd, LOCK_EX | LOCK_NB) != 0) { + const int err = errno; + ::close(lock_fd); + if (err == EWOULDBLOCK || err == EAGAIN) { + SendToPrimary(sock_path, arguments); + } + return false; + } + + ::unlink(sock_path.c_str()); + + int listen_fd = ::socket(AF_UNIX, SOCK_STREAM, 0); + if (listen_fd < 0) { + ::close(lock_fd); + return false; + } + SetCloexec(listen_fd); + + sockaddr_un addr{}; + addr.sun_family = AF_UNIX; + if (sock_path.size() >= sizeof(addr.sun_path)) { + ::close(listen_fd); + ::close(lock_fd); + return false; + } + std::strncpy(addr.sun_path, sock_path.c_str(), sizeof(addr.sun_path) - 1); + + if (::bind(listen_fd, reinterpret_cast(&addr), sizeof(addr)) != 0 || + ::listen(listen_fd, 8) != 0) { + ::close(listen_fd); + ::unlink(sock_path.c_str()); + ::close(lock_fd); + return false; + } + ::chmod(sock_path.c_str(), 0600); + + int wake_fds[2] = {-1, -1}; + if (::pipe(wake_fds) != 0) { + ::close(listen_fd); + ::unlink(sock_path.c_str()); + ::close(lock_fd); + return false; + } + SetCloexec(wake_fds[0]); + SetCloexec(wake_fds[1]); + SetNonBlocking(wake_fds[0]); + SetNonBlocking(wake_fds[1]); + + { + std::lock_guard lock(mutex_); + if (lock_fd_ >= 0) { + const bool same = (identifier_ == identifier); + ::close(wake_fds[0]); + ::close(wake_fds[1]); + ::close(listen_fd); + ::close(lock_fd); + return same; + } + lock_fd_ = lock_fd; + listen_fd_ = listen_fd; + wake_fds_[0] = wake_fds[0]; + wake_fds_[1] = wake_fds[1]; + identifier_ = identifier; + sock_path_ = sock_path; + callback_ = std::move(callback); + listener_thread_ = std::thread([this] { ListenLoop(); }); + } + return true; + } + + bool HasLock() const { + std::lock_guard lock(mutex_); + return lock_fd_ >= 0; + } + + void ReleaseLock() { + int wake_write = -1; + int wake_read = -1; + int listen_fd = -1; + int lock_fd = -1; + std::string sock_path; + std::thread thread_to_join; + { + std::lock_guard lock(mutex_); + if (lock_fd_ < 0) { + return; + } + wake_read = wake_fds_[0]; + wake_write = wake_fds_[1]; + wake_fds_[0] = -1; + wake_fds_[1] = -1; + listen_fd = listen_fd_; + listen_fd_ = -1; + lock_fd = lock_fd_; + lock_fd_ = -1; + sock_path = std::move(sock_path_); + identifier_.clear(); + callback_ = nullptr; + thread_to_join = std::move(listener_thread_); + } + + if (wake_write >= 0) { + const char byte = 1; + ssize_t ignored = ::write(wake_write, &byte, 1); + (void)ignored; + } + if (thread_to_join.joinable()) { + thread_to_join.join(); + } + if (wake_read >= 0) { + ::close(wake_read); + } + if (wake_write >= 0) { + ::close(wake_write); + } + if (listen_fd >= 0) { + ::close(listen_fd); + } + if (!sock_path.empty()) { + ::unlink(sock_path.c_str()); + } + if (lock_fd >= 0) { + ::close(lock_fd); + } + } + + private: + static void SetCloexec(int fd) { + int flags = ::fcntl(fd, F_GETFD); + if (flags >= 0) { + ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); + } + } + + static void SetNonBlocking(int fd) { + int flags = ::fcntl(fd, F_GETFL); + if (flags >= 0) { + ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + } + + static std::string PickRuntimeDir() { + auto usable = [](const char* dir) -> std::string { + if (!dir || dir[0] == '\0') { + return {}; + } + std::string s(dir); + while (s.size() > 1 && s.back() == '/') { + s.pop_back(); + } + if (::access(s.c_str(), W_OK | X_OK) == 0) { + return s; + } + return {}; + }; +#if !defined(__APPLE__) + if (auto dir = usable(std::getenv("XDG_RUNTIME_DIR")); !dir.empty()) { + return dir; + } +#endif + if (auto dir = usable(std::getenv("TMPDIR")); !dir.empty()) { + return dir; + } + return "/tmp"; + } + + static void BuildPaths(const std::string& identifier, + std::string& lock_path, + std::string& sock_path) { + const std::string key = MakeSingleInstanceKey(identifier); + const std::string uid = std::to_string(static_cast(::getuid())); + const std::string dir = PickRuntimeDir(); + sockaddr_un probe{}; + const size_t max_sun = sizeof(probe.sun_path) - 1; + + sock_path = dir + "/nasi-" + uid + "-" + key + ".sock"; + lock_path = dir + "/nasi-" + uid + "-" + key + ".lock"; + if (sock_path.size() > max_sun) { + sock_path = "/tmp/nasi-" + uid + "-" + key + ".sock"; + lock_path = "/tmp/nasi-" + uid + "-" + key + ".lock"; + } + } + + static std::string CurrentWorkingDirectoryUtf8() { + char stack_buf[4096]; + if (::getcwd(stack_buf, sizeof(stack_buf))) { + return std::string(stack_buf); + } + return {}; + } + + static void SendToPrimary(const std::string& sock_path, + const std::vector& arguments) { + std::vector payload; + if (!EncodeSingleInstancePayload(arguments, CurrentWorkingDirectoryUtf8(), payload)) { + return; + } + + sockaddr_un addr{}; + addr.sun_family = AF_UNIX; + if (sock_path.size() >= sizeof(addr.sun_path)) { + return; + } + std::strncpy(addr.sun_path, sock_path.c_str(), sizeof(addr.sun_path) - 1); + + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(1500); + int fd = -1; + while (std::chrono::steady_clock::now() < deadline) { + fd = ::socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) { + return; + } + SetCloexec(fd); +#if defined(SO_NOSIGPIPE) + int one = 1; + ::setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one)); +#endif + if (::connect(fd, reinterpret_cast(&addr), sizeof(addr)) == 0) { + break; + } + const int err = errno; + ::close(fd); + fd = -1; + if (err == ENOENT || err == ECONNREFUSED || err == EAGAIN) { + std::this_thread::sleep_for(std::chrono::milliseconds(25)); + } else { + break; + } + } + if (fd < 0) { + return; + } + + size_t sent_total = 0; + while (sent_total < payload.size()) { + int flags = 0; +#if defined(MSG_NOSIGNAL) + flags |= MSG_NOSIGNAL; +#endif + ssize_t n = ::send(fd, payload.data() + sent_total, payload.size() - sent_total, flags); + if (n <= 0) { + if (n < 0 && errno == EINTR) { + continue; + } + break; + } + sent_total += static_cast(n); + } + ::close(fd); + } + + void ListenLoop() { + int listen_fd = -1; + int wake_read = -1; + SecondInstanceCallback callback; + { + std::lock_guard lock(mutex_); + listen_fd = listen_fd_; + wake_read = wake_fds_[0]; + callback = callback_; + } + + while (listen_fd >= 0 && wake_read >= 0) { + pollfd fds[2]{}; + fds[0].fd = wake_read; + fds[0].events = POLLIN; + fds[1].fd = listen_fd; + fds[1].events = POLLIN; + + int ready = ::poll(fds, 2, -1); + if (ready < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (fds[0].revents & (POLLIN | POLLHUP | POLLERR)) { + break; + } + if (!(fds[1].revents & POLLIN)) { + continue; + } + + int client = ::accept(listen_fd, nullptr, nullptr); + if (client < 0) { + continue; + } + SetCloexec(client); + timeval tv{}; + tv.tv_sec = 2; + tv.tv_usec = 0; + ::setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + + std::vector data; + uint8_t buffer[4096]; + while (data.size() < kSingleInstanceMaxPayloadBytes) { + ssize_t n = ::recv(client, buffer, sizeof(buffer), 0); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + break; + } + const size_t remaining = kSingleInstanceMaxPayloadBytes - data.size(); + const size_t take = static_cast(n) < remaining ? static_cast(n) : remaining; + data.insert(data.end(), buffer, buffer + take); + } + ::close(client); + + if (!data.empty() && callback) { + std::vector args; + std::string cwd; + if (DecodeSingleInstancePayload(data, args, cwd)) { + callback(std::move(args), std::move(cwd)); + } + } + } + } + + mutable std::mutex mutex_; + int lock_fd_ = -1; + int listen_fd_ = -1; + int wake_fds_[2] = {-1, -1}; + std::string identifier_; + std::string sock_path_; + SecondInstanceCallback callback_; + std::thread listener_thread_; +}; + +} // namespace nativeapi::detail diff --git a/src/platform/wasm/application_wasm.cpp b/src/platform/wasm/application_wasm.cpp index a346c74..ee71a81 100644 --- a/src/platform/wasm/application_wasm.cpp +++ b/src/platform/wasm/application_wasm.cpp @@ -21,6 +21,14 @@ bool Application::IsRunning() const { bool Application::IsSingleInstance() const { return false; } +bool Application::RequestSingleInstanceLock(const std::string&, + const std::vector&) { + return false; +} +bool Application::HasSingleInstanceLock() const { + return false; +} +void Application::ReleaseSingleInstanceLock() {} bool Application::Show() { return false; } diff --git a/src/platform/windows/application_windows.cpp b/src/platform/windows/application_windows.cpp index 8b78a32..5f99c44 100644 --- a/src/platform/windows/application_windows.cpp +++ b/src/platform/windows/application_windows.cpp @@ -18,6 +18,7 @@ #include "../../window_manager.h" #include "application_theme_windows.h" #include "dpi_utils_windows.h" +#include "single_instance_windows.h" #include "string_utils_windows.h" #include "window_taskbar_windows.h" @@ -526,14 +527,24 @@ class Application::Impl { void CleanupEventMonitoring() { StopEventMonitoring(); // Clean up Windows-specific event monitoring - if (mutex_) { - CloseHandle(mutex_); - mutex_ = nullptr; - } + single_instance_.ReleaseLock(); CoUninitialize(); } + bool RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments) { + return single_instance_.RequestLock( + identifier, arguments, + [this](std::vector args, std::string cwd) { + app_->NotifySecondInstance(std::move(args), std::move(cwd)); + }); + } + + bool HasSingleInstanceLock() const { return single_instance_.HasLock(); } + + void ReleaseSingleInstanceLock() { single_instance_.ReleaseLock(); } + private: static LRESULT CALLBACK ThemeWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { if (msg == WM_NCCREATE) { @@ -557,7 +568,7 @@ class Application::Impl { Application* app_; HINSTANCE hinstance_; - HANDLE mutex_ = nullptr; + detail::SingleInstanceWindows single_instance_; HWND theme_hwnd_ = nullptr; Brightness last_system_brightness_ = Brightness::System; // SetIcon()'s icons, held by the windows they were set on. @@ -616,6 +627,7 @@ Application::Application() } Application::~Application() { + ReleaseSingleInstanceLock(); ShutdownEmitter(); InvalidateQuitRequest(); // Clean up platform-specific event monitoring @@ -672,7 +684,20 @@ bool Application::IsRunning() const { } bool Application::IsSingleInstance() const { - return false; + return HasSingleInstanceLock(); +} + +bool Application::RequestSingleInstanceLock(const std::string& identifier, + const std::vector& arguments) { + return pimpl_->RequestSingleInstanceLock(identifier, arguments); +} + +bool Application::HasSingleInstanceLock() const { + return pimpl_->HasSingleInstanceLock(); +} + +void Application::ReleaseSingleInstanceLock() { + pimpl_->ReleaseSingleInstanceLock(); } // No application-level hiding here; see Application::Hide(). diff --git a/src/platform/windows/single_instance_windows.h b/src/platform/windows/single_instance_windows.h new file mode 100644 index 0000000..588a328 --- /dev/null +++ b/src/platform/windows/single_instance_windows.h @@ -0,0 +1,315 @@ +#pragma once + +// clang-format off +#include +// clang-format on + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../single_instance_internal.h" +#include "string_utils_windows.h" + +namespace nativeapi::detail { + +class SingleInstanceWindows { + public: + using SecondInstanceCallback = + std::function, std::string)>; + + SingleInstanceWindows() = default; + ~SingleInstanceWindows() { ReleaseLock(); } + + SingleInstanceWindows(const SingleInstanceWindows&) = delete; + SingleInstanceWindows& operator=(const SingleInstanceWindows&) = delete; + + bool RequestLock(const std::string& identifier, + const std::vector& arguments, + SecondInstanceCallback callback) { + if (identifier.empty()) { + return false; + } + + { + std::lock_guard lock(mutex_); + if (mutex_handle_) { + return identifier_ == identifier; + } + } + + const std::string key = MakeSingleInstanceKey(identifier); + const std::wstring wkey = StringToWString(key); + const std::wstring mutex_name = L"Local\\NativeAPISingleInstance_" + wkey; + const std::wstring pipe_name = L"\\\\.\\pipe\\NativeAPISingleInstance_" + wkey; + + HANDLE hmutex = CreateMutexW(nullptr, FALSE, mutex_name.c_str()); + if (!hmutex) { + return false; + } + if (GetLastError() == ERROR_ALREADY_EXISTS) { + CloseHandle(hmutex); + // Grant the existing primary instance permission to focus its window. + AllowSetForegroundWindow(ASFW_ANY); + SendToPrimary(pipe_name, arguments); + return false; + } + + HANDLE stop_event = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_event) { + CloseHandle(hmutex); + return false; + } + + HANDLE first_pipe = CreateServerPipe(pipe_name); + if (first_pipe == INVALID_HANDLE_VALUE) { + CloseHandle(stop_event); + CloseHandle(hmutex); + return false; + } + + { + std::lock_guard lock(mutex_); + if (mutex_handle_) { + const bool same = (identifier_ == identifier); + CloseHandle(first_pipe); + CloseHandle(stop_event); + CloseHandle(hmutex); + return same; + } + mutex_handle_ = hmutex; + stop_event_ = stop_event; + identifier_ = identifier; + pipe_name_ = pipe_name; + callback_ = std::move(callback); + listener_thread_ = std::thread( + [this, first_pipe] { ListenLoop(first_pipe); }); + } + return true; + } + + bool HasLock() const { + std::lock_guard lock(mutex_); + return mutex_handle_ != nullptr; + } + + void ReleaseLock() { + HANDLE stop_event = nullptr; + HANDLE hmutex = nullptr; + std::thread thread_to_join; + { + std::lock_guard lock(mutex_); + if (!mutex_handle_) { + return; + } + stop_event = stop_event_; + stop_event_ = nullptr; + hmutex = mutex_handle_; + mutex_handle_ = nullptr; + identifier_.clear(); + pipe_name_.clear(); + callback_ = nullptr; + thread_to_join = std::move(listener_thread_); + } + + if (stop_event) { + SetEvent(stop_event); + } + if (thread_to_join.joinable()) { + thread_to_join.join(); + } + if (stop_event) { + CloseHandle(stop_event); + } + if (hmutex) { + CloseHandle(hmutex); + } + } + + private: + static std::string CurrentWorkingDirectoryUtf8() { + DWORD needed = GetCurrentDirectoryW(0, nullptr); + if (needed == 0) { + return {}; + } + std::wstring buf(needed, L'\0'); + DWORD written = GetCurrentDirectoryW(needed, buf.data()); + if (written == 0 || written >= needed) { + return {}; + } + buf.resize(written); + return WStringToString(buf); + } + + static HANDLE CreateServerPipe(const std::wstring& pipe_name) { + return CreateNamedPipeW( + pipe_name.c_str(), + PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + PIPE_UNLIMITED_INSTANCES, + 0, + 65536, + 0, + nullptr); + } + + static void SendToPrimary(const std::wstring& pipe_name, + const std::vector& arguments) { + std::vector payload; + if (!EncodeSingleInstancePayload(arguments, CurrentWorkingDirectoryUtf8(), payload)) { + return; + } + + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(1500); + HANDLE pipe = INVALID_HANDLE_VALUE; + while (std::chrono::steady_clock::now() < deadline) { + pipe = CreateFileW(pipe_name.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (pipe != INVALID_HANDLE_VALUE) { + break; + } + const DWORD err = GetLastError(); + if (err == ERROR_PIPE_BUSY) { + WaitNamedPipeW(pipe_name.c_str(), 100); + } else if (err == ERROR_FILE_NOT_FOUND) { + Sleep(25); + } else { + break; + } + } + if (pipe == INVALID_HANDLE_VALUE) { + return; + } + + size_t written_total = 0; + while (written_total < payload.size()) { + DWORD written = 0; + const DWORD chunk = static_cast(payload.size() - written_total); + if (!WriteFile(pipe, payload.data() + written_total, chunk, &written, nullptr) || + written == 0) { + break; + } + written_total += written; + } + FlushFileBuffers(pipe); + CloseHandle(pipe); + } + + bool WaitForOverlapped(HANDLE pipe, HANDLE io_event, HANDLE stop_event, OVERLAPPED& ov, + DWORD timeout_ms, DWORD& bytes_out) { + HANDLE handles[2] = {stop_event, io_event}; + const DWORD wait = WaitForMultipleObjects(2, handles, FALSE, timeout_ms); + if (wait == WAIT_OBJECT_0 + 1) { + return GetOverlappedResult(pipe, &ov, &bytes_out, FALSE) != FALSE; + } + CancelIoEx(pipe, &ov); + DWORD ignored = 0; + GetOverlappedResult(pipe, &ov, &ignored, TRUE); + return false; + } + + void ListenLoop(HANDLE pipe) { + HANDLE io_event = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!io_event) { + CloseHandle(pipe); + return; + } + + HANDLE stop_event = nullptr; + std::wstring pipe_name; + SecondInstanceCallback callback; + { + std::lock_guard lock(mutex_); + stop_event = stop_event_; + pipe_name = pipe_name_; + callback = callback_; + } + + while (pipe != INVALID_HANDLE_VALUE) { + ResetEvent(io_event); + OVERLAPPED ov{}; + ov.hEvent = io_event; + + bool connected = false; + if (ConnectNamedPipe(pipe, &ov)) { + connected = true; + } else { + const DWORD err = GetLastError(); + if (err == ERROR_PIPE_CONNECTED) { + connected = true; + } else if (err == ERROR_IO_PENDING) { + DWORD ignored = 0; + connected = WaitForOverlapped(pipe, io_event, stop_event, ov, INFINITE, ignored); + } + } + + if (!connected) { + if (WaitForSingleObject(stop_event, 0) == WAIT_OBJECT_0) { + break; + } + CloseHandle(pipe); + pipe = CreateServerPipe(pipe_name); + continue; + } + + std::vector data; + uint8_t buffer[4096]; + while (data.size() < kSingleInstanceMaxPayloadBytes) { + ResetEvent(io_event); + OVERLAPPED read_ov{}; + read_ov.hEvent = io_event; + DWORD bytes_read = 0; + const BOOL ok = ReadFile(pipe, buffer, sizeof(buffer), &bytes_read, &read_ov); + if (!ok) { + const DWORD err = GetLastError(); + if (err == ERROR_IO_PENDING) { + if (!WaitForOverlapped(pipe, io_event, stop_event, read_ov, 2000, bytes_read)) { + break; + } + } else { + break; + } + } + if (bytes_read == 0) { + break; + } + const size_t remaining = kSingleInstanceMaxPayloadBytes - data.size(); + const size_t take = bytes_read < remaining ? bytes_read : remaining; + data.insert(data.end(), buffer, buffer + take); + } + + DisconnectNamedPipe(pipe); + + if (!data.empty() && callback) { + std::vector args; + std::string cwd; + if (DecodeSingleInstancePayload(data, args, cwd)) { + callback(std::move(args), std::move(cwd)); + } + } + + if (WaitForSingleObject(stop_event, 0) == WAIT_OBJECT_0) { + break; + } + } + + if (pipe != INVALID_HANDLE_VALUE) { + CloseHandle(pipe); + } + CloseHandle(io_event); + } + + mutable std::mutex mutex_; + HANDLE mutex_handle_ = nullptr; + HANDLE stop_event_ = nullptr; + std::string identifier_; + std::wstring pipe_name_; + SecondInstanceCallback callback_; + std::thread listener_thread_; +}; + +} // namespace nativeapi::detail diff --git a/src/single_instance_internal.h b/src/single_instance_internal.h new file mode 100644 index 0000000..bddebe4 --- /dev/null +++ b/src/single_instance_internal.h @@ -0,0 +1,134 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace nativeapi::detail { + +constexpr uint32_t kSingleInstanceMagic = 0x4E415349u; // "NASI" +constexpr uint32_t kSingleInstanceVersion = 1u; +constexpr size_t kSingleInstanceMaxPayloadBytes = 1024 * 1024; // 1 MiB +constexpr uint32_t kSingleInstanceMaxArgCount = 4096u; + +// Derives a deterministic, filesystem- and kernel-object-safe key from an +// arbitrary UTF-8 identifier (keeping a short sanitized ASCII prefix for +// readability plus a 64-bit FNV-1a hex digest to avoid collisions and path +// length limits such as sockaddr_un::sun_path). +inline std::string MakeSingleInstanceKey(const std::string& identifier) { + std::string prefix; + prefix.reserve(24); + for (unsigned char ch : identifier) { + if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || + ch == '_' || ch == '-') { + prefix.push_back(static_cast(ch)); + } else if (!prefix.empty() && prefix.back() != '_') { + prefix.push_back('_'); + } + if (prefix.size() >= 24) { + break; + } + } + while (!prefix.empty() && prefix.back() == '_') { + prefix.pop_back(); + } + if (prefix.empty()) { + prefix = "app"; + } + + uint64_t hash = 14695981039346656037ULL; + for (unsigned char ch : identifier) { + hash ^= static_cast(ch); + hash *= 1099511628211ULL; + } + + std::ostringstream oss; + oss << prefix << '_' << std::hex << std::setfill('0') << std::setw(16) << hash; + return oss.str(); +} + +inline void AppendU32LE(std::vector& out, uint32_t value) { + out.push_back(static_cast(value & 0xFFu)); + out.push_back(static_cast((value >> 8) & 0xFFu)); + out.push_back(static_cast((value >> 16) & 0xFFu)); + out.push_back(static_cast((value >> 24) & 0xFFu)); +} + +inline bool ReadU32LE(const std::vector& data, size_t& offset, uint32_t& out) { + if (offset + 4 > data.size()) { + return false; + } + out = static_cast(data[offset]) | (static_cast(data[offset + 1]) << 8) | + (static_cast(data[offset + 2]) << 16) | + (static_cast(data[offset + 3]) << 24); + offset += 4; + return true; +} + +inline bool EncodeSingleInstancePayload(const std::vector& arguments, + const std::string& working_directory, + std::vector& out) { + out.clear(); + const size_t arg_count = + arguments.size() > kSingleInstanceMaxArgCount ? kSingleInstanceMaxArgCount : arguments.size(); + size_t total = 16 + working_directory.size(); + for (size_t i = 0; i < arg_count; ++i) { + total += 4 + arguments[i].size(); + if (total > kSingleInstanceMaxPayloadBytes) { + return false; + } + } + if (total > kSingleInstanceMaxPayloadBytes) { + return false; + } + + out.reserve(total); + AppendU32LE(out, kSingleInstanceMagic); + AppendU32LE(out, kSingleInstanceVersion); + AppendU32LE(out, static_cast(working_directory.size())); + out.insert(out.end(), working_directory.begin(), working_directory.end()); + AppendU32LE(out, static_cast(arg_count)); + for (size_t i = 0; i < arg_count; ++i) { + AppendU32LE(out, static_cast(arguments[i].size())); + out.insert(out.end(), arguments[i].begin(), arguments[i].end()); + } + return true; +} + +inline bool DecodeSingleInstancePayload(const std::vector& data, + std::vector& arguments, + std::string& working_directory) { + arguments.clear(); + working_directory.clear(); + size_t offset = 0; + uint32_t magic = 0; + uint32_t version = 0; + uint32_t cwd_len = 0; + if (!ReadU32LE(data, offset, magic) || !ReadU32LE(data, offset, version) || + magic != kSingleInstanceMagic || version != kSingleInstanceVersion || + !ReadU32LE(data, offset, cwd_len) || offset + cwd_len > data.size()) { + return false; + } + working_directory.assign(reinterpret_cast(data.data() + offset), cwd_len); + offset += cwd_len; + + uint32_t arg_count = 0; + if (!ReadU32LE(data, offset, arg_count) || arg_count > kSingleInstanceMaxArgCount) { + return false; + } + arguments.reserve(arg_count); + for (uint32_t i = 0; i < arg_count; ++i) { + uint32_t arg_len = 0; + if (!ReadU32LE(data, offset, arg_len) || offset + arg_len > data.size()) { + return false; + } + arguments.emplace_back(reinterpret_cast(data.data() + offset), arg_len); + offset += arg_len; + } + return true; +} + +} // namespace nativeapi::detail diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 89baab6..797542b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -717,3 +717,10 @@ if(WIN32) COMMAND window_geometry_and_shadow_windows_test) set_tests_properties(window_geometry_and_shadow_windows_test PROPERTIES TIMEOUT 30) endif() + +if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux" OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) + add_executable(application_single_instance_test application_single_instance_test.cpp) + target_link_libraries(application_single_instance_test PRIVATE nativeapi) + add_test(NAME application_single_instance_test COMMAND application_single_instance_test) + set_tests_properties(application_single_instance_test PROPERTIES TIMEOUT 20) +endif() diff --git a/tests/application_single_instance_test.cpp b/tests/application_single_instance_test.cpp new file mode 100644 index 0000000..825b3e7 --- /dev/null +++ b/tests/application_single_instance_test.cpp @@ -0,0 +1,202 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +#include "nativeapi.h" + +namespace { + +int g_failures = 0; + +void Check(bool ok, const char* label) { + if (!ok) { + std::cerr << "FAIL: " << label << std::endl; + ++g_failures; + } +} + +std::string CurrentProcessPath(const char* argv0) { +#ifdef _WIN32 + wchar_t buf[MAX_PATH * 4]; + DWORD len = GetModuleFileNameW(nullptr, buf, static_cast(sizeof(buf) / sizeof(buf[0]))); + if (len == 0) { + return argv0 ? argv0 : ""; + } + int utf8_len = WideCharToMultiByte(CP_UTF8, 0, buf, static_cast(len), nullptr, 0, nullptr, + nullptr); + std::string out(utf8_len, '\0'); + WideCharToMultiByte(CP_UTF8, 0, buf, static_cast(len), out.data(), utf8_len, nullptr, + nullptr); + return out; +#else + return argv0 ? argv0 : ""; +#endif +} + +int RunChild(const std::string& exe, const std::vector& args) { +#ifdef _WIN32 + auto quote = [](const std::string& s) { + std::string q = "\""; + for (char c : s) { + if (c == '"') { + q += "\\\""; + } else { + q += c; + } + } + q += "\""; + return q; + }; + std::string cmd = quote(exe); + for (const auto& a : args) { + cmd += " "; + cmd += quote(a); + } + int wlen = MultiByteToWideChar(CP_UTF8, 0, cmd.c_str(), -1, nullptr, 0); + std::wstring wcmd(wlen, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, cmd.c_str(), -1, wcmd.data(), wlen); + + STARTUPINFOW si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, wcmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, + &pi)) { + return -1; + } + WaitForSingleObject(pi.hProcess, 10000); + DWORD code = 99; + GetExitCodeProcess(pi.hProcess, &code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return static_cast(code); +#else + pid_t pid = fork(); + if (pid < 0) { + return -1; + } + if (pid == 0) { + std::vector argv; + argv.push_back(const_cast(exe.c_str())); + for (const auto& a : args) { + argv.push_back(const_cast(a.c_str())); + } + argv.push_back(nullptr); + execv(exe.c_str(), argv.data()); + _exit(127); + } + int status = 0; + if (waitpid(pid, &status, 0) < 0) { + return -1; + } + return WIFEXITED(status) ? WEXITSTATUS(status) : -1; +#endif +} + +void PumpEventsBriefly() { + nativeapi::RunMainThreadLoopFor(20); +} + +} // namespace + +int main(int argc, char** argv) { + using namespace nativeapi; + auto& app = Application::GetInstance(); + + // Child mode: --secondary [forwarded args...] + if (argc >= 4 && std::string(argv[1]) == "--secondary") { + const std::string id = argv[2]; + const bool expect_locked = std::string(argv[3]) == "1"; + std::vector forwarded; + for (int i = 4; i < argc; ++i) { + forwarded.emplace_back(argv[i]); + } + const bool acquired = app.RequestSingleInstanceLock(id, forwarded); + if (acquired) { + app.ReleaseSingleInstanceLock(); + } + return (acquired == expect_locked) ? 0 : 2; + } + + const std::string exe = CurrentProcessPath(argc > 0 ? argv[0] : ""); + const auto now_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); + const std::string id = "com.libnativeapi.test.single_instance." + std::to_string(now_ms); + const std::string other_id = id + ".other"; + + // 1. Empty identifier must be rejected. + Check(!app.RequestSingleInstanceLock(""), "Empty identifier should return false"); + Check(!app.HasSingleInstanceLock(), "HasSingleInstanceLock should be false initially"); + + // 2. Acquire lock as primary instance. + Check(app.RequestSingleInstanceLock(id), "Primary RequestSingleInstanceLock should succeed"); + Check(app.HasSingleInstanceLock(), "HasSingleInstanceLock should be true after acquisition"); + Check(app.IsSingleInstance(), "IsSingleInstance should reflect held lock"); + + // 3. Re-requesting with same ID is idempotent; different ID is rejected. + Check(app.RequestSingleInstanceLock(id), "Same identifier should return true"); + Check(!app.RequestSingleInstanceLock(other_id), + "Different identifier while holding lock should return false"); + + // 4. Listen for second-instance event and spawn a real secondary process. + std::mutex ev_mutex; + std::vector received_args; + std::string received_cwd; + std::atomic event_count{0}; + + const size_t listener_id = app.AddListener( + [&](const ApplicationSecondInstanceEvent& ev) { + std::lock_guard lock(ev_mutex); + received_args = ev.GetArguments(); + received_cwd = ev.GetWorkingDirectory(); + event_count.fetch_add(1); + }); + + const int child_rc = + RunChild(exe, {"--secondary", id, "0", "--open", "hello world", "second_arg"}); + Check(child_rc == 0, "Secondary process should report lock denied (acquired == false)"); + + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (event_count.load() == 0 && std::chrono::steady_clock::now() < deadline) { + PumpEventsBriefly(); + } + + Check(event_count.load() == 1, "Primary should receive ApplicationSecondInstanceEvent once"); + { + std::lock_guard lock(ev_mutex); + Check(received_args.size() == 3 && received_args[0] == "--open" && + received_args[1] == "hello world" && received_args[2] == "second_arg", + "Forwarded arguments should match exactly"); + Check(!received_cwd.empty(), "Forwarded working directory should be non-empty"); + } + + app.RemoveListener(listener_id); + + // 5. Release lock and confirm a new process can now acquire it. + app.ReleaseSingleInstanceLock(); + Check(!app.HasSingleInstanceLock(), "HasSingleInstanceLock should be false after release"); + Check(!app.IsSingleInstance(), "IsSingleInstance should be false after release"); + + const int after_release_rc = RunChild(exe, {"--secondary", id, "1"}); + Check(after_release_rc == 0, + "Another process should acquire the lock after ReleaseSingleInstanceLock()"); + + if (g_failures > 0) { + std::cerr << g_failures << " check(s) failed." << std::endl; + return 1; + } + std::cout << "PASS: application_single_instance_test" << std::endl; + return 0; +}