feat: implement linux

This commit is contained in:
amrbashir
2022-05-03 13:52:52 +02:00
parent ff1035740e
commit c86f4dc024
7 changed files with 278 additions and 197 deletions
+94
View File
@@ -0,0 +1,94 @@
#![cfg(target_os = "linux")]
use crate::SingleInstanceCallback;
use std::{cell::RefCell, rc::Rc};
use tauri::{
plugin::{self, TauriPlugin},
Manager, RunEvent, Runtime,
};
use zbus::{
blocking::{Connection, ConnectionBuilder},
dbus_interface,
};
struct ConnectionHandle(Connection);
const CLOSE_NEW_INSTANCE_ID: u32 = 1542;
struct SingleInstanceDBus {
callback: Box<SingleInstanceCallback>,
}
#[dbus_interface(name = "org.SingleInstance.DBus")]
impl SingleInstanceDBus {
fn execute_callback(&mut self, argv: Vec<String>, cwd: String) -> u32 {
let ret = Rc::new(RefCell::new(1));
let ret_c = Rc::clone(&ret);
(self.callback)(
argv,
cwd,
Box::new(move || {
let mut ret = ret_c.borrow_mut();
*ret = CLOSE_NEW_INSTANCE_ID;
}),
);
ret.take()
}
}
pub fn init<R: Runtime>(f: Box<SingleInstanceCallback>) -> TauriPlugin<R> {
plugin::Builder::new("single-instance")
.setup(|app| {
let app_name = app.package_info().name.clone();
let single_instance_dbus = SingleInstanceDBus { callback: f };
let dbus_name = format!("org.{}.SingleInstance", app_name);
let dbus_path = format!("/org/{}/SingleInstance", app_name);
match ConnectionBuilder::session()
.unwrap()
.name(dbus_name.as_str())
.unwrap()
.serve_at(dbus_path.as_str(), single_instance_dbus)
.unwrap()
.build()
{
Ok(connection) => {
app.manage(ConnectionHandle(connection));
}
Err(zbus::Error::NameTaken) => {
let connection = Connection::session().unwrap();
if let Ok(m) = connection.call_method(
Some(dbus_name.as_str()),
dbus_path.as_str(),
Some("org.SingleInstance.DBus"),
"ExecuteCallback",
&(
std::env::args().collect::<Vec<String>>(),
std::env::current_dir()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
),
) {
let reply: u32 = m.body().unwrap_or_default();
if reply == CLOSE_NEW_INSTANCE_ID {
std::process::exit(0);
}
}
}
_ => {}
}
Ok(())
})
.on_event(|app, event| {
if let RunEvent::Exit = event {
if let Some(connection) = app.try_state::<ConnectionHandle>() {
let app_name = app.package_info().name.clone();
let dbus_name = format!("org.{}.SingleInstance", app_name);
let _ = connection.0.release_name(dbus_name);
}
}
})
.build()
}
+10
View File
@@ -0,0 +1,10 @@
#![cfg(target_os = "macos")]
use crate::SingleInstanceCallback;
use tauri::{
plugin::{self, TauriPlugin},
Runtime,
};
pub fn init<R: Runtime>(f: Box<SingleInstanceCallback>) -> TauriPlugin<R> {
plugin::Builder::new("single-instance").build()
}
+89 -83
View File
@@ -1,8 +1,7 @@
#![cfg(target_os = "windows")]
use std::{cell::RefCell, ffi::CStr, rc::Rc};
use crate::SingleInstanceCallback;
use std::{cell::RefCell, ffi::CStr, rc::Rc};
use tauri::{
plugin::{self, TauriPlugin},
Manager, RunEvent, Runtime,
@@ -22,9 +21,19 @@ use windows_sys::Win32::{
},
};
struct MutexHandle(isize);
struct TargetWindowHandle(isize);
const WMCOPYDATA_SINGLE_INSTANCE_DATA: usize = 1542;
const CLOSE_NEW_INSTANCE_ID: isize = 1542;
pub fn init<R: Runtime>(f: Box<SingleInstanceCallback>) -> TauriPlugin<R> {
plugin::Builder::new("single-instance")
.setup(|app| {
let app_name = &app.package_info().name;
let class_name = format!("{}-single-instance-class", app_name);
let window_name = format!("{}-single-instance-window", app_name);
let hmutex = unsafe {
CreateMutexW(
std::ptr::null(),
@@ -33,10 +42,6 @@ pub fn init<R: Runtime>(f: Box<SingleInstanceCallback>) -> TauriPlugin<R> {
)
};
let app_name = &app.package_info().name;
let class_name = format!("{}-single-instance-class", app_name);
let window_name = format!("{}-single-instance-window", app_name);
if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {
unsafe {
let hwnd = FindWindowW(
@@ -60,82 +65,33 @@ pub fn init<R: Runtime>(f: Box<SingleInstanceCallback>) -> TauriPlugin<R> {
lpData: bytes.as_ptr() as _,
};
let ret = SendMessageW(hwnd, WM_COPYDATA, 0, &cds as *const _ as _);
if ret == CLOSE_NEW_INSTANCE {
if ret == CLOSE_NEW_INSTANCE_ID {
std::process::exit(0);
}
}
}
}
} else {
app.manage(MutexHandle(hmutex));
app.manage(MutexHandle(hmutex));
unsafe {
let class = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: 0,
lpfnWndProc: Some(single_instance_window_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: GetModuleHandleW(std::ptr::null()),
hIcon: 0,
hCursor: 0,
hbrBackground: 0,
lpszMenuName: std::ptr::null(),
lpszClassName: encode_wide(&class_name).as_ptr(),
hIconSm: 0,
};
RegisterClassExW(&class);
let hwnd = CreateWindowExW(
WS_EX_NOACTIVATE
| WS_EX_TRANSPARENT
| WS_EX_LAYERED
// WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which
// we want to avoid. If you remove this style, this window won't show up in the
// taskbar *initially*, but it can show up at some later point. This can sometimes
// happen on its own after several hours have passed, although this has proven
// difficult to reproduce. Alternatively, it can be manually triggered by killing
// `explorer.exe` and then starting the process back up.
// It is unclear why the bug is triggered by waiting for several hours.
| WS_EX_TOOLWINDOW,
encode_wide(&class_name).as_ptr(),
encode_wide(&window_name).as_ptr(),
WS_OVERLAPPED,
0,
0,
0,
0,
0,
0,
GetModuleHandleW(std::ptr::null()),
std::ptr::null(),
);
SetWindowLongPtrW(
hwnd,
GWL_STYLE,
// The window technically has to be visible to receive WM_PAINT messages (which are used
// for delivering events during resizes), but it isn't displayed to the user because of
// the LAYERED style.
(WS_VISIBLE | WS_POPUP) as isize,
);
SetWindowLongPtrW(hwnd, GWL_USERDATA, Box::into_raw(Box::new(f)) as _);
let hwnd = create_event_target_window(&class_name, &window_name);
unsafe { SetWindowLongPtrW(hwnd, GWL_USERDATA, Box::into_raw(Box::new(f)) as _) };
app.manage(TargetWindowHandle(hwnd));
}
Ok(())
})
.on_event(|app, event| {
if let RunEvent::Exit = event {
let hmutex = app.state::<MutexHandle>().0;
unsafe {
ReleaseMutex(hmutex);
CloseHandle(hmutex);
};
let hwnd = app.state::<TargetWindowHandle>().0;
unsafe { DestroyWindow(hwnd) };
if let Some(hmutex) = app.try_state::<MutexHandle>() {
unsafe {
ReleaseMutex(hmutex.0);
CloseHandle(hmutex.0);
}
}
if let Some(hwnd) = app.try_state::<TargetWindowHandle>() {
unsafe { DestroyWindow(hwnd.0) };
}
}
})
.build()
@@ -165,7 +121,7 @@ unsafe extern "system" fn single_instance_window_proc(
cwd.to_string(),
Box::new(move || {
let mut ret = ret_c.borrow_mut();
*ret = CLOSE_NEW_INSTANCE;
*ret = CLOSE_NEW_INSTANCE_ID;
}),
);
}
@@ -180,10 +136,60 @@ unsafe extern "system" fn single_instance_window_proc(
}
}
struct MutexHandle(isize);
struct TargetWindowHandle(isize);
const WMCOPYDATA_SINGLE_INSTANCE_DATA: usize = 1542;
const CLOSE_NEW_INSTANCE: isize = 1542;
fn create_event_target_window(class_name: &str, window_name: &str) -> HWND {
unsafe {
let class = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: 0,
lpfnWndProc: Some(single_instance_window_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: GetModuleHandleW(std::ptr::null()),
hIcon: 0,
hCursor: 0,
hbrBackground: 0,
lpszMenuName: std::ptr::null(),
lpszClassName: encode_wide(&class_name).as_ptr(),
hIconSm: 0,
};
RegisterClassExW(&class);
let hwnd = CreateWindowExW(
WS_EX_NOACTIVATE
| WS_EX_TRANSPARENT
| WS_EX_LAYERED
// WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which
// we want to avoid. If you remove this style, this window won't show up in the
// taskbar *initially*, but it can show up at some later point. This can sometimes
// happen on its own after several hours have passed, although this has proven
// difficult to reproduce. Alternatively, it can be manually triggered by killing
// `explorer.exe` and then starting the process back up.
// It is unclear why the bug is triggered by waiting for several hours.
| WS_EX_TOOLWINDOW,
encode_wide(&class_name).as_ptr(),
encode_wide(&window_name).as_ptr(),
WS_OVERLAPPED,
0,
0,
0,
0,
0,
0,
GetModuleHandleW(std::ptr::null()),
std::ptr::null(),
);
SetWindowLongPtrW(
hwnd,
GWL_STYLE,
// The window technically has to be visible to receive WM_PAINT messages (which are used
// for delivering events during resizes), but it isn't displayed to the user because of
// the LAYERED style.
(WS_VISIBLE | WS_POPUP) as isize,
);
hwnd
}
}
pub fn encode_wide(string: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
std::os::windows::prelude::OsStrExt::encode_wide(string.as_ref())
@@ -193,24 +199,24 @@ pub fn encode_wide(string: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
#[cfg(target_pointer_width = "32")]
#[allow(non_snake_case)]
pub fn SetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize {
unsafe { w32wm::SetWindowLongW(hwnd, index, value as _) as _ }
unsafe fn SetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize {
w32wm::SetWindowLongW(hwnd, index, value as _) as _
}
#[cfg(target_pointer_width = "64")]
#[allow(non_snake_case)]
pub fn SetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize {
unsafe { w32wm::SetWindowLongPtrW(hwnd, index, value) }
unsafe fn SetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize {
w32wm::SetWindowLongPtrW(hwnd, index, value)
}
#[cfg(target_pointer_width = "32")]
#[allow(non_snake_case)]
pub fn GetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize {
unsafe { w32wm::GetWindowLongW(hwnd, index) as _ }
unsafe fn GetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize {
w32wm::GetWindowLongW(hwnd, index) as _
}
#[cfg(target_pointer_width = "64")]
#[allow(non_snake_case)]
pub fn GetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize {
unsafe { w32wm::GetWindowLongPtrW(hwnd, index) }
unsafe fn GetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize {
w32wm::GetWindowLongPtrW(hwnd, index)
}