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.

11.6 KB
Raw Blame
//! DirectLook programının girişi: ayrı süreç, kendi tek örnek borusu, kendi bildirim alanı simgesi.
//! rustyfiles'tan iletiler (`ipc::Msg`) ve isteğe bağlı sistem geneli klavye kancasıyla çalışır.
//! rustyfiles'ın `settings.toml`'undan yalnız dil ve temayı okur, hiç yazmaz.

use gpui_kit::*;

use super::config::LookSettings;
use super::ipc::{Msg, ToApp, app_name};
use super::{LookManager, ShowOpts};

/// Açılış argümanları: `--msg <ileti>` (rustyfiles), `--look <yol> [top,pin]` (komut satırı),
/// `--background` (Windows'la başlama, ön ısıtma).
pub fn parse_args(args: &[&str]) -> Msg {
    match args.first().copied() {
        Some("--msg") => args.get(1).and_then(|m| Msg::decode(m)).unwrap_or(Msg::Wake),
        Some("--look") => match super::system::parse_look_args(args) {
            Some((p, o)) => Msg::Show(p, o),
            None => Msg::Wake,
        },
        // yalnız bir yol: göster
        Some(p) if !p.starts_with("--") => Msg::Show(p.into(), ShowOpts::default()),
        _ => Msg::Wake,
    }
}

fn tray_labels() -> rf_win::tray::Labels {
    rf_win::tray::Labels {
        tooltip: "DirectLook".into(),
        open: crate::t!("DirectLook ayarları").into(),
        new_window: String::new(),
        settings: String::new(),
        quit: crate::t!("Çıkış").into(),
    }
}

/// An arrow key: tells rustyfiles to move its selection by one (see `ToApp::Step`). Nothing happens when rustyfiles is not running
/// or the preview was not opened from it: it then has no list to step through.
pub(crate) fn step(forward: bool) {
    std::thread::spawn(move || {
        let _ = rf_win::single_instance::send_to(&rf_win::single_instance::instance_name(), &ToApp::Step(forward).encode());
    });
}

/// Ayarlar sayfasını rustyfiles'ta açar (çalışmıyorsa başlatır).
fn open_settings() {
    std::thread::spawn(|| {
        if rf_win::single_instance::send_to(&rf_win::single_instance::instance_name(), &ToApp::OpenSettings.encode()) {
            return;
        }
        if let Ok(me) = std::env::current_exe() {
            let _ = std::process::Command::new(me.with_file_name("rustyfiles.exe")).arg("--settings=directlook").spawn();
        }
    });
}

/// DirectLook's own icon: when its setting is on and rustyfiles has none (rustyfiles running in
/// the background has one, with the settings in its menu): one icon, not two. `app_has_icon`: rustyfiles' icon is there now (its
/// sign, `background::tray_sign`); the setting alone left no icon at all once rustyfiles had quit with background mode on.
fn tray_wanted(own_setting: bool, app_has_icon: bool) -> bool {
    own_setting && !app_has_icon
}

/// The word that the icon is to be looked at again reaches the app through this (the wait below runs on a thread of its own).
static AGAIN: std::sync::OnceLock<futures::channel::mpsc::UnboundedSender<Msg>> = std::sync::OnceLock::new();

#[derive(Default)]
struct PngSaves {
    pending: usize,
    quit_requested: bool,
}

impl Global for PngSaves {}

impl PngSaves {
    fn request_quit(&mut self) -> bool {
        self.quit_requested = self.pending != 0;
        !self.quit_requested
    }

    fn finish(&mut self) -> bool {
        self.pending -= 1;
        self.pending == 0 && std::mem::take(&mut self.quit_requested)
    }
}

pub(super) fn png_save_started(cx: &mut App) {
    cx.default_global::<PngSaves>().pending += 1;
}

pub(super) fn png_save_finished(cx: &mut App) {
    if cx.default_global::<PngSaves>().finish() {
        quit(cx);
    }
}

fn quit(cx: &mut App) {
    rf_win::tray::hide();
    cx.quit();
}

