rmux-server 0.10.0

Tokio daemon and request dispatcher for the RMUX terminal multiplexer.
Documentation
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
use rmux_core::{
    AlertFlags, LifecycleEvent, WINDOW_ACTIVITY, WINDOW_BELL, WINDOW_SILENCE, WINLINK_ACTIVITY,
    WINLINK_BELL, WINLINK_SILENCE,
};
use rmux_proto::{OptionName, SessionId, SessionName, WindowId, WindowTarget};
use tokio::task::JoinHandle;

use super::{RequestHandler, UnsequencedLifecycleEvent};
use crate::pane_io::AttachControl;

#[cfg(test)]
#[derive(Debug, Default)]
pub(in crate::handler) struct AlertOverlayIdentityPause {
    reached: tokio::sync::Notify,
    release: tokio::sync::Notify,
}

#[cfg(test)]
impl AlertOverlayIdentityPause {
    pub(in crate::handler) async fn wait_until_reached(&self) {
        self.reached.notified().await;
    }

    pub(in crate::handler) fn release(&self) {
        self.release.notify_one();
    }
}

#[cfg(test)]
static ALERT_OVERLAY_IDENTITY_PAUSES: std::sync::Mutex<
    Vec<(usize, std::sync::Arc<AlertOverlayIdentityPause>)>,
> = std::sync::Mutex::new(Vec::new());

#[path = "handler_alerts/automatic_names.rs"]
mod automatic_names;
#[path = "handler_alerts/clipboard_relay.rs"]
mod clipboard_relay;
#[path = "handler_alerts/pane_alert_coalescer.rs"]
mod pane_alert_coalescer;
#[path = "handler_alerts/pane_events.rs"]
mod pane_events;
#[path = "handler_alerts/queue.rs"]
mod queue;
#[path = "handler_alerts/show_messages.rs"]
mod show_messages;
#[path = "handler_alerts/silence_timers.rs"]
mod silence_timers;

pub(in crate::handler) use pane_alert_coalescer::PaneAlertCoalescer;

const SHOW_MESSAGES_TEMPLATE: &str = "#{t/p:message_time}: #{message_text}";

