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.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
//! rustyfiles as the Open / Save dialog of other apps (see crates/rf-dialog). The DLL in the
//! app starts `rustyfiles --pick <pipe>`; we read its request from the pipe, open a normal
//! rustyfiles window with a strip at the bottom (name, file type, OK / Cancel) and write the
//! answer back. Opening a file in that window (double click, Enter) picks it.
use std::cell::{Cell, RefCell};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use gpui_kit::component::{Icon, h_flex, v_flex};
use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use rf_core::Location;
use rustyfiles_dialog::proto::{Mode, Request, Response, first_ext, read_msg, write_msg};
use crate::folder_view::FolderView;
use crate::t;
use crate::theme::{self, Palette};
use crate::workspace::Workspace;
/// Single-instance message: "pick this pipe's request".
pub const PICK_PREFIX: &str = "\u{1}pick:";
/// At most this many folders of rustyfiles' windows come into the dialog as tabs.
const MORE_TABS: usize = 12;
pub struct PickSession {
pub req: Request,
/// Taken by the answer: each request is answered exactly once.
pipe: RefCell<Option<File>>,
pub name: Entity<InputState>,
/// 1-based, as in the request.
pub filter_ix: Cell<u32>,
/// The selection the name box was last filled from.
last_selection: RefCell<Vec<PathBuf>>,
/// The user has picked something in the list (a click in it, the arrow keys there). Until then a Save dialog's name box keeps
/// the name the app gave: a file the list selected by itself (the one saved last time, say) took its place, and a browser's
/// next download was saved over the file before it (issue 389).
pub touched: Cell<bool>,
_sub: RefCell<Option<Subscription>>,
/// Where the Open / Save button was last drawn, for Windows' "Snap To" (issue 148).
pub ok_at: Rc<Cell<Option<Bounds<Pixels>>>>,
}
impl PickSession {
/// The patterns of the chosen file type ("" = all files).
pub fn patterns(&self) -> String {
self.req.filters.get(self.filter_ix.get().saturating_sub(1) as usize).map(|f| f.spec.clone()).unwrap_or_default()
}
pub fn folders_only(&self) -> bool {
self.req.mode == Mode::Folder
}
/// Written right here, before the window closes: when rustyfiles was started only for this
/// dialog it quits with its last window, and an answer left to another thread could be lost.
/// The app is already waiting to read, so the write doesn't block.
fn answer(&self, resp: Response) {
if let Some(mut f) = self.pipe.borrow_mut().take() {
if self.req.owner != 0 {
let (top, taken) = rf_win::window::hand_foreground(self.req.owner);
dialog_log(&format!("app picker: the foreground goes back to {top:#x} (owner {:#x}), taken: {taken}", self.req.owner));
}
if let Err(e) = write_msg(&mut f, &resp) {
log::warn!("picker answer: {e}");
// the app that asked is gone (crashed, ended): it disabled its window for the
// dialog and can no longer enable it again; left so, that window ignored every
// click (a Chrome window whose print to PDF ended mid-way)
if self.req.owner != 0 {
rf_win::window::enable(self.req.owner);
}
}
}
}
}
impl Drop for PickSession {
/// Whatever closed the window, the app must not wait forever: an unanswered request is
/// cancelled.
fn drop(&mut self) {
self.answer(Response { ok: false, paths: Vec::new(), filter_index: self.filter_ix.get(), windows: false });
}
}
/// Whether `pipe` is a dialog's pipe as the dialog DLL names it: `\\.\pipe\rustyfiles-pick-` and then only letters, digits and dashes.
/// Anything else is not opened (a private security report: `--pick \\host\share\x` opened a file on another PC, sending it this user's
/// credentials, and any local path could be opened).
fn is_pick_pipe(pipe: &str) -> bool {
const PREFIX: &str = r"\\.\pipe\rustyfiles-pick-";
pipe.len() > PREFIX.len()
&& pipe.len() < 200
&& pipe[..PREFIX.len()].eq_ignore_ascii_case(PREFIX)
&& pipe[PREFIX.len()..].chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
}
/// `--pick <pipe>` (or the same message from a second launch): read the request, open the window.
pub fn begin(pipe: String, cx: &mut App) {
if !is_pick_pipe(&pipe) {
log::warn!("picker request: not a dialog's pipe, ignored: {pipe:?}");
return;
}
let task = cx.background_spawn(async move {
let mut f = std::fs::OpenOptions::new().read(true).write(true).open(&pipe)?;
let req: Request = read_msg(&mut f)?;
Ok::<_, std::io::Error>((f, req))
});
cx.spawn(async move |cx| match task.await {
Ok((f, req)) => {
cx.update(|cx| open_window(f, req, cx));
}
Err(e) => log::warn!("picker request: {e}"),
})
.detach();
}
/// Whether the app that asked takes a folder from its Open dialog too (`rustyfiles_dialog::proto::folder_label_from`).
fn takes_folders(req: &Request) -> bool {
req.mode == Mode::Open && !req.folder_label.trim().is_empty()
}
/// In an Open dialog whose app also takes a folder: the folder the OK button answers with, when it answers with one. One selected
/// folder is it, whatever is left in the name box; with nothing selected and nothing typed it is the folder that is open (walk into
/// the project's folder and press the button). Selected or typed files stay files. Pure.
pub(crate) fn folder_choice(takes: bool, sel: &[(PathBuf, bool)], typed: &str, dir: Option<&Path>) -> Option<PathBuf> {
if !takes {
return None;
}
match sel {
[(p, true)] => Some(p.clone()),
[] if typed.trim().is_empty() => dir.map(Path::to_path_buf),
_ => None,
}
}
/// Writes `Settings::dialog_windows_apps` to the file the dialog DLL reads (issue 371). Off the interface's thread.
pub(crate) fn mirror_windows_apps(apps: Vec<String>) {
std::thread::spawn(move || {
let Some(path) = rustyfiles_dialog::proto::windows_apps_path() else { return };
if apps.is_empty() && !path.exists() {
return;
}
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Err(e) = std::fs::write(&path, rustyfiles_dialog::proto::windows_apps_text(&apps)) {
log::warn!("dialog app list: {e}");
}
});
}
/// "Use Windows' dialog for this app" (issue 371): the app is remembered, and this dialog is handed to Windows' own at once, set
/// up as the app asked.
fn use_windows_dialog(ws: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
let Some(s) = ws.picker() else { return };
let key = app_key(&s.req);
if !key.is_empty() {
crate::settings::update(cx, move |st| {
if !st.dialog_windows_apps.contains(&key) {
st.dialog_windows_apps.push(key);
st.dialog_windows_apps.sort();
}
});
}
s.answer(Response { ok: false, paths: Vec::new(), filter_index: s.filter_ix.get(), windows: true });
Workspace::release_preview_host(window);
window.remove_window();
}
/// The button for it, beside the pin; only when the dialog named its app.
fn windows_dialog_button(s: &PickSession, p: &Palette, cx: &mut Context<Workspace>) -> Option<AnyElement> {
use gpui_kit::assets::IconName as L;
if app_key(&s.req).is_empty() {
return None;
}
let app = s.req.app.trim().trim_end_matches(".exe").trim_end_matches(".EXE").to_string();
let tip: SharedString = format!("{} {app}", t!("Bundan sonra Windows'un penceresini kullan:")).into();
Some(
div()
.id("pick-windows-dialog")
.size(px(36.))
.flex()
.flex_shrink_0()
.items_center()
.justify_center()
.rounded(theme::RADIUS_SM)
.cursor_pointer()
.border_1()
.border_color(p.border)
.bg(p.card_bg)
.hover(|d| d.bg(p.hover))
.child(Icon::new(L::AppWindow).size(px(16.)).text_color(p.text_secondary))
.tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx))
.on_click(cx.listener(|ws, _, window, cx| use_windows_dialog(ws, window, cx)))
.into_any_element(),
)
}
/// The app's key in `Settings::dialog_folders`: its program name in lower case (empty when the dialog did not say).
fn app_key(req: &Request) -> String {
req.app.trim().to_lowercase()
}
/// The pin button of the dialog's strip: the app's Open / Save window always starts in the folder shown now, or (pressed again
/// there) starts where the app asks again. Only when the dialog named its app.
fn start_pin(ws: &Workspace, s: &PickSession, p: &Palette, cx: &mut Context<Workspace>) -> Option<AnyElement> {
use gpui_kit::assets::IconName as L;
let key = app_key(&s.req);
if key.is_empty() {
return None;
}
let kept = cx.try_global::<crate::settings::Settings>().and_then(|st| st.dialog_folders.get(&key).cloned());
let dir = ws.active_view().read(cx).current_dir();
let here = matches!((&kept, &dir), (Some(k), Some(d)) if Path::new(k) == d.as_path());
let app = s.req.app.trim().trim_end_matches(".exe").trim_end_matches(".EXE").to_string();
let tip: SharedString = if here {
format!("{} {app}", t!("Artık hep burada açılmasın:")).into()
} else {
format!("{} {app}", t!("Hep bu klasörde açılsın:")).into()
};
let (accent, icon_color) = (p.accent, p.text_secondary);
Some(
div()
.id("pick-start-pin")
.size(px(36.))
.flex()
.flex_shrink_0()
.items_center()
.justify_center()
.rounded(theme::RADIUS_SM)
.cursor_pointer()
.border_1()
.border_color(p.border)
.bg(p.card_bg)
.hover(|d| d.bg(p.hover))
.child(Icon::new(L::Pin).size(px(16.)).text_color(if here { accent } else { icon_color }))
.tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx))
.on_click(move |_, _, cx| {
let (key, dir) = (key.clone(), dir.clone());
crate::settings::update(cx, move |st| {
if here {
st.dialog_folders.remove(&key);
} else if let Some(d) = dir {
st.dialog_folders.insert(key, d.display().to_string());
}
});
})
.into_any_element(),
)
}
fn mode_title(mode: Mode) -> &'static str {
match mode {
Mode::Open => t!("Aç"),
Mode::Save => t!("Farklı kaydet"),
Mode::Folder => t!("Klasör seç"),
}
}
fn ok_label(req: &Request) -> SharedString {
if !req.ok_label.trim().is_empty() {
return req.ok_label.replace('&', "").into();
}
match req.mode {
Mode::Open => t!("Aç"),
Mode::Save => t!("Kaydet"),
Mode::Folder => t!("Klasörü seç"),
}
.into()
}
/// The size the user left the dialog at, else room for the list and the preview side by side: 1100x700, at most 70 % of the screen
/// (issue 89: 1240x780 up to 85 % covered nearly all of a 1080p laptop's screen at its usual scaling).
fn picker_size(display: Option<DisplayId>, cx: &App) -> Size<Pixels> {
let on = display.and_then(|id| cx.displays().into_iter().find(|d| d.id() == id)).or_else(|| cx.primary_display());
let screen = on.map(|d| d.bounds().size).unwrap_or(size(px(1920.), px(1080.)));
picker_size_for(cx.global::<crate::settings::Settings>().picker_size, screen)
}
/// The display the window `owner` is on (a display's id is its monitor's handle), when the toolkit lists it.
fn owner_display(owner: isize, cx: &App) -> Option<DisplayId> {
if owner == 0 {
return None;
}
let id = DisplayId::new(rf_win::dock::monitors::monitor_of_window(owner)? as u64);
cx.displays().into_iter().any(|d| d.id() == id).then_some(id)
}
fn picker_size_for(kept: Option<[u16; 2]>, screen: Size<Pixels>) -> Size<Pixels> {
match kept {
// (a size kept on a bigger screen still fits this one)
Some([w, h]) => size(px(f32::from(w)).min(screen.width * 0.95).max(px(640.)), px(f32::from(h)).min(screen.height * 0.95).max(px(400.))),
None => size(px(1100.).min(screen.width * 0.7), px(700.).min(screen.height * 0.7)),
}
}
#[cfg(test)]
mod size_tests {
#[test]
fn only_a_dialogs_pipe_is_opened() {
assert!(super::is_pick_pipe(r"\\.\pipe\rustyfiles-pick-1234-0-0123456789abcdef0123456789abcdef"));
assert!(!super::is_pick_pipe(r"\\host\share\x"));
assert!(!super::is_pick_pipe(r"C:\Users\me\secret.txt"));
assert!(!super::is_pick_pipe(r"\\.\pipe\rustyfiles-pick-..\x"));
assert!(!super::is_pick_pipe(r"\\.\pipe\other"));
}
// (not `super::*`: GPUI's own `test` attribute would come with it)
use super::picker_size_for;
use gpui_kit::{px, size};
#[test]
fn the_dialog_opens_at_the_size_it_was_left_at_within_the_screen() {
let laptop = size(px(1280.), px(720.));
let first = picker_size_for(None, laptop);
assert!(first.width <= px(896.) && first.height <= px(504.), "at most 70 % of a 1080p laptop at 150 %: {first:?}");
assert_eq!(picker_size_for(None, size(px(2560.), px(1440.))), size(px(1100.), px(700.)));
assert_eq!(picker_size_for(Some([900, 560]), laptop), size(px(900.), px(560.)));
let big = picker_size_for(Some([2400, 1300]), laptop);
assert!(big.width <= px(1216.) && big.height <= px(684.), "{big:?}");
}
}
/// The folders the window may start in, the first one that exists wins: the one pinned for the app, then the app's own choice; when
/// the app named no folder itself (only a default), the folder it was last finished in comes before that default. Pure.
///
/// WHY (HANO on Discord, 2026-12-05: "possible to have the file save the previous folder for open and save dialogs?"). Windows' own
/// dialog keeps, per program, the folder it was last used in, and starts there when the program asks for no folder. rustyfiles'
/// window read that memory (the DLL's `GetFolder` fallback) but a pick made in it never updated it, so an app kept opening where
/// Windows' dialog had last been, days ago.
fn start_folders(pinned: Option<String>, last: Option<String>, req: &Request) -> Vec<String> {
let mut out: Vec<String> = pinned.into_iter().collect();
if req.folder_from_app == Some(false) {
out.extend(last);
}
out.extend(req.folder.clone());
out
}
/// The folder a finished pick is remembered by: the folder itself when one was picked, else the folder of the first file.
fn finished_folder(mode: Mode, paths: &[PathBuf]) -> Option<PathBuf> {
let first = paths.first()?;
if mode == Mode::Folder || first.is_dir() { Some(first.clone()) } else { first.parent().map(Path::to_path_buf) }
}
fn open_window(pipe: File, req: Request, cx: &mut App) {
crate::preview_trace::process_facts("picker: window requested");
// (bounded: a folder on a place that has to wake up first, a WSL distribution, must not hold the dialog's window back)
let (pinned, last) = cx.try_global::<crate::settings::Settings>().map_or((None, None), |s| {
let key = app_key(&req);
(s.dialog_folders.get(&key).cloned(), s.dialog_last_folders.get(&key).cloned())
});
let start = start_folders(pinned, last, &req)
.into_iter()
.map(PathBuf::from)
.find(|p| crate::is_dir_bounded(p.clone(), std::time::Duration::from_secs(2)) != Some(false))
.map(Location::Path)
.unwrap_or(Location::Home);
let title = {
let base = if req.title.trim().is_empty() { mode_title(req.mode).to_string() } else { req.title.clone() };
if req.app.is_empty() { base } else { format!("{base} — {}", req.app.trim_end_matches(".exe")) }
};
let owner = req.owner;
// On the monitor of the window that asked, as Windows' own dialog is (issue 1022: an app on the second monitor got its Open
// dialog in the middle of the primary one). Without an owner, or with one whose monitor the toolkit does not list: the primary.
let display = owner_display(owner, cx);
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(display, picker_size(display, cx), cx))),
display_id: display,
window_min_size: Some(size(px(640.), px(400.))),
window_background: crate::theme::window_material(WindowBackgroundAppearance::MicaBackdrop),
..gpui_kit::component::TitleBar::window_options()
};
// the folders open in rustyfiles' own windows come along as tabs (issue 226), after the one the dialog starts in
let start_path = start.path().map(Path::to_path_buf);
let others: Vec<PathBuf> = crate::workspace::open_folders(cx)
.into_iter()
.filter(|p| start_path.as_ref().is_none_or(|s| !s.as_os_str().eq_ignore_ascii_case(p.as_os_str())))
.take(MORE_TABS)
.collect();
let pipe = RefCell::new(Some(pipe));
let shown_hwnd = Rc::new(Cell::new(0isize));
let sh = shown_hwnd.clone();
let opened = gpui_kit::open_window(options, cx, move |window, cx| {
window.set_window_title(&title);
let hwnd = crate::look::window::hwnd_of(window);
sh.set(hwnd);
if owner != 0 {
// stays above the app that asked, like its own dialog would
rf_win::window::set_owner(hwnd, owner);
}
if owner != 0 && rf_win::window::owner_chain_topmost(owner) {
// the app's window is "always on top" (Prism's Download File dialog): a normal window, however far forward, stays under
// it. Windows' own dialog would be topmost with its owner, so ours is too (it goes away with the picker).
let _ = rf_win::window::set_topmost(hwnd, true);
dialog_log("app picker: owner is always on top, picker made topmost");
}
rf_win::window::bring_to_front(hwnd);
if owner != 0 {
// setting the owner did not move us above it (see raise_above_owner)
dialog_log(&format!("app picker: shown, above its owner: {:?}", rf_win::window::is_above(hwnd, owner)));
raise_off_thread(hwnd);
}
let pipe = pipe.borrow_mut().take();
cx.new(|cx| {
let mut ws = Workspace::new(Some(start), None, window, cx);
for p in others {
ws.add_quiet_tab(Location::Path(p), window, cx);
}
// (the box's own words, shown while it is empty: the strip has no label beside it any more)
let hint = if req.mode == Mode::Folder { t!("Klasör:") } else { t!("Dosya adı:") }.trim_end_matches(':').to_string();
let name = cx.new(|cx| InputState::new(window, cx).placeholder(hint).default_value(req.file_name.clone()));
let session = Rc::new(PickSession {
filter_ix: Cell::new(req.filter_index.max(1)),
req,
pipe: RefCell::new(pipe),
name: name.clone(),
last_selection: RefCell::new(Vec::new()),
touched: Cell::new(false),
_sub: RefCell::new(None),
ok_at: Rc::new(Cell::new(None)),
});
let sub = cx.subscribe_in(&name, window, |ws: &mut Workspace, _, ev: &InputEvent, window, cx| {
if let InputEvent::PressEnter { .. } = ev {
accept(ws, window, cx);
}
});
*session._sub.borrow_mut() = Some(sub);
let save = session.req.mode == Mode::Save;
let ok_at = session.ok_at.clone();
ws.set_picker(session, window, cx);
// Windows' "Snap To" (Mouse settings: "Automatically move pointer to the default button in a dialog box"): its own Open
// and Save dialogs put the pointer on their Open / Save button, and a browser's "Save as" through ours did not (issue 148,
// "this works for deleting or renaming items, but not ... when the save download window appears"). Once the dialog is
// drawn and in place, as the app's own questions do (`prompt::show`).
if rf_win::sysparams::snap_to_default_button() {
window
.spawn(cx, async move |cx| {
cx.background_executor().timer(std::time::Duration::from_millis(300)).await;
let _ = cx.update(|window, _| {
let Some(b) = ok_at.get() else { return };
let k = window.scale_factor();
let c = b.center();
rf_win::sysparams::put_pointer_in(crate::look::window::hwnd_of(window), (f32::from(c.x) * k).round() as i32, (f32::from(c.y) * k).round() as i32);
});
})
.detach();
}
// Save: the name is what the user came to type, so the box has the keyboard with the name selected up to its extension,
// as in Windows' own dialog; nothing had it, and typing went nowhere (Discord, 2026-11-23). On the next frame: a focus
// target that is not part of the frame being drawn is dropped by GPUI.
if save {
cx.on_next_frame(window, move |_, window, cx| {
name.update(cx, |s, cx| {
let text = s.value().to_string();
let stem = text.rfind('.').filter(|&i| i > 0).unwrap_or(text.len());
s.focus(window, cx);
s.set_selected_range(0..stem, cx);
});
});
}
crate::preview_trace::mark("picker: workspace built");
ws
})
});
let picker = match opened {
Ok(picker) => picker,
Err(e) => {
log::error!("picker window: {e:#}");
return;
}
};
// The app that asked can go away while its dialog is up (it crashed, or was ended): its window goes with it, and the dialog
// stayed on the screen with nobody left to answer (seen on 2026-12-04, with a test program closed under its Open dialog: two
// such windows were still there minutes later). Windows closes a dialog with its owner; ours belongs to another process, so
// it looks for the owner itself and leaves with it.
if owner != 0 {
let shown = shown_hwnd.clone();
cx.spawn(async move |cx| {
loop {
cx.background_executor().timer(std::time::Duration::from_millis(500)).await;
let hwnd = shown.get();
if hwnd != 0 && !rf_win::window::exists(hwnd) {
break;
}
if !rf_win::window::exists(owner) {
dialog_log("app picker: the window that asked is gone, the picker closes");
let (handle, workspace) = &picker;
let _ = handle.update(cx, |_, window, cx| workspace.update(cx, |ws, _| cancel(ws, window)));
break;
}
}
})
.detach();
}
// Asked from a background process (Chrome's file dialog helper), Windows may refuse the
// switch while the window is still being shown: try again once it is on screen.
cx.spawn(async move |cx| {
let mut waited = 0;
let mut retries = 0;
for ms in [50u64, 250, 600, 1200] {
cx.background_executor().timer(std::time::Duration::from_millis(ms)).await;
waited += ms;
let hwnd = shown_hwnd.get();
if !should_retry_picker_front(hwnd, rf_win::window::foreground(), rf_win::window::app_in_front()) {
break;
}
log::info!("picker: not in front after {ms} ms, bringing it forward");
retries += 1;
rf_win::window::bring_to_front(hwnd);
}
let hwnd = shown_hwnd.get();
// next to the dialog DLL's own lines: a picker that opened behind is visible there
dialog_log(&format!(
"app picker: owner 0x{owner:x}, in front: {}, {retries} retries in {waited} ms",
hwnd != 0 && rf_win::window::is_foreground(hwnd)
));
// Chrome: the picker is in front at first, yet users find it behind Chrome afterwards.
// For the next 10 s, every change of what is in front, whether the picker still has its
// owner and lies above it: which window takes over, and when, is in the log.
let mut last = String::new();
let mut lines = 0;
let mut t = waited;
while hwnd != 0 && t < 10_000 && lines < 20 {
cx.background_executor().timer(std::time::Duration::from_millis(100)).await;
t += 100;
if !rf_win::window::exists(hwnd) {
dialog_log(&format!("app picker: closed at {t} ms"));
break;
}
// For the first seconds, whoever puts the app back over the picker (the app's own
// activation, a late show) is answered: the picker goes back above it — unless another
// window of ours (such as a newly opened main window, issue 658) now holds the front.
if owner != 0 && t <= 3_000 && !rf_win::window::app_in_front() && rf_win::window::is_above(hwnd, owner) == Some(false) {
dialog_log(&format!("app picker at {t} ms: under its owner again, raised"));
raise_off_thread(hwnd);
}
let front = rf_win::window::foreground();
let state = format!(
"front {}, picker's owner 0x{:x}, picker above its owner: {:?}",
if front == hwnd { "picker".to_string() } else { rf_win::window::describe(front) },
rf_win::window::owner_of(hwnd),
if owner != 0 { rf_win::window::is_above(hwnd, owner) } else { None },
);
if state != last {
dialog_log(&format!("app picker at {t} ms: {state}"));
last = state;
lines += 1;
}
}
})
.detach();
}
/// Whether the picker's startup retry loop should keep pulling the dialog back to the front.
/// Stops once the picker itself or another window of our own process (such as a newly opened
/// RustyFiles window from "Open in New Window", issue 658) already holds the foreground.
fn should_retry_picker_front(picker_hwnd: isize, front_hwnd: isize, front_is_our_app: bool) -> bool {
picker_hwnd != 0 && front_hwnd != picker_hwnd && !front_is_our_app
}
#[cfg(test)]
mod front_retry_tests {
use super::should_retry_picker_front;
#[test]
fn stops_retrying_once_picker_or_another_rustyfiles_window_is_in_front() {
assert!(!should_retry_picker_front(0, 100, false), "invalid picker hwnd");
assert!(!should_retry_picker_front(42, 42, true), "picker itself is foreground");
assert!(!should_retry_picker_front(42, 99, true), "another RustyFiles window is foreground");
assert!(should_retry_picker_front(42, 99, false), "host app or another app is foreground");
assert!(should_retry_picker_front(42, 0, false), "nothing is foreground");
}
}
/// Raises the picker above its owner on a short-lived thread: the owner moves with it, and a
/// hung owner would block the caller (measured: 7.7 s), here the whole file manager.
fn raise_off_thread(hwnd: isize) {
let _ = std::thread::Builder::new().name("picker-raise".into()).spawn(move || rf_win::window::raise_above_owner(hwnd));
}
/// The selected entries of the current folder, with whether each is a folder.
fn selection(ws: &Workspace, cx: &App) -> Vec<(PathBuf, bool)> {
ws.active_view().read(cx).selection_with_kind()
}
fn names_text(paths: &[PathBuf]) -> String {
let name = |p: &PathBuf| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
match paths {
[one] => name(one),
_ => paths.iter().map(|p| format!("\"{}\"", name(p))).collect::<Vec<_>>().join(" "),
}
}
/// `"a.txt" "b.txt"` or `a.txt` → names.
fn parse_names(text: &str) -> Vec<String> {
let t = text.trim();
if !t.contains('"') {
return if t.is_empty() { Vec::new() } else { vec![t.to_string()] };
}
t.split('"').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect()
}
fn resolve(dir: Option<&Path>, name: &str) -> Option<PathBuf> {
let p = Path::new(name);
if p.is_absolute() {
return Some(p.to_path_buf());
}
dir.map(|d| d.join(name))
}
/// The extension a typed name without one gets when saving: the chosen file type's (issue 424: "JPEG" chosen and "photo" typed
/// came back as photo.png, the app's default), else the app's default, else none ("All files").
pub(crate) fn save_ext(spec: &str, default_ext: &str) -> Option<String> {
first_ext(spec).or_else(|| (!default_ext.is_empty()).then(|| default_ext.to_string()))
}
/// The name box's text after the file type changed from `old` to `new`, as Windows' own dialog does it: a name ending in one of the
/// old type's extensions gets the new type's first one ("photo.png" → "photo.jpg"). `None`: the text stays (no extension, one of
/// another type, or a type with no extension of its own such as "All files").
pub(crate) fn renamed_for_type(name: &str, old: &str, new: &str) -> Option<String> {
let to = first_ext(new)?;
let (stem, ext) = name.rsplit_once('.')?;
if stem.is_empty() || ext.eq_ignore_ascii_case(&to) {
return None;
}
let of_old = old.split(';').map(str::trim).filter_map(|p| p.strip_prefix("*.")).any(|e| e.eq_ignore_ascii_case(ext));
of_old.then(|| format!("{stem}.{to}"))
}
/// Keeps the name box in step with the selection (files when opening or saving, a folder when
/// picking one).
fn sync_name(ws: &Workspace, s: &PickSession, window: &mut Window, cx: &mut App) {
let sel = selection(ws, cx);
let wanted: Vec<PathBuf> = sel.iter().filter(|(_, dir)| *dir == (s.req.mode == Mode::Folder)).map(|(p, _)| p.clone()).collect();
// An app that takes a folder too: a folder selected after a file takes the file's name out of the box, so that the box and the
// button ("Select Folder") do not say two things.
if takes_folders(&s.req) && matches!(sel.as_slice(), [(_, true)]) && !s.last_selection.borrow().is_empty() {
s.last_selection.borrow_mut().clear();
s.name.update(cx, |st, cx| st.set_value("", window, cx));
return;
}
if s.req.mode == Mode::Save && !s.touched.get() {
// (taken as seen: only a selection the user makes from now on fills the box)
*s.last_selection.borrow_mut() = wanted;
return;
}
if wanted.is_empty() || *s.last_selection.borrow() == wanted {
return;
}
*s.last_selection.borrow_mut() = wanted.clone();
let text = names_text(&wanted);
s.name.update(cx, |st, cx| st.set_value(text, window, cx));
}
fn finish(ws: &mut Workspace, paths: Vec<PathBuf>, window: &mut Window, cx: &mut App) {
if let Some(s) = ws.picker() {
let key = app_key(&s.req);
if let Some(dir) = finished_folder(s.req.mode, &paths).filter(|_| !key.is_empty()) {
crate::settings::update(cx, move |st| {
st.dialog_last_folders.insert(key, dir.display().to_string());
});
}
s.answer(Response { ok: true, paths: paths.iter().map(|p| p.to_string_lossy().into_owned()).collect(), filter_index: s.filter_ix.get(), windows: false });
}
Workspace::release_preview_host(window);
window.remove_window();
}
pub(crate) fn cancel(ws: &mut Workspace, window: &mut Window) {
answer_cancel(ws);
Workspace::release_preview_host(window);
window.remove_window();
}
/// The window is closing anyway (X, Alt+F4): just tell the app.
pub(crate) fn answer_cancel(ws: &mut Workspace) {
if let Some(s) = ws.picker() {
s.answer(Response { ok: false, paths: Vec::new(), filter_index: s.filter_ix.get(), windows: false });
}
}
/// Files opened in the window (double click, Enter on the list).
pub(crate) fn picked(ws: &mut Workspace, paths: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Workspace>) {
let Some(s) = ws.picker() else { return };
match s.req.mode {
Mode::Folder => {}
Mode::Open => {
let paths = if s.req.multi { paths } else { paths.into_iter().take(1).collect() };
finish(ws, paths, window, cx);
}
// saving over an existing file: the same question as the button
Mode::Save => {
if let Some(p) = paths.into_iter().next() {
let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
s.name.update(cx, |st, cx| st.set_value(name, window, cx));
accept(ws, window, cx);
}
}
}
}
/// OK button / Enter in the name box.
pub(crate) fn accept(ws: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
let Some(s) = ws.picker() else { return };
let view = ws.active_view();
let dir = view.read(cx).current_dir();
let text = s.name.read(cx).value().trim().to_string();
let sel = selection(ws, cx);
let navigate = |ws: &mut Workspace, to: PathBuf, window: &mut Window, cx: &mut Context<Workspace>| {
ws.active_view().update(cx, |v, cx| v.navigate(Location::Path(to), cx));
s.name.update(cx, |st, cx| st.set_value("", window, cx));
};
match s.req.mode {
Mode::Folder => {
let chosen = match sel.as_slice() {
[(p, true)] => Some(p.clone()),
_ => resolve(dir.as_deref(), &text).filter(|p| !text.is_empty() && p.is_dir()).or(dir),
};
match chosen {
Some(p) => finish(ws, vec![p], window, cx),
None => tell(t!("Bir klasöre girin ya da bir klasör seçin."), window, cx),
}
}
Mode::Open => {
// (an app that takes a folder as well, such as IntelliJ IDEA opening a project)
if let Some(folder) = folder_choice(takes_folders(&s.req), &sel, &text, dir.as_deref()) {
return finish(ws, vec![folder], window, cx);
}
let files: Vec<PathBuf> = sel.iter().filter(|(_, d)| !d).map(|(p, _)| p.clone()).collect();
if !files.is_empty() && text == names_text(&files) {
return finish(ws, if s.req.multi { files } else { files.into_iter().take(1).collect() }, window, cx);
}
let names = parse_names(&text);
if names.is_empty() {
if let [(p, true)] = sel.as_slice() {
navigate(ws, p.clone(), window, cx);
}
return;
}
let targets: Vec<PathBuf> = names.iter().filter_map(|n| resolve(dir.as_deref(), n)).collect();
if let [one] = targets.as_slice() {
if one.is_dir() {
return navigate(ws, one.clone(), window, cx);
}
}
if targets.is_empty() || targets.iter().any(|t| !t.is_file()) {
return tell(t!("Dosya bulunamadı. Adı ve klasörü denetleyin."), window, cx);
}
finish(ws, if s.req.multi { targets } else { targets.into_iter().take(1).collect() }, window, cx);
}
Mode::Save => {
if text.is_empty() {
return;
}
let Some(mut target) = resolve(dir.as_deref(), &text) else {
return tell(t!("Önce kaydedilecek klasörü açın."), window, cx);
};
if target.is_dir() {
return navigate(ws, target, window, cx);
}
if target.extension().is_none() {
let ext = save_ext(&s.patterns(), &s.req.default_ext);
if let Some(ext) = ext {
target.set_extension(ext);
}
}
if target.exists() && s.req.overwrite_prompt {
confirm_overwrite(target, window, cx);
return;
}
finish(ws, vec![target], window, cx);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AddressFileAction {
Finish(PathBuf),
ConfirmOverwrite { target: PathBuf, parent: Option<PathBuf>, name: String },
Navigate(PathBuf),
}
pub(crate) fn address_file_action(mode: Mode, overwrite_prompt: bool, path: PathBuf) -> AddressFileAction {
match mode {
Mode::Open => AddressFileAction::Finish(path),
Mode::Save if !overwrite_prompt => AddressFileAction::Finish(path),
Mode::Save => AddressFileAction::ConfirmOverwrite {
parent: path.parent().map(Path::to_path_buf),
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
target: path,
},
Mode::Folder => AddressFileAction::Navigate(path.parent().map(Path::to_path_buf).unwrap_or(path)),
}
}
pub(crate) fn pick_address_file(ws: &mut Workspace, tab: Entity<FolderView>, path: PathBuf, window: &mut Window, cx: &mut Context<Workspace>) {
let Some(s) = ws.picker() else { return };
match address_file_action(s.req.mode, s.req.overwrite_prompt, path) {
AddressFileAction::Finish(target) => finish(ws, vec![target], window, cx),
AddressFileAction::ConfirmOverwrite { target, parent, name } => {
if let Some(parent) = parent {
let same_dir = tab.read(cx).current_dir().is_some_and(|d| d.as_os_str().eq_ignore_ascii_case(parent.as_os_str()));
if same_dir {
if !name.is_empty() {
tab.update(cx, |v, cx| v.select_now(name.clone(), cx));
}
} else {
if !name.is_empty() {
tab.update(cx, |v, _| v.set_reselect(name.clone()));
}
tab.update(cx, |v, cx| v.navigate(Location::Path(parent), cx));
}
}
s.touched.set(true);
*s.last_selection.borrow_mut() = vec![target.clone()];
s.name.update(cx, |st, cx| st.set_value(name, window, cx));
confirm_overwrite(target, window, cx);
}
AddressFileAction::Navigate(dir) => {
tab.update(cx, |v, cx| v.navigate(Location::Path(dir), cx));
if ws.active_view() == tab {
ws.focus_active(window, cx);
}
}
}
}
fn confirm_overwrite(target: PathBuf, window: &mut Window, cx: &mut Context<Workspace>) {
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let ws_handle = cx.entity().downgrade();
let t2 = target.clone();
crate::prompt::show(
format!("{name} {}", t!("zaten var.")),
Some(t!("Değiştirmek istiyor musunuz?").to_string()),
None,
vec![
crate::prompt::Button::new(t!("Değiştir"), crate::prompt::Kind::Primary, move |_, window, cx| {
if let Some(ws) = ws_handle.upgrade() {
let p = t2.clone();
ws.update(cx, |ws, cx| finish(ws, vec![p], window, cx));
}
Ok(())
}),
crate::prompt::Button::cancel(),
],
window,
cx,
);
}
fn tell(msg: &str, window: &mut Window, cx: &mut App) {
crate::prompt::show(msg.to_string(), None, None, vec![crate::prompt::Button::new(t!("Tamam"), crate::prompt::Kind::Primary, |_, _, _| Ok(()))], window, cx);
}
/// The strip at the bottom of the window.
pub(crate) fn footer(ws: &mut Workspace, s: &Rc<PickSession>, p: &Palette, window: &mut Window, cx: &mut Context<Workspace>) -> AnyElement {
sync_name(ws, s, window, cx);
// the button says what it will do: the app's own words for a folder while a folder is what OK answers with
let ok: SharedString = {
let dir = ws.active_view().read(cx).current_dir();
let typed = s.name.read(cx).value().to_string();
match folder_choice(takes_folders(&s.req), &selection(ws, cx), &typed, dir.as_deref()) {
Some(_) => s.req.folder_label.replace('&', "").into(),
None => ok_label(&s.req),
}
};
// file type: a select box, like the ones in Settings
let filter = (!s.req.filters.is_empty() && s.req.mode != Mode::Folder).then(|| {
let current: SharedString =
s.req.filters.get(s.filter_ix.get().saturating_sub(1) as usize).map(|f| f.name.clone()).unwrap_or_default().into();
let me = cx.entity().downgrade();
let filters = s.req.filters.clone();
let sel = s.filter_ix.get();
// 36 px like the name field and the buttons beside it
div().w(px(240.)).flex_shrink(1.).min_w(px(140.)).child(crate::select_box::select_box_h("pick-filter", p, current, 36., move |_| {
filters
.iter()
.enumerate()
.map(|(i, f)| {
let me = me.clone();
crate::select_box::Choice::new(f.name.clone(), sel == i as u32 + 1, move |window, cx| {
if let Some(ws) = me.upgrade() {
ws.update(cx, |ws, cx| ws.set_pick_filter(i as u32 + 1, window, cx));
}
})
})
.collect()
}))
});
let button = |id: &'static str, label: SharedString, primary: bool| {
div()
.id(id)
.h(px(36.))
.min_w(px(104.))
.px_4()
.flex()
.flex_shrink_0()
.items_center()
.justify_center()
.rounded(theme::RADIUS_SM)
.text_sm()
.cursor_pointer()
.when(primary, |d| d.bg(p.accent).text_color(p.accent_text).font_weight(FontWeight::SEMIBOLD).hover(|d| d.opacity(0.9)))
.when(!primary, |d| d.border_1().border_color(p.border).bg(p.card_bg).hover(|d| d.bg(p.hover)))
.child(label)
};
// Two rows, as Windows' own dialog has them: the name over the whole width (it had what the type box and the buttons left over,
// less its label), then the window's switches, the file type, and the buttons at the right.
// [ 🗎 name ……………………………………………………… ]
// [pin][Windows] [ file type ▾ ] [ Save ] [ Cancel ]
use gpui_kit::assets::IconName as L;
let icon = if s.req.mode == Mode::Folder { L::Folder } else { L::File };
let prefix = div().pl_1().pr_1().text_color(p.text_secondary).child(Icon::new(icon).size(px(15.)));
let name_row = h_flex()
.w_full()
.h(px(36.))
.px_2()
.items_center()
.rounded(theme::RADIUS_SM)
.bg(p.hover)
.border_1()
.border_color(p.border)
.child(div().flex_1().min_w_0().child(crate::text_menu::input(&s.name).appearance(false).prefix(prefix)));
let action_row = h_flex()
.w_full()
.gap_3()
.items_center()
.children(start_pin(ws, s, p, cx))
.children(windows_dialog_button(s, p, cx))
.children(filter)
.child(div().flex_1())
.child({
// (where it is drawn, for "Snap To")
let at = s.ok_at.clone();
button("pick-ok", ok, true)
.relative()
.child(canvas(move |b, _, _| at.set(Some(b)), |_, _, _, _| {}).absolute().top_0().left_0().size_full())
.on_click(cx.listener(|ws, _, window, cx| accept(ws, window, cx)))
})
.child(button("pick-cancel", t!("İptal").into(), false).on_click(cx.listener(|ws, _, window, _| cancel(ws, window))));
v_flex()
.w_full()
.flex_shrink_0()
.px_4()
.py_3()
.gap_2p5()
.border_t_1()
.border_color(p.divider)
// over glass this strip (name field, file type, buttons) has a wash of its own, as the window's layers are thin there
.bg(p.bar_bg)
.child(name_row)
.child(action_row)
.into_any_element()
}
#[cfg(test)]
mod tests {
// not `super::*`: gpui's `test` macro would shadow the built-in one
use super::{folder_choice, names_text, parse_names, renamed_for_type, resolve, save_ext};
/// Issue 424: the chosen file type decides the extension, as in Windows' own dialog.
#[test]
fn the_chosen_file_type_gives_the_extension() {
assert_eq!(save_ext("*.jpg;*.jpeg", "png").as_deref(), Some("jpg"), "the chosen type over the app's default");
assert_eq!(save_ext("*.*", "png").as_deref(), Some("png"), "All files: the app's default");
assert_eq!(save_ext("*.*", ""), None);
assert_eq!(renamed_for_type("photo.png", "*.png", "*.jpg;*.jpeg").as_deref(), Some("photo.jpg"));
assert_eq!(renamed_for_type("photo.PNG", "*.png", "*.jpg").as_deref(), Some("photo.jpg"));
assert_eq!(renamed_for_type("photo", "*.png", "*.jpg"), None, "no extension: it is added when saving");
assert_eq!(renamed_for_type("notes.txt", "*.png", "*.jpg"), None, "an extension of another type stays");
assert_eq!(renamed_for_type("photo.png", "*.png", "*.*"), None, "All files has no extension of its own");
assert_eq!(renamed_for_type("my.photo.png", "*.png", "*.webp").as_deref(), Some("my.photo.webp"));
}
use std::path::{Path, PathBuf};
#[test]
fn an_app_that_takes_folders_gets_the_selected_folder_or_the_open_one() {
let dir = Path::new(r"C:\projeler");
let folder = (PathBuf::from(r"C:\projeler\uygulama"), true);
let file = (PathBuf::from(r"C:\projeler\pom.xml"), false);
// one selected folder: that folder, also with a file's name still in the box
assert_eq!(folder_choice(true, &[folder.clone()], "", Some(dir)), Some(folder.0.clone()));
assert_eq!(folder_choice(true, &[folder.clone()], "pom.xml", Some(dir)), Some(folder.0.clone()));
// nothing selected and nothing typed: the folder that is open
assert_eq!(folder_choice(true, &[], " ", Some(dir)), Some(dir.to_path_buf()));
assert_eq!(folder_choice(true, &[], "", None), None, "no folder is open (a list of drives)");
// files stay files: a selected one, a typed one, several things selected
assert_eq!(folder_choice(true, &[file.clone()], "pom.xml", Some(dir)), None);
assert_eq!(folder_choice(true, &[], "pom.xml", Some(dir)), None);
assert_eq!(folder_choice(true, &[folder.clone(), file.clone()], "", Some(dir)), None);
// an ordinary Open dialog never answers with a folder
assert_eq!(folder_choice(false, &[folder], "", Some(dir)), None);
assert_eq!(folder_choice(false, &[], "", Some(dir)), None);
}
#[test]
fn names_round_trip() {
let ps = vec![PathBuf::from(r"C:\a\bir.txt"), PathBuf::from(r"C:\a\iki dosya.txt")];
assert_eq!(names_text(&ps), "\"bir.txt\" \"iki dosya.txt\"");
assert_eq!(parse_names(&names_text(&ps)), vec!["bir.txt", "iki dosya.txt"]);
assert_eq!(parse_names(" rapor.pdf "), vec!["rapor.pdf"]);
assert!(parse_names("").is_empty());
assert_eq!(resolve(Some(Path::new(r"C:\a")), "b.txt"), Some(PathBuf::from(r"C:\a\b.txt")));
assert_eq!(resolve(None, r"D:\x.txt"), Some(PathBuf::from(r"D:\x.txt")));
assert_eq!(resolve(None, "x.txt"), None);
}
#[test]
fn address_file_action_handles_open_save_and_folder_modes() {
use super::{AddressFileAction, address_file_action};
use rustyfiles_dialog::proto::Mode;
let xpi = PathBuf::from(r"C:\Users\tb\Documents\firefox-extensions\Picket Domain Router-2.0.3.xpi");
let zip = PathBuf::from(r"C:\Users\tb\archive.zip");
assert_eq!(address_file_action(Mode::Open, true, xpi.clone()), AddressFileAction::Finish(xpi.clone()));
assert_eq!(address_file_action(Mode::Open, false, zip.clone()), AddressFileAction::Finish(zip));
assert_eq!(address_file_action(Mode::Save, false, xpi.clone()), AddressFileAction::Finish(xpi.clone()));
assert_eq!(
address_file_action(Mode::Save, true, xpi.clone()),
AddressFileAction::ConfirmOverwrite {
target: xpi.clone(),
parent: Some(PathBuf::from(r"C:\Users\tb\Documents\firefox-extensions")),
name: "Picket Domain Router-2.0.3.xpi".into(),
}
);
assert_eq!(
address_file_action(Mode::Folder, false, xpi),
AddressFileAction::Navigate(PathBuf::from(r"C:\Users\tb\Documents\firefox-extensions"))
);
}
}
/// Appends a line to `%LOCALAPPDATA%/rustyfiles/dialog.log` (where the dialog DLL logs).
fn dialog_log(line: &str) {
use std::io::Write;
let Some(dir) = std::env::var_os("LOCALAPPDATA") else { return };
let path = PathBuf::from(dir).join("rustyfiles").join("dialog.log");
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(&path) {
let _ = writeln!(f, "{secs} rustyfiles[{}] app {} {line}", std::process::id(), env!("CARGO_PKG_VERSION"));
}
}
#[cfg(test)]
mod start_folder_tests {
use super::{finished_folder, start_folders};
use rustyfiles_dialog::proto::{Mode, Request};
use std::path::PathBuf;
fn req(folder: Option<&str>, from_app: Option<bool>) -> Request {
Request { folder: folder.map(Into::into), folder_from_app: from_app, ..Default::default() }
}
/// HANO on Discord: an app that names no folder of its own starts where the last pick for it ended.
#[test]
fn the_last_folder_comes_before_a_default_but_not_before_the_apps_choice_or_a_pin() {
let last = || Some(r"D:\Projects".to_string());
assert_eq!(start_folders(None, last(), &req(Some(r"C:\Users\me\Documents"), Some(false))), [r"D:\Projects", r"C:\Users\me\Documents"]);
assert_eq!(start_folders(None, last(), &req(Some(r"C:\Work"), Some(true))), [r"C:\Work"], "the app's own folder wins");
assert_eq!(start_folders(Some(r"E:\Pinned".into()), last(), &req(None, Some(false))), [r"E:\Pinned", r"D:\Projects"]);
assert_eq!(start_folders(None, last(), &req(Some(r"C:\Old"), None)), [r"C:\Old"], "an older DLL: as before");
}
#[test]
fn a_pick_is_remembered_by_its_folder() {
let dir = std::env::temp_dir();
assert_eq!(finished_folder(Mode::Open, &[dir.join("rapor.pdf")]), Some(dir.clone()));
assert_eq!(finished_folder(Mode::Save, &[dir.join("new.txt")]), Some(dir.clone()));
assert_eq!(finished_folder(Mode::Folder, &[dir.join("x")]), Some(dir.join("x")));
assert_eq!(finished_folder(Mode::Open, &[]), None::<PathBuf>);
}
}