cellix 0.5.1

The AI companion IDE inside your agent: a Claude Code mod, Codex plugin and Gemini CLI extension
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Source Control in the sidebar: what's staged, what isn't, and a message to commit it with.
//! Review is for reading what changed. This is for deciding what goes in.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver};

use cellix_render::{Bounds, Font, Grid, Icon, Measure, Rect, Style};
use cellix_review::{Entry, ahead_behind, status_entries};

use crate::explorer::file_color;
use crate::theme::Theme;
use crate::threads::wrap;

const SIDE: u16 = 2;
/// Rows of the message box.
const MESSAGE_ROWS: u16 = 3;
/// Where a row's marks stand, from the panel's right edge.
const LETTER_FROM_RIGHT: u16 = 3;
pub const STAGE_FROM_RIGHT: u16 = 5;
pub const DISCARD_FROM_RIGHT: u16 = 7;
/// How wide the button beside Commit is.
const SYNC_WIDTH: u16 = 10;
/// Columns from a row's icon to its name.
const NAME_FROM_ICON: u16 = 3;
/// Cells between a file's name and its folder.
const FOLDER_GAP: f32 = 0.8;
/// How far the message box stands past its rows, so its text has air above it.
const BOX_ROOM: f32 = 0.12;

/// What a click in the panel lands on.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Hit {
    Message,
    Commit,
    Sync,
    StageAll,
    UnstageAll,
    Open(PathBuf),
    Stage(PathBuf),
    Unstage(PathBuf),
    Discard(PathBuf, bool),
}

/// One row of the panel.
#[derive(Clone, Debug, PartialEq)]
enum Line {
    Title,
    Message(u16),
    Gap,
    Buttons,
    Heading(bool, usize),
    Change(usize, bool),
    Clean,
}

/// How things stand with the remote.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Remote {
    /// Commits to push and to pull, or None with no upstream.
    pub counts: Option<(usize, usize)>,
    pub can_publish: bool,
}

#[derive(Default)]
pub struct Source {
    pub entries: Vec<Entry>,
    pub message: String,
    pub focused: bool,
    pub remote: Remote,
    /// Pushing or pulling, as what to say while it does.
    pub busy: Option<&'static str>,
    /// The file whose changes are showing beside the panel.
    pub shown: Option<PathBuf>,
    top: usize,
    reading: Option<Receiver<(Vec<Entry>, Remote)>>,
}

impl Source {
    /// Reads the state of the repository, away from the screen.
    pub fn refresh(&mut self, root: &Path) {
        if self.reading.is_some() {
            return;
        }
        let root = root.to_path_buf();
        let (done, reading) = mpsc::channel();
        std::thread::spawn(move || {
            let entries = status_entries(&root);
            let counts = ahead_behind(&root);
            let remote = Remote {
                counts,
                can_publish: counts.is_none() && cellix_review::has_remote(&root),
            };
            let _ = done.send((entries, remote));
        });
        self.reading = Some(reading);
    }

    /// Reads again after a change, so what was already on its way can't undo it.
    pub fn reread(&mut self, root: &Path) {
        self.reading = None;
        self.refresh(root);
    }

    /// Takes in what was read. Returns true if it changed anything.
    pub fn poll(&mut self) -> bool {
        let Some(read) = self.reading.as_ref().and_then(|r| r.try_recv().ok()) else {
            return false;
        };
        self.reading = None;
        let changed = self.entries != read.0 || self.remote != read.1;
        (self.entries, self.remote) = read;
        changed
    }

    pub fn staged(&self) -> Vec<PathBuf> {
        let staged = self.entries.iter().filter(|e| e.is_staged());
        staged.map(|e| e.path.clone()).collect()
    }

    pub fn unstaged(&self) -> Vec<PathBuf> {
        let open = self.entries.iter().filter(|e| e.is_unstaged());
        open.map(|e| e.path.clone()).collect()
    }

    pub fn scroll_by(&mut self, delta: isize) {
        self.top = self.top.saturating_add_signed(delta);
    }