#[derive(Debug)]
pub(super) struct SilenceTimerState {
    session_id: SessionId,
    window_id: WindowId,
    generation: u64,
    deadline: tokio::time::Instant,
    task: JoinHandle<()>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AlertKind {
    Bell,
    Activity,
    Silence,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AlertAction {
    None,
    Any,
    Current,
    Other,
}

impl AlertAction {
    fn applies(self, is_current: bool) -> bool {
        match self {
            Self::None => false,
            Self::Any => true,
            Self::Current => is_current,
            Self::Other => !is_current,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VisualMode {
    Off,
    On,
    Both,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::handler) struct AlertPlan {
    session_id: SessionId,
    refresh_session: bool,
    send_bell: bool,
    show_message: bool,
    message_text: String,
    lifecycle_event: Option<UnsequencedLifecycleEvent>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct TerminalSummary {
    attach_pid: u32,
    session_name: SessionName,
    cols: u16,
    rows: u16,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct JobSummary {
    attach_pid: u32,
    session_name: SessionName,
}

impl AlertKind {
    const fn window_flag(self) -> AlertFlags {
        match self {
            Self::Bell => WINDOW_BELL,
            Self::Activity => WINDOW_ACTIVITY,
            Self::Silence => WINDOW_SILENCE,
        }
    }

    const fn winlink_flag(self) -> AlertFlags {
        match self {
            Self::Bell => WINLINK_BELL,
            Self::Activity => WINLINK_ACTIVITY,
            Self::Silence => WINLINK_SILENCE,
        }
    }

    const fn monitor_option(self) -> OptionName {
        match self {
            Self::Bell => OptionName::MonitorBell,
            Self::Activity => OptionName::MonitorActivity,
            Self::Silence => OptionName::MonitorSilence,
        }
    }

    const fn visual_option(self) -> OptionName {
        match self {
            Self::Bell => OptionName::VisualBell,
            Self::Activity => OptionName::VisualActivity,
            Self::Silence => OptionName::VisualSilence,
        }
    }

    const fn action_option(self) -> OptionName {
        match self {
            Self::Bell => OptionName::BellAction,
            Self::Activity => OptionName::ActivityAction,
            Self::Silence => OptionName::SilenceAction,
        }
    }

    const fn lifecycle_event(self, target: WindowTarget) -> LifecycleEvent {
        match self {
            Self::Bell => LifecycleEvent::AlertBell { target },
            Self::Activity => LifecycleEvent::AlertActivity { target },
            Self::Silence => LifecycleEvent::AlertSilence { target },
        }
    }

    const fn label(self) -> &'static str {
        match self {
            Self::Bell => "Bell",
            Self::Activity => "Activity",
            Self::Silence => "Silence",
        }
    }
}

impl RequestHandler {
    #[cfg(test)]
    pub(in crate::handler) fn install_alert_overlay_identity_pause(
        &self,
    ) -> std::sync::Arc<AlertOverlayIdentityPause> {
        let handler_key = std::sync::Arc::as_ptr(&self.state).addr();
        let pause = std::sync::Arc::new(AlertOverlayIdentityPause::default());
        ALERT_OVERLAY_IDENTITY_PAUSES
            .lock()
            .expect("alert overlay identity pause lock")
            .push((handler_key, pause.clone()));
        pause
    }

    #[cfg(test)]
    async fn pause_after_alert_overlay_identity_capture(&self) {
        let handler_key = std::sync::Arc::as_ptr(&self.state).addr();
        let pause = {
            let mut pauses = ALERT_OVERLAY_IDENTITY_PAUSES
                .lock()
                .expect("alert overlay identity pause lock");
            pauses
                .iter()
                .position(|(key, _)| *key == handler_key)
                .map(|position| pauses.swap_remove(position).1)
        };
        if let Some(pause) = pause {
            pause.reached.notify_one();
            pause.release.notified().await;
        }
    }

    pub(super) async fn clear_session_alerts_on_focus(
        &self,
        session_name: &SessionName,
        window_index: u32,
    ) -> bool {
        let changed = {
            let mut state = self.state.lock().await;
            let Some(session) = state.sessions.session_mut(session_name) else {
                return false;
            };
            session.clear_all_winlink_alert_flags(window_index)
        };

        if changed {
            self.refresh_attached_session(session_name).await;
        }
        changed
    }

    async fn show_alert_message(&self, plan: &AlertPlan) {
        let duration = {
            let state = self.state.lock().await;
            let Some(session) = state.sessions.session_by_id(plan.session_id) else {
                return;
            };
            let session_name = session.name().clone();
            display_time(&state.options, &session_name)
        };

        // Log for a still-live session even when no client can display the overlay,
        // matching tmux's server_add_message behavior without crossing an identity reuse.
        {
            let mut state = self.state.lock().await;
            if state.sessions.session_by_id(plan.session_id).is_none() {
                return;
            }
            state.add_message(plan.message_text.clone());
        }
        self.send_alert_overlay(plan.session_id, plan.message_text.clone(), duration)
            .await;
    }

    async fn send_alert_overlay(
        &self,
        session_id: SessionId,
        message: String,
        duration: std::time::Duration,
    ) {
        let session_name = {
            let state = self.state.lock().await;
            let Some(session_name) = state
                .sessions
                .session_by_id(session_id)
                .map(|session| session.name().clone())
            else {
                return;
            };
            session_name
        };
        #[cfg(test)]
        self.pause_after_alert_overlay_identity_capture().await;
        let _ = self
            .send_attached_overlay_to_session_identity(
                &session_name,
                session_id,
                message,
                (!duration.is_zero()).then_some(duration),
                crate::handler::attach_support::TransientMessageInputPolicy::DismissAndForward,
            )
            .await;
    }

    async fn send_attached_bell(&self, session_id: SessionId) {
        let state = self.state.lock().await;
        let Some(session_name) = state
            .sessions
            .session_by_id(session_id)
            .map(|session| session.name().clone())
        else {
            return;
        };
        let mut active_attach = self.active_attach.lock().await;
        active_attach.by_pid.retain(|_, active| {
            if active.session_name != session_name {
                return true;
            }
            active
                .control_tx
                .send(AttachControl::Write(vec![0x07]))
                .is_ok()
        });
    }

    async fn refresh_alert_plan_session(&self, session_id: SessionId) {
        let session_name = {
            let state = self.state.lock().await;
            state
                .sessions
                .session_by_id(session_id)
                .map(|session| session.name().clone())
        };
        if let Some(session_name) = session_name {
            self.refresh_attached_session(&session_name).await;
        }
    }
}

fn alert_flags_enabled(
    options: &rmux_core::OptionStore,
    session_name: &SessionName,
    window_index: u32,
    flags: AlertFlags,
) -> bool {
    (flags.contains(WINDOW_BELL)
        && flag_option_is_on(options.resolve_for_window(
            session_name,
            window_index,
            OptionName::MonitorBell,
        )))
        || (flags.contains(WINDOW_ACTIVITY)
            && flag_option_is_on(options.resolve_for_window(
                session_name,
                window_index,
                OptionName::MonitorActivity,
            )))
        || (flags.contains(WINDOW_SILENCE)
            && monitor_silence_seconds(options, session_name, window_index) != 0)
}

fn alert_kind_enabled(
    options: &rmux_core::OptionStore,
    session_name: &SessionName,
    window_index: u32,
    kind: AlertKind,
) -> bool {
    match kind {
        AlertKind::Bell | AlertKind::Activity => flag_option_is_on(options.resolve_for_window(
            session_name,
            window_index,
            kind.monitor_option(),
        )),
        AlertKind::Silence => monitor_silence_seconds(options, session_name, window_index) != 0,
    }
}

fn monitor_silence_seconds(
    options: &rmux_core::OptionStore,
    session_name: &SessionName,
    window_index: u32,
) -> u64 {
    options
        .resolve_for_window(session_name, window_index, OptionName::MonitorSilence)
        .and_then(|value| value.parse::<u64>().ok())
        .unwrap_or(0)
}

fn flag_option_is_on(value: Option<&str>) -> bool {
    matches!(value, Some("on"))
}

fn alert_action(
    options: &rmux_core::OptionStore,
    session_name: &SessionName,
    option: OptionName,
) -> AlertAction {
    match options.resolve(Some(session_name), option).unwrap_or("any") {
        "none" => AlertAction::None,
        "current" => AlertAction::Current,
        "other" => AlertAction::Other,
        _ => AlertAction::Any,
    }
}

fn visual_mode(
    options: &rmux_core::OptionStore,
    session_name: &SessionName,
    option: OptionName,
) -> VisualMode {
    match options.resolve(Some(session_name), option).unwrap_or("off") {
        "on" => VisualMode::On,
        "both" => VisualMode::Both,
        _ => VisualMode::Off,
    }
}

fn display_time(
    options: &rmux_core::OptionStore,
    session_name: &SessionName,
) -> std::time::Duration {
    std::time::Duration::from_millis(
        options
            .resolve(Some(session_name), OptionName::DisplayTime)
            .and_then(|value| value.parse::<u64>().ok())
            .unwrap_or(750),
    )
}