π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use single-instance plugin on Windows
setalpc8c967c9d830
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.tomlindex 141cac04fd..ddbc3584af 100644--- a/rust/apps/ensu/src-tauri/Cargo.toml+++ b/rust/apps/ensu/src-tauri/Cargo.toml@@ -29,9 +29,9 @@ libc = "0.2.0"rustix = { version = "1.1.4", features = ["fs"] }[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_SystemInformation"] }-[target.'cfg(target_os = "linux")'.dependencies]+[target.'cfg(any(windows, target_os = "linux"))'.dependencies]tauri-plugin-single-instance = "2.4.4"[features]diff --git a/rust/apps/ensu/src-tauri/src/single_instance.rs b/rust/apps/ensu/src-tauri/src/single_instance.rsindex 4f2578020d..b4c510b84f 100644--- a/rust/apps/ensu/src-tauri/src/single_instance.rs+++ b/rust/apps/ensu/src-tauri/src/single_instance.rs@@ -1,99 +1,26 @@-use tauri::{AppHandle, Manager, plugin::TauriPlugin};+use tauri::{Manager, plugin::TauriPlugin};use crate::logging;-#[cfg(windows)]-mod windows;-pub fn plugin() -> TauriPlugin<tauri::Wry> {- #[cfg(target_os = "linux")]- {- tauri_plugin_single_instance::init(|app, _, _| focus_main_window(app))- }- #[cfg(windows)]- {- tauri::plugin::Builder::new("single-instance")- .setup(|app, _| {- match windows::Instance::acquire(&app.config().identifier)? {- Some(instance) => {- app.manage(instance);- }- None => {- app.cleanup_before_exit();- std::process::exit(0);- }- }- Ok(())- })- .on_event(|app, event| {- let instance = app.state::<windows::Instance>();- match event {- tauri::RunEvent::Ready => {- let handle = app.clone();- let result = instance- .listen(move || {- let app = handle.clone();- if let Err(error) = handle.run_on_main_thread(move || {- if let Err(error) = app- .state::<windows::Instance>()- .activate(|| focus_main_window(&app))- {- logging::log(- "App",- format!(- "failed to acknowledge activation error={error}"- ),- );- app.exit(1);- }- }) {- logging::log(- "App",- format!("failed to dispatch activation error={error}"),- );- }- })- .and_then(|()| instance.activate(|| {}));- if let Err(error) = result {- logging::log(- "App",- format!("failed to listen for activation error={error}"),- );- app.exit(1);- }- }- tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit => {- instance.mark_exiting()- }- tauri::RunEvent::WindowEvent {- label,- event: tauri::WindowEvent::CloseRequested { .. } | tauri::WindowEvent::Destroyed,- ..- } if label == "main" => instance.mark_exiting(),- _ => {}+ tauri_plugin_single_instance::init(|app, _, _| {+ logging::log(+ "App",+ "additional launch received; focusing existing window",+ );+ if let Some(window) = app.get_webview_window("main") {+ for (operation, result) in [+ ("show", window.show()),+ ("restore", window.unminimize()),+ ("focus", window.set_focus()),+ ] {+ if let Err(error) = result {+ logging::log(+ "App",+ format!("failed to {operation} existing window error={error}"),+ );}- })- .build()- }-}--fn focus_main_window(app: &AppHandle) {- logging::log(- "App",- "additional launch received; focusing existing window",- );- if let Some(window) = app.get_webview_window("main") {- for (operation, result) in [- ("show", window.show()),- ("restore", window.unminimize()),- ("focus", window.set_focus()),- ] {- if let Err(error) = result {- logging::log(- "App",- format!("failed to {operation} existing window error={error}"),- );}}- }+ })}diff --git a/rust/apps/ensu/src-tauri/src/single_instance/windows.rs b/rust/apps/ensu/src-tauri/src/single_instance/windows.rsdeleted file mode 100644index 3a6181059c..0000000000--- a/rust/apps/ensu/src-tauri/src/single_instance/windows.rs+++ /dev/null@@ -1,170 +0,0 @@-use std::io;-use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};-use std::sync::Arc;-use std::sync::atomic::{AtomicBool, Ordering};--use windows_sys::Win32::Foundation::{- HANDLE, LocalFree, WAIT_ABANDONED_0, WAIT_OBJECT_0, WAIT_TIMEOUT,-};-use windows_sys::Win32::Security::Authorization::{- ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,-};-use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;-use windows_sys::Win32::System::Threading::{- CREATE_EVENT_MANUAL_RESET, CreateEventExW, CreateMutexExW, EVENT_MODIFY_STATE, INFINITE,- ResetEvent, SYNCHRONIZATION_SYNCHRONIZE, SetEvent, WaitForMultipleObjects, WaitForSingleObject,-};--pub(super) struct Instance {- _ownership: OwnedHandle,- activation: Arc<OwnedHandle>,- acknowledged: OwnedHandle,- exiting: AtomicBool,-}--impl Instance {- #[expect(- unsafe_code,- reason = "Acquire Win32 instance ownership or await activation"- )]- pub(super) fn acquire(identifier: &str) -> io::Result<Option<Self>> {- let ownership = named_handle(- &format!("Local\\{identifier}.instance"),- |attrs, name| unsafe { CreateMutexExW(attrs, name, 0, SYNCHRONIZATION_SYNCHRONIZE) },- )?;- let activation = named_handle(- &format!("Local\\{identifier}.activation"),- |attrs, name| unsafe {- CreateEventExW(- attrs,- name,- 0,- SYNCHRONIZATION_SYNCHRONIZE | EVENT_MODIFY_STATE,- )- },- )?;- let acknowledged = named_handle(- &format!("Local\\{identifier}.activated"),- |attrs, name| unsafe {- CreateEventExW(- attrs,- name,- CREATE_EVENT_MANUAL_RESET,- SYNCHRONIZATION_SYNCHRONIZE | EVENT_MODIFY_STATE,- )- },- )?;- match unsafe { WaitForSingleObject(ownership.as_raw_handle(), 0) } {- WAIT_OBJECT_0 | WAIT_ABANDONED_0 => {}- WAIT_TIMEOUT => {- if unsafe { ResetEvent(acknowledged.as_raw_handle()) } == 0- || unsafe { SetEvent(activation.as_raw_handle()) } == 0- {- return Err(io::Error::last_os_error());- }- let handles = [ownership.as_raw_handle(), acknowledged.as_raw_handle()];- match unsafe { WaitForMultipleObjects(2, handles.as_ptr(), 0, INFINITE) } {- WAIT_OBJECT_0 | WAIT_ABANDONED_0 => {}- result if result == WAIT_OBJECT_0 + 1 => return Ok(None),- _ => return Err(io::Error::last_os_error()),- }- }- _ => return Err(io::Error::last_os_error()),- }- if unsafe { ResetEvent(acknowledged.as_raw_handle()) } == 0 {- return Err(io::Error::last_os_error());- }- Ok(Some(Self {- _ownership: ownership,- activation: Arc::new(activation),- acknowledged,- exiting: AtomicBool::new(false),- }))- }-- pub(super) fn mark_exiting(&self) {- self.exiting.store(true, Ordering::Relaxed);- }-- #[expect(- unsafe_code,- reason = "Acknowledge activation only while the primary is running"- )]- pub(super) fn activate(&self, on_activation: impl FnOnce()) -> io::Result<()> {- if !self.exiting.load(Ordering::Relaxed) {- on_activation();- if unsafe { SetEvent(self.acknowledged.as_raw_handle()) } == 0 {- return Err(io::Error::last_os_error());- }- }- Ok(())- }-- pub(super) fn listen(&self, on_activation: impl Fn() + Send + 'static) -> io::Result<()> {- let activation = Arc::clone(&self.activation);- std::thread::Builder::new()- .name("ensu-activation".into())- .spawn(move || {- loop {- match wait_for_activation(&activation) {- Ok(()) => on_activation(),- Err(error) => {- crate::logging::log(- "App",- format!("activation listener failed error={error}"),- );- break;- }- }- }- })?;- Ok(())- }-}--#[expect(- unsafe_code,- reason = "Create a medium-integrity Win32 object with the token's default ACL"-)]-fn named_handle(- name: &str,- create: impl FnOnce(&SECURITY_ATTRIBUTES, *const u16) -> HANDLE,-) -> io::Result<OwnedHandle> {- let mut descriptor = std::ptr::null_mut();- if unsafe {- ConvertStringSecurityDescriptorToSecurityDescriptorW(- windows_sys::core::w!("S:(ML;;NW;;;ME)"),- SDDL_REVISION_1,- &mut descriptor,- std::ptr::null_mut(),- )- } == 0- {- return Err(io::Error::last_os_error());- }- let attributes = SECURITY_ATTRIBUTES {- nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,- lpSecurityDescriptor: descriptor,- bInheritHandle: 0,- };- let name = name.encode_utf16().chain(Some(0)).collect::<Vec<_>>();- let handle = create(&attributes, name.as_ptr());- let result = if handle.is_null() {- Err(io::Error::last_os_error())- } else {- Ok(unsafe { OwnedHandle::from_raw_handle(handle) })- };- unsafe { LocalFree(descriptor) };- result-}--#[expect(- unsafe_code,- reason = "Wait on the activation event while its handle remains owned"-)]-fn wait_for_activation(activation: &OwnedHandle) -> io::Result<()> {- match unsafe { WaitForSingleObject(activation.as_raw_handle(), INFINITE) } {- WAIT_OBJECT_0 => Ok(()),- _ => Err(io::Error::last_os_error()),- }-}