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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
|
use std::{
io::Write,
os::fd::RawFd,
path::PathBuf,
process::{Command, Stdio},
};
use super::{
read_limited_reader, ClipboardCommand, ClipboardImage, ForegroundJob, ForegroundProcess,
LimitedRead, Signal,
};
pub fn raise_server_nofile_limit() {}
/// Collect the foreground terminal job for a given child PID.
pub fn foreground_job(child_pid: u32) -> Option<ForegroundJob> {
let tpgid = foreground_process_group_id(child_pid)?;
let mut processes = Vec::new();
for entry in std::fs::read_dir("/proc").ok()? {
let entry = entry.ok()?;
let file_name = entry.file_name();
let pid_str = file_name.to_str()?;
if !pid_str.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let pid: u32 = match pid_str.parse() {
Ok(pid) => pid,
Err(_) => continue,
};
let Some((pgrp, name)) = process_pgrp_and_comm(pid) else {
continue;
};
if pgrp as u32 != tpgid {
continue;
}
let argv = process_argv(pid);
processes.push(ForegroundProcess {
pid,
name,
argv0: None,
cmdline: argv.as_ref().map(|parts| parts.join(" ")),
argv,
});
}
if processes.is_empty() {
return None;
}
Some(ForegroundJob {
process_group_id: tpgid,
processes,
})
}
pub fn foreground_group_leader_job(process_group_id: u32) -> Option<ForegroundJob> {
let (pgrp, name) = process_pgrp_and_comm(process_group_id)?;
if pgrp as u32 != process_group_id {
return None;
}
let argv = process_argv(process_group_id);
Some(ForegroundJob {
process_group_id,
processes: vec![ForegroundProcess {
pid: process_group_id,
name,
argv0: None,
cmdline: argv.as_ref().map(|parts| parts.join(" ")),
argv,
}],
})
}
pub fn foreground_process_group_id(child_pid: u32) -> Option<u32> {
// /proc/<pid>/stat format: "pid (comm) state ppid pgrp session tty_nr tpgid ..."
// The (comm) field can contain spaces and parens, so we find the last ')' first.
let stat = std::fs::read_to_string(format!("/proc/{child_pid}/stat")).ok()?;
let rest = stat.get(stat.rfind(')')? + 2..)?;
let fields: Vec<&str> = rest.split_whitespace().collect();
// After (comm): state(0) ppid(1) pgrp(2) session(3) tty_nr(4) tpgid(5)
let tpgid: i32 = fields.get(5)?.parse().ok()?;
(tpgid > 0).then_some(tpgid as u32)
}
pub fn foreground_process_group_id_for_tty_fd(fd: RawFd) -> Option<u32> {
let pgid = unsafe { libc::tcgetpgrp(fd) };
(pgid > 0).then_some(pgid as u32)
}
fn process_pgrp_and_comm(pid: u32) -> Option<(i32, String)> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let close = stat.rfind(')')?;
let comm = stat.get(1 + stat.find('(')?..close)?.to_string();
let rest = stat.get(close + 2..)?;
let fields: Vec<&str> = rest.split_whitespace().collect();
let pgrp: i32 = fields.get(2)?.parse().ok()?;
Some((pgrp, comm))
}
fn process_argv(pid: u32) -> Option<Vec<String>> {
let bytes = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
if bytes.is_empty() {
return None;
}
let parts: Vec<String> = bytes
.split(|&b| b == 0)
.filter(|part| !part.is_empty())
.map(|part| String::from_utf8_lossy(part).into_owned())
.collect();
(!parts.is_empty()).then_some(parts)
}
/// Get the current working directory of a process.
/// Uses /proc/<pid>/cwd symlink.
pub fn process_cwd(pid: u32) -> Option<PathBuf> {
if pid == 0 {
return None;
}
std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}
/// Read a Herdr agent identity hint from a process environment.
pub fn process_agent_hint(pid: u32) -> Option<crate::detect::Agent> {
if pid == 0 {
return None;
}
let environ = std::fs::read(format!("/proc/{pid}/environ")).ok()?;
parse_agent_env_hint(&environ)
}
fn parse_agent_env_hint(environ: &[u8]) -> Option<crate::detect::Agent> {
for record in environ.split(|&byte| byte == 0) {
let Some(value) = record.strip_prefix(b"HERDR_AGENT=") else {
continue;
};
let value = std::str::from_utf8(value).ok()?;
return crate::detect::parse_agent_label(value);
}
None
}
pub fn session_processes(child_pid: u32) -> Vec<u32> {
let Some(session_id) = process_session_id(child_pid) else {
return Vec::new();
};
let mut pids = Vec::new();
for entry in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
let file_name = entry.file_name();
let Some(pid_str) = file_name.to_str() else {
continue;
};
if !pid_str.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let Ok(pid) = pid_str.parse::<u32>() else {
continue;
};
if process_session_id(pid) == Some(session_id) {
pids.push(pid);
}
}
pids
}
pub fn signal_processes(pids: &[u32], signal: Signal) {
let sig = match signal {
Signal::Hangup => libc::SIGHUP,
Signal::Terminate => libc::SIGTERM,
Signal::Kill => libc::SIGKILL,
};
for &pid in pids {
if pid == 0 {
continue;
}
unsafe {
libc::kill(pid as i32, sig);
}
}
}
pub fn process_exists(pid: u32) -> bool {
if pid == 0 {
return false;
}
let result = unsafe { libc::kill(pid as i32, 0) };
if result == 0 {
true
} else {
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
}
pub fn write_clipboard(bytes: &[u8]) -> bool {
for command in clipboard_commands() {
if run_clipboard_command(&command, bytes) {
return true;
}
}
false
}
pub fn read_clipboard_text() -> Option<String> {
for command in read_clipboard_text_commands() {
if let Some(text) = read_clipboard_text_with_command(&command) {
return Some(text);
}
}
None
}
pub fn open_url(url: &str) -> std::io::Result<()> {
Command::new("xdg-open")
.arg(url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
Ok(())
}
pub fn read_clipboard_image() -> Option<ClipboardImage> {
for (mime, extension) in [
("image/png", "png"),
("image/jpeg", "jpg"),
("image/jpg", "jpg"),
("image/gif", "gif"),
("image/webp", "webp"),
("image/bmp", "bmp"),
] {
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
if let Some(image) =
read_validated_clipboard_image("wl-paste", &["--type", mime], extension)
{
return Some(image);
}
}
if std::env::var_os("DISPLAY").is_some() {
if let Some(image) = read_validated_clipboard_image(
"xclip",
&["-selection", "clipboard", "-t", mime, "-o"],
extension,
) {
return Some(image);
}
}
}
None
}
fn read_validated_clipboard_image(
program: &str,
args: &[&str],
extension: &'static str,
) -> Option<ClipboardImage> {
let bytes = read_clipboard_image_with_command(program, args)?;
if !bytes_match_image_signature(extension, &bytes) {
return None;
}
Some(ClipboardImage { bytes, extension })
}
fn bytes_match_image_signature(extension: &str, bytes: &[u8]) -> bool {
match extension {
"png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n"),
"jpg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]),
"gif" => bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a"),
"webp" => bytes.len() >= 12 && bytes.starts_with(b"RIFF") && bytes[8..12] == *b"WEBP",
"bmp" => {
if bytes.len() < 26 || !bytes.starts_with(b"BM") {
return false;
}
let offset = u32::from_le_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]) as usize;
(26..=bytes.len()).contains(&offset)
}
_ => false,
}
}
/// Show a native desktop notification through libnotify's command-line helper.
pub fn show_desktop_notification(title: &str, body: Option<&str>) -> std::io::Result<bool> {
show_desktop_notification_with_command(title, body, |program| Command::new(program))
}
fn show_desktop_notification_with_command(
title: &str,
body: Option<&str>,
mut command: impl FnMut(&str) -> Command,
) -> std::io::Result<bool> {
if std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() {
return Ok(false);
}
let mut cmd = command("notify-send");
cmd.arg("--").arg(title);
if let Some(body) = body.filter(|body| !body.is_empty()) {
cmd.arg(body);
}
run_notification_command(cmd)
}
fn run_notification_command(mut command: Command) -> std::io::Result<bool> {
let status = match command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
{
Ok(status) => status,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(err) => return Err(err),
};
Ok(status.success())
}
fn read_clipboard_image_with_command(program: &str, args: &[&str]) -> Option<Vec<u8>> {
let mut command = Command::new(program);
command.args(args);
read_clipboard_image_with_spawned_command(command)
}
fn read_clipboard_image_with_spawned_command(command: Command) -> Option<Vec<u8>> {
read_clipboard_image_with_spawned_command_max(
command,
crate::protocol::MAX_CLIPBOARD_IMAGE_PAYLOAD,
)
}
fn read_clipboard_image_with_spawned_command_max(
mut command: Command,
max_bytes: usize,
) -> Option<Vec<u8>> {
let mut child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let stdout = child.stdout.take()?;
let read = match read_limited_reader(stdout, max_bytes) {
Ok(read) => read,
Err(_) => {
let _ = child.kill();
let _ = child.wait();
return None;
}
};
if read == LimitedRead::Oversized {
let _ = child.kill();
let _ = child.wait();
return None;
}
let status = child.wait().ok()?;
if !status.success() {
return None;
}
match read {
LimitedRead::Complete(bytes) => Some(bytes),
LimitedRead::Empty | LimitedRead::Oversized => None,
}
}
fn clipboard_commands() -> Vec<ClipboardCommand> {
let mut commands = Vec::new();
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
commands.push(ClipboardCommand {
program: "wl-copy",
args: &["--type", "text/plain;charset=utf-8"],
});
}
if std::env::var_os("DISPLAY").is_some() {
commands.push(ClipboardCommand {
program: "xclip",
args: &["-selection", "clipboard", "-in"],
});
commands.push(ClipboardCommand {
program: "xsel",
args: &["--clipboard", "--input"],
});
}
commands
}
fn read_clipboard_text_commands() -> Vec<ClipboardCommand> {
let mut commands = Vec::new();
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
commands.push(ClipboardCommand {
program: "wl-paste",
args: &["--type", "text/plain;charset=utf-8"],
});
commands.push(ClipboardCommand {
program: "wl-paste",
args: &["--type", "text/plain"],
});
}
if std::env::var_os("DISPLAY").is_some() {
commands.push(ClipboardCommand {
program: "xclip",
args: &["-selection", "clipboard", "-out"],
});
commands.push(ClipboardCommand {
program: "xsel",
args: &["--clipboard", "--output"],
});
}
commands
}
fn read_clipboard_text_with_command(command: &ClipboardCommand) -> Option<String> {
const MAX_CLIPBOARD_TEXT_BYTES: usize = 1024 * 1024;
let mut child = Command::new(command.program)
.args(command.args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let stdout = child.stdout.take()?;
let read = match read_limited_reader(stdout, MAX_CLIPBOARD_TEXT_BYTES) {
Ok(LimitedRead::Oversized) => {
let _ = child.kill();
let _ = child.wait();
return None;
}
Ok(read) => read,
Err(_) => {
let _ = child.kill();
let _ = child.wait();
return None;
}
};
let status = child.wait().ok()?;
if !status.success() {
return None;
}
match read {
LimitedRead::Complete(bytes) => String::from_utf8(bytes).ok(),
LimitedRead::Empty => None,
LimitedRead::Oversized => unreachable!("oversized clipboard text is handled before wait"),
}
}
fn run_clipboard_command(command: &ClipboardCommand, bytes: &[u8]) -> bool {
let mut child = match Command::new(command.program)
.args(command.args)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
Ok(child) => child,
Err(_) => return false,
};
let Some(mut stdin) = child.stdin.take() else {
let _ = child.kill();
let _ = child.wait();
return false;
};
if stdin.write_all(bytes).is_err() {
let _ = child.kill();
let _ = child.wait();
return false;
}
drop(stdin);
child.wait().map(|status| status.success()).unwrap_or(false)
}
fn process_session_id(pid: u32) -> Option<i32> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let rest = stat.get(stat.rfind(')')? + 2..)?;
let fields: Vec<&str> = rest.split_whitespace().collect();
fields.get(3)?.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Mutex, OnceLock};
fn env_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
#[test]
fn parse_agent_env_hint_accepts_known_agents() {
assert_eq!(
parse_agent_env_hint(b"PATH=/bin\0HERDR_AGENT=claude\0TERM=xterm\0"),
Some(crate::detect::Agent::Claude)
);
assert_eq!(
parse_agent_env_hint(b"HERDR_AGENT=codex"),
Some(crate::detect::Agent::Codex)
);
}
#[test]
fn parse_agent_env_hint_ignores_missing_or_unknown_agents() {
assert_eq!(parse_agent_env_hint(b"PATH=/bin\0TERM=xterm\0"), None);
assert_eq!(parse_agent_env_hint(b"HERDR_AGENT=not-an-agent\0"), None);
}
#[test]
fn clipboard_commands_prefer_wayland_when_available() {
let _guard = env_lock().lock().unwrap();
unsafe {
std::env::set_var("WAYLAND_DISPLAY", "wayland-0");
std::env::remove_var("DISPLAY");
}
let commands = clipboard_commands();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].program, "wl-copy");
}
#[test]
fn clipboard_commands_include_x11_fallbacks() {
let _guard = env_lock().lock().unwrap();
unsafe {
std::env::remove_var("WAYLAND_DISPLAY");
std::env::set_var("DISPLAY", ":0");
}
let commands = clipboard_commands();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].program, "xclip");
assert_eq!(commands[1].program, "xsel");
}
#[test]
fn read_clipboard_text_commands_include_session_backends() {
let _guard = env_lock().lock().unwrap();
unsafe {
std::env::set_var("WAYLAND_DISPLAY", "wayland-0");
std::env::set_var("DISPLAY", ":0");
}
let commands = read_clipboard_text_commands();
assert_eq!(commands[0].program, "wl-paste");
assert_eq!(commands[1].program, "wl-paste");
assert_eq!(commands[2].program, "xclip");
assert_eq!(commands[3].program, "xsel");
}
#[test]
fn read_clipboard_text_with_command_reads_utf8() {
let command = ClipboardCommand {
program: "printf",
args: &["feature/linear-302"],
};
assert_eq!(
read_clipboard_text_with_command(&command).as_deref(),
Some("feature/linear-302")
);
}
#[test]
fn read_clipboard_text_with_command_rejects_oversized_output() {
let command = ClipboardCommand {
program: "sh",
args: &["-c", "yes x | head -c 1048578"],
};
assert_eq!(read_clipboard_text_with_command(&command), None);
}
#[test]
fn read_clipboard_image_with_spawned_command_reads_under_limit() {
let mut command = Command::new("sh");
command.arg("-c").arg("printf image");
assert_eq!(
read_clipboard_image_with_spawned_command_max(command, 16),
Some(b"image".to_vec())
);
}
#[test]
fn read_clipboard_image_with_spawned_command_rejects_over_limit() {
let mut command = Command::new("sh");
command.arg("-c").arg("printf oversized");
assert_eq!(
read_clipboard_image_with_spawned_command_max(command, 4),
None
);
}
#[test]
fn read_clipboard_image_rejects_xclip_text_served_for_image_target() {
let _guard = env_lock().lock().unwrap();
let temp_dir =
std::env::temp_dir().join(format!("herdr-fake-xclip-{}", std::process::id()));
std::fs::create_dir_all(&temp_dir).expect("temp dir should be created");
let fake_xclip = temp_dir.join("xclip");
std::fs::write(&fake_xclip, "#!/bin/sh\nprintf '# Tasks'\n")
.expect("fake xclip should be written");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut permissions = std::fs::metadata(&fake_xclip)
.expect("fake xclip metadata")
.permissions();
permissions.set_mode(0o700);
std::fs::set_permissions(&fake_xclip, permissions)
.expect("fake xclip should be executable");
}
let old_path = std::env::var_os("PATH");
let test_path = match old_path.as_ref() {
Some(path) => {
let mut paths = vec![temp_dir.clone()];
paths.extend(std::env::split_paths(path));
std::env::join_paths(paths).expect("test path should be valid")
}
None => temp_dir.clone().into_os_string(),
};
unsafe {
std::env::remove_var("WAYLAND_DISPLAY");
std::env::set_var("DISPLAY", ":0");
std::env::set_var("PATH", test_path);
}
let result = read_clipboard_image();
unsafe {
match old_path {
Some(path) => std::env::set_var("PATH", path),
None => std::env::remove_var("PATH"),
}
}
let _ = std::fs::remove_file(fake_xclip);
let _ = std::fs::remove_dir(temp_dir);
assert_eq!(result, None);
}
#[test]
fn read_clipboard_image_rejects_wayland_xclip_fallback_text_for_image_target() {
let _guard = env_lock().lock().unwrap();
let temp_dir =
std::env::temp_dir().join(format!("herdr-fake-wayland-xclip-{}", std::process::id()));
std::fs::create_dir_all(&temp_dir).expect("temp dir should be created");
let fake_wl_paste = temp_dir.join("wl-paste");
let fake_xclip = temp_dir.join("xclip");
std::fs::write(&fake_wl_paste, "#!/bin/sh\nexit 1\n")
.expect("fake wl-paste should be written");
std::fs::write(&fake_xclip, "#!/bin/sh\nprintf '# Tasks'\n")
.expect("fake xclip should be written");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for command in [&fake_wl_paste, &fake_xclip] {
let mut permissions = std::fs::metadata(command)
.expect("fake clipboard command metadata")
.permissions();
permissions.set_mode(0o700);
std::fs::set_permissions(command, permissions)
.expect("fake clipboard command should be executable");
}
}
let old_path = std::env::var_os("PATH");
let test_path = match old_path.as_ref() {
Some(path) => {
let mut paths = vec![temp_dir.clone()];
paths.extend(std::env::split_paths(path));
std::env::join_paths(paths).expect("test path should be valid")
}
None => temp_dir.clone().into_os_string(),
};
unsafe {
std::env::set_var("WAYLAND_DISPLAY", "wayland-0");
std::env::set_var("DISPLAY", ":0");
std::env::set_var("PATH", test_path);
}
let result = read_clipboard_image();
unsafe {
match old_path {
Some(path) => std::env::set_var("PATH", path),
None => std::env::remove_var("PATH"),
}
}
let _ = std::fs::remove_file(fake_wl_paste);
let _ = std::fs::remove_file(fake_xclip);
let _ = std::fs::remove_dir(temp_dir);
assert_eq!(result, None);
}
#[test]
fn read_validated_clipboard_image_accepts_real_png_payload() {
assert_eq!(
read_validated_clipboard_image(
"sh",
&["-c", "printf '\\211PNG\\r\\n\\032\\nrest-of-image'"],
"png"
),
Some(ClipboardImage {
bytes: b"\x89PNG\r\n\x1a\nrest-of-image".to_vec(),
extension: "png",
})
);
}
#[test]
fn image_signatures_match_only_their_format() {
assert!(bytes_match_image_signature("png", b"\x89PNG\r\n\x1a\n..."));
assert!(bytes_match_image_signature(
"jpg",
&[0xFF, 0xD8, 0xFF, 0xE0]
));
assert!(bytes_match_image_signature("gif", b"GIF87a..."));
assert!(bytes_match_image_signature("gif", b"GIF89a..."));
assert!(bytes_match_image_signature(
"webp",
b"RIFF\x10\x00\x00\x00WEBPVP8 "
));
let mut bmp = vec![0u8; 26];
bmp[..2].copy_from_slice(b"BM");
bmp[10] = 26;
assert!(bytes_match_image_signature("bmp", &bmp));
assert!(!bytes_match_image_signature("png", b"# Tasks"));
assert!(!bytes_match_image_signature("jpg", b"plain clipboard text"));
assert!(!bytes_match_image_signature("gif", b""));
assert!(!bytes_match_image_signature("webp", b"RIFF but not webp"));
assert!(!bytes_match_image_signature("bmp", b"\x89PNG\r\n\x1a\n"));
assert!(!bytes_match_image_signature(
"bmp",
b"BM text is not a bitmap"
));
assert!(!bytes_match_image_signature("svg", b"<svg></svg>"));
}
#[test]
fn desktop_notification_separates_option_like_titles() {
let _guard = env_lock().lock().unwrap();
unsafe {
std::env::remove_var("WAYLAND_DISPLAY");
std::env::set_var("DISPLAY", ":0");
}
let path =
std::env::temp_dir().join(format!("herdr-notify-send-args-{}", std::process::id()));
let script = "printf '%s\\n' \"$@\" > \"$HERDR_NOTIFY_ARGS\"";
let shown = show_desktop_notification_with_command("-danger", Some("body"), |_| {
let mut cmd = Command::new("sh");
cmd.arg("-c")
.arg(script)
.arg("notify-send")
.env("HERDR_NOTIFY_ARGS", &path);
cmd
})
.expect("notification command should run");
assert!(shown);
let args = std::fs::read_to_string(&path).expect("args file");
let _ = std::fs::remove_file(&path);
assert_eq!(args, "--\n-danger\nbody\n");
}
}
|