par-term 0.38.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
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
//! File transfer handling for downloads and uploads.
//!
//! This module manages file transfer state, processes completed downloads via
//! native save dialogs, handles upload requests via native file pickers, and
//! renders an egui progress overlay for active transfers.
//!
//! Organized into four sub-layers:
//! - `types`   — data structures (`FileTransferState`, `TransferInfo`, etc.)
//! - `overlay` — egui overlay rendering (`render_file_transfer_overlay`)
//! - `upload`  — upload dialog, background upload thread, tar.gz helper
//! - `mod`     — `WindowState` impl methods (poll, save dialog, download)

mod overlay;
mod types;
mod upload;

pub(crate) use overlay::render_file_transfer_overlay;
pub(crate) use types::{
    FileTransferState, PendingSave, PendingUpload, RecentTransfer, TransferInfo,
};

use std::path::PathBuf;
use std::sync::atomic::Ordering;

use par_term_emu_core_rust::terminal::file_transfer::{
    FileTransfer, TransferDirection, TransferStatus,
};

use super::window_state::WindowState;
use crate::config::DownloadSaveLocation;

/// Chunk size for writing upload data to the PTY.
/// Matches typical macOS PTY buffer size for efficient writes.
const UPLOAD_CHUNK_SIZE: usize = 65536;

/// How long to show the overlay before opening the save dialog (ms).
/// Gives the egui overlay time to render before the blocking dialog steals focus.
const SAVE_DIALOG_DELAY_MS: u64 = 750;

/// How long to show completed transfers in the overlay (seconds).
const RECENT_TRANSFER_DISPLAY_SECS: u64 = 3;

