Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

6.0 KB
Raw Blame
//! Settings › Advanced › "Let scripts read the open folders" (issue 690): the open windows, their tabs, each tab's folder and selection,
//! for the user's own scripts and launchers, read-only and off by default. The pipe is `rf_win::statepipe`; `rustyfiles --state` asks
//! it and prints the answer:
//!
//! ```json
//! {"version":1,"windows":[{"active":true,"active_tab":0,"tabs":[{"path":"C:\\Users\\me","kind":"folder","selection":["C:\\Users\\me\\a.txt"]}]}]}
//! ```
//!
//! A tab in dual pane gives its two panes as `path`/`selection` (the active one) and `other_path`/`other_selection`. A tab that is not
//! a folder (Home, the Recycle Bin, a search) has `"kind"` saying so and a `path` of `null` (a search gives the folder it searches).

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use gpui_kit::App;
use rf_core::history::Location;

/// Whether the switch is on now; the pipe, once started, answers only while it is.
static ON: AtomicBool = AtomicBool::new(false);
/// Whether the pipe was started in this process (it then lives as long as the process).
static STARTED: AtomicBool = AtomicBool::new(false);

/// The most selected paths given per pane: a selection of a whole drive must not make an answer of hundreds of megabytes.
const SELECTION_MOST: usize = 10_000;

/// Follows the setting: the pipe starts the first time it is on, and answers only while it is.
pub fn apply(on: bool, cx: &mut App) {
    ON.store(on, Ordering::Relaxed);
    if !on || STARTED.swap(true, Ordering::Relaxed) {
        return;
    }
    // the pipe's thread asks the interface's thread for each answer, and waits for it at most a moment
    let (tx, mut rx) = futures::channel::mpsc::unbounded::<std::sync::mpsc::Sender<String>>();
    let served = rf_win::statepipe::serve(move || {
        if !ON.load(Ordering::Relaxed) {
            return "{\"version\":1,\"enabled\":false}".to_string();
        }
        let (back, answer) = std::sync::mpsc::channel();
        if tx.unbounded_send(back).is_err() {
            return "{\"version\":1,\"error\":\"rustyfiles is closing\"}".to_string();
        }
        answer.recv_timeout(Duration::from_secs(2)).unwrap_or_else(|_| "{\"version\":1,\"error\":\"rustyfiles did not answer\"}".to_string())
    });
    if !served {
        log::warn!("state API: the pipe could not be started");
        STARTED.store(false, Ordering::Relaxed);
        return;
    }
    cx.spawn(async move |cx| {
        use futures::StreamExt;
        while let Some(back) = rx.next().await {
            let text = cx.update(|cx| json(cx));
            let _ = back.send(text);
        }
    })
    .detach();
}

fn kind_of(l: &Location) -> &'static str {
    match l {
        Location::Home => "home",
        Location::Path(_) => "folder",
        Location::RecycleBin => "recycle_bin",
        Location::Search { .. } => "search",
        Location::Settings => "settings",
        Location::Tag(_) => "tag",
        Location::Library { .. } => "library",
        Location::Shell { .. } => "shell",
        #[allow(unreachable_patterns)]
        _ => "other",
    }
}

/// The state as JSON (see the module docs).
pub fn json(cx: &mut App) -> String {
    use serde_json::{Value, json};
    let active_window = cx.active_window();
    let mut windows: Vec<Value> = Vec::new();
    for (handle, ws) in crate::workspace::open_workspaces(cx) {
        let Some(ws) = ws.upgrade() else { continue };
        let w = ws.read(cx);
        if w.is_picker() {
            continue;
        }
        let pane = |v: &gpui_kit::Entity<crate::folder_view::FolderView>, cx: &App| {
            let v = v.read(cx);
            let loc = v.location();
            let path = loc.path().map(|p| p.to_string_lossy().into_owned());
            let selection: Vec<String> = v.selection_paths().into_iter().take(SELECTION_MOST).map(|p| p.to_string_lossy().into_owned()).collect();
            (path, kind_of(loc), selection)
        };
        let tabs: Vec<Value> = w
            .tab_panes()
            .into_iter()
            .map(|(active, other)| {
                let (path, kind, selection) = pane(&active, cx);
                let mut t = json!({ "path": path, "kind": kind, "selection": selection });
                if let Some(o) = other {
                    let (op, ok, os) = pane(&o, cx);
                    t["other_path"] = json!(op);
                    t["other_kind"] = json!(ok);
                    t["other_selection"] = json!(os);
                }
                t
            })
            .collect();
        windows.push(json!({ "active": active_window == Some(handle), "active_tab": w.active_tab_index(), "tabs": tabs }));
    }
    json!({ "version": 1, "windows": windows }).to_string()
}

/// `rustyfiles --state`: prints the running rustyfiles' state and returns the exit code (0: printed; 1: none answered).
pub fn cli_main() -> i32 {
    match rf_win::statepipe::ask(Duration::from_secs(2)) {
        Some(text) => {
            write_out(&text);
            0
        }
        None => {
            write_out("{\"version\":1,\"error\":\"rustyfiles is not running, or Settings > Advanced > 'Let scripts read the open folders' is off\"}");
            1
        }
    }
}

/// Writes a line where the caller can read it: the redirected output when there is one (`rustyfiles --state > s.json`, a pipe into a
/// script), else the console of the terminal that started it (a windowed program has none of its own).
fn write_out(text: &str) {
    use std::io::Write;
    unsafe extern "system" {
        fn GetStdHandle(which: u32) -> isize;
        fn AttachConsole(pid: u32) -> i32;
    }
    const STD_OUTPUT: u32 = -11i32 as u32;
    const PARENT: u32 = u32::MAX;
    let redirected = unsafe { GetStdHandle(STD_OUTPUT) };
    if redirected != 0 && redirected != -1 {
        let mut out = std::io::stdout();
        let _ = writeln!(out, "{text}");
        let _ = out.flush();
        return;
    }
    if unsafe { AttachConsole(PARENT) } != 0
        && let Ok(mut con) = std::fs::OpenOptions::new().write(true).open("CONOUT$")
    {
        let _ = writeln!(con, "{text}");
    }
}