Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,31 @@ void Application::InvalidateQuitRequest() {
quit_state_.reset();
}

void Application::NotifySecondInstance(std::vector<std::string> arguments,
std::string working_directory) try {
if (IsMainThread()) {
Emit<ApplicationSecondInstanceEvent>(std::move(arguments),
std::move(working_directory));
return;
}
struct Payload {
std::vector<std::string> args;
std::string cwd;
};
auto payload = std::make_shared<Payload>(
Payload{std::move(arguments), std::move(working_directory)});
auto dispatch = CreateGuardedCallback<>(std::function<void()>([this, payload] {
try {
Emit<ApplicationSecondInstanceEvent>(payload->args, payload->cwd);
} catch (...) {
}
}));
if (!RunOnMainThread(std::move(dispatch))) {
EmitAsync<ApplicationSecondInstanceEvent>(payload->args, payload->cwd);
}
} catch (...) {
}

void detail::ApplicationQuitDispatch::RequestForLoop(int exit_code,
std::function<void(int)> stop_loop,
std::shared_ptr<void> loop_owner) {
Expand Down
90 changes: 90 additions & 0 deletions src/application.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> 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<std::string> 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<std::string> arguments_;
std::string working_directory_;
};

/**
* @brief Application is a singleton class that manages the application lifecycle
*
Expand Down Expand Up @@ -298,6 +331,61 @@ class Application : public EventEmitter<ApplicationEvent> {
*/
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<std::string>& 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.
*
Expand Down Expand Up @@ -572,6 +660,8 @@ class Application : public EventEmitter<ApplicationEvent> {
std::function<void(bool)> native_confirmation = nullptr);
void PerformQuit(int exit_code);
void InvalidateQuitRequest();
void NotifySecondInstance(std::vector<std::string> arguments,
std::string working_directory);
std::shared_ptr<detail::ApplicationQuitState> quit_state_;

// Prevent copy construction and assignment to maintain singleton property
Expand Down
43 changes: 43 additions & 0 deletions src/capi/application_c.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> 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();
Expand Down Expand Up @@ -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<const nativeapi::ApplicationSecondInstanceEvent*>(&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;
}

Expand All @@ -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;
}
}

15 changes: 15 additions & 0 deletions src/capi/application_c.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <stdint.h>

#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;
Expand Down Expand Up @@ -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.
Expand All @@ -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;

Expand All @@ -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);

Expand Down
11 changes: 11 additions & 0 deletions src/platform/android/application_android.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ bool Application::IsSingleInstance() const {
return false;
}

bool Application::RequestSingleInstanceLock(const std::string&,
const std::vector<std::string>&) {
return false;
}

bool Application::HasSingleInstanceLock() const {
return false;
}

void Application::ReleaseSingleInstanceLock() {}

// No application-level hiding here; see Application::Hide().
bool Application::Show() {
return false;
Expand Down
11 changes: 11 additions & 0 deletions src/platform/ios/application_ios.mm
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@
return true; // iOS apps are always single instance
}

bool Application::RequestSingleInstanceLock(const std::string&,
const std::vector<std::string>&) {
return false;
}

bool Application::HasSingleInstanceLock() const {
return false;
}

void Application::ReleaseSingleInstanceLock() {}

// No application-level hiding here; see Application::Hide().
bool Application::Show() {
return false;
Expand Down
39 changes: 32 additions & 7 deletions src/platform/linux/application_linux.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -325,21 +326,31 @@ 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_);
gtk_app_ = nullptr;
}
}

bool RequestSingleInstanceLock(const std::string& identifier,
const std::vector<std::string>& arguments) {
return single_instance_.RequestLock(
identifier, arguments,
[this](std::vector<std::string> 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;
Expand Down Expand Up @@ -435,6 +446,7 @@ Application::Application()
}

Application::~Application() {
ReleaseSingleInstanceLock();
ShutdownEmitter();
InvalidateQuitRequest();
// Clean up platform-specific event monitoring
Expand Down Expand Up @@ -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<std::string>& 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().
Expand Down
Loading
Loading