par-term 0.49.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! Helper keybinding actions and WindowState helpers: visual notifications,
//! shader toggles, and the clear actions.
//!
//! - `show_toast`, `show_pane_indices`: visual notification helpers
//! - `toggle_background_shader`, `toggle_cursor_shader`: shader toggle helpers
//! - `clear_scrollback`, `clear_screen`, `send_clear_screen_sequence`: the
//!   clear family (moved here when keybinding_actions crossed the 800-line
//!   gate)

use crate::app::window_state::WindowState;
use crate::config::resolve_shader_config;

impl WindowState {
    /// The `mux-restart-pane` palette row: restart the focused daemon
    /// pane's process. Offered only while a transport is attached; with no
    /// daemon pane focused (a local tab) there is nothing to respawn.
    pub(crate) fn palette_restart_mux_pane(&mut self) -> bool {
        #[cfg(feature = "mux")]
        if self.restart_focused_mux_pane() {
            return true;
        }
        log::warn!("par-mux pane restart requested but no daemon pane is focused");
        false
    }

    /// Show an info toast (UX.md OV7): it joins the top-right stack and
    /// expires after two seconds.
    pub(crate) fn show_toast(&mut self, message: impl Into<String>) {
        self.post_toast(crate::app::overlay::toast::ToastKind::Info, message, None);
    }

    /// Post a toast of `kind`, with an optional action button, to the
    /// toast stack. Errors persist until dismissed. Returns the toast's id.
    pub(crate) fn post_toast(
        &mut self,
        kind: crate::app::overlay::toast::ToastKind,
        message: impl Into<String>,
        action: Option<crate::app::overlay::toast::ToastAction>,
    ) -> u64 {
        let id = self
            .overlay_state
            .toasts
            .push(kind, message, action, std::time::Instant::now());
        self.focus_state.needs_redraw = true;
        self.request_redraw();
        id
    }

    /// The text of the newest toast still on screen — what a test asserts
    /// was announced.
    #[cfg(test)]
    pub(crate) fn last_toast_text(&self) -> Option<&str> {
        self.overlay_state
            .toasts
            .newest()
            .map(|toast| toast.message.as_str())
    }

    /// The toast that says a tab went away (closed, or a par-mux tab
    /// hidden), with an action button that brings it back and a hint that
    /// names the live chord — never the raw config string
    /// (`CmdOrCtrl+Z`), and nothing at all when `reopen_closed_tab` is
    /// unbound (UX.md OV7).
    pub(crate) fn post_reopen_toast(&mut self, what: &str, button: &str) {
        let hint = self
            .live_chord_hint("reopen_closed_tab")
            .map(|chord| format!(" ({chord})"))
            .unwrap_or_default();
        self.post_toast(
            crate::app::overlay::toast::ToastKind::Info,
            format!("{what}{hint}"),
            Some(crate::app::overlay::toast::ToastAction {
                label: button.to_string(),
                action_id: "reopen_closed_tab".to_string(),
            }),
        );
    }

    /// The live chord for a registry action, formatted for a toast hint
    /// ("Press Cmd+Z to undo"), or `None` when nothing is bound — so hints
    /// never show a raw config string like `CmdOrCtrl+Z` (UX.md OV7).
    pub(crate) fn live_chord_hint(&self, action: &str) -> Option<String> {
        self.keybinding_registry
            .chord_for_action(action)
            .map(|combo| crate::command_palette::catalog::chord_display(&combo))
    }

    /// A par-mux failure: an error toast that persists until dismissed
    /// (UX.md OV7: errors persist), held on the session chip too (M12, V1).
    ///
    /// par-mux errors share one toast slot: a new one replaces the previous
    /// par-mux error toast, the way the chip holds only the latest error.
    /// Without the slot, three unrelated par-mux failures would fill the
    /// three-toast queue with persistent errors, and every later info toast
    /// (the tab-close Undo) would evict itself on arrival.
    pub(crate) fn record_mux_error(&mut self, message: impl Into<String>) {
        let message = message.into();
        self.tmux_state.mux_last_error = Some(message.clone());
        if let Some(previous) = self.tmux_state.mux_error_toast.take() {
            self.overlay_state.toasts.dismiss(previous);
        }
        let id = self.show_persistent_toast(message);
        self.tmux_state.mux_error_toast = Some(id);
    }

