par-term 0.30.9

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
463
464
465
466
467
468
469
470
471
472
473
474
//! Script state synchronization for the window manager.
//!
//! This module handles forwarding terminal events to scripts, reading script
//! commands/output, and syncing their running state to the settings window UI.
//!
//! ## Sub-modules
//!
//! - `config_change` — `PendingScriptAction` enum, command tokenisation, and
//!   allowlisted config-key application
//! - `scripting_lifecycle` — `start_script` and `stop_script` implementations

mod config_change;
mod scripting_lifecycle;

use std::process::Stdio;

use config_change::{PendingScriptAction, tokenise_command};

use super::WindowManager;

impl WindowManager {
    /// Maximum number of output lines kept per script in the UI.
    const SCRIPT_OUTPUT_MAX_LINES: usize = 200;

    /// Sync script running state to the settings window.
    ///
    /// Drains events from forwarders, sends them to scripts, reads commands
    /// and errors back, and updates the settings UI state.
    pub fn sync_script_running_state(&mut self) {
        let focused = self.get_focused_window_id();

        // Pass 1 — Collect state from the active tab.
        //
        // Safe commands (Log, SetPanel, ClearPanel) are executed immediately.
        // Commands that need `WindowState` methods (Notify, SetBadge, etc.) or
        // require permission checks (WriteText, RunCommand, ChangeConfig) are
        // deferred into `pending_actions` and processed in Pass 2.
        struct ScriptPassResult {
            running_state: Vec<bool>,
            error_state: Vec<String>,
            new_output: Vec<Vec<String>>,
            panel_state: Vec<Option<(String, String)>>,
            pending_actions: Vec<PendingScriptAction>,
        }
        let ScriptPassResult {
            running_state,
            error_state,
            new_output,
            panel_state,
            pending_actions,
        } = if let Some(window_id) = focused
            && let Some(ws) = self.windows.get_mut(&window_id)
            && let Some(tab) = ws.tab_manager.active_tab_mut()
        {
            let script_count = ws.config.scripts.len();
            let mut running = Vec::with_capacity(script_count);
            let mut errors = Vec::with_capacity(script_count);
            let mut output = Vec::with_capacity(script_count);
            let mut panels = Vec::with_capacity(script_count);
            let mut pending: Vec<PendingScriptAction> = Vec::new();

            for i in 0..script_count {
                let has_script_id = tab.scripting.script_ids.get(i).and_then(|opt| *opt);
                let is_running =
                    has_script_id.is_some_and(|id| tab.scripting.script_manager.is_running(id));

                // Drain events from forwarder and send to script
                if is_running && let Some(Some(forwarder)) = tab.scripting.script_forwarders.get(i)
                {
                    let events = forwarder.drain_events();
                    if let Some(script_id) = has_script_id {
                        for event in &events {
                            let _ = tab.scripting.script_manager.send_event(script_id, event);
                        }
                    }
                }

                // Read commands from script and process them
                let mut log_lines = Vec::new();
                let mut panel_val = tab
                    .scripting
                    .script_manager
                    .get_panel(has_script_id.unwrap_or(0))
                    .cloned();

                if let Some(script_id) = has_script_id {
                    let commands = tab.scripting.script_manager.read_commands(script_id);
                    for cmd in commands {
                        match cmd {
                            crate::scripting::protocol::ScriptCommand::Log { level, message } => {
                                log_lines.push(format!("[{}] {}", level, message));
                            }
                            crate::scripting::protocol::ScriptCommand::SetPanel {
                                title,
                                content,
                            } => {
                                tab.scripting.script_manager.set_panel(
                                    script_id,
                                    title.clone(),
                                    content.clone(),
                                );
                                panel_val = Some((title, content));
                            }
                            crate::scripting::protocol::ScriptCommand::ClearPanel {} => {
                                tab.scripting.script_manager.clear_panel(script_id);
                                panel_val = None;
                            }
                            // Safe display-only commands — defer to Pass 2 so they can
                            // call `WindowState` methods without borrow conflicts.
                            crate::scripting::protocol::ScriptCommand::Notify { title, body } => {
                                pending.push(PendingScriptAction::Notify { title, body });
                            }
                            crate::scripting::protocol::ScriptCommand::SetBadge { text } => {
                                pending.push(PendingScriptAction::SetBadge { text });
                            }
                            crate::scripting::protocol::ScriptCommand::SetVariable {
                                name,
                                value,
                            } => {
                                pending.push(PendingScriptAction::SetVariable { name, value });
                            }
                            // Restricted commands — permission-checked in Pass 2.
                            crate::scripting::protocol::ScriptCommand::WriteText { text } => {
                                pending.push(PendingScriptAction::WriteText {
                                    text,
                                    config_index: i,
                                });
                            }
                            crate::scripting::protocol::ScriptCommand::RunCommand { command } => {
                                pending.push(PendingScriptAction::RunCommand {
                                    command,
                                    config_index: i,
                                });
                            }
                            crate::scripting::protocol::ScriptCommand::ChangeConfig {
                                key,
                                value,
                            } => {
                                pending.push(PendingScriptAction::ChangeConfig {
                                    key,
                                    value,
                                    config_index: i,
                                });
                            }
                        }
                    }
                }

                // Read errors from script
                let err_text = if let Some(script_id) = has_script_id {
                    if is_running {
                        // Drain any stderr lines even while running
                        let err_lines = tab.scripting.script_manager.read_errors(script_id);
                        if !err_lines.is_empty() {
                            err_lines.join("\n")
                        } else {
                            String::new()
                        }
                    } else {
                        let err_lines = tab.scripting.script_manager.read_errors(script_id);
                        err_lines.join("\n")
                    }
                } else if let Some(sw) = &self.settings_window
                    && let Some(existing) = sw.settings_ui.script_errors.get(i)
                    && !existing.is_empty()
                {
                    existing.clone()
                } else {
                    String::new()
                };

                running.push(is_running);
                errors.push(err_text);
                output.push(log_lines);
                panels.push(panel_val);
            }

            ScriptPassResult {
                running_state: running,
                error_state: errors,
                new_output: output,
                panel_state: panels,
                pending_actions: pending,
            }
        } else {
            ScriptPassResult {
                running_state: Vec::new(),
                error_state: Vec::new(),
                new_output: Vec::new(),
                panel_state: Vec::new(),
                pending_actions: Vec::new(),
            }
        };

        // Pass 2 — Execute deferred actions that need `WindowState` access.
        //
        // The mutable borrow of `self.windows` from Pass 1 has been released,
        // so we can take a fresh mutable borrow here.
        if !pending_actions.is_empty()
            && let Some(window_id) = focused
            && let Some(ws) = self.windows.get_mut(&window_id)
        {
            for action in pending_actions {
                match action {
                    // ── Notify ──────────────────────────────────────────────────
                    PendingScriptAction::Notify { title, body } => {
                        crate::debug_info!(
                            "SCRIPT",
                            "AUDIT Script Notify title={:?} body={:?}",
                            title,
                            body
                        );
                        ws.deliver_notification(&title, &body);
                    }

                    // ── SetBadge ────────────────────────────────────────────────
                    PendingScriptAction::SetBadge { text } => {
                        if let Some(tab) = ws.tab_manager.active_tab_mut() {
                            tab.profile.badge_override = Some(text.clone());
                        }
                        ws.request_redraw();
                        crate::debug_info!("SCRIPT", "SetBadge text={:?}", text);
                    }

                    // ── SetVariable ─────────────────────────────────────────────
                    PendingScriptAction::SetVariable { name, value } => {
                        {
                            let mut vars = ws.badge_state.variables_mut();
                            vars.custom.insert(name.clone(), value.clone());
                        }
                        ws.badge_state.mark_dirty();
                        ws.request_redraw();
                        crate::debug_info!("SCRIPT", "SetVariable {}={:?}", name, value);
                    }

                    // ── WriteText ───────────────────────────────────────────────
                    // NOTE: Uses `try_write()` for the terminal lock.  If the
                    // lock is held (e.g. by the PTY reader), the write is
                    // silently skipped this frame.  The script receives no
                    // failure signal — it may retry on the next event cycle.
                    PendingScriptAction::WriteText { text, config_index } => {
                        // Permission check (copy value to release config borrow)
                        let allow = ws
                            .config
                            .scripts
                            .get(config_index)
                            .map(|s| s.allow_write_text)
                            .unwrap_or(false);
                        let rate_limit = ws
                            .config
                            .scripts
                            .get(config_index)
                            .map(|s| s.write_text_rate_limit)
                            .unwrap_or(0);

                        if !allow {
                            log::warn!(
                                "Script[{}] WriteText DENIED: allow_write_text=false",
                                config_index
                            );
                            continue;
                        }

                        // Strip VT/ANSI sequences before PTY injection
                        let clean = crate::scripting::protocol::strip_vt_sequences(&text);
                        if clean.is_empty() {
                            continue;
                        }

                        // Rate limit and write
                        if let Some(tab) = ws.tab_manager.active_tab_mut() {
                            let script_id =
                                tab.scripting.script_ids.get(config_index).and_then(|o| *o);
                            if let Some(sid) = script_id
                                && !tab
                                    .scripting
                                    .script_manager
                                    .check_write_text_rate(sid, rate_limit)
                            {
                                log::warn!("Script[{}] WriteText RATE-LIMITED", config_index);
                                continue;
                            }
                            // try_lock: acceptable — script WriteText in sync event
                            // loop. On miss the write is skipped this frame; the
                            // script can retry.
                            if let Ok(term) = tab.terminal.try_write()
                                && let Err(e) = term.write_str(&clean)
                            {
                                log::error!(
                                    "Script[{}] WriteText write failed: {}",
                                    config_index,
                                    e
                                );
                            }
                            crate::debug_info!(
                                "SCRIPT",
                                "AUDIT Script[{}] WriteText wrote {} bytes",
                                config_index,
                                clean.len()
                            );
                        }
                    }

                    // ── RunCommand ──────────────────────────────────────────────
                    // NOTE: Spawned processes run fire-and-forget with
                    // stdout/stderr discarded (`Stdio::null()`).  Scripts that
                    // need command output should read it from the PTY stream
                    // or use a side-channel (e.g. writing to a temp file).
                    PendingScriptAction::RunCommand {
                        command,
                        config_index,
                    } => {
                        let allow = ws
                            .config
                            .scripts
                            .get(config_index)
                            .map(|s| s.allow_run_command)
                            .unwrap_or(false);
                        let rate_limit = ws
                            .config
                            .scripts
                            .get(config_index)
                            .map(|s| s.run_command_rate_limit)
                            .unwrap_or(0);

                        if !allow {
                            log::warn!(
                                "Script[{}] RunCommand DENIED: allow_run_command=false",
                                config_index
                            );
                            continue;
                        }

                        // Tokenise without invoking a shell
                        let Some((program, args)) = tokenise_command(&command) else {
                            log::warn!("Script[{}] RunCommand DENIED: empty command", config_index);
                            continue;
                        };

                        // Command denylist check
                        if let Some(pattern) =
                            par_term_config::check_command_denylist(&program, &args)
                        {
                            log::error!(
                                "Script[{}] RunCommand DENIED: '{}' matches denylist \
                                     pattern '{}'",
                                config_index,
                                command,
                                pattern
                            );
                            continue;
                        }

                        // Rate limit check
                        if let Some(tab) = ws.tab_manager.active_tab_mut() {
                            let script_id =
                                tab.scripting.script_ids.get(config_index).and_then(|o| *o);
                            if let Some(sid) = script_id
                                && !tab
                                    .scripting
                                    .script_manager
                                    .check_run_command_rate(sid, rate_limit)
                            {
                                log::warn!(
                                    "Script[{}] RunCommand RATE-LIMITED: '{}'",
                                    config_index,
                                    command
                                );
                                continue;
                            }
                        }

                        crate::debug_info!(
                            "SCRIPT",
                            "AUDIT Script[{}] RunCommand program={} args={:?}",
                            config_index,
                            program,
                            args
                        );

                        match std::process::Command::new(&program)
                            .args(&args)
                            .stdout(Stdio::null())
                            .stderr(Stdio::null())
                            .spawn()
                        {
                            Ok(child) => {
                                log::debug!(
                                    "Script[{}] RunCommand spawned PID={}",
                                    config_index,
                                    child.id()
                                );
                            }
                            Err(e) => {
                                log::error!(
                                    "Script[{}] RunCommand failed to spawn '{}': {}",
                                    config_index,
                                    command,
                                    e
                                );
                            }
                        }
                    }

                    // ── ChangeConfig ────────────────────────────────────────────
                    PendingScriptAction::ChangeConfig {
                        key,
                        value,
                        config_index,
                    } => {
                        let allow = ws
                            .config
                            .scripts
                            .get(config_index)
                            .map(|s| s.allow_change_config)
                            .unwrap_or(false);

                        if !allow {
                            log::warn!(
                                "Script[{}] ChangeConfig DENIED: \
                                     allow_change_config=false",
                                config_index
                            );
                            continue;
                        }

                        Self::apply_script_config_change(ws, &key, &value, config_index);
                    }
                }
            }
        }

        // Pass 3 — Update settings window state
        if let Some(sw) = &mut self.settings_window {
            let running_changed = sw.settings_ui.script_running != running_state;
            let errors_changed = sw.settings_ui.script_errors != error_state;
            let has_new_output = new_output.iter().any(|lines| !lines.is_empty());
            let panels_changed = sw.settings_ui.script_panels != panel_state;

            if running_changed || errors_changed {
                crate::debug_info!(
                    "SCRIPT",
                    "sync: state change - running={:?} errors_changed={}",
                    running_state,
                    errors_changed
                );
            }

            let count = running_state.len();
            sw.settings_ui.script_output.resize_with(count, Vec::new);
            sw.settings_ui.script_output_expanded.resize(count, false);
            sw.settings_ui.script_panels.resize_with(count, || None);

            // Append new output lines, capping at max
            for (i, lines) in new_output.into_iter().enumerate() {
                if !lines.is_empty() {
                    let buf = &mut sw.settings_ui.script_output[i];
                    buf.extend(lines);
                    let overflow = buf.len().saturating_sub(Self::SCRIPT_OUTPUT_MAX_LINES);
                    if overflow > 0 {
                        buf.drain(..overflow);
                    }
                }
            }

            if running_changed || errors_changed || has_new_output || panels_changed {
                sw.settings_ui.script_running = running_state;
                sw.settings_ui.script_errors = error_state;
                sw.settings_ui.script_panels = panel_state;
                sw.request_redraw();
            }
        }
    }
}