/// Format a byte count as a human-readable string
pub(super) fn format_bytes(bytes: usize) -> String {
    if bytes < 1024 {
        format!("{} B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    }
}

/// Reduce a remote-supplied download filename to a bare basename (SEC-010).
///
/// The OSC 1337 `File=name=` value is chosen by whatever is on the other end of
/// the PTY, and `rfd` *joins* it onto the dialog's directory: `../../.ssh/x`
/// escapes that directory and an absolute name replaces it outright, letting
/// the remote aim the save panel wherever it likes. `upload.rs` already reduces
/// picked files this way; downloads must do the same.
///
/// Returns `None` when the name has no file component at all (empty, `.`, `..`,
/// or a bare separator) — the caller rejects rather than inventing a name.
fn sanitize_download_filename(name: &str) -> Option<String> {
    let base = std::path::Path::new(name)
        .file_name()?
        .to_string_lossy()
        .to_string();
    if base.is_empty() || base == "." || base == ".." {
        return None;
    }
    Some(base)
}

/// Extract UI transfer info from a core `FileTransfer`
fn transfer_to_info(ft: &FileTransfer) -> TransferInfo {
    let (bytes_transferred, total_bytes) = match &ft.status {
        TransferStatus::InProgress {
            bytes_transferred,
            total_bytes,
        } => (*bytes_transferred, *total_bytes),
        TransferStatus::Completed => (ft.data.len(), Some(ft.data.len())),
        _ => (0, None),
    };

    TransferInfo {
        filename: if ft.filename.is_empty() {
            format!("transfer-{}", ft.id)
        } else {
            ft.filename.clone()
        },
        direction: ft.direction,
        bytes_transferred,
        total_bytes,
    }
}

impl WindowState {
    /// Poll terminal for file transfer events each frame.
    ///
    /// Called from `about_to_wait()` to:
    /// - Update active transfer list for the progress overlay
    /// - Collect completed downloads for save dialogs
    /// - Collect upload requests for file pickers
    /// - Notify on failures
    /// - Track background upload progress
    /// - Process pending save/upload dialogs
    pub(crate) fn check_file_transfers(&mut self) {
        let tab = if let Some(t) = self.tab_manager.active_tab() {
            t
        } else {
            return;
        };

        // Always clear active_transfers before rebuilding — this must happen outside
        // the try_lock block so it's reset even when the terminal is locked by the
        // upload thread. poll_active_uploads will re-add upload entries below.
        self.file_transfer_state.active_transfers.clear();

        // try_lock: intentional — file transfer polling in about_to_wait (sync event loop).
        // On miss: active_transfers stays cleared (cleared above) and no transfer progress
        // is shown for this frame. The overlay will be repopulated on the next poll.
        if let Ok(term) = tab.terminal.try_read() {
            // 1. Update active transfers for overlay (terminal-side transfers like downloads)
            let active = term.get_active_transfers();
            self.file_transfer_state
                .active_transfers
                .extend(active.iter().map(transfer_to_info));

            // 2. Check for completed downloads
            let completed = term.get_completed_transfers();
            let completed_ids: Vec<u64> = completed
                .iter()
                .filter(|ft| {
                    ft.direction == TransferDirection::Download
                        && ft.status == TransferStatus::Completed
                })
                .map(|ft| ft.id)
                .collect();

            // Drop the lock before taking completed transfers (needs &self not &mut)
            drop(term);

            // Take each completed download and queue for save dialog
            let terminal_arc = std::sync::Arc::clone(&tab.terminal);
            for id in completed_ids {
                // try_lock: intentional — taking a completed download from the terminal in
                // a spawned async task using sync try_lock. On miss: the completed transfer
                // is not taken this iteration; it will be picked up on the next poll.
                if let Ok(term) = terminal_arc.try_read()
                    && let Some(ft) = term.take_completed_transfer(id)
                {
                    let raw_filename = if ft.filename.is_empty() {
                        format!("download-{}", ft.id)
                    } else {
                        ft.filename.clone()
                    };
                    // SEC-010: reduce to a basename before the name reaches the
                    // save dialog, the notification, or the transfer list.
                    let filename = match sanitize_download_filename(&raw_filename) {
                        Some(name) => name,
                        None => {
                            crate::debug_info!(
                                "FILE_TRANSFER",
                                "[SEC-010] rejecting download with unusable filename {:?}",
                                raw_filename
                            );
                            self.deliver_notification(
                                "Download Rejected",
                                &format!("Remote sent an invalid filename: {}", raw_filename),
                            );
                            continue;
                        }
                    };
                    if filename != raw_filename {
                        crate::debug_info!(
                            "FILE_TRANSFER",
                            "[SEC-010] reduced remote filename {:?} to {:?}",
                            raw_filename,
                            filename
                        );
                    }
                    crate::debug_info!(
                        "FILE_TRANSFER",
                        "Download completed: {} ({} bytes)",
                        filename,
                        ft.data.len()
                    );
                    let size = ft.data.len();
                    self.file_transfer_state
                        .pending_saves
                        .push_back(PendingSave {
                            filename: filename.clone(),
                            data: ft.data,
                        });
                    self.file_transfer_state
                        .recent_transfers
                        .push(RecentTransfer {
                            filename: filename.clone(),
                            size,
                            direction: TransferDirection::Download,
                            completed_at: std::time::Instant::now(),
                        });
                    self.file_transfer_state.last_completion_time = Some(std::time::Instant::now());
                    self.deliver_notification(
                        "Download Received",
                        &format!("Received {} ({})", filename, format_bytes(size)),
                    );
                }
            }

            // 3. Check for failed transfers and notify
            // try_lock: intentional — checking for failed transfers in a spawned async task.
            // On miss: failure detection is deferred to the next poll iteration. No data lost.
            if let Ok(term) = terminal_arc.try_read() {
                let failed: Vec<(u64, String)> = term
                    .get_completed_transfers()
                    .iter()
                    .filter_map(|ft| {
                        if let TransferStatus::Failed(reason) = &ft.status {
                            Some((ft.id, reason.clone()))
                        } else {
                            None
                        }
                    })
                    .collect();

                // Take failed transfers to consume them
                drop(term);
                for (id, reason) in &failed {
                    // QA-026: the notification belongs inside the same gate that
                    // consumes the transfer. A `try_read()` miss — or an entry a
                    // concurrent path already took — leaves the failure in the
                    // core's completed list, so notifying unconditionally re-fires
                    // for the same failure on the next poll, and the next. There is
                    // no dedupe in `deliver_notification`, and this runs once per
                    // event-loop iteration, so the symptom is a desktop-notification
                    // storm at frame rate (plus an overlay timer that never expires,
                    // because `last_completion_time` is refreshed each repeat) —
                    // not a single duplicate.
                    let consumed = terminal_arc
                        .try_read()
                        .is_ok_and(|term| term.take_completed_transfer(*id).is_some());
                    if !consumed {
                        continue;
                    }
                    self.deliver_notification(
                        "File Transfer Failed",
                        &format!("Transfer failed: {}", reason),
                    );
                    self.file_transfer_state.last_completion_time = Some(std::time::Instant::now());
                }
            }

            // 4. Poll for upload requests
            // try_lock: intentional — upload request polling in spawned async task.
            // On miss: upload requests are deferred to the next poll. No user data is lost.
            if let Ok(term) = terminal_arc.try_read() {
                let upload_requests = term.poll_upload_requests();
                for _format in upload_requests {
                    self.file_transfer_state
                        .pending_uploads
                        .push_back(PendingUpload {});
                    self.deliver_notification(
                        "Upload Requested",
                        "Remote application is requesting a file upload",
                    );
                }
            }
        }

        // 5. Expire old recent transfers
        self.file_transfer_state.recent_transfers.retain(|t| {
            t.completed_at.elapsed() < std::time::Duration::from_secs(RECENT_TRANSFER_DISPLAY_SECS)
        });
        if !self.file_transfer_state.recent_transfers.is_empty() {
            self.request_redraw();
        }

        // 6. Track background upload progress
        self.poll_active_uploads();

        // 7. Process pending save/upload dialogs (outside the terminal lock)
        // Delay save dialogs briefly so the transfer overlay has time to render
        // before the blocking native dialog steals focus.
        if !self.file_transfer_state.dialog_open {
            let save_ready = self.file_transfer_state.pending_saves.front().is_some()
                && self
                    .file_transfer_state
                    .last_completion_time
                    .is_some_and(|t| {
                        t.elapsed() >= std::time::Duration::from_millis(SAVE_DIALOG_DELAY_MS)
                    });

            if save_ready {
                if let Some(pending) = self.file_transfer_state.pending_saves.pop_front() {
                    self.process_save_dialog(pending);
                    // Refresh recent transfer timers so overlay stays visible
                    // after the blocking dialog returns
                    let now = std::time::Instant::now();
                    for t in &mut self.file_transfer_state.recent_transfers {
                        t.completed_at = now;
                    }
                    self.file_transfer_state.last_completion_time = Some(now);
                }
            } else if self.file_transfer_state.pending_saves.front().is_some() {
                // Keep redrawing while waiting for the delay
                self.request_redraw();
            } else if let Some(pending) = self.file_transfer_state.pending_uploads.pop_front() {
                self.process_upload_dialog(pending);
            }
        }
    }

    /// Check background upload threads for progress and completion.
    fn poll_active_uploads(&mut self) {
        // Collect completed uploads and their results
        let mut completed_info: Vec<(String, usize, Option<String>)> = Vec::new();
        self.file_transfer_state.active_uploads.retain(|upload| {
            if upload.completed.load(Ordering::Relaxed) {
                let error = upload.error.lock().take();
                completed_info.push((upload.filename.clone(), upload.file_size, error));
                false
            } else {
                true
            }
        });

        // Notify for completed uploads and add to recent transfers
        for (filename, file_size, error) in completed_info {
            if let Some(e) = error {
                self.deliver_notification("Upload Failed", &e);
            } else {
                self.file_transfer_state
                    .recent_transfers
                    .push(RecentTransfer {
                        filename: filename.clone(),
                        size: file_size,
                        direction: TransferDirection::Upload,
                        completed_at: std::time::Instant::now(),
                    });
                self.deliver_notification(
                    "Upload Complete",
                    &format!("Uploaded {} ({})", filename, format_bytes(file_size)),
                );
            }
            self.file_transfer_state.last_completion_time = Some(std::time::Instant::now());
        }

        // Add active upload progress to the transfer overlay
        for upload in &self.file_transfer_state.active_uploads {
            let wire_written = upload.bytes_written.load(Ordering::Relaxed);
            // Map wire bytes back to file-size proportion for display
            let bytes_transferred = if upload.total_wire_bytes > 0 {
                ((wire_written as f64 / upload.total_wire_bytes as f64) * upload.file_size as f64)
                    as usize
            } else {
                0
            };

            self.file_transfer_state
                .active_transfers
                .push(TransferInfo {
                    filename: upload.filename.clone(),
                    direction: TransferDirection::Upload,
                    bytes_transferred,
                    total_bytes: Some(upload.file_size),
                });
        }

        // Redraws during active uploads are managed by about_to_wait's
        // file transfer progress section (section 8) for proper scheduling.
    }

    /// Show a native save dialog for a completed download and write the file.
    fn process_save_dialog(&mut self, pending: PendingSave) {
        // SEC-010: `set_file_name` is joined onto the dialog directory, so the
        // name must be a bare basename. Enforced here at the sink as well as at
        // ingest, because this is the call `rfd` actually resolves.
        let Some(safe_name) = sanitize_download_filename(&pending.filename) else {
            crate::debug_info!(
                "FILE_TRANSFER",
                "[SEC-010] refusing save dialog for unusable filename {:?}",
                pending.filename
            );
            self.deliver_notification(
                "Download Save Failed",
                &format!("Remote sent an invalid filename: {}", pending.filename),
            );
            return;
        };

        self.file_transfer_state.dialog_open = true;

        let default_dir = self.resolve_download_directory();

        let mut dialog = rfd::FileDialog::new().set_file_name(&safe_name);

        if let Some(dir) = &default_dir {
            dialog = dialog.set_directory(dir);
        }

        let result = dialog.save_file();

        self.file_transfer_state.dialog_open = false;

        if let Some(path) = result {
            match std::fs::write(&path, &pending.data) {
                Ok(()) => {
                    let size_str = format_bytes(pending.data.len());
                    crate::debug_info!(
                        "FILE_TRANSFER",
                        "Saved download to: {} ({})",
                        path.display(),
                        size_str
                    );
                    self.deliver_notification(
                        "Download Saved",
                        &format!(
                            "Saved {} to {} ({})",
                            pending.filename,
                            path.display(),
                            size_str
                        ),
                    );

                    // Update last_download_directory for LastUsed config option
                    if let Some(parent) = path.parent() {
                        self.config.rcu(|old| {
                            let mut new = (**old).clone();
                            new.last_download_directory =
                                Some(parent.to_string_lossy().to_string());
                            std::sync::Arc::new(new)
                        });
                    }
                }
                Err(e) => {
                    crate::debug_info!("FILE_TRANSFER", "Failed to save download: {}", e);
                    self.deliver_notification(
                        "Download Save Failed",
                        &format!("Failed to save {}: {}", pending.filename, e),
                    );
                }
            }
        } else {
            crate::debug_info!(
                "FILE_TRANSFER",
                "Save dialog cancelled for {}",
                pending.filename
            );
        }
    }

    /// Resolve the default download directory based on config settings.
    fn resolve_download_directory(&self) -> Option<PathBuf> {
        match &self.config.load().download_save_location {
            DownloadSaveLocation::Downloads => dirs::download_dir(),
            DownloadSaveLocation::LastUsed => self
                .config
                .load()
                .last_download_directory
                .as_ref()
                .map(PathBuf::from)
                .or_else(dirs::download_dir),
            DownloadSaveLocation::Cwd => {
                // Try to get CWD from shell integration
                // try_lock: intentional — getting download save path in sync event loop.
                // On miss: falls through to the Downloads fallback below. Acceptable UX.
                if let Some(tab) = self.tab_manager.active_tab()
                    && let Ok(term) = tab.terminal.try_read()
                    && let Some(cwd) = term.shell_integration_cwd()
                {
                    // SEC-010: the shell-integration CWD comes from OSC 7, which
                    // the remote end controls. Without this it would supply the
                    // dialog's base directory as well as the filename. Resolve
                    // symlinks and `..` and require a real directory; anything
                    // else falls back to Downloads.
                    match std::fs::canonicalize(&cwd) {
                        Ok(dir) if dir.is_dir() => return Some(dir),
                        _ => {
                            crate::debug_info!(
                                "FILE_TRANSFER",
                                "[SEC-010] ignoring OSC 7 cwd {:?}: not a resolvable directory",
                                cwd
                            );
                        }
                    }
                }
                // Fall back to Downloads if CWD not available
                dirs::download_dir()
            }
            DownloadSaveLocation::Custom(path) => {
                let p = PathBuf::from(path);
                if p.is_dir() {
                    Some(p)
                } else {
                    dirs::download_dir()
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::sanitize_download_filename;

    #[test]
    fn traversal_and_absolute_names_reduce_to_a_basename() {
        assert_eq!(
            sanitize_download_filename("../../.ssh/authorized_keys").as_deref(),
            Some("authorized_keys")
        );
        assert_eq!(
            sanitize_download_filename("/etc/passwd").as_deref(),
            Some("passwd")
        );
        assert_eq!(
            sanitize_download_filename("../../../../../../tmp/x.sh").as_deref(),
            Some("x.sh")
        );
    }

    #[test]
    fn ordinary_names_pass_through_unchanged() {
        assert_eq!(
            sanitize_download_filename("report.pdf").as_deref(),
            Some("report.pdf")
        );
        assert_eq!(
            sanitize_download_filename("my file (1).tar.gz").as_deref(),
            Some("my file (1).tar.gz")
        );
    }

    #[test]
    fn names_without_a_file_component_are_rejected() {
        assert_eq!(sanitize_download_filename(""), None);
        assert_eq!(sanitize_download_filename("."), None);
        assert_eq!(sanitize_download_filename(".."), None);
        assert_eq!(sanitize_download_filename("/"), None);
        assert_eq!(sanitize_download_filename("../.."), None);
    }
}