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.

30.4 KB
Raw Blame
//! The bookmarks bar (`crate::bookmarks`, issue 694), under the address bar, as browsers have it: a button per bookmark (a folder of
//! bookmarks opens as a menu), folders dropped on it become bookmarks, and its right-click menu opens, renames, moves and removes
//! them, adds the current folder, and imports or exports the bar as a browser's bookmark file.

use crate::bookmarks::{self, Bookmark};
use crate::fluent_menu::{Item, Menu, MenuIcon};
use gpui_kit::component::Sizable as _;
use gpui_kit::component::input::Input;
use std::sync::Arc;

use super::*;

/// The bar's measures: its height, its buttons' and its text's.
#[derive(Clone, Copy)]
pub(super) struct Measures {
    bar: Pixels,
    button: Pixels,
    text: Pixels,
}

impl Measures {
    /// As high as the tab row, with buttons and text as the tabs' (Settings), or as high as the bar's text needs.
    fn now(window: &Window, cx: &App) -> Self {
        if cx.global::<crate::settings::Settings>().bookmarks_bar_tab_height {
            Measures { bar: theme::titlebar_h(), button: px(28.), text: rems(0.875).to_pixels(window.rem_size()) }
        } else {
            let text = rems(0.875).to_pixels(window.rem_size());
            let button = (text + px(12.)).round();
            Measures { bar: button + px(6.), button, text }
        }
    }
}

/// What is carried while a bookmark is dragged: to another place on the bar, or onto the sidebar's pinned folders (it is pinned).
/// It is drawn as the bookmark's own button, following the pointer.
#[derive(Clone)]
pub(super) struct BookmarkDrag {
    pub(super) ix: usize,
    name: SharedString,
    target: Option<String>,
    picture: Option<Arc<RenderImage>>,
    folder: bool,
    m: Measures,
}

impl Render for BookmarkDrag {
    fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        let p = Palette::for_window(window);
        let icon: AnyElement = match (&self.picture, self.folder, &self.target) {
            (Some(picture), _, _) => img(picture.clone()).size(px(16.)).flex_shrink_0().into_any_element(),
            (None, true, _) => Icon::new(L::Folder).size(px(16.)).text_color(theme::kind_color(crate::icons::Category::Folder, p.dark)).into_any_element(),
            (None, false, Some(t)) if bookmarks::local_path(t).is_none() => Icon::new(L::Globe).size(px(16.)).text_color(p.text_secondary).into_any_element(),
            _ => div().size(px(16.)).into_any_element(),
        };
        h_flex()
            .h(self.m.button)
            .px_2()
            .gap_1p5()
            .items_center()
            .rounded(theme::RADIUS_SM)
            .bg(p.card_bg)
            .border_1()
            .border_color(p.accent)
            .shadow_md()
            .text_size(self.m.text)
            .text_color(p.text)
            .child(icon)
            .child(div().max_w(px(180.)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(self.name.clone()))
    }
}

/// With "live" dragging (Settings): what is being dragged over the bar and the place it would take there.
#[derive(Clone)]
pub(super) struct DropPreview {
    /// The bookmark being moved, by its place on the bar; `None`: something new is being put on the bar.
    from: Option<usize>,
    /// Its place among the other bookmarks (the bar without the one being moved).
    to: usize,
    /// What a new one would be (one folder or file; several make a count).
    new: Option<Bookmark>,
    count: usize,
}

