返回 CodeWhale
delivery.rs
根目录 / crates / notify / src / delivery.rs
1 use std::io::Write;
2 use std::time::Duration;
3
4 use super::payload::{NotificationKind, NotificationPayload};
5 use super::{DeliveryOutcome, Method, NotificationGate};
6
7 /// Resolve `Auto` to a concrete method by inspecting `$TERM_PROGRAM`,
8 /// `$LC_TERMINAL`, and `$TERM`.
9 ///
10 /// Resolution table:
11 /// - `iTerm.app`, `WezTerm`, `Cmux` → `Osc9`
12 /// - `Ghostty` → `Ghostty` (OSC 777)
13 /// - `kitty` → `Kitty` (OSC 99)
14 /// - `$LC_TERMINAL` matches OSC-9 capable → `Osc9` (Cmux that sets LC_TERMINAL)
15 /// - `$TERM` contains `ghostty` → `Osc9` (cmux etc.)
16 /// - `$TERM` contains `kitty` → `Kitty`
17 /// - Unknown terminal → `Off` (never invent an audible fallback)
18 #[must_use]
19 pub fn resolve_method() -> Method {
20 let term_program = std::env::var("TERM_PROGRAM").unwrap_or_default();
21 match term_program.as_str() {
22 "iTerm.app" | "WezTerm" | "Cmux" => return Method::Osc9,
23 "Ghostty" => return Method::Ghostty,
24 "kitty" => return Method::Kitty,
25 _ => {}
26 }
27
28 // LC_TERMINAL fallback for terminals (e.g. Cmux) that set
29 // LC_TERMINAL instead of TERM_PROGRAM.
30 let lc_terminal = std::env::var("LC_TERMINAL").unwrap_or_default();
31 match lc_terminal.as_str() {
32 "iTerm.app" | "Ghostty" | "WezTerm" | "Cmux" => return Method::Osc9,
33 _ => {}
34 }
35
36 // A banner selection must never invent audio. Windows users who want the
37 // system sound can explicitly select `method = "bel"` or a completion
38 // sound; unknown automatic transports fail closed.
39 if cfg!(target_os = "windows") {
40 return Method::Off;
41 }
42
43 if cfg!(target_os = "macos") {
44 return Method::MacOS;
45 }
46
47 // Ghostty-based terminals (cmux, etc.) may not set their own
48 // TERM_PROGRAM but do set TERM=xterm-ghostty. Likewise for Kitty.
49 let term = std::env::var("TERM").unwrap_or_default();
50 if term.contains("ghostty") {
51 Method::Osc9
52 } else if term.contains("kitty") {
53 Method::Kitty
54 } else {
55 Method::Off
56 }
57 }
58
59 /// Wrap an escape sequence for terminal multiplexer passthrough.
60 ///
61 /// tmux intercepts escape sequences; DCS passthrough tunnels them to
62 /// the outer terminal unmodified. Every ESC inside the payload is
63 /// doubled so tmux does not interpret it as DCS end.
64 fn wrap_for_multiplexer(seq: &str, in_tmux: bool) -> String {
65 if in_tmux {
66 let escaped = seq.replace('\x1b', "\x1b\x1b");
67 format!("\x1bPtmux;{escaped}\x1b\\")
68 } else {
69 seq.to_string()
70 }
71 }
72
73 /// Build the raw escape bytes for the given method and message.
74 ///
75 /// When `in_tmux` is `true`, OSC sequences are wrapped in DCS passthrough
76 /// so tmux forwards them to the outer terminal.
77 #[must_use]
78 fn build_escape(method: Method, in_tmux: bool, msg: &str) -> Vec<u8> {
79 match method {
80 Method::Bel => vec![b'\x07'],
81 Method::Osc9 => {
82 let inner = format!("\x1b]9;{msg}\x07");
83 if in_tmux {
84 let escaped_inner = inner.replace('\x1b', "\x1b\x1b");
85 format!("\x1bPtmux;{escaped_inner}\x1b\\").into_bytes()
86 } else {
87 inner.into_bytes()
88 }
89 }
90 Method::Kitty => {
91 // Kitty notification: OSC 99 ; params ST
92 // ST terminator (ESC \) instead of BEL to avoid audible beep.
93 let title_seq = "\x1b]99;d=0:p=title\x1b\\";
94 let body_seq = format!("\x1b]99;p=body;{msg}\x1b\\");
95 let focus_seq = "\x1b]99;d=1:a=focus\x1b\\";
96 let combined = format!("{title_seq}{body_seq}{focus_seq}");
97 wrap_for_multiplexer(&combined, in_tmux).into_bytes()
98 }
99 Method::Ghostty => {
100 // Ghostty notification: OSC 777 ; notify ; title ; message BEL
101 let seq = format!("\x1b]777;notify;codewhale;{msg}\x07");
102 wrap_for_multiplexer(&seq, in_tmux).into_bytes()
103 }
104 // Auto and Off and MacOS should not reach build_escape.
105 Method::Auto | Method::Off | Method::MacOS => vec![],
106 }
107 }
108
109 /// All side effects sit behind injected sinks. A disallowed event reaches none.
110 #[allow(clippy::too_many_arguments)]
111 pub fn notify_with_sinks(
112 method: Method,
113 in_tmux: bool,
114 payload: &NotificationPayload,
115 threshold: Duration,
116 elapsed: Duration,
117 gate: NotificationGate,
118 attention_allowed: bool,
119 sink: &mut dyn Write,
120 decide_sound: &mut dyn FnMut(NotificationKind, bool) -> crate::sound_policy::SoundDecision,
121 audio: &mut dyn FnMut(
122 &crate::sound_policy::SoundCue,
123 &mut dyn Write,
124 ) -> crate::audio::AudioOutcome,
125 native: &mut dyn FnMut(&NotificationPayload) -> DeliveryOutcome,
126 ) -> DeliveryOutcome {
127 use crate::audio::AudioOutcome;
128 use crate::sound_policy::SoundDecision;
129 if !attention_allowed {
130 return DeliveryOutcome::SuppressedByAttention;
131 }
132 if elapsed < threshold {
133 return DeliveryOutcome::SuppressedByThreshold;
134 }
135 if method == Method::Off {
136 return DeliveryOutcome::SuppressedByMethod;
137 }
138 if !gate.allows(payload.kind()) {
139 return DeliveryOutcome::SuppressedByGate;
140 }
141 let effective = if method == Method::Auto {
142 resolve_method()
143 } else {
144 method
145 };
146 if effective == Method::Off {
147 return DeliveryOutcome::UnsupportedTransport;
148 }
149 let banner = match effective {
150 Method::MacOS => native(payload),
151 Method::Bel => DeliveryOutcome::Delivered(effective),
152 _ => {
153 let bytes = build_escape(effective, in_tmux, &payload.render_inline());
154 if bytes.is_empty() {
155 return DeliveryOutcome::UnsupportedTransport;
156 }
157 if sink.write_all(&bytes).and_then(|()| sink.flush()).is_err() {
158 return DeliveryOutcome::DeliveryFailed;
159 }
160 DeliveryOutcome::Delivered(effective)
161 }
162 };
163 if !matches!(
164 banner,
165 DeliveryOutcome::Delivered(_) | DeliveryOutcome::Dispatched(_)
166 ) {
167 return banner;
168 }
169 // BEL is itself audio: select and emit one cue instead of adding a
170 // transport bell to the chosen sound. Never fall back after suppression.
171 match decide_sound(payload.kind(), effective == Method::Bel) {
172 SoundDecision::Suppress(_) if effective == Method::Bel => {
173 DeliveryOutcome::SuppressedBySound
174 }
175 SoundDecision::Suppress(_) => banner,
176 SoundDecision::Play(cue) => match audio(&cue, sink) {
177 AudioOutcome::Emitted => banner,
178 AudioOutcome::Dispatched if effective == Method::Bel => {
179 DeliveryOutcome::Dispatched(effective)
180 }
181 AudioOutcome::Dispatched => banner,
182 AudioOutcome::Busy if effective == Method::Bel => DeliveryOutcome::SuppressedBySound,
183 AudioOutcome::Unsupported if effective == Method::Bel => {
184 DeliveryOutcome::UnsupportedTransport
185 }
186 AudioOutcome::Failed if effective == Method::Bel => DeliveryOutcome::DeliveryFailed,
187 AudioOutcome::Busy => banner,
188 AudioOutcome::Unsupported | AudioOutcome::Failed => {
189 if matches!(banner, DeliveryOutcome::Dispatched(_)) {
190 DeliveryOutcome::DispatchedWithoutSound(effective)
191 } else {
192 DeliveryOutcome::DeliveredWithoutSound(effective)
193 }
194 }
195 },
196 }
197 }
198
198 lines RUST