    /// Show an error toast: it persists until dismissed, the V11
    /// error-surface shape for failures the user must see and act on
    /// rather than watch fade. A later toast stacks beside it instead of
    /// replacing it (UX.md OV7).
    pub(crate) fn show_persistent_toast(&mut self, message: impl Into<String>) -> u64 {
        self.post_toast(crate::app::overlay::toast::ToastKind::Error, message, None)
    }

    /// Show pane index overlays for a specified duration.
    pub(crate) fn show_pane_indices(&mut self, duration: std::time::Duration) {
        self.overlay_state.pane_identify_hide_time = Some(std::time::Instant::now() + duration);
        self.focus_state.needs_redraw = true;
        self.request_redraw();
    }

    /// Apply current background shader config to the live renderer.
    pub(crate) fn refresh_background_shader_renderer(&mut self) {
        if let Some(renderer) = &mut self.renderer {
            let metadata = self
                .config
                .load()
                .shader
                .custom_shader
                .as_ref()
                .and_then(|name| self.shader_state.shader_metadata_cache.get(name).cloned());
            let shader_override =
                self.config
                    .load()
                    .shader
                    .custom_shader
                    .as_ref()
                    .and_then(|name| {
                        self.config
                            .load()
                            .shader_overrides
                            .shader_configs
                            .get(name)
                            .cloned()
                    });
            let mut resolved = resolve_shader_config(
                shader_override.as_ref(),
                metadata.as_ref(),
                &self.config.load(),
            );
            if self.config.load().shader.custom_shader_readability_mode {
                resolved.brightness = resolved.brightness.min(
                    self.config
                        .load()
                        .shader
                        .custom_shader_readability_brightness,
                );
            }

            let _ = renderer.set_custom_shader_enabled(
                par_term_render::renderer::shaders::CustomShaderEnableParams {
                    enabled: self.config.load().shader.custom_shader_enabled,
                    shader_path: self.config.load().shader.custom_shader.as_deref(),
                    window_opacity: self.config.load().window.window_opacity,
                    animation_enabled: self.config.load().shader.custom_shader_animation
                        && !self.config.load().shader.custom_shader_readability_mode,
                    animation_speed: resolved.animation_speed,
                    full_content: resolved.full_content,
                    brightness: resolved.brightness,
                    channel_paths: &resolved.channel_paths(),
                    cubemap_path: resolved.cubemap_path().map(|p| p.as_path()),
                    custom_uniforms: &resolved.custom_uniforms,
                    background_channel0_blend_mode: resolved.background_channel0_blend_mode,
                    auto_dim_under_text: resolved.auto_dim_under_text,
                    auto_dim_strength: resolved.auto_dim_strength,
                },
            );
        }
    }

