Skip to content

Commit a260b82

Browse files
authored
single instance (#226)
1 parent eef5849 commit a260b82

File tree

4 files changed

+39
-2
lines changed

4 files changed

+39
-2
lines changed

Cargo.lock

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ cargo-packager-resource-resolver = { version = "0.1", features = [
8888
pretty_assertions = "1"
8989
mslnk = "0.1"
9090
anyhow = "1"
91+
fslock = "0.2"
9192

9293
[workspace.dependencies.libcosmic]
9394
git = "https://github.com/pop-os/libcosmic"

ui/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ libcosmic.workspace = true
2828
constcat.workspace = true
2929
directories.workspace = true
3030
anyhow.workspace = true
31+
fslock.workspace = true
3132

3233
[target.'cfg(target_os = "windows")'.dependencies]
3334
mslnk.workspace = true

ui/src/lib.rs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{collections::HashMap, time::Duration};
1+
use std::{collections::HashMap, path::PathBuf, time::Duration};
22

33
use data::{
44
AppState,
@@ -41,6 +41,10 @@ use crate::config_dialogs::{
4141
};
4242
use crate::udev_dialog::UdevDialogMsg;
4343

44+
use common::{APP, ORG, QUALIFIER};
45+
use directories::ProjectDirs;
46+
use fslock::LockFile;
47+
4448
#[macro_use]
4549
extern crate log;
4650

@@ -69,7 +73,27 @@ impl<H: HardwareBridge> CosmicFlags for Flags<H> {
6973
type Args = Vec<String>;
7074
}
7175

72-
pub fn run_ui<H: HardwareBridge + 'static>(app_state: AppState<H>) {
76+
pub fn run_ui<H: HardwareBridge + 'static>(mut app_state: AppState<H>) {
77+
// ensure single instance
78+
let instance_lock_path = if cfg!(debug_assertions) {
79+
let _ = std::fs::create_dir_all("temp");
80+
PathBuf::from("temp").join("app.lock")
81+
} else {
82+
let project_dirs = ProjectDirs::from(QUALIFIER, ORG, APP).unwrap();
83+
project_dirs.cache_dir().join("app.lock")
84+
};
85+
let mut app_lock = LockFile::open(&instance_lock_path).expect("Failed to open app lock file");
86+
if !app_lock.try_lock_with_pid().unwrap_or(false) {
87+
info!(
88+
"Another instance is already running. PID can be found in {:?}",
89+
instance_lock_path
90+
);
91+
if let Err(e) = app_state.bridge.shutdown() {
92+
error!("shutdown hardware: {e}");
93+
}
94+
return;
95+
}
96+
7397
utils::setup_wgpu();
7498

7599
let settings = cosmic::app::Settings::default()

0 commit comments

Comments
 (0)