curd-editor 0.27.1

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! Where everything is on the screen, and drawing it.

use super::*;

impl Workspace {
    // ---- Drawing -------------------------------------------------------

    pub(super) fn layout(&self, width: usize, height: usize) -> Layout {
        let tabs = (self.editors.len() > 1) as usize;
        let tree = if self.show_tree {
            // The tree and the line that separates it from the text.
            TREE_WIDTH.min(width / 2) + 1
        } else {
            0
        };
        let below_tabs = height.saturating_sub(tabs);
        let room = width.saturating_sub(tree);
        // On a wide screen the Claude panel stands to the right of the
        // text, with a line between them.
        let agent_side = if self.show_agent && room >= AGENT_SIDE_MIN {
            let cols = self.agent_cols.unwrap_or(room * 2 / 5);
            cols.clamp(AGENT_MIN_WIDTH, room - TEXT_MIN_WIDTH - 1) + 1
        } else {
            0
        };
        // Otherwise it takes the lower two fifths, where there is room.
        // It can be made taller, but two rows of the text always stay.
        // What a command printed lies there too, and comes first.
        let under = |wanted: Option<usize>| {
            wanted.unwrap_or(below_tabs * 2 / 5).clamp(3, below_tabs.max(5) - 2)
        };
        let output = if self.show_output && below_tabs >= 6 { under(None) } else { 0 };
        let agent = if self.show_agent && agent_side == 0 && output == 0 && below_tabs >= 6 {
            under(self.agent_rows)
        } else {
            0
        };
        Layout {
            tabs,
            tree,
            output,
            agent,
            agent_side,
            pane_width: room - agent_side,
            pane_height: below_tabs - agent - output,
        }
    }

    /// The text of each tab: the file's name, a dot if it has unsaved
    /// changes, and the mark that closes it.
    pub(super) fn tab_labels(&self) -> Vec<String> {
        self.editors
            .iter()
            .map(|editor| {
                let dot = if editor.document.dirty { " ●" } else { "" };
                format!(" {}{dot} {CLOSE_ICON} ", widen(editor.name()))
            })
            .collect()
    }

    /// The tab under screen column `x`, if any, and whether `x` is on its
    /// close mark.
    pub(super) fn tab_at(&self, x: usize) -> Option<(usize, bool)> {
        let mut end = 0;
        let tab = self.tab_labels().iter().position(|label| {
            end += label.chars().count();
            x < end
        })?;
        // The mark and the space after it.
        Some((tab, x + 2 >= end))
    }

    pub(super) fn tab_row(&self, width: usize) -> Row {
        let mut row = Row::new();
        let mut used = 0;
        for (index, label) in self.tab_labels().iter().enumerate() {
            let label = fit(label, label.chars().count().min(width - used));
            used += label.chars().count();
            let style = if index == self.active { Style::TabActive } else { Style::Tab };
            row.push(Span::new(style, label));
        }
        row
    }

    /// What fills the text area when no file is open.
    pub(super) fn empty_pane(&self, width: usize, height: usize) -> Vec<Row> {
        let mut rows = Vec::with_capacity(height);
        for y in 0..height.saturating_sub(1) {
            let text = match y.checked_sub(height / 3) {
                Some(0) => concat!("curd editor -- v", env!("CARGO_PKG_VERSION")),
                Some(2) => "Enter   open the selected file",
                Some(3) => "Ctrl+P  find a file by name",
                Some(4) => "Alt+I   ask Claude",
                Some(5) => "F1      every command",
                Some(6) => "Ctrl+Q  quit",
                _ => "",
            };
            let padding = width.saturating_sub(30) / 2;
            let line: String = format!("{}{text}", " ".repeat(padding))
                .chars()
                .take(width)
                .collect();
            rows.push(vec![Span::new(Style::Dim, line)]);
        }
        if height > 0 {
            let status = if self.message.is_empty() { "No file open" } else { &self.message };
            rows.push(vec![Span::new(Style::Bar, fit(status, width))]);
        }
        rows
    }