    /// Toggle this window's always-on-top level (UX.md A20). Writes the
    /// window's config copy, never the file (Settings edits the manager's
    /// global config), and any Settings apply re-applies the configured
    /// value. Most Linux window managers, and Wayland
    /// compositors, ignore the window-level request.
    pub(crate) fn toggle_always_on_top(&mut self) {
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.window.window_always_on_top = !old.window.window_always_on_top;
            std::sync::Arc::new(new)
        });
        let on = self.config.load().window.window_always_on_top;
        if let Some(window) = &self.window {
            window.set_window_level(if on {
                winit::window::WindowLevel::AlwaysOnTop
            } else {
                winit::window::WindowLevel::Normal
            });
        }
        self.show_toast(if on {
            "Always on Top: ON"
        } else {
            "Always on Top: OFF"
        });
    }

    /// Toggle the background/custom shader on/off.
    pub(crate) fn toggle_background_shader(&mut self) {
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.shader.custom_shader_enabled = !old.shader.custom_shader_enabled;
            std::sync::Arc::new(new)
        });
        self.refresh_background_shader_renderer();

        self.focus_state.needs_redraw = true;
        self.request_redraw();

        log::info!(
            "Background shader {}",
            if self.config.load().shader.custom_shader_enabled {
                "enabled"
            } else {
                "disabled"
            }
        );
    }

    /// Cycle to the next available background shader.
    pub(crate) fn cycle_background_shader(&mut self) {
        let mut shaders = Vec::new();
        if let Ok(entries) = std::fs::read_dir(crate::config::Config::shaders_dir()) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().and_then(|ext| ext.to_str()) == Some("glsl")
                    && let Some(name) = path.file_name().and_then(|name| name.to_str())
                    && !name.starts_with("cursor_")
                {
                    shaders.push(name.to_string());
                }
            }
        }
        shaders.sort();
        if shaders.is_empty() {
            self.post_toast(
                crate::app::overlay::toast::ToastKind::Warning,
                "No background shaders found",
                None,
            );
            return;
        }

        let next_index = self
            .config
            .load()
            .shader
            .custom_shader
            .as_ref()
            .and_then(|current| shaders.iter().position(|shader| shader == current))
            .map(|index| (index + 1) % shaders.len())
            .unwrap_or(0);
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.shader.custom_shader = Some(shaders[next_index].clone());
            std::sync::Arc::new(new)
        });
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.shader.custom_shader_enabled = true;
            std::sync::Arc::new(new)
        });
        self.refresh_background_shader_renderer();
        self.post_toast(
            crate::app::overlay::toast::ToastKind::Success,
            format!("Shader: {}", shaders[next_index]),
            None,
        );
    }

    /// Pause/resume background shader animation.
    pub(crate) fn toggle_shader_animation(&mut self) {
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.shader.custom_shader_animation = !old.shader.custom_shader_animation;
            std::sync::Arc::new(new)
        });
        if let Some(renderer) = &mut self.renderer {
            renderer.set_custom_shader_animation(self.config.load().shader.custom_shader_animation);
        }
        self.show_toast(if self.config.load().shader.custom_shader_animation {
            "Shader animation resumed"
        } else {
            "Shader animation paused"
        });
    }

    /// Toggle low-power/readability shader mode.
    pub(crate) fn toggle_shader_readability_mode(&mut self) {
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.shader.custom_shader_readability_mode = !old.shader.custom_shader_readability_mode;
            std::sync::Arc::new(new)
        });
        self.refresh_background_shader_renderer();
        self.show_toast(
            if self.config.load().shader.custom_shader_readability_mode {
                "Shader readability mode on"
            } else {
                "Shader readability mode off"
            },
        );
    }

    /// Toggle the cursor shader on/off.
    pub(crate) fn toggle_cursor_shader(&mut self) {
        self.config.rcu(|old| {
            let mut new = (**old).clone();
            new.shader.cursor_shader_enabled = !old.shader.cursor_shader_enabled;
            std::sync::Arc::new(new)
        });

        if let Some(renderer) = &mut self.renderer {
            let _ = renderer.set_cursor_shader_enabled(
                self.config.load().shader.cursor_shader_enabled,
                self.config.load().shader.cursor_shader.as_deref(),
                self.config.load().window.window_opacity,
                self.config.load().shader.cursor_shader_animation,
                self.config.load().shader.cursor_shader_animation_speed,
            );
        }

        self.focus_state.needs_redraw = true;
        self.request_redraw();

        log::info!(
            "Cursor shader {}",
            if self.config.load().shader.cursor_shader_enabled {
                "enabled"
            } else {
                "disabled"
            }
        );
    }
}

// ── clear actions (moved from keybinding_actions to stay under the
// 800-line gate) ──────────────────────────────────────────────────────────

