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.

17.4 KB
Raw Blame
//! Settings > Eklentiler: the add-ons rustyfiles can install (`addons.rs`), each with its version, licence and source, and Install,
//! Update and Remove. The list is read when the page is first shown (and with "Yeniden dene" after a failure); an install runs on a
//! thread of its own and says how far it is.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use gpui_kit::assets::IconName as L;
use gpui_kit::component::{h_flex, v_flex};
use gpui_kit::*;

use crate::addons::{self, AddonInfo, Manifest};
use crate::settings_view::{button, card, section};
use crate::t;
use crate::theme::Palette;

/// An install or update under way: the bytes so far and in all, and its cancel switch.
struct Busy {
    done: Arc<AtomicU64>,
    total: u64,
    cancel: Arc<AtomicBool>,
}

#[derive(Default)]
struct State {
    manifest: Option<Result<Manifest, String>>,
    loading: bool,
    busy: HashMap<String, Busy>,
    /// The last thing that went wrong with an add-on (shown under it until the next try).
    errors: HashMap<String, String>,
}

impl Global for State {}

fn state(cx: &mut App) -> &mut State {
    if !cx.has_global::<State>() {
        cx.set_global(State::default());
    }
    cx.global_mut::<State>()
}

fn load(cx: &mut App) {
    let st = state(cx);
    if st.loading {
        return;
    }
    st.loading = true;
    cx.spawn(async move |cx| {
        let got = cx.background_spawn(async { addons::fetch_manifest() }).await;
        cx.update(|cx| {
            let st = cx.global_mut::<State>();
            st.loading = false;
            st.manifest = Some(got);
            cx.refresh_windows();
        });
    })
    .detach();
}

/// What the add-on is for, in the user's language (the list's own words are English).
fn description(id: &str) -> Option<&'static str> {
    match id {
        "hyperdownload" => Some(t!("İndirme yöneticisi: bir dosyayı birçok bağlantıyla birden indirir, duraklatılıp kaldığı yerden sürdürülür; torrent ve magnet bağlantılarını da indirir")),
        _ => None,
    }
}

fn install(info: AddonInfo, cx: &mut App) {
    let id = info.id.clone();
    let done = Arc::new(AtomicU64::new(0));
    let cancel = Arc::new(AtomicBool::new(false));
    let total = info.file().map_or(0, |f| f.size);
    let st = state(cx);
    st.errors.remove(&id);
    st.busy.insert(id.clone(), Busy { done: done.clone(), total, cancel: cancel.clone() });
    // the page shows the progress: it is drawn again now and then while the install runs
    cx.spawn({
        let id = id.clone();
        async move |cx| {
            loop {
                cx.background_executor().timer(std::time::Duration::from_millis(250)).await;
                let going = cx.update(|cx| {
                    cx.refresh_windows();
                    cx.try_global::<State>().is_some_and(|s| s.busy.contains_key(&id))
                });
                if !going {
                    break;
                }
            }
        }
    })
    .detach();
    cx.spawn(async move |cx| {
        let (d, c) = (done.clone(), cancel.clone());
        let hd = info.id == crate::hyperdownload::ID;
        let got = cx
            .background_spawn(async move {
                let r = addons::install(&info, &|n, _| d.store(n, Ordering::Relaxed), &|| c.load(Ordering::Relaxed)).map(|_| ());
                // HyperDownload: the browsers learn where its host is
                if r.is_ok() && hd {
                    crate::hyperdownload::register_host();
                }
                r
            })
            .await;
        cx.update(|cx| {
            let st = cx.global_mut::<State>();
            st.busy.remove(&id);
            if let Err(e) = got {
                st.errors.insert(id, e);
            }
            cx.refresh_windows();
        });
    })
    .detach();
}