impl Workspace {
    /// The bar, when Settings has it on (not in the Open / Save dialog).
    pub(super) fn render_bookmarks_bar(&mut self, p: &Palette, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let s = cx.global::<crate::settings::Settings>();
        if !s.bookmarks_bar || self.picker.is_some() {
            return None;
        }
        let explorer_look = s.windows_file_explorer_theme;
        let live = s.bookmarks_live_drag;
        let m = Measures::now(window, cx);
        let items = bookmarks::items(cx);
        // (a drag that ended anywhere but on the bar leaves nothing behind)
        if !live || !cx.has_active_drag() || self.bookmark_drop.as_ref().is_some_and(|pv| pv.from.is_some_and(|f| f >= items.len())) {
            self.bookmark_drop = None;
        }
        let drop_bg = p.selection;
        let mut bar = h_flex()
            .id("bookmarks-bar")
            .w_full()
            .h(m.bar)
            .flex_shrink_0()
            .px_2()
            .gap_0p5()
            .items_center()
            .overflow_hidden()
            .text_size(m.text)
            .text_color(p.text)
            .when(explorer_look, |d| d.bg(p.toolbar_bg))
            .border_b_1()
            // (the command bar's top edge when it comes right under: the same grey as its other edges)
            .border_color(self.bar_border(p, explorer_look))
            // (without live dragging: the whole bar tinted, and a line by the bookmark it goes next to)
            .when(!live, |d| {
                d.drag_over::<ExternalPaths>(move |st, _, _, _| st.bg(drop_bg))
                    .drag_over::<BookmarkDrag>(move |st, _, _, _| st.bg(drop_bg))
                    .drag_over::<PinDrag>(move |st, _, _, _| st.bg(drop_bg))
            })
            // live: what comes over the bar gets a place on it, which follows the pointer (`bookmark_drop_over`)
            .when(live, |d| {
                d.on_drag_move::<BookmarkDrag>(cx.listener(|this, ev: &DragMoveEvent<BookmarkDrag>, _, cx| {
                    let inside = ev.bounds.contains(&ev.event.position);
                    let from = ev.drag(cx).ix;
                    this.bookmark_drop_track(inside, Some(from), || (None, 1), cx);
                }))
                .on_drag_move::<PinDrag>(cx.listener(|this, ev: &DragMoveEvent<PinDrag>, _, cx| {
                    let inside = ev.bounds.contains(&ev.event.position);
                    let path = ev.drag(cx).path.clone();
                    this.bookmark_drop_track(inside, None, || (Some(Bookmark::for_path(&path)), 1), cx);
                }))
                .on_drag_move::<ExternalPaths>(cx.listener(|this, ev: &DragMoveEvent<ExternalPaths>, _, cx| {
                    let inside = ev.bounds.contains(&ev.event.position);
                    let paths = ev.drag(cx).paths().to_vec();
                    this.bookmark_drop_track(inside, None, || (paths.first().map(|p| Bookmark::for_path(p)), paths.len()), cx);
                }))
            })
            // Let go of on the bar: folders and files (from the list, the desktop, Explorer) and the sidebar's pinned folders become
            // bookmarks, a bookmark changes place. Where: the place shown while dragging, else the bar's end (without live dragging, a
            // bookmark takes what is let go of on it).
            .on_drop(cx.listener(|this, paths: &ExternalPaths, _, cx| {
                let at = this.bookmark_drop.take().filter(|pv| pv.from.is_none()).map(|pv| pv.to);
                let list: Vec<Bookmark> = paths.paths().iter().map(|p| Bookmark::for_path(p)).collect();
                bookmarks::update(cx, |b| {
                    let at = at.unwrap_or(b.len()).min(b.len());
                    b.splice(at..at, list);
                });
            }))
            .on_drop(cx.listener(|this, d: &BookmarkDrag, _, cx| {
                let from = d.ix;
                let at = this.bookmark_drop.take().filter(|pv| pv.from == Some(from)).map(|pv| pv.to);
                bookmarks::update(cx, |b| {
                    if from < b.len() {
                        let item = b.remove(from);
                        b.insert(at.unwrap_or(b.len()).min(b.len()), item);
                    }
                })
            }))
            .on_drop(cx.listener(|this, d: &PinDrag, _, cx| {
                let at = this.bookmark_drop.take().filter(|pv| pv.from.is_none()).map(|pv| pv.to);
                let b = Bookmark::for_path(&d.path);
                bookmarks::update(cx, |list| list.insert(at.unwrap_or(list.len()).min(list.len()), b));
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(|this, ev: &MouseDownEvent, window, cx| this.bookmarks_bar_menu(None, ev.position, window, cx)));
        let preview = self.bookmark_drop.clone();
        if items.is_empty() && preview.is_none() {
            bar = bar.child(
                div()
                    .px_1()
                    .text_xs()
                    .text_color(p.text_tertiary)
                    .whitespace_nowrap()
                    .child(t!("Klasörleri saklamak için buraya sürükleyin ya da yer imlerini içe aktarmak için sağ tıklayın")),
            );
        }
        // the bookmarks in their order; while something is dragged over the bar (live), without the one being moved and with a
        // place left for what is dragged
        let others: Vec<usize> = (0..items.len()).filter(|&i| preview.as_ref().is_none_or(|pv| pv.from != Some(i))).collect();
        let n = others.len();
        for k in 0..=n {
            if let Some(pv) = &preview
                && pv.to.min(n) == k
            {
                let hole = self.bookmark_hole(pv, &items, m, p, cx);
                bar = bar.child(hole);
            }
            if let Some(&i) = others.get(k) {
                let slot = live.then_some((k, k + 1 == n));
                let button = self.bookmark_button(i, &items[i], slot, m, p, cx);
                bar = bar.child(button);
            }
        }
        Some(bar.into_any_element())
    }

    /// A bookmark's icon: a folder of bookmarks', the folder's (or file's) own as Windows draws it, a web address's.
    fn bookmark_icon(&mut self, b: &Bookmark, p: &Palette, cx: &mut Context<Self>) -> (AnyElement, Option<Arc<RenderImage>>) {
        let folder_color = theme::kind_color(crate::icons::Category::Folder, p.dark);
        match b {
            Bookmark::Folder { .. } => (Icon::new(L::Folder).size(px(16.)).text_color(folder_color).into_any_element(), None),
            Bookmark::Link { target, .. } => match bookmarks::local_path(target) {
                Some(path) => match self.images.update(cx, |im, cx| im.shell_icon_ui(&path.to_string_lossy(), 16, cx)) {
                    Some(picture) => (img(picture.clone()).size(px(16.)).flex_shrink_0().into_any_element(), Some(picture)),
                    None => (Icon::new(L::Folder).size(px(16.)).text_color(folder_color).into_any_element(), None),
                },
                None => (Icon::new(L::Globe).size(px(16.)).text_color(p.text_secondary).into_any_element(), None),
            },
        }
    }

    /// The place what is dragged would take (live dragging): the moved bookmark, or the new one, faded on a tinted ground.
    fn bookmark_hole(&mut self, pv: &DropPreview, items: &[Bookmark], m: Measures, p: &Palette, cx: &mut Context<Self>) -> AnyElement {
        let shown = match pv.from {
            Some(f) => items.get(f).cloned(),
            None => pv.new.clone(),
        };
        let (icon, name): (AnyElement, SharedString) = match (&shown, pv.count) {
            (Some(b), 1) => (self.bookmark_icon(b, p, cx).0, b.name().to_string().into()),
            (_, count) => (Icon::new(L::Bookmark).size(px(16.)).text_color(p.accent).into_any_element(), crate::i18n::items(count).into()),
        };
        h_flex()
            .id("bookmark-hole")
            .h(m.button)
            .px_2()
            .gap_1p5()
            .items_center()
            .flex_shrink_0()
            .rounded(theme::RADIUS_SM)
            .bg(p.selection)
            .border_1()
            .border_color(p.selection_border)
            .child(div().opacity(0.45).child(icon))
            .child(div().opacity(0.45).max_w(px(180.)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(name))
            .into_any_element()
    }

    /// Something dragged came onto the bar (its place is shown: the moved bookmark's own, or the bar's end until it is over a
    /// bookmark) or left it (a new one's place goes away, a moved bookmark's goes back where it was).
    fn bookmark_drop_track(&mut self, inside: bool, from: Option<usize>, new: impl FnOnce() -> (Option<Bookmark>, usize), cx: &mut Context<Self>) {
        match (&mut self.bookmark_drop, inside) {
            (None, true) => {
                let n = bookmarks::items(cx).len();
                let (new, count) = new();
                self.bookmark_drop = Some(DropPreview { from, to: from.unwrap_or(n), new, count });
                cx.notify();
            }
            (Some(pv), false) => match pv.from {
                Some(f) if pv.to != f => {
                    pv.to = f;
                    cx.notify();
                }
                Some(_) => {}
                None => {
                    self.bookmark_drop = None;
                    cx.notify();
                }
            },
            _ => {}
        }
    }

    /// The pointer, dragging something, is over the bookmark at place `k` among the others (`last`: the rightmost, which takes the
    /// rest of the bar): once past its middle, what is dragged takes the place on its other side. (Past its middle, not just over
    /// it: bookmarks of different widths would otherwise trade places back and forth under a pointer that stands still.)
    fn bookmark_drop_over(&mut self, k: usize, last: bool, bounds: Bounds<Pixels>, pos: Point<Pixels>, cx: &mut Context<Self>) {
        let Some(pv) = self.bookmark_drop.as_mut() else { return };
        if pos.y < bounds.top() - px(2.) || pos.y > bounds.bottom() + px(2.) || (k > 0 && pos.x < bounds.left()) || (!last && pos.x >= bounds.right()) {
            return;
        }
        let middle = bounds.center().x;
        let to = if k >= pv.to && pos.x > middle {
            k + 1
        } else if k < pv.to && pos.x < middle {
            k
        } else {
            return;
        };
        if to != pv.to {
            pv.to = to;
            cx.notify();
        }
    }

    /// Bookmark `i`'s button; `slot`, with live dragging: its place among the others and whether it is the last.
    fn bookmark_button(&mut self, i: usize, b: &Bookmark, slot: Option<(usize, bool)>, m: Measures, p: &Palette, cx: &mut Context<Self>) -> AnyElement {
        let (icon, picture) = self.bookmark_icon(b, p, cx);
        let is_folder = matches!(b, Bookmark::Folder { .. });
        let tip: SharedString = match b {
            Bookmark::Link { target, .. } => target.clone().into(),
            Bookmark::Folder { children, .. } => t!("{n} yer imi").replace("{n}", &children.len().to_string()).into(),
        };
        let (clicked, middle) = (b.clone(), b.clone());
        let accent = p.accent;
        let drag = BookmarkDrag {
            ix: i,
            name: b.name().to_string().into(),
            target: if let Bookmark::Link { target, .. } = b { Some(target.clone()) } else { None },
            picture,
            folder: is_folder,
            m,
        };
        // (the name being edited: a text field in its place, with the bar's text, in a box that shows it, as a name edited in the list)
        let renaming = self.bookmark_rename.as_ref().is_some_and(|(at, _, _)| *at == i);
        let label: AnyElement = match &self.bookmark_rename {
            Some((at, input, _)) if *at == i => div()
                .w(px(180.))
                .h(m.button - px(4.))
                .flex()
                .items_center()
                .px_1()
                .rounded(px(4.))
                .bg(p.card_bg)
                .border_1()
                .border_color(p.accent)
                .text_size(m.text)
                .text_color(p.text)
                // (a press in it is for the text: it neither drags nor opens the bookmark)
                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
                // Escape leaves the name as it was
                .capture_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| {
                    if ev.keystroke.key == "escape" {
                        cx.stop_propagation();
                        this.bookmark_rename = None;
                        cx.notify();
                    }
                }))
                .child(Input::new(input).appearance(false).small().px_0().text_size(m.text))
                .into_any_element(),
            _ => div().max_w(px(180.)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(b.name().to_string()).into_any_element(),
        };
        let mut button = h_flex()
            .id(("bookmark", i))
            .h(m.button)
            .px(if renaming { px(4.) } else { px(8.) })
            .gap_1p5()
            .items_center()
            .flex_shrink_0()
            .rounded(theme::RADIUS_SM)
            .cursor_pointer()
            .hover(|st| st.bg(p.hover))
            .active(|st| st.bg(p.pressed))
            .tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx))
            .child(icon)
            .child(label)
            // dragged along the bar it changes place; onto the sidebar's pinned folders it is pinned
            .on_drag(drag, |d: &BookmarkDrag, _, _, cx| cx.new(|_| d.clone()));
        button = match slot {
            // live: the place of what is dragged follows the pointer over the bookmarks (the bar takes the drop)
            Some((k, last)) => button
                .on_drag_move::<BookmarkDrag>(cx.listener(move |this, ev: &DragMoveEvent<BookmarkDrag>, _, cx| this.bookmark_drop_over(k, last, ev.bounds, ev.event.position, cx)))
                .on_drag_move::<PinDrag>(cx.listener(move |this, ev: &DragMoveEvent<PinDrag>, _, cx| this.bookmark_drop_over(k, last, ev.bounds, ev.event.position, cx)))
                .on_drag_move::<ExternalPaths>(cx.listener(move |this, ev: &DragMoveEvent<ExternalPaths>, _, cx| this.bookmark_drop_over(k, last, ev.bounds, ev.event.position, cx))),
            // else a line where it will go, and the drop is the bookmark's
            None => button
                .drag_over::<BookmarkDrag>(move |st, d: &BookmarkDrag, _, _| {
                    // (moving right puts it after this one, moving left before it)
                    if d.ix < i { st.border_r_2().border_color(accent) } else { st.border_l_2().border_color(accent) }
                })
                .on_drop(cx.listener(move |_, d: &BookmarkDrag, _, cx| {
                    cx.stop_propagation();
                    let from = d.ix;
                    bookmarks::update(cx, |b| {
                        if from < b.len() && from != i {
                            let item = b.remove(from);
                            b.insert(i.min(b.len()), item);
                        }
                    })
                }))
                .drag_over::<PinDrag>(move |st, _, _, _| st.border_l_2().border_color(accent))
                .on_drop(cx.listener(move |_, d: &PinDrag, _, cx| {
                    cx.stop_propagation();
                    let b = Bookmark::for_path(&d.path);
                    bookmarks::update(cx, |list| list.insert(i.min(list.len()), b));
                })),
        };
        button
            .when(is_folder, |d| d.child(Icon::new(L::ChevronDown).size(px(12.)).text_color(p.text_secondary)))
            // a click opens it here (Ctrl: in a new tab), a folder of bookmarks drops its menu
            .on_click(cx.listener(move |this, ev: &ClickEvent, window, cx| {
                // (a click into its own name being edited is for the text field)
                if this.bookmark_rename.as_ref().is_some_and(|(at, _, _)| *at == i) {
                    return;
                }
                let new_tab = ev.modifiers().control.then_some(ev.modifiers().shift);
                match &clicked {
                    Bookmark::Link { target, .. } => this.open_bookmark(target, new_tab, window, cx),
                    Bookmark::Folder { children, .. } => {
                        let me = cx.entity().downgrade();
                        let pos = point(ev.position().x - px(8.), ev.position().y + px(16.));
                        crate::fluent_menu::show(Menu { quick: Vec::new(), items: bookmark_items(me, children) }, pos, window, cx);
                    }
                }
            }))
            // the middle button: in a new tab, as in a browser
            .on_mouse_down(MouseButton::Middle, cx.listener(move |this, ev: &MouseDownEvent, window, cx| {
                if let Bookmark::Link { target, .. } = &middle {
                    this.open_bookmark(target, Some(ev.modifiers.shift), window, cx);
                }
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(move |this, ev: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                this.bookmarks_bar_menu(Some(i), ev.position, window, cx);
            }))
            .into_any_element()
    }

    /// Opens a bookmark: a folder in this tab (or a new one), a file with its program, a web address in the browser.
    /// `new_tab`: `None` opens it in the active tab, `Some(shift)` in a new tab placed as the setting says (see `open_tab_as_set`).
    pub(super) fn open_bookmark(&mut self, target: &str, new_tab: Option<bool>, window: &mut Window, cx: &mut Context<Self>) {
        match bookmarks::local_path(target) {
            Some(path) if !path.is_file() => {
                let loc = Location::Path(path);
                if let Some(shift) = new_tab {
                    self.open_tab_as_set(loc, shift, window, cx);
                } else {
                    self.active_tab().clone().update(cx, |v, cx| v.navigate(loc, cx));
                }
            }
            Some(path) => {
                if let Err(e) = rf_win::shell::open(&path) {
                    log::warn!("bookmark: {e:#}");
                }
            }
            None => {
                if let Err(e) = rf_win::shell::open(Path::new(target)) {
                    log::warn!("bookmark: {e:#}");
                }
            }
        }
    }

    /// The right-click menu of the bar, or of its bookmark `ix`.
    fn bookmarks_bar_menu(&mut self, ix: Option<usize>, pos: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let me = cx.entity().downgrade();
        let now = bookmarks::items(cx);
        let icon = |l: L| MenuIcon::Lucide(l);
        let mut v: Vec<Item> = Vec::new();
        if let Some(i) = ix
            && let Some(b) = now.get(i)
        {
            if let Bookmark::Link { target, .. } = b {
                let (m, t) = (me.clone(), target.clone());
                v.push(Item::action(t!("Aç"), icon(L::SquareArrowOutUpRight), move |w, cx| {
                    let _ = m.update(cx, |ws, cx| ws.open_bookmark(&t, None, w, cx));
                }));
                if bookmarks::local_path(target).is_some() {
                    let (m, t) = (me.clone(), target.clone());
                    v.push(Item::action(t!("Yeni sekmede aç"), icon(L::Plus), move |w, cx| {
                        let _ = m.update(cx, |ws, cx| ws.open_bookmark(&t, Some(false), w, cx));
                    }));
                }
            }
            let m = me.clone();
            v.push(Item::action(t!("Yeniden adlandır"), icon(L::PencilLine), move |w, cx| {
                let _ = m.update(cx, |ws, cx| ws.start_bookmark_rename(i, w, cx));
            }));
            if i > 0 {
                v.push(Item::action(t!("Sola taşı"), icon(L::ArrowLeft), move |_, cx| {
                    bookmarks::update(cx, |b| {
                        if i < b.len() {
                            b.swap(i - 1, i)
                        }
                    })
                }));
            }
            if i + 1 < now.len() {
                v.push(Item::action(t!("Sağa taşı"), icon(L::ArrowRight), move |_, cx| {
                    bookmarks::update(cx, |b| {
                        if i + 1 < b.len() {
                            b.swap(i, i + 1)
                        }
                    })
                }));
            }
            v.push(Item::action(t!("Çubuktan kaldır"), icon(L::Trash), move |_, cx| {
                bookmarks::update(cx, |b| {
                    if i < b.len() {
                        b.remove(i);
                    }
                })
            }));
            v.push(Item::Separator);
        }
        if let Some(here) = self.active_tab().read(cx).location().path().map(Path::to_path_buf) {
            v.push(Item::action(t!("Bu klasörü çubuğa ekle"), icon(L::Bookmark), move |_, cx| {
                let b = Bookmark::for_path(&here);
                bookmarks::update(cx, |list| list.push(b));
            }));
        }
        let m = me.clone();
        v.push(Item::action(t!("Yer imlerini içe aktar…"), icon(L::Download), move |_, cx| {
            let _ = m.update(cx, |ws, cx| ws.import_bookmarks(cx));
        }));
        let m = me.clone();
        v.push(Item::action(t!("Yer imlerini dışa aktar…"), icon(L::Upload), move |_, cx| {
            let _ = m.update(cx, |ws, cx| ws.export_bookmarks(cx));
        }));
        let tall = cx.global::<crate::settings::Settings>().bookmarks_bar_tab_height;
        v.push(Item::Separator);
        v.push(Item::sub(
            t!("Çubuğun yüksekliği"),
            icon(L::MoveVertical),
            vec![
                Item::action(t!("Otomatik, yazıya göre"), MenuIcon::None, |_, cx| crate::settings::update(cx, |s| s.bookmarks_bar_tab_height = false)).checked(!tall),
                Item::action(t!("Sekme satırı kadar"), MenuIcon::None, |_, cx| crate::settings::update(cx, |s| s.bookmarks_bar_tab_height = true)).checked(tall),
            ],
        ));
        v.push(Item::action(t!("Yer imleri çubuğunu gizle"), icon(L::EyeOff), |_, cx| crate::settings::update(cx, |s| s.bookmarks_bar = false)));
        crate::fluent_menu::show(Menu { quick: Vec::new(), items: v }, pos, window, cx);
    }

    /// A bookmark dropped on the sidebar's pinned folders: its folder is pinned (the bookmark stays on the bar).
    pub(super) fn pin_bookmark(&mut self, d: &BookmarkDrag, cx: &mut Context<Self>) {
        if let Some(path) = d.target.as_deref().and_then(bookmarks::local_path)
            && path.is_dir()
        {
            self.set_pinned(path, true, cx);
        }
    }

    /// Puts a text field in the place of bookmark `i`'s name: Enter, or a click elsewhere, keeps what was typed.
    fn start_bookmark_rename(&mut self, i: usize, window: &mut Window, cx: &mut Context<Self>) {
        let name = bookmarks::items(cx).get(i).map(|b| b.name().to_string()).unwrap_or_default();
        let input = cx.new(|cx| InputState::new(window, cx));
        input.update(cx, |st, cx| st.set_value(name, window, cx));
        let sub = cx.subscribe_in(&input, window, |_, input, ev: &InputEvent, _, cx| {
            if matches!(ev, InputEvent::PressEnter { .. } | InputEvent::Blur) {
                let typed = input.read(cx).value().to_string();
                // (after this event: the field and its subscription go away with the edit)
                cx.spawn(async move |this, cx| {
                    let _ = this.update(cx, |ws, cx| ws.finish_bookmark_rename(typed, cx));
                })
                .detach();
            }
        });
        input.update(cx, |st, cx| st.focus(window, cx));
        self.bookmark_rename = Some((i, input, sub));
        cx.notify();
    }

    fn finish_bookmark_rename(&mut self, typed: String, cx: &mut Context<Self>) {
        let Some((i, _, _)) = self.bookmark_rename.take() else { return };
        let name = typed.trim().to_string();
        if !name.is_empty() {
            bookmarks::update(cx, |b| match b.get_mut(i) {
                Some(Bookmark::Link { name: n, .. } | Bookmark::Folder { name: n, .. }) => *n = name,
                None => {}
            });
        }
        cx.notify();
    }

    /// Reads a browser's bookmark file into the bar: its bookmarks become the bar when the bar is empty, else a folder of it.
    fn import_bookmarks(&mut self, cx: &mut Context<Self>) {
        let (tx, rx) = futures::channel::oneshot::channel::<Option<PathBuf>>();
        rf_win::sta::run(move |owner| {
            let filters = [(t!("Yer imleri (HTML)"), "*.html;*.htm")];
            let _ = tx.send(rf_win::dialogs::pick(owner, t!("Yer imlerini içe aktar"), rf_win::dialogs::Pick::File { filters: &filters }));
        });
        cx.spawn(async move |_, cx| {
            let Ok(Some(path)) = rx.await else { return };
            let Ok(text) = std::fs::read_to_string(&path) else { return };
            let found = bookmarks::parse_html(text.trim_start_matches('\u{feff}'));
            log::info!("bookmarks: {} read from {}", found.len(), path.display());
            if found.is_empty() {
                return;
            }
            let name = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| t!("İçe aktarılanlar").into());
            cx.update(|cx| {
                bookmarks::update(cx, |b| {
                    if b.is_empty() {
                        *b = found;
                    } else {
                        b.push(Bookmark::Folder { name, children: found });
                    }
                })
            });
        })
        .detach();
    }

