File size: 5,341 Bytes
2d8be8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#[cfg(feature = "semver")]
use crate::semver_compat::semver_compat_string;

use crate::SingleInstanceCallback;
use tauri::{
    plugin::{self, TauriPlugin},
    AppHandle, Config, Manager, RunEvent, Runtime,
};
use zbus::{
    blocking::{connection::Builder, Connection},
    interface,
};

struct ConnectionHandle(Connection);

struct SingleInstanceDBus<R: Runtime> {
    callback: Box<SingleInstanceCallback<R>>,
    app_handle: AppHandle<R>,
}

#[interface(name = "org.SingleInstance.DBus")]
impl<R: Runtime> SingleInstanceDBus<R> {
    fn execute_callback(&mut self, argv: Vec<String>, cwd: String) {
        (self.callback)(&self.app_handle, argv, cwd);
    }
}

#[cfg(feature = "semver")]
fn dbus_id(config: &Config, version: semver::Version) -> (String, bool) {
    let mut override_id = crate::OVERRIDE_DBUS_ID.try_lock();
    while override_id.is_err() {
        override_id = crate::OVERRIDE_DBUS_ID.try_lock();
    }
    let override_id = override_id.unwrap();
    if let Some(ovr_id) = override_id.as_ref() {
        return (ovr_id.to_owned(), true);
    }
    let mut id = config.identifier.replace(['.', '-'], "_");
    id.push('_');
    id.push_str(semver_compat_string(version).as_str());
    (id, false)
}

// Return a bool in order to indicate that the DBUS ID was set at runtime
#[cfg(not(feature = "semver"))]
fn dbus_id(config: &Config) -> (String, bool) {
    let mut override_id = crate::OVERRIDE_DBUS_ID.try_lock();
    while override_id.is_err() {
        override_id = crate::OVERRIDE_DBUS_ID.try_lock();
    }
    let override_id = override_id.unwrap();
    if let Some(ovr_id) = override_id.as_ref() {
        return (ovr_id.to_owned(), true);
    }

    // Check whether a custom DBUS_ID is present at compile time.
    let custom_id = std::option_env!("DBUS_ID");
    match custom_id {
        Some(id) => (id.to_string(), false),
        None => (config.identifier.clone(), false),
    }
}

fn dbus_path(config: &Config) -> String {
    // Check whether a custom DBUS_ID is present at compile time.
    let custom_id = std::option_env!("DBUS_ID");
    match custom_id {
        Some(id) => id.to_string().replace(['.', '-'], "_"),
        None => config.identifier.replace(['.', '-'], "_"),
    }
}

pub fn init<R: Runtime>(f: Box<SingleInstanceCallback<R>>) -> TauriPlugin<R> {
    plugin::Builder::new("single-instance")
        .setup(|app, _api| {
            #[cfg(feature = "semver")]
            let id = dbus_id(app.config(), app.package_info().version.clone());
            #[cfg(not(feature = "semver"))]
            let (id, is_id_custom) = dbus_id(app.config());

            let single_instance_dbus = SingleInstanceDBus {
                callback: f,
                app_handle: app.clone(),
            };

            let path = dbus_path(app.config());
            let dbus_path = format!("/{path}/SingleInstance");
            let dbus_name = if is_id_custom {
                id
            } else {
                format!("{id}.SingleInstance")
            };

            match Builder::session()
                .unwrap()
                .name(dbus_name.as_str())
                .unwrap()
                .replace_existing_names(false)
                .allow_name_replacements(false)
                .serve_at(dbus_path.as_str(), single_instance_dbus)
                .unwrap()
                .build()
            {
                Ok(connection) => {
                    app.manage(ConnectionHandle(connection));
                }
                Err(zbus::Error::NameTaken) => {
                    if let Ok(connection) = Connection::session() {
                        let _ = 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(),
                            ),
                        );
                    }
                    app.cleanup_before_exit();
                    std::process::exit(0);
                }
                _ => {}
            }

            Ok(())
        })
        .on_event(|app, event| {
            if let RunEvent::Exit = event {
                destroy(app);
            }
        })
        .build()
}

pub fn destroy<R: Runtime, M: Manager<R>>(manager: &M) {
    if let Some(connection) = manager.try_state::<ConnectionHandle>() {
        #[cfg(feature = "semver")]
        let id = dbus_id(
            manager.config(),
            manager.app_handle().package_info().version.clone(),
        );
        #[cfg(not(feature = "semver"))]
        let (id, is_id_custom) = dbus_id(manager.config());

        let dbus_name = if is_id_custom {
            id.clone()
        } else {
            format!("{id}.SingleInstance",)
        };
        let _ = connection.0.release_name(dbus_name);
    }
}