pub(crate) fn clear_scrollback(s: &mut WindowState) -> bool {
    let cleared = if let Some(tab) = s.tab_manager.active_tab_mut() {
        // The focused pane's terminal, so a split clears the pane the user is
        // looking at (parity with the dissolved utility-layer branch).
        let terminal = if let Some(ref pm) = tab.pane_manager
            && let Some(focused_pane) = pm.focused_pane()
        {
            std::sync::Arc::clone(&focused_pane.terminal)
        } else {
            std::sync::Arc::clone(&tab.terminal)
        };
        // try_lock: intentional — keybinding action in sync event loop.
        // On miss: scrollback not cleared this invocation. User can retry.
        let did_clear = if let Ok(mut term) = terminal.try_write() {
            term.clear_scrollback();
            term.clear_scrollback_metadata();
            true
        } else {
            false
        };
        if did_clear {
            tab.active_cache_mut().scrollback_len = 0;
            tab.scripting.trigger_marks.clear();
            if let Some(pm) = tab.pane_manager_mut() {
                for pane in pm.all_panes_mut() {
                    if std::sync::Arc::ptr_eq(&pane.terminal, &terminal) {
                        pane.cache.invalidate_pane_cells();
                    }
                }
            }
        }
        did_clear
    } else {
        false
    };
    if cleared {
        s.set_scroll_target(0);
        log::info!("Cleared scrollback buffer (focused pane)");
    }
    true
}

/// Send the Ctrl+L clear-screen byte (0x0C) to the focused pane. In a mux
/// tab the focused pane is a daemon mirror, so the byte routes to the
/// daemon — `tab.terminal` there is the hidden login shell the clear must
/// never reach.
pub(crate) fn clear_screen(s: &mut WindowState) -> bool {
    s.send_clear_screen_sequence();
    true
}

/// Font size the config file on disk specifies; 14.0 when it cannot be
/// read (the pre-B68 behavior, kept as the failure fallback).
pub(crate) fn configured_font_size() -> f32 {
    crate::config::Config::load()
        .map(|c| c.font_size)
        .unwrap_or(14.0)
}

/// B68: "Reset Font Size" restores the size the config file specifies —
/// the same source `reload_config` reads — not a hard-coded 14.0. Shared by
/// the registry binding and the View menu item, which the native
/// accelerator can intercept first (the B58 pattern).
pub(crate) fn reset_font_size_to_configured(s: &mut WindowState) -> bool {
    let configured = configured_font_size();
    s.config.rcu(|old| {
        let mut new = (**old).clone();
        new.font_size = configured;
        std::sync::Arc::new(new)
    });
    s.render_loop.pending_font_rebuild = true;
    log::info!("Font size reset to configured size ({configured})");
    s.request_redraw();
    true
}

impl WindowState {
    /// Send the Ctrl+L clear-screen byte (0x0C) to the focused pane.
    ///
    /// A method (not inline in the handler) so the tmux pane-write path and
    /// tests can drive it without fabricating a winit `KeyEvent` (which has
    /// a private field and no public constructor).
    pub(crate) fn send_clear_screen_sequence(&self) {
        let Some(tab) = self.tab_manager.active_tab() else {
            return;
        };
        let clear_sequence = vec![0x0C]; // Ctrl+L character
        if self.route_mux_tab_write(tab, &clear_sequence) {
            return;
        }
        // Use the focused pane's terminal so Ctrl+L clears the correct
        // pane in split-pane mode, falling back to the tab's root terminal.
        let terminal_clone = if let Some(ref pm) = tab.pane_manager {
            if let Some(focused_pane) = pm.focused_pane() {
                std::sync::Arc::clone(&focused_pane.terminal)
            } else {
                std::sync::Arc::clone(&tab.terminal)
            }
        } else {
            std::sync::Arc::clone(&tab.terminal)
        };
        self.runtime.spawn(async move {
            // try_lock: intentional — spawned async task uses try-lock to avoid
            // blocking the tokio worker. On miss: the Ctrl+L clear is silently
            // dropped. User can press the shortcut again.
            if let Ok(term) = terminal_clone.try_read() {
                if let Err(e) = term.write(&clear_sequence) {
                    crate::debug_error!("INPUT", "PTY write failed (clear screen): {e}");
                } else {
                    log::debug!("Sent clear screen sequence (Ctrl+L)");
                }
            }
        });
    }
}