/// Removes an add-on: its running program is ended first, off the interface thread.
///
/// WHY (discussions 825 and 827: "clicking the Remove button did nothing ... I had to manually open Task Manager, locate the process,
/// and end the task before I could remove it"). HyperDownload keeps running in the background after a download, and a browser keeps
/// its host started from the same folder while the extension is on; Windows does not delete a program that is running, so the folder
/// stayed and the button only showed an error under the card. The add-on is asked to end (HyperDownload's own shutdown call, which
/// saves its list), and whatever still runs from its folder a moment later is ended.
fn remove(id: String, cx: &mut App) {
    let task = cx.background_spawn({
        let id = id.clone();
        async move {
            if id == crate::hyperdownload::ID {
                crate::hyperdownload::unregister_host();
                if let Some(rpc) = crate::hyperdownload::running() {
                    let _ = rpc.call("aria2.shutdown", vec![]);
                }
            }
            if let Some(dir) = addons::dir_of(&id) {
                let until = std::time::Instant::now() + std::time::Duration::from_secs(3);
                while std::time::Instant::now() < until && !rf_win::folder_procs::running_in(&dir).is_empty() {
                    std::thread::sleep(std::time::Duration::from_millis(100));
                }
                rf_win::folder_procs::end_in(&dir, std::time::Duration::from_secs(3));
            }
            addons::remove(&id)
        }
    });
    cx.spawn(async move |cx| {
        let got = task.await;
        let _ = cx.update(|cx| {
            let st = state(cx);
            match got {
                Ok(()) => {
                    st.errors.remove(&id);
                }
                Err(e) => {
                    st.errors.insert(id, format!("{}: {e}", t!("Kaldırılamadı (program açık olabilir)")));
                }
            }
            cx.refresh_windows();
        });
    })
    .detach();
}

fn open_url(url: String) {
    std::thread::spawn(move || {
        let _ = rf_win::shell::open(std::path::Path::new(&url));
    });
}

/// HyperDownload's folder for what the browsers hand it (HyperDownload issues 1 and 3). The browser's helper reads it from
/// `host.json`, written again at each change, so it holds from the next download on.
fn download_folder_card(p: &Palette, cx: &mut App) -> AnyElement {
    let s = cx.global::<crate::settings::Settings>();
    let custom = !s.hd_downloads.trim().is_empty();
    let shown = crate::hyperdownload::download_folder(s).map(|d| d.display().to_string()).unwrap_or_default();
    card(
        p,
        L::FolderDown,
        t!("İndirme klasörü"),
        Some(shown.as_str()),
        h_flex()
            .gap_2()
            .children(custom.then(|| {
                button("hd-downloads-reset", p, t!("Varsayılan"), |_, cx| {
                    crate::settings::update(cx, |s| s.hd_downloads.clear());
                    // (off this thread: the registration waits a moment for the add-on's own)
                    let now = cx.global::<crate::settings::Settings>().clone();
                    cx.background_spawn(async move { crate::hyperdownload::register_host_with(&now) }).detach();
                })
            }))
            .child(button("hd-downloads", p, t!("Değiştir…"), |_, cx| {
                let (tx, rx) = futures::channel::oneshot::channel::<Option<std::path::PathBuf>>();
                let title = t!("İndirmelerin klasörünü seçin");
                rf_win::sta::run(move |owner| {
                    let _ = tx.send(rf_win::dialogs::pick(owner, title, rf_win::dialogs::Pick::Folder));
                });
                cx.spawn(async move |cx| {
                    if let Ok(Some(path)) = rx.await {
                        let _ = cx.update(|cx| {
                            crate::settings::update(cx, |s| s.hd_downloads = path.to_string_lossy().into_owned());
                            let now = cx.global::<crate::settings::Settings>().clone();
                            cx.background_spawn(async move { crate::hyperdownload::register_host_with(&now) }).detach();
                        });
                    }
                })
                .detach();
            }))
            .into_any_element(),
    )
}

/// The key of an add-on's browser extension in the page's state (what is busy, what went wrong).
fn extension_key(id: &str) -> String {
    format!("{id}-extension")
}

