-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtray.rs
More file actions
513 lines (469 loc) · 17.6 KB
/
Copy pathtray.rs
File metadata and controls
513 lines (469 loc) · 17.6 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! Windows system-tray icon. Hidden message-only window receives clicks
//! on the tray icon, pops a context menu, and signals shutdown back to
//! the tokio runtime via a oneshot when the user picks Quit.
//!
//! Runs on its own OS thread (Windows GUI requires a message loop on the
//! thread that created the window), so it stays out of tokio's
//! current-thread runtime entirely.
//!
//! Why we have it: with `windows_subsystem = "windows"` there is no
//! console for the user to close, and we still need an exit affordance
//! that doesn't require Task Manager.
//!
//! The menu is rebuilt every time the user clicks the icon, so the
//! status row and conditional items reflect *live* state (read from
//! the controller). Actions like "Cut delay" call straight into the
//! controller's sync methods - they're atomics-only, no runtime needed.
#![cfg(windows)]
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::ptr;
use std::sync::{Arc, Mutex};
use tokio::sync::watch;
use crate::config::Settings;
use crate::controller::Controller;
use windows_sys::Win32::Foundation::{GlobalFree, HANDLE, HWND, LPARAM, LRESULT, POINT, WPARAM};
use windows_sys::Win32::System::DataExchange::{
CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData,
};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::System::Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE};
use windows_sys::Win32::System::Ole::CF_UNICODETEXT;
use windows_sys::Win32::UI::Shell::{
Shell_NotifyIconW, NIF_ICON, NIF_MESSAGE, NIF_TIP, NIM_ADD, NIM_DELETE, NOTIFYICONDATAW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
AppendMenuW, CreateIconFromResourceEx, CreatePopupMenu, CreateWindowExW, DefWindowProcW,
DestroyMenu, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics,
GetWindowLongPtrW, LoadIconW, LookupIconIdFromDirectoryEx, PostMessageW, PostQuitMessage,
RegisterClassW, SetForegroundWindow, SetWindowLongPtrW, TrackPopupMenu, TranslateMessage,
GWLP_USERDATA, HMENU, IDI_APPLICATION, LR_DEFAULTCOLOR, MF_DISABLED, MF_GRAYED, MF_SEPARATOR,
MF_STRING, MSG, SM_CXSMICON, SM_CYSMICON, TPM_BOTTOMALIGN, TPM_LEFTALIGN, TPM_RIGHTBUTTON,
WM_APP, WM_COMMAND, WM_DESTROY, WM_LBUTTONUP, WM_RBUTTONUP, WNDCLASSW,
};
const TRAY_MSG: u32 = WM_APP + 1;
// Menu item IDs. Kept above 0x100 so they can't collide with system IDs.
const ID_OPEN_DASH: usize = 0x101;
const ID_OPEN_DOCK: usize = 0x102;
const ID_CUT_DELAY: usize = 0x103;
const ID_COPY_URL: usize = 0x104;
const ID_LAUNCH_EB: usize = 0x105;
const ID_QUIT: usize = 0x1FF;
/// The icon bytes are generated by build.rs (cyan rounded square + white
/// pause bars at 16/32/48 px). We embed the whole multi-resolution ICO
/// and let `LookupIconIdFromDirectoryEx` pick the right size at runtime.
static ICON_DATA: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/icon.ico"));
/// Per-tray-window state, parked behind GWLP_USERDATA on the hidden
/// window so the WNDPROC can find it on every message.
struct TrayState {
web_url: String,
dock_url: String,
ctrl: Arc<Controller>,
settings: watch::Receiver<Settings>,
/// `Mutex<Option<…>>` so the WNDPROC can `take()` the sender on the
/// Quit click and `send(())` once. (`oneshot::Sender::send` consumes
/// `self`, hence the `take` shape.) Previous design used Notify which
/// was a no-op if no receiver was awaiting at that moment; oneshot
/// has no such race.
quit: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
}
/// Spawn the tray on its own OS thread. Returns immediately; the thread
/// runs the message loop until the user picks Quit (or the process dies).
pub fn spawn(
settings: watch::Receiver<Settings>,
ctrl: Arc<Controller>,
quit: tokio::sync::oneshot::Sender<()>,
) {
let s = settings.borrow().clone();
let web_url = format!("http://127.0.0.1:{}/", s.web_port);
let dock_url = format!("http://127.0.0.1:{}/dock", s.web_port);
std::thread::Builder::new()
.name("instantclone-tray".into())
.spawn(move || {
if let Err(e) = run(web_url, dock_url, ctrl, settings, quit) {
eprintln!("[tray] init failed: {e}");
}
})
.ok();
}
fn run(
web_url: String,
dock_url: String,
ctrl: Arc<Controller>,
settings: watch::Receiver<Settings>,
quit: tokio::sync::oneshot::Sender<()>,
) -> Result<(), String> {
unsafe {
let h_instance = GetModuleHandleW(ptr::null());
let class_name = wide("InstantCloneTrayClass");
let wc = WNDCLASSW {
style: 0,
lpfnWndProc: Some(wnd_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: h_instance as _,
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
};
if RegisterClassW(&wc) == 0 {
return Err("RegisterClassW failed".into());
}
let title = wide("InstantClone");
// HWND_MESSAGE = -3 cast to ptr - message-only window, never visible.
let parent: HWND = -3isize as HWND;
let hwnd = CreateWindowExW(
0,
class_name.as_ptr(),
title.as_ptr(),
0,
0,
0,
0,
0,
parent,
ptr::null_mut(),
h_instance as _,
ptr::null(),
);
if hwnd.is_null() {
return Err("CreateWindowExW failed".into());
}
// Park state on the window so the WNDPROC can find it.
let state = Box::new(TrayState {
web_url,
dock_url,
ctrl,
settings,
quit: Mutex::new(Some(quit)),
});
SetWindowLongPtrW(hwnd, GWLP_USERDATA, Box::into_raw(state) as isize);
// Load the embedded ICO. If anything goes wrong (corrupted bytes,
// unsupported feature flag on this Windows version) fall back to
// the generic application icon so the tray still appears.
let h_icon =
load_embedded_icon().unwrap_or_else(|| LoadIconW(ptr::null_mut(), IDI_APPLICATION));
let mut nid: NOTIFYICONDATAW = std::mem::zeroed();
nid.cbSize = std::mem::size_of::<NOTIFYICONDATAW>() as u32;
nid.hWnd = hwnd;
nid.uID = 1;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = TRAY_MSG;
nid.hIcon = h_icon;
write_tip(&mut nid.szTip, "InstantClone - click for menu");
if Shell_NotifyIconW(NIM_ADD, &nid) == 0 {
return Err("Shell_NotifyIconW(NIM_ADD) failed".into());
}
// Message loop until WM_QUIT (PostQuitMessage from the Quit handler
// or DefWindowProc on WM_DESTROY).
let mut msg: MSG = std::mem::zeroed();
while GetMessageW(&mut msg, ptr::null_mut(), 0, 0) > 0 {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
Shell_NotifyIconW(NIM_DELETE, &nid);
// Reclaim and drop the TrayState.
let raw = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut TrayState;
if !raw.is_null() {
drop(Box::from_raw(raw));
}
DestroyWindow(hwnd);
}
Ok(())
}
/// Decode the embedded ICO into an HICON at the system's small-icon size.
/// Returns `None` on any FFI failure - caller falls back to the stock icon.
unsafe fn load_embedded_icon() -> Option<windows_sys::Win32::UI::WindowsAndMessaging::HICON> {
let cx = GetSystemMetrics(SM_CXSMICON);
let cy = GetSystemMetrics(SM_CYSMICON);
// `1` = looking for an icon (not a cursor).
let offset = LookupIconIdFromDirectoryEx(ICON_DATA.as_ptr(), 1, cx, cy, LR_DEFAULTCOLOR);
if offset <= 0 {
return None;
}
let off = offset as usize;
if off >= ICON_DATA.len() {
return None;
}
let h = CreateIconFromResourceEx(
ICON_DATA.as_ptr().add(off),
(ICON_DATA.len() - off) as u32,
1, // fIcon = true
0x00030000, // version
cx,
cy,
LR_DEFAULTCOLOR,
);
if h.is_null() {
None
} else {
Some(h)
}
}
unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
match msg {
// Tray icon: left- or right-click → show the menu near the cursor.
TRAY_MSG => {
let ev = lp as u32;
if ev == WM_LBUTTONUP || ev == WM_RBUTTONUP {
show_menu(hwnd);
}
0
}
// Menu selection.
WM_COMMAND => {
let id = wp & 0xFFFF;
let state_ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut TrayState;
if state_ptr.is_null() {
return 0;
}
let state = &*state_ptr;
match id {
ID_OPEN_DASH => {
let _ = open_url(&state.web_url);
}
ID_OPEN_DOCK => {
let _ = open_url(&state.dock_url);
}
ID_CUT_DELAY => {
// Direct sync call - Controller methods are atomic stores,
// no runtime needed.
state.ctrl.stop_delay();
}
ID_COPY_URL => {
let url = obs_rtmp_url(&state.settings.borrow());
let _ = set_clipboard_text(hwnd, &url);
}
ID_LAUNCH_EB => {
// One-click VOD + EB from the tray: write OBS's
// VOD-track flag, then launch OBS with --config-url.
// Both are synchronous and degrade quietly (missing
// OBS just logs) so a click never wedges the tray.
let web_port = state.settings.borrow().web_port;
let _ = crate::obs_register::set_vod_audio_flag(true);
match crate::obs_register::launch_obs_with_eb_config(web_port) {
Ok(exe) => state.ctrl.log(format!(
"[tray] launched OBS for VOD + EB ({})",
exe.display()
)),
Err(e) => state.ctrl.log(format!("[tray] OBS launch failed: {e}")),
}
}
ID_QUIT => {
// Take the sender so a second click can't double-send.
// Ignore the Err: it just means the main task already shut
// down (race with ctrl-c) and dropped the receiver.
if let Some(tx) = state.quit.lock().unwrap().take() {
let _ = tx.send(());
}
PostQuitMessage(0);
}
_ => {}
}
0
}
WM_DESTROY => {
PostQuitMessage(0);
0
}
_ => DefWindowProcW(hwnd, msg, wp, lp),
}
}
unsafe fn show_menu(hwnd: HWND) {
let state_ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut TrayState;
if state_ptr.is_null() {
return;
}
let state = &*state_ptr;
let menu: HMENU = CreatePopupMenu();
if menu.is_null() {
return;
}
// Top: live status header. Disabled item, no action - just a glance.
let status = wide(&status_label(&state.ctrl));
AppendMenuW(
menu,
MF_STRING | MF_DISABLED | MF_GRAYED,
0,
status.as_ptr(),
);
AppendMenuW(menu, MF_SEPARATOR, 0, ptr::null());
// "Cut delay" only when the delay is actually live. Otherwise greyed.
let cut_label = wide("Cut delay");
let cut_flags = if state.ctrl.phase() == "active" {
MF_STRING
} else {
MF_STRING | MF_DISABLED | MF_GRAYED
};
AppendMenuW(menu, cut_flags, ID_CUT_DELAY, cut_label.as_ptr());
AppendMenuW(menu, MF_SEPARATOR, 0, ptr::null());
let open = wide("Open dashboard");
let dock = wide("Open OBS dock");
let copy = wide("Copy RTMP URL");
AppendMenuW(menu, MF_STRING, ID_OPEN_DASH, open.as_ptr());
AppendMenuW(menu, MF_STRING, ID_OPEN_DOCK, dock.as_ptr());
AppendMenuW(menu, MF_STRING, ID_COPY_URL, copy.as_ptr());
AppendMenuW(menu, MF_SEPARATOR, 0, ptr::null());
let launch_eb = wide("Launch OBS (VOD + EB)");
AppendMenuW(menu, MF_STRING, ID_LAUNCH_EB, launch_eb.as_ptr());
AppendMenuW(menu, MF_SEPARATOR, 0, ptr::null());
let quit = wide("Quit InstantClone");
AppendMenuW(menu, MF_STRING, ID_QUIT, quit.as_ptr());
let mut pt = POINT { x: 0, y: 0 };
GetCursorPos(&mut pt);
// SetForegroundWindow is required for TrackPopupMenu to behave -
// without it the menu can vanish on first outside click.
SetForegroundWindow(hwnd);
TrackPopupMenu(
menu,
TPM_BOTTOMALIGN | TPM_LEFTALIGN | TPM_RIGHTBUTTON,
pt.x,
pt.y,
0,
hwnd,
ptr::null(),
);
// Post a dummy message so the menu actually closes on outside-click -
// standard Win32 dance.
PostMessageW(hwnd, 0, 0, 0);
DestroyMenu(menu);
}
/// One-line summary of the controller's current state. Read on every
/// menu open so it's always fresh.
fn status_label(ctrl: &Controller) -> String {
let phase = ctrl.phase();
match phase {
"active" => {
let s = (ctrl.current_delay_ms() + 500) / 1000;
format!("Status: ACTIVE - {s}s delay")
}
"ready" => {
let s = (ctrl.armed_delay_ms() + 500) / 1000;
format!("Status: ARMED - {s}s ready to activate")
}
"preparing" => {
let armed = ctrl.armed_delay_ms().max(1) as f32;
let fill = ctrl.buffer_fill_ms() as f32;
let pct = ((fill / armed) * 100.0).min(99.0) as u32;
format!("Status: BUFFERING - {pct}%")
}
_ => {
if ctrl.ingest_alive() {
"Status: LIVE (no delay)".into()
} else {
"Status: idle (no source)".into()
}
}
}
}
/// Reconstruct the same rtmp URL the dashboard shows in the OBS tab.
fn obs_rtmp_url(s: &Settings) -> String {
let host = if s.ingest_bind_all {
"0.0.0.0"
} else {
"127.0.0.1"
};
format!("rtmp://{}:{}/live", host, s.ingest_port)
}
/// RAII wrapper around an HGLOBAL. Frees on Drop unless ownership is
/// transferred (call `.release()` after a successful `SetClipboardData`
/// since the system takes over the handle at that point).
///
/// Previous version of `set_clipboard_text` had three early-return paths
/// between `GlobalAlloc` and `SetClipboardData` that all leaked the
/// HGLOBAL. This struct closes that hole structurally.
struct HglobalGuard(HANDLE);
impl HglobalGuard {
/// Take the HGLOBAL out of the guard. Caller is now responsible for
/// it (typically because they just handed it to the OS).
fn release(mut self) -> HANDLE {
let h = self.0;
self.0 = std::ptr::null_mut();
h
}
}
impl Drop for HglobalGuard {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
GlobalFree(self.0);
}
}
}
}
/// RAII wrapper around the Windows clipboard: ensures `CloseClipboard`
/// runs on every exit path. Constructed via `open(hwnd)` which returns
/// `None` if `OpenClipboard` fails.
struct ClipboardGuard;
impl ClipboardGuard {
unsafe fn open(hwnd: HWND) -> Option<Self> {
if OpenClipboard(hwnd) == 0 {
None
} else {
Some(Self)
}
}
}
impl Drop for ClipboardGuard {
fn drop(&mut self) {
unsafe {
CloseClipboard();
}
}
}
/// Put UTF-16 text on the Windows clipboard. Best-effort: failures are
/// silent (clipboard may be locked by another app). The RAII guards
/// above guarantee no HGLOBAL leak on any error path.
unsafe fn set_clipboard_text(hwnd: HWND, text: &str) -> Result<(), ()> {
let _clip = ClipboardGuard::open(hwnd).ok_or(())?;
if EmptyClipboard() == 0 {
return Err(());
}
let utf16: Vec<u16> = text.encode_utf16().chain(std::iter::once(0)).collect();
let bytes = utf16.len() * 2;
let h_mem = HglobalGuard(GlobalAlloc(GMEM_MOVEABLE, bytes));
if h_mem.0.is_null() {
return Err(());
}
// Copy in. If GlobalLock fails (rare), h_mem's Drop runs GlobalFree.
let dst = GlobalLock(h_mem.0) as *mut u16;
if dst.is_null() {
return Err(());
}
ptr::copy_nonoverlapping(utf16.as_ptr(), dst, utf16.len());
GlobalUnlock(h_mem.0);
// SetClipboardData transfers ownership ONLY on success. If it
// returns null we still own the HGLOBAL, so let h_mem's Drop free it.
if SetClipboardData(CF_UNICODETEXT as u32, h_mem.0).is_null() {
return Err(());
}
// System now owns the HGLOBAL - release the guard so Drop is a no-op.
let _ = h_mem.release();
Ok(())
}
fn open_url(url: &str) -> std::io::Result<std::process::Child> {
std::process::Command::new("cmd")
.args(["/c", "start", "", url])
.spawn()
}
fn wide(s: &str) -> Vec<u16> {
OsStr::new(s)
.encode_wide()
.chain(std::iter::once(0))
.collect()
}
/// Copy a string into the fixed-cap `szTip` array, NUL-terminated, with
/// the truncation-at-127-chars cap NOTIFYICONDATAW requires. Splitting
/// a surrogate pair near the boundary is acceptable: it would render as
/// a tofu glyph in the tooltip, not crash.
fn write_tip(dst: &mut [u16; 128], s: &str) {
let mut v: Vec<u16> = OsStr::new(s).encode_wide().collect();
if v.len() > 127 {
v.truncate(127);
}
v.push(0);
let n = v.len().min(dst.len());
dst[..n].copy_from_slice(&v[..n]);
}