    fn lines(&self) -> Vec<Line> {
        let mut lines = vec![Line::Title, Line::Gap, Line::Message(0)];
        lines.extend((1..MESSAGE_ROWS).map(Line::Message));
        lines.extend([Line::Gap, Line::Buttons, Line::Gap]);
        let list = |lines: &mut Vec<Line>, staged: bool| {
            let matching = |entry: &&Entry| {
                if staged {
                    entry.is_staged()
                } else {
                    entry.is_unstaged()
                }
            };
            let count = self.entries.iter().filter(matching).count();
            if count == 0 {
                return;
            }
            lines.push(Line::Heading(staged, count));
            let rows = self.entries.iter().enumerate();
            let rows = rows.filter(|(_, entry)| matching(entry));
            lines.extend(rows.map(|(index, _)| Line::Change(index, staged)));
            lines.push(Line::Gap);
        };
        if self.entries.is_empty() {
            lines.push(Line::Clean);
        }
        list(&mut lines, true);
        list(&mut lines, false);
        lines
    }

    /// Where the Commit and Sync buttons stand on their row.
    fn buttons(&self, area: Rect, y: u16) -> (Rect, Option<Rect>) {
        let left = area.x + SIDE;
        let width = area.w.saturating_sub(SIDE * 2);
        if self.sync_label().is_some() && width > SYNC_WIDTH + 8 {
            let commit = Rect::new(left, y, width - SYNC_WIDTH - 1, 1);
            let sync = Rect::new(commit.right() + 1, y, SYNC_WIDTH, 1);
            (commit, Some(sync))
        } else {
            (Rect::new(left, y, width, 1), None)
        }
    }