/// HyperDownload's browser extension, which is not in the browsers' stores yet and so is loaded by hand. What can be done for
/// the user is done here: the extension's folder is put ready (downloaded, checked against the list's SHA-256, in a place that
/// stays), its path is copied, and the browser is opened. The rest is theirs there (the extensions page, Developer mode, "Load
/// unpacked", paste): a browser lets no program add an extension for it, and Chrome does not even open `chrome://extensions`
/// when it is named on its command line (tried 2026-12-05: a new tab came up instead), so the card says the address to type.
///
/// WHY (Discord, 2026-12-04: "i can't load the unpacked extension", after choosing the repository's folder instead of the one
/// inside it; the user: "there is no way to install the extension in HyperDownload's settings").
fn extension_card(info: &AddonInfo, p: &Palette, cx: &mut App) -> Option<AnyElement> {
    info.extension.as_ref()?;
    let key = extension_key(&info.id);
    let busy = state(cx).busy.contains_key(&key);
    let error = state(cx).errors.get(&key).cloned();
    let mut desc = t!("Tarayıcının indirmelerini HyperDownload'a verir. Henüz mağazalarda değil, elle yüklenir: tarayıcınızın düğmesine basın (klasör hazırlanır, yolu panoya kopyalanır, tarayıcı açılır). Tarayıcıda adres çubuğuna chrome://extensions yazın (Edge: edge://extensions, Brave: brave://extensions), Geliştirici modunu açın, \"Paketlenmemiş öğe yükle\"ye basın ve klasör kutusuna yolu yapıştırın.").to_string();
    if let (Some(v), Some(dir)) = (addons::extension_version(&info.id), addons::extension_dir(&info.id)) {
        desc.push('\n');
        desc.push_str(&format!("{} {v} · {}", t!("Hazır olan sürüm:"), dir.display()));
    }
    if let Some(e) = &error {
        desc.push('\n');
        desc.push_str(e);
    }
    let browsers = crate::hyperdownload::browsers();
    if browsers.is_empty() {
        desc.push('\n');
        desc.push_str(t!("Chrome, Edge ya da Brave bulunamadı."));
    }
    let control: AnyElement = if busy {
        div().text_sm().text_color(p.text_secondary).child(t!("Hazırlanıyor…")).into_any_element()
    } else {
        let mut row = h_flex().gap_2();
        for b in browsers {
            let (info, exe) = (info.clone(), b.exe);
            row = row.child(button(SharedString::from(format!("hd-extension-{}", b.name)), p, b.name, move |_, cx| load_extension(info.clone(), exe.clone(), cx)));
        }
        row.into_any_element()
    };
    Some(card(p, L::Puzzle, t!("Tarayıcı uzantısı"), Some(&desc), control))
}

/// A browser's button of [`extension_card`]: the folder ready (as it is when it already is this version's), its path on the
/// clipboard, the browser open.
fn load_extension(info: AddonInfo, exe: std::path::PathBuf, cx: &mut App) {
    let key = extension_key(&info.id);
    let st = state(cx);
    st.errors.remove(&key);
    st.busy.insert(key.clone(), Busy { done: Arc::new(AtomicU64::new(0)), total: 0, cancel: Arc::new(AtomicBool::new(false)) });
    cx.refresh_windows();
    cx.spawn(async move |cx| {
        let got = cx
            .background_spawn(async move {
                match (addons::extension_version(&info.id), addons::extension_dir(&info.id)) {
                    (Some(v), Some(dir)) if v == info.version => Ok(dir),
                    _ => addons::install_extension(&info, &|| false),
                }
            })
            .await;
        cx.update(|cx| {
            let failed = match got {
                Ok(dir) => {
                    cx.write_to_clipboard(ClipboardItem::new_string(dir.to_string_lossy().into_owned()));
                    std::process::Command::new(&exe).spawn().err().map(|e| format!("{}: {e}", exe.display()))
                }
                Err(e) => Some(e),
            };
            let st = cx.global_mut::<State>();
            st.busy.remove(&key);
            if let Some(e) = failed {
                st.errors.insert(key, e);
            }
            cx.refresh_windows();
        });
    })
    .detach();
}

pub fn page(p: &Palette, cx: &mut App) -> Vec<AnyElement> {
    if state(cx).manifest.is_none() {
        load(cx);
    }
    let mut out: Vec<AnyElement> = vec![
        div()
            .text_sm()
            .text_color(p.text_secondary)
            .child(t!("Eklentiler rustyfiles'a ayrı programlar olarak eklenir: yalnızca siz kurunca indirilir, rustyfiles'ın listesindeki parmak iziyle (SHA-256) denetlenir ve istediğiniz zaman kaldırılır."))
            .into_any_element(),
    ];
    let st = state(cx);
    let manifest = match &st.manifest {
        None => {
            out.push(div().pt_3().text_sm().text_color(p.text_secondary).child(t!("Eklenti listesi okunuyor…")).into_any_element());
            return out;
        }
        Some(Err(e)) => {
            let e = e.clone();
            out.push(card(p, L::CircleAlert, t!("Eklenti listesi okunamadı"), Some(&e), button("addons-retry", p, t!("Yeniden dene"), |_, cx| {
                state(cx).manifest = None;
                load(cx);
            })));
            return out;
        }
        Some(Ok(m)) => m.clone(),
    };
    out.push(section(p, t!("Kullanılabilir")));
    if manifest.addons.is_empty() {
        out.push(div().text_sm().text_color(p.text_secondary).child(t!("Şu an kurulabilecek bir eklenti yok.")).into_any_element());
    }
    for info in manifest.addons {
        let id = info.id.clone();
        let have = addons::installed(&id);
        let busy = state(cx).busy.get(&id).map(|b| (b.done.load(Ordering::Relaxed), b.total, b.cancel.clone()));
        let error = state(cx).errors.get(&id).cloned();
        let available = info.file().is_some();
        let mut facts = Vec::new();
        match &have {
            Some(h) => facts.push(format!("{} {}", t!("Kurulu:"), h.version)),
            None => facts.push(format!("{} {}", t!("Sürüm:"), info.version)),
        }
        if let Some(h) = &have
            && addons::newer(&info.version, &h.version)
        {
            facts.push(format!("{} {}", t!("Yeni sürüm:"), info.version));
        }
        facts.push(info.license.clone());
        if let Some(f) = info.file().filter(|f| f.size > 0) {
            facts.push(format!("{:.1} MB", f.size as f64 / 1e6));
        }
        let mut desc = description(&id).map(str::to_string).unwrap_or_default();
        if !desc.is_empty() {
            desc.push('\n');
        }
        desc.push_str(&facts.join(" · "));
        if let Some(e) = &error {
            desc.push('\n');
            desc.push_str(e);
        }
        if !available {
            desc.push('\n');
            desc.push_str(t!("Bu işlemci için henüz bir sürümü yok."));
        }
        let control: AnyElement = match (busy, &have) {
            (Some((done, total, cancel)), _) => {
                let text = if total > 0 { format!("{} {}%", t!("İndiriliyor"), (done * 100 / total.max(1)).min(100)) } else { format!("{} {:.1} MB", t!("İndiriliyor"), done as f64 / 1e6) };
                h_flex()
                    .gap_2()
                    .items_center()
                    .child(div().text_sm().text_color(p.text_secondary).child(text))
                    .child(button(SharedString::from(format!("addon-cancel-{id}")), p, t!("İptal"), move |_, _| cancel.store(true, Ordering::Relaxed)))
                    .into_any_element()
            }
            (None, Some(h)) => {
                let mut row = h_flex().gap_2();
                if available && addons::newer(&info.version, &h.version) {
                    let i = info.clone();
                    row = row.child(button(SharedString::from(format!("addon-update-{id}")), p, t!("Güncelle"), move |_, cx| install(i.clone(), cx)));
                }
                let rid = id.clone();
                row.child(button(SharedString::from(format!("addon-remove-{id}")), p, t!("Kaldır"), move |_, cx| remove(rid.clone(), cx))).into_any_element()
            }
            (None, None) if available => {
                let i = info.clone();
                button(SharedString::from(format!("addon-install-{id}")), p, t!("Kur"), move |_, cx| install(i.clone(), cx))
            }
            (None, None) => div().into_any_element(),
        };
        out.push(card(p, L::Download, &info.name, Some(&desc), control));
        if id == crate::hyperdownload::ID && have.is_some() {
            out.push(download_folder_card(p, cx));
            out.extend(extension_card(&info, p, cx));
        }
        let source = info.source.clone();
        if !source.is_empty() {
            out.push(
                div()
                    .id(SharedString::from(format!("addon-source-{id}")))
                    .pl_4()
                    .pt_1()
                    .text_xs()
                    .text_color(p.accent)
                    .cursor_pointer()
                    .hover(|s| s.underline())
                    .child(format!("{} {}", t!("Kaynak kodu:"), source))
                    .on_click(move |_, _, _| open_url(source.clone()))
                    .into_any_element(),
            );
        }
    }
    let _ = v_flex;
    out
}