    /// Writes the bar as a browser's bookmark file.
    fn export_bookmarks(&mut self, cx: &mut Context<Self>) {
        let html = bookmarks::to_html(&bookmarks::items(cx));
        rf_win::sta::run(move |owner| {
            let filters = [(t!("Yer imleri (HTML)"), "*.html")];
            let picked = rf_win::dialogs::pick(
                owner,
                t!("Yer imlerini dışa aktar"),
                rf_win::dialogs::Pick::Save { filters: &filters, default_name: "rustyfiles-bookmarks.html" },
            );
            if let Some(path) = picked
                && let Err(e) = std::fs::write(&path, html)
            {
                log::warn!("bookmarks: {e:#}");
            }
        });
    }
}

/// A folder of bookmarks as the rows of its menu (its folders as submenus).
fn bookmark_items(me: WeakEntity<Workspace>, list: &[Bookmark]) -> Vec<Item> {
    if list.is_empty() {
        return vec![Item::action(t!("Boş"), MenuIcon::None, |_, _| {}).enabled(false)];
    }
    list.iter()
        .map(|b| match b {
            Bookmark::Link { name, target } => {
                let (m, t) = (me.clone(), target.clone());
                let icon = if bookmarks::local_path(target).is_some() { MenuIcon::Lucide(L::Folder) } else { MenuIcon::Lucide(L::Globe) };
                Item::action(name.clone(), icon, move |w, cx| {
                    let _ = m.update(cx, |ws, cx| ws.open_bookmark(&t, None, w, cx));
                })
            }
            Bookmark::Folder { name, children } => Item::sub(name.clone(), MenuIcon::Lucide(L::Folder), bookmark_items(me.clone(), children)),
        })
        .collect()
}