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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::{
collections::HashMap,
ffi::c_void,
path::PathBuf,
sync::{Mutex, OnceLock},
};
use tauri::{LogicalPosition, LogicalSize, Manager, Runtime, State};
type MessageHandler = unsafe extern "C" fn(*mut c_void);
type MessageHandlerFn = dyn Fn(&mut Message) + Send + Sync;
static MESSAGE_HANDLER: OnceLock<Box<MessageHandlerFn>> = OnceLock::new();
#[tauri::command]
async fn resolve<R: Runtime>(
_app: tauri::AppHandle<R>,
automation: State<'_, Automation>,
id: String,
result: Option<serde_json::Value>,
) -> Result<(), ()> {
automation
.pending_scripts
.lock()
.expect("Failed to lock pending scripts for resolve")
.remove(&id)
.expect("Failed to remove from pending scripts")
.send(result.unwrap_or_default())
.expect("Failed to send result in resolve");
Ok(())
}
// repr(C) is load-bearing, not cosmetic: this type is never built here — it is
// reinterpreted from a pointer handed over by the automation library, which is
// a separate compilation behind dlopen (see handle_message). repr(Rust)
// guarantees nothing about field order or discriminant encoding across that
// boundary, and rustc does reorder these fields, so a divergent choice
// silently swaps `kind` and `response_tx` and every message is misread.
// Must stay in sync with tauri-plugin-automation-impl — including the repr.
#[allow(dead_code)]
#[derive(Debug)]
#[repr(C)]
enum MessageKind {
EvalScript {
id: String,
label: Option<String>,
script: String,
},
GetWindowHandle,
GetWindowHandles,
CloseWindow {
label: String,
},
GetWindowRect {
label: Option<String>,
},
GetWindowInsets {
label: Option<String>,
},
SetWindowRect {
label: Option<String>,
x: Option<i32>,
y: Option<i32>,
width: Option<i32>,
height: Option<i32>,
},
FullscreenWindow {
label: Option<String>,
},
MinimizeWindow {
label: Option<String>,
},
MaximizeWindow {
label: Option<String>,
},
}
#[repr(C)]
struct Message {
kind: MessageKind,
response_tx: Option<tokio::sync::oneshot::Sender<serde_json::Value>>,
}
struct Automation {
pending_scripts: Mutex<HashMap<String, tokio::sync::oneshot::Sender<serde_json::Value>>>,
}
#[allow(dead_code)]
struct AutomationLib(libloading::Library);
pub fn init<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {
let (webview_created_tx, webview_created_rx) = tokio::sync::broadcast::channel(16);
tauri::plugin::Builder::new("automation")
.invoke_handler(tauri::generate_handler![resolve])
.js_init_script(include_str!("init.js").to_string())
.on_webview_ready(move |webview| {
webview_created_tx
.send(
webview
.get_webview_window(webview.label())
.unwrap_or_else(|| {
panic!("Failed to get webview window for label {}", webview.label())
}),
)
// This could fail if there's no task on the receiving end,
// we can ignore safely.
.unwrap_or_default();
})
.setup(|app, _api| {
app.manage(Automation {
pending_scripts: Mutex::new(HashMap::new()),
});
app.add_capability(
tauri::ipc::CapabilityBuilder::new("automation")
.local(true)
.window("*")
.remote("http://*".into())
.remote("https://*".into())
.permission("automation:default"),
)?;
unsafe {
if let Some(lib_path) =
std::env::var_os("AUTOMATION_LIBRARY_PATH").map(PathBuf::from)
{
let lib = libloading::Library::new(&lib_path).expect("Could not load library");
let start: unsafe extern "C" fn(MessageHandler) = *lib
.get::<unsafe extern "C" fn(MessageHandler)>(b"tauri_plugin_automation_start")
.expect("Failed to get the automation start function from automation lib");
// keep the lib around - dropping it unloads it (doesn't work on Windows)
app.manage(AutomationLib(lib));
let app_ = app.clone();
MESSAGE_HANDLER
.set(Box::new(move |message| match &message.kind {
MessageKind::EvalScript { id, label, script } => {
let automation = app_.state::<Automation>();
automation
.pending_scripts
.lock()
.expect("Failed to lock pending scripts for eval insert")
.insert(
id.clone(),
message
.response_tx
.take()
.expect("Failed to take response_tx for EvalScript"),
);
let script = script.clone();
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
let _ = window.eval(&script);
},
);
}
MessageKind::GetWindowHandle => {
message
.response_tx
.take()
.expect("Failed to take response_tx for GetWindowHandle")
.send(if app_.get_webview_window("main").is_some() {
"main".to_string().into()
} else {
app_.webview_windows()
.into_values()
.next()
.map(|w| w.label().into())
.unwrap_or_default()
})
.expect("Failed to send GetWindowHandle response");
}
MessageKind::GetWindowHandles => {
message
.response_tx
.take()
.expect("Failed to take response_tx for GetWindowHandles")
.send(
app_.webview_windows()
.into_values()
.map(|w| w.label().to_string())
.collect(),
)
.expect("Failed to send GetWindowHandles response");
}
MessageKind::CloseWindow { label } => {
let window = app_.get_webview_window(label);
if let Some(window) = &window {
window.close().expect("Failed to close the window");
}
message
.response_tx
.take()
.expect("Failed to take response_tx for CloseWindow")
.send(window.is_some().into())
.expect("Failed to send CloseWindow response");
}
MessageKind::GetWindowRect { label } => {
let response_tx = message
.response_tx
.take()
.expect("Failed to take response_tx for GetWindowRect");
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
let scale_factor = window
.scale_factor()
.expect("Failed to get window scale factor");
let size = window
.inner_size()
.expect("Failed to get window inner size")
.to_logical::<i32>(scale_factor);
let position = window
.inner_position()
.expect("Failed to get window inner position")
.to_logical::<i32>(scale_factor);
response_tx
.send(serde_json::json!({
"x": position.x,
"y": position.y,
"width": size.width,
"height": size.height,
}))
.expect("Failed to send GetWindowRect response");
},
);
}
MessageKind::GetWindowInsets { label } => {
let response_tx = message
.response_tx
.take()
.expect("Failed to take response_tx for GetWindowInsets");
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
#[cfg(target_os = "macos")]
{
let ns_view: &objc2_app_kit::NSView = &*window.ns_view().unwrap().cast();
let insets = ns_view.safeAreaInsets();
response_tx
.send(serde_json::json!({
"x": insets.left as i32,
"y": insets.top as i32,
"bottom": insets.bottom as i32,
"top": insets.top as i32,
}))
.expect("Failed to send GetWindowInsets response");
}
#[cfg(not(target_os = "macos"))]
{
response_tx
.send(serde_json::json!({
"value": {
"error": "unknown error",
"message": "GetWindowInsets is only supported on macOS"
}
}))
.expect("Failed to send GetWindowInsets error response");
}
},
);
}
MessageKind::SetWindowRect {
label,
x,
y,
width,
height,
} => {
let response_tx = message
.response_tx
.take()
.expect("Failed to take response_tx for SetWindowRect");
let x = *x;
let y = *y;
let width = *width;
let height = *height;
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
if let (Some(x), Some(y)) = (x, y) {
window
.set_position(LogicalPosition::new(x, y))
.expect("Failed to set window position");
}
if let (Some(width), Some(height)) = (width, height) {
window
.set_size(LogicalSize::new(width, height))
.expect("Failed to set window size");
}
response_tx
.send(true.into())
.expect("Failed to send SetWindowRect response");
},
);
}
MessageKind::FullscreenWindow { label } => {
let response_tx = message
.response_tx
.take()
.expect("Failed to take response_tx for FullscreenWindow");
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
window
.set_fullscreen(true)
.expect("Failed to fullscreen the window");
response_tx
.send(true.into())
.expect("Failed to send FullscreenWindow response");
},
);
}
MessageKind::MinimizeWindow { label } => {
let response_tx = message
.response_tx
.take()
.expect("Failed to take response_tx for MinimizeWindow");
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
window.minimize().expect("Failed to minimize the window");
response_tx
.send(true.into())
.expect("Failed to send MinimizeWindow response");
},
);
}
MessageKind::MaximizeWindow { label } => {
let response_tx = message
.response_tx
.take()
.expect("Failed to take response_tx for MaximizeWindow");
with_window(
&app_,
label.as_deref(),
&webview_created_rx,
move |window| {
window.maximize().expect("Failed to maximize window");
response_tx
.send(true.into())
.expect("Failed to send MaximizeWindow response");
},
);
}
}))
.unwrap_or_else(|_| {
panic!("Failed to set message handler");
});
start(handle_message);
}
}
Ok(())
})
.build()
}
extern "C" fn handle_message(message: *mut c_void) {
let message = unsafe { &mut *(message as *mut Message) };
MESSAGE_HANDLER.get().unwrap()(message);
}
fn with_window<R: Runtime, F: FnOnce(tauri::WebviewWindow<R>) + Send + 'static>(
app: &tauri::AppHandle<R>,
label: Option<&str>,
webview_created_rx: &tokio::sync::broadcast::Receiver<tauri::WebviewWindow<R>>,
f: F,
) {
if let Some(window) = window_by_label(app, label) {
f(window);
} else {
let mut webview_created_rx = webview_created_rx.resubscribe();
tauri::async_runtime::spawn(async move {
loop {
let window = webview_created_rx.recv().await;
if let Ok(webview) = window {
f(webview);
break;
}
}
});
}
}
fn window_by_label<R: Runtime>(
app: &tauri::AppHandle<R>,
label: Option<&str>,
) -> Option<tauri::WebviewWindow<R>> {
if let Some(label) = label {
app.get_webview_window(label)
} else {
app.get_webview_window("main")
.or_else(|| app.webview_windows().into_values().next())
}
}