fn sync_tray(cx: &App) {
    let sign = crate::background::tray_sign();
    let app_has_icon = rf_win::single_instance::is_announced(&sign);
    if tray_wanted(cx.global::<LookSettings>().look_tray_icon, app_has_icon) {
        rf_win::tray::show(tray_labels());
    } else {
        rf_win::tray::hide();
    }
    if app_has_icon {
        // one thread sleeps until rustyfiles' icon is gone (it quit, crashed, or background mode was turned off), then ours is
        // looked at again; no polling
        static WAITING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
        if !WAITING.swap(true, std::sync::atomic::Ordering::AcqRel) {
            std::thread::spawn(move || {
                rf_win::single_instance::wait_until_gone(&sign);
                // (never a tight loop, whatever the other side does)
                std::thread::sleep(std::time::Duration::from_millis(300));
                WAITING.store(false, std::sync::atomic::Ordering::Release);
                if let Some(tx) = AGAIN.get() {
                    let _ = tx.unbounded_send(Msg::TrayAgain);
                }
            });
        }
    }
}

fn handle(msg: Msg, cx: &mut App) {
    match msg {
        Msg::Show(p, o) => LookManager::show(p, o, cx),
        Msg::Toggle(p) => {
            if LookManager::is_visible(cx) {
                LookManager::close(cx);
            } else {
                super::system::app_source(cx);
                super::system::show_filtered(p, ShowOpts::default(), cx);
            }
        }
        Msg::Follow(p) => {
            if LookManager::is_visible(cx) {
                LookManager::switch(p, cx);
            }
        }
        Msg::Close => LookManager::close(cx),
        Msg::Reload => {
            cx.set_global(LookSettings::load());
            // rustyfiles' settings too: language, theme, and whether it has a tray icon
            let settings = crate::settings::Settings::load();
            let explorer_theme_changed = cx.global::<crate::settings::Settings>().windows_file_explorer_theme != settings.windows_file_explorer_theme;
            cx.set_global(settings);
            if explorer_theme_changed {
                cx.refresh_windows();
            }
            sync_tray(cx);
        }
        Msg::Quit => {
            // A standalone rustyfiles picker can send Quit as it hands back the save path.
            if cx.default_global::<PngSaves>().request_quit() {
                quit(cx);
            } else {
                log::debug!("look: waiting for pending PNG saves before quitting");
            }
        }
        Msg::Wake => {}
        Msg::TrayAgain => sync_tray(cx),
    }
}