    /// Everything that should be on a `width` x `height` screen, and where
    /// the cursor goes (nowhere, while the keys are in the file tree).
    pub(super) fn render(&mut self, width: usize, height: usize) -> (Vec<Row>, Option<(usize, usize)>) {
        if let Some(top) = self.help {
            return (Self::help_page(width, height, top), None);
        }
        let layout = self.layout(width, height);
        let (pane_width, pane_height) = (layout.pane_width, layout.pane_height);

        let mut pane = match self.editors.get_mut(self.active) {
            Some(editor) => {
                editor.scroll(
                    pane_width.saturating_sub(editor.gutter_width()),
                    pane_height.saturating_sub(1),
                );
                editor.render(pane_width, pane_height)
            }
            None => self.empty_pane(pane_width, pane_height),
        };
        let mut cursor = match (self.focus, self.editors.get(self.active)) {
            (Focus::Editor, Some(editor)) => Some(editor.cursor_on_screen()),
            _ => None,
        };
        if layout.output > 0 {
            let focused = self.focus == Focus::Output && self.finder.is_none();
            let mut rows = self.output.render(pane_width, layout.output, focused);
            place(&mut rows, Zone::Panel);
            pane.extend(rows);
        }
        if layout.agent > 0 {
            let focused = self.focus == Focus::Agent
                && (self.finder.is_none() || self.picker.is_for_claude());
            self.fit_agent_title(pane_width);
            let (mut rows, (x, y)) = self.agent.render(pane_width, layout.agent, focused);
            place(&mut rows, Zone::Panel);
            if focused {
                cursor = Some((x.min(pane_width.saturating_sub(1)), pane.len() + y));
            }
            pane.extend(rows);
        }

        // Beside the text: each row of the text, the line, a row of the panel.
        if layout.agent_side > 0 {
            let focused = self.focus == Focus::Agent
                && (self.finder.is_none() || self.picker.is_for_claude());
            self.fit_agent_title(layout.agent_side - 1);
            let (mut panel, (x, y)) = self.agent.render(layout.agent_side - 1, pane.len(), focused);
            place(&mut panel, Zone::Panel);
            for (row, panel_row) in pane.iter_mut().zip(panel) {
                let used: usize = row.iter().map(|span| span.text.chars().count()).sum();
                row.push(Span::new(Style::Plain, " ".repeat(pane_width.saturating_sub(used))));
                row.push(Span::new(Style::Border, "│"));
                row.extend(panel_row);
            }
            if focused {
                cursor = Some((pane_width + 1 + x, y));
            }
        }

        let mut sidebar = (layout.tree > 0).then(|| {
            let focused = self.focus == Focus::Tree && self.finder.is_none();
            let mut rows = self.tree.render(layout.tree - 1, pane.len(), focused, self.git.as_ref());
            place(&mut rows, Zone::Side);
            rows
        });

        let mut rows = Vec::with_capacity(height);
        if layout.tabs > 0 && height > 0 {
            rows.push(self.tab_row(width));
        }
        for (y, pane_row) in pane.into_iter().enumerate() {
            let mut row = Row::new();
            if let Some(sidebar) = &mut sidebar {
                row.append(&mut sidebar[y]);
                row.push(Span::new(Style::Border, "│"));
            }
            row.extend(pane_row);
            rows.push(row);
        }
        let mut cursor = cursor.map(|(x, y)| (x + layout.tree, y + layout.tabs));

        // The title of the panel ends with a tab for each assistant, the
        // way an editor shows its extensions side by side: the one in
        // front, and the others, which keep their own conversations.
        self.agent_tabs.clear();
        let panel = if layout.agent_side > 0 {
            Some((layout.tree + pane_width + 1, layout.agent_side - 1, layout.tabs))
        } else if layout.agent > 0 {
            Some((layout.tree, pane_width, layout.tabs + pane_height))
        } else {
            None
        };
        if let Some((left, cells, y)) = panel.filter(|_| self.agents.len() > 1) {
            let title: String = rows[y].iter().flat_map(|span| span.text.chars()).skip(left).take(cells).collect();
            let used = title.trim_end().chars().count();
            let labels = self.agent_tab_labels();
            let all: usize = labels.iter().map(|label| label.chars().count()).sum();
            // Where they do not all fit: which one this is, of how many.
            let short = format!(" {}/{} ", self.agent_index + 1, self.agents.len());
            let mut x = left + cells;
            if used + 1 + all <= cells {
                x -= all;
                for (index, label) in labels.iter().enumerate() {
                    let style = if index == self.agent_index { Style::TabActive } else { Style::Tab };
                    overlay(&mut rows[y], x, &Span { zone: Zone::Panel, ..Span::new(style, label.as_str()) });
                    self.agent_tabs.push((y, x, index));
                    x += label.chars().count();
                }
            } else if used + 1 + short.len() <= cells {
                x -= short.len();
                overlay(&mut rows[y], x, &Span { zone: Zone::Panel, ..Span::new(Style::Tab, short.as_str()) });
                // A click on it goes on to the next one.
                self.agent_tabs.push((y, x, (self.agent_index + 1) % self.agents.len()));
                x += short.len();
            }
            // The end of the last tab, for telling which one a click is on.
            self.agent_tabs.push((y, x, usize::MAX));
        }

        // A list that is open lies over all of that, as a box with a
        // background of its own.
        if let Some(finder) = &self.finder {
            let popup = self.popup(width, height);
            let piece = |style, text: &str| Span {
                zone: Zone::Popup,
                ..Span::new(style, fit(text, popup.width))
            };
            let typed = format!("{}{}", self.picker.prompt(), widen(&finder.query));
            if let Some(row) = rows.get_mut(popup.input_y) {
                overlay(row, popup.x, &piece(Style::Input, &typed));
                // A reminder of the keys, where it does not crowd the typing.
                let hint = POPUP_HINT.chars().count();
                if popup.width >= typed.chars().count() + hint + 8 {
                    let note = Span { zone: Zone::Popup, ..Span::new(Style::FieldNote, POPUP_HINT) };
                    overlay(row, popup.x + popup.width - hint, &note);
                }
            }
            let matches = finder.visible(popup.capacity);
            let mut lines: Vec<Span> = matches
                .iter()
                .map(|(item, selected)| match selected {
                    true => piece(Style::Selected, &format!(" > {}", widen(item))),
                    false => piece(Style::Menu, &format!("   {}", widen(item))),
                })
                .collect();
            if lines.is_empty() && !self.picker.is_question() && popup.capacity > 0 {
                let nothing = match self.picker {
                    Picker::Files | Picker::Attach => "   no matching files",
                    _ => "   nothing matches",
                };
                lines.push(piece(Style::Menu, nothing));
            }
            for (index, line) in lines.iter().enumerate() {
                if let Some(row) = rows.get_mut(popup.list_y + index) {
                    overlay(row, popup.x, line);
                }
            }
            let x = typed.chars().count().min(popup.width.saturating_sub(1));
            cursor = Some((popup.x + x, popup.input_y));
        }
        (rows, cursor)
    }
}