    fn commit_label(&self) -> &'static str {
        if self.staged().is_empty() && !self.entries.is_empty() {
            "Commit All"
        } else {
            "Commit"
        }
    }

    /// What the button beside Commit says, if there's anything to do with the remote.
    pub fn sync_label(&self) -> Option<String> {
        if let Some(busy) = self.busy {
            return Some(busy.to_string());
        }
        match self.remote.counts {
            Some((0, 0)) => None,
            Some((ahead, 0)) => Some(format!("Push {ahead}")),
            Some((0, behind)) => Some(format!("Pull {behind}")),
            Some(_) => Some("Sync".to_string()),
            None if self.remote.can_publish => Some("Publish".to_string()),
            None => None,
        }
    }

    pub fn hit(&self, area: Rect, x: u16, y: u16) -> Option<Hit> {
        let row = y.checked_sub(area.y)? as usize + self.top;
        let line = self.lines().into_iter().nth(row)?;
        let right = area.right();
        match line {
            Line::Message(_) => Some(Hit::Message),
            Line::Buttons => {
                let (commit, sync) = self.buttons(area, y);
                if sync.is_some_and(|b| b.contains(x, y)) {
                    return Some(Hit::Sync);
                }
                commit.contains(x, y).then_some(Hit::Commit)
            }
            Line::Heading(staged, _) => {
                let on_action = x + STAGE_FROM_RIGHT + 1 >= right;
                on_action.then_some(if staged {
                    Hit::UnstageAll
                } else {
                    Hit::StageAll
                })
            }
            Line::Change(index, staged) => {
                let entry = self.entries.get(index)?;
                let path = entry.path.clone();
                let stage = right.saturating_sub(STAGE_FROM_RIGHT);
                let discard = right.saturating_sub(DISCARD_FROM_RIGHT);
                if x == stage || x == stage + 1 {
                    return Some(if staged {
                        Hit::Unstage(path)
                    } else {
                        Hit::Stage(path)
                    });
                }
                if !staged && (x == discard || x == discard + 1) {
                    return Some(Hit::Discard(path, entry.is_untracked()));
                }
                Some(Hit::Open(path))
            }
            _ => None,
        }
    }

    pub fn draw(
        &self,
        grid: &mut Grid,
        area: Rect,
        branch: Option<&str>,
        hover: Option<(u16, u16)>,
        measure: &dyn Measure,
        theme: &Theme,
    ) {
        grid.fill(area, theme.sidebar);
        let quiet = Style {
            fg: theme.gutter.fg,
            ..theme.sidebar
        };
        let left = area.x + SIDE;
        let right = area.right();
        let lines = self.lines();
        for (row, line) in lines
            .iter()
            .skip(self.top)
            .take(area.h as usize)
            .enumerate()
        {
            let y = area.y + row as u16;
            let whole = Rect::new(area.x, y, area.w, 1);
            let hovered = hover.is_some_and(|h| whole.contains(h.0, h.1));
            match line {
                Line::Title => {
                    grid.label(left, y, "SOURCE CONTROL", quiet, right);
                    if let Some(branch) = branch {
                        grid.label_right(right.saturating_sub(SIDE), y, branch, quiet, 90);
                    }
                }
                Line::Message(0) => self.draw_message(grid, area, y, measure, theme),
                Line::Message(_) | Line::Gap => {}
                Line::Buttons => self.draw_buttons(grid, area, y, hover, theme),
                Line::Clean => {
                    grid.label(left, y, "No changes", quiet, right);
                }
                Line::Heading(staged, count) => {
                    let name = if *staged { "STAGED CHANGES" } else { "CHANGES" };
                    grid.label(left, y, name, quiet, right);
                    let number = count.to_string();
                    grid.label_right(right.saturating_sub(SIDE), y, &number, quiet, 100);
                    if hovered {
                        let mark = if *staged { "−" } else { "+" };
                        let x = right.saturating_sub(STAGE_FROM_RIGHT);
                        grid.label(x, y, mark, theme.sidebar, right);
                    }
                }
                Line::Change(index, staged) => {
                    let Some(entry) = self.entries.get(*index) else {
                        continue;
                    };
                    let showing = self.shown.as_ref() == Some(&entry.path);
                    if hovered || showing {
                        let tone = if showing {
                            theme.row_active
                        } else {
                            theme.row_hover
                        };
                        let wash = Bounds::inset(whole, 0.4, 0.06);
                        grid.panel(wash, 14, Some(tone), None);
                    }
                    let look = (measure, theme);
                    self.draw_change(grid, area, y, (entry, *staged), hovered, look);
                }
            }
        }
    }

    fn draw_message(
        &self,
        grid: &mut Grid,
        area: Rect,
        y: u16,
        measure: &dyn Measure,
        theme: &Theme,
    ) {
        let left = area.x + SIDE;
        let width = area.w.saturating_sub(SIDE * 2);
        let frame = Rect::new(left, y, width, MESSAGE_ROWS);
        let edge = if self.focused {
            theme.accent
        } else {
            theme.popup_border
        };
        let tall = MESSAGE_ROWS as f32 + BOX_ROOM * 2.0;
        let outline = Bounds::cells(left as f32, y as f32 - BOX_ROOM, width as f32, tall);
        grid.panel(outline, 22, Some(theme.text.bg), Some(edge));
        let inner = width.saturating_sub(2).max(1) as f32;
        let hint = "Message (Enter to commit)";
        let rows = if self.message.is_empty() {
            Vec::new()
        } else {
            wrap(&format!("{} ", self.message), inner, measure)
        };
        let writing = Style {
            bg: theme.text.bg,
            ..theme.text
        };
        if rows.is_empty() {
            let quiet = Style {
                fg: theme.gutter.fg,
                ..writing
            };
            grid.label(left + 1, y, hint, quiet, frame.right());
        }
        let shown = rows.len().saturating_sub(MESSAGE_ROWS as usize);
        let visible = rows.iter().skip(shown).take(MESSAGE_ROWS as usize);
        for (offset, row) in visible.enumerate() {
            grid.label(left + 1, y + offset as u16, row, writing, frame.right());
        }
        if self.focused {
            let last = rows.len().saturating_sub(shown).saturating_sub(1) as u16;
            let across = rows.last().map_or(0.0, |r| {
                measure.width(r.trim_end_matches(' '), Font::default())
            });
            grid.set_caret(left as f32 + 1.0 + across, y + last, 0.62);
        }
    }

    fn draw_buttons(
        &self,
        grid: &mut Grid,
        area: Rect,
        y: u16,
        hover: Option<(u16, u16)>,
        theme: &Theme,
    ) {
        let (commit, sync) = self.buttons(area, y);
        let ready = !self.entries.is_empty();
        let fill = if ready {
            theme.button
        } else {
            theme.quiet_button(theme.sidebar.bg)
        };
        let label = Style {
            fg: if ready {
                theme.button_text
            } else {
                theme.gutter.fg
            },
            bg: fill,
            ..theme.sidebar
        };
        let name = self.commit_label();
        let cells = format!("{name:^0$}", commit.w as usize);
        grid.large_button(commit.x, y, &cells, name, fill, label);
        if let (Some(button), Some(name)) = (sync, self.sync_label()) {
            let on_it = hover.is_some_and(|h| button.contains(h.0, h.1));
            let fill = if on_it {
                theme.row_hover
            } else {
                theme.quiet_button(theme.sidebar.bg)
            };
            let label = Style {
                bg: fill,
                ..theme.sidebar
            };
            let cells = format!("{name:^0$}", button.w as usize);
            grid.large_button(button.x, y, &cells, &name, fill, label);
        }
    }

    fn draw_change(
        &self,
        grid: &mut Grid,
        area: Rect,
        y: u16,
        (entry, staged): (&Entry, bool),
        hovered: bool,
        (measure, theme): (&dyn Measure, &Theme),
    ) {
        let right = area.right();
        let letter = entry.letter(staged);
        let colour = match letter {
            'A' | 'U' => theme.git_added,
            'D' => theme.deleted(),
            _ => theme.git_modified,
        };
        let name = entry
            .path
            .file_name()
            .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
        let end = right.saturating_sub(if hovered {
            DISCARD_FROM_RIGHT + 1
        } else {
            LETTER_FROM_RIGHT + 1
        });
        let icon = area.x + SIDE;
        grid.glyph(
            icon as f32,
            y,
            Icon::File,
            file_color(&name),
            "▪",
            theme.sidebar,
        );
        let at = icon + NAME_FROM_ICON;
        grid.label(at, y, &name, theme.sidebar, end);
        if let Some(folder) = entry.path.parent().filter(|f| !f.as_os_str().is_empty()) {
            let quiet = Style {
                fg: theme.gutter.fg,
                ..theme.sidebar
            };
            // Set after the name as it's drawn, which isn't how many cells it would fill.
            let x = at as f32 + measure.width(&name, Font::default()) + FOLDER_GAP;
            let folder = folder.display().to_string();
            grid.label_at(x, x.ceil() as u16, y, &folder, quiet, end, 100);
        }
        let mark = Style {
            fg: colour,
            ..theme.sidebar
        };
        let edge = right.saturating_sub(SIDE);
        grid.label_right(edge, y, letter.encode_utf8(&mut [0; 4]), mark, 100);
        if hovered {
            let stage = right.saturating_sub(STAGE_FROM_RIGHT);
            grid.label(
                stage,
                y,
                if staged { "−" } else { "+" },
                theme.sidebar,
                stage + 2,
            );
            if !staged {
                let discard = right.saturating_sub(DISCARD_FROM_RIGHT);
                grid.label(discard, y, "↺", theme.sidebar, discard + 2);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_read_from_before_a_change_doesnt_undo_it() {
        let dir = tempfile::tempdir().unwrap();
        let (late, reading) = mpsc::channel();
        let mut source = Source {
            reading: Some(reading),
            ..Source::default()
        };
        source.reread(dir.path());
        let stale = Entry {
            path: PathBuf::from("gone.txt"),
            index: 'M',
            worktree: ' ',
        };
        // The channel it came down was dropped, so nothing can arrive by it.
        assert!(late.send((vec![stale], Remote::default())).is_err());
    }
}