/// directlook.exe
pub fn main() {
    // (not in the installation folder: see `rf_win::ownfolder`)
    rf_win::ownfolder::leave();
    crate::install_panic_log();
    rf_win::shell::suppress_critical_error_dialogs();
    rf_win::thumbs::keep_gdiplus_alive();
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).target(env_logger::Target::Stderr).init();
    crate::background::DIRECTLOOK_PROCESS.store(true, std::sync::atomic::Ordering::Relaxed);

    let raw: Vec<String> = std::env::args().skip(1).collect();
    let first = parse_args(&raw.iter().map(String::as_str).collect::<Vec<_>>());
    let _instance = match rf_win::single_instance::acquire_app(&app_name(), &first.encode()) {
        rf_win::single_instance::Role::Forwarded => return,
        rf_win::single_instance::Role::Primary(g) => g,
    };
    let (tx, mut rx) = futures::channel::mpsc::unbounded::<Msg>();
    let _ = AGAIN.set(tx.clone());
    {
        let tx = tx.clone();
        rf_win::single_instance::serve_app(&app_name(), move |m| {
            if let Some(msg) = Msg::decode(&m) {
                let _ = tx.unbounded_send(msg);
            }
        });
    }
    let (tray_tx, mut tray_rx) = futures::channel::mpsc::unbounded::<rf_win::tray::TrayEvent>();
    rf_win::tray::set_handler(move |e| {
        let _ = tray_tx.unbounded_send(e);
    });

    // (DirectLook opens on the card: the fast start is for the file manager's own window only, see `fast_start::before_app`)
    crate::fast_start::before_app(false);
    gpui_kit::application().with_assets(gpui_kit::assets::AllAssets).run(move |cx| {
        rf_win::shell::mark_ui_thread();
        gpui_kit::init(cx);
        // rustyfiles'ın ayarları: yalnız dil, tema, tarih biçimi için okunur, asla yazılmaz
        cx.set_global(crate::settings::Settings::load());
        if !rf_win::encoding::user_locale_is_turkish() {
            rf_core::textload::set_locale_hint(None);
        }
        crate::settings::apply_component_theme(cx);
        cx.set_global(LookSettings::load());
        sync_tray(cx);
        // önizleme penceresi kapanınca DirectLook çalışmayı sürdürür (arka planda bekler)
        cx.set_quit_mode(gpui_kit::QuitMode::Explicit);
        cx.on_window_closed(|cx, _| {
            if !LookManager::is_visible(cx) {
                let stays = cx.global::<LookSettings>().stays_alone();
                std::thread::spawn(move || {
                    let told = rf_win::single_instance::send_to(&rf_win::single_instance::instance_name(), &ToApp::LookClosed.encode());
                    // rustyfiles is gone and nothing else needs DirectLook (issue 440): it leaves too
                    if !told && !stays && let Some(tx) = AGAIN.get() {
                        let _ = tx.unbounded_send(Msg::Quit);
                    }
                });
                // with no preview open for a while, the memory the last one used goes back to Windows (issue 440: ~200 MB idle)
                cx.spawn(async move |cx| {
                    cx.background_executor().timer(std::time::Duration::from_secs(20)).await;
                    if !cx.update(LookManager::is_visible) {
                        rf_win::memory::trim_working_set();
                    }
                })
                .detach();
            }
        })
        .detach();
        super::system::sync(cx);
        cx.observe_global::<LookSettings>(|cx| {
            super::system::sync(cx);
            sync_tray(cx);
        })
        .detach();
        handle(first.clone(), cx);
        cx.spawn(async move |cx| {
            use futures::StreamExt;
            while let Some(m) = rx.next().await {
                cx.update(|cx| handle(m, cx));
            }
        })
        .detach();
        cx.spawn(async move |cx| {
            use futures::StreamExt;
            while let Some(e) = tray_rx.next().await {
                match e {
                    rf_win::tray::TrayEvent::Quit => cx.update(|cx| handle(Msg::Quit, cx)),
                    _ => open_settings(),
                }
            }
        })
        .detach();
        drop(tx);
    });
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::{PngSaves, parse_args};
    use crate::look::ShowOpts;
    use crate::look::ipc::Msg;

    #[test]
    fn a_picker_quit_waits_for_every_pending_png_save() {
        let mut saves = PngSaves { pending: 2, ..PngSaves::default() };
        assert!(!saves.request_quit());
        assert!(!saves.finish());
        assert!(saves.finish());
        assert!(saves.request_quit());
    }

    #[test]
    fn one_icon_in_the_notification_area_and_never_none() {
        use super::tray_wanted;
        assert!(tray_wanted(true, false), "rustyfiles has no icon (it quit, or background mode is off): ours is there");
        assert!(!tray_wanted(true, true), "rustyfiles' icon is there: not two");
        assert!(!tray_wanted(false, false) && !tray_wanted(false, true), "turned off in DirectLook's settings");
    }

    #[test]
    fn launch_arguments() {
        assert_eq!(parse_args(&["--background"]), Msg::Wake);
        assert_eq!(parse_args(&[]), Msg::Wake);
        let m = Msg::Toggle(PathBuf::from(r"C:\a.jpg"));
        assert_eq!(parse_args(&["--msg", &m.encode()]), m);
        assert_eq!(parse_args(&["--look", r"C:\x.mp4", "top"]), Msg::Show(PathBuf::from(r"C:\x.mp4"), ShowOpts { topmost: true, pin: false }));
        assert_eq!(parse_args(&[r"C:\y.png"]), Msg::Show(PathBuf::from(r"C:\y.png"), ShowOpts::default()));
    }
}