ferrodock 1.30.1

A fast, native container manager for Docker, written in Rust.
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
//! The list table every page uses: header row, whole-row hover and click
//! to select, plus a few standard cell styles.

use eframe::egui::{self, Align, Layout, RichText, Sense};
use egui_extras::{Column, TableBuilder, TableRow};

use super::icons::{self, Icon};
use crate::theme::Palette;

const ROW_HEIGHT: f32 = 48.0;
/// The narrowest a name column gets before other columns make way for it.
const NAME_MIN: f32 = 180.0;
const COMPACT_ROW_HEIGHT: f32 = 30.0;

/// Switches every table between two-line and one-line rows.
pub fn set_compact(ctx: &egui::Context, compact: bool) {
    ctx.data_mut(|d| d.insert_temp(compact_id(), compact));
}

/// Whether tables use one-line rows (the Compact density setting).
pub fn is_compact(ui: &egui::Ui) -> bool {
    ui.data(|d| d.get_temp(compact_id()).unwrap_or(false))
}

fn compact_id() -> egui::Id {
    egui::Id::unique("ferrodock-compact")
}

/// How many of the shown rows are ticked, for the Select all box.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ticked {
    None,
    Some,
    All,
}

impl Ticked {
    pub fn of(ticked: usize, shown: usize) -> Self {
        match ticked {
            0 => Ticked::None,
            n if n >= shown => Ticked::All,
            _ => Ticked::Some,
        }
    }
}

/// A column: header title and sizing.
pub struct Col {
    pub title: &'static str,
    pub width: Column,
    /// For the tick-box column: draws Select all in the header.
    pub ticked: Option<Ticked>,
}

impl Col {
    /// The narrow first column of tick boxes, with Select all on top.
    pub fn ticks(ticked: Ticked) -> Self {
        Self {
            title: "",
            width: Column::exact(28.0),
            ticked: Some(ticked),
        }
    }

    /// Takes the space left over by the fixed columns.
    pub fn fill(title: &'static str) -> Self {
        Self {
            title,
            width: Column::remainder().at_least(160.0).clip(true),
            ticked: None,
        }
    }

    pub fn fixed(title: &'static str, width: f32) -> Self {
        Self {
            title,
            width: Column::exact(width).clip(true),
            ticked: None,
        }
    }
}

/// Which of the `optional` column widths fit next to a name column of a
/// readable width, given the widths of the always-shown columns. Columns
/// are tried in order, so put the most useful first.
pub fn fitting(ui: &egui::Ui, required: &[f32], optional: &[f32]) -> Vec<bool> {
    let gap = ui.spacing().item_spacing.x;
    let scroll = &ui.spacing().scroll;
    let taken: f32 = required.iter().map(|w| w + gap).sum();
    let mut room = ui.available_width()
        - taken
        - (NAME_MIN + gap)
        - (scroll.bar_width + scroll.bar_outer_margin);
    optional
        .iter()
        .map(|&width| {
            let fits = width + gap <= room;
            if fits {
                room -= width + gap;
            }
            fits
        })
        .collect()
}

/// Asks the next table drawn to move its selection by `delta` rows (↑/↓),
/// or with 0 just to scroll the selected row into view.
pub fn request_step(ctx: &egui::Context, delta: i32) {
    ctx.data_mut(|d| d.insert_temp(step_id(), delta));
}

/// Drops a step no table picked up this frame (e.g. the list was empty).
pub fn clear_step(ctx: &egui::Context) {
    ctx.data_mut(|d| d.remove_temp::<i32>(step_id()));
}

fn step_id() -> egui::Id {
    egui::Id::unique("ferrodock-table-step")
}

fn select_all_id(table: &str) -> egui::Id {
    egui::Id::unique("ferrodock-table-select-all").with(table)
}

/// Whether the Select all box of table `id` was clicked when it was last
/// drawn (this frame).
pub fn select_all_clicked(ui: &egui::Ui, id: &str) -> bool {
    ui.data_mut(|d| d.remove_temp::<bool>(select_all_id(id)))
        .unwrap_or(false)
}

/// A tick box for one row; `name` is what it selects, for screen readers.
/// Returns true when clicked.
pub fn tick(ui: &mut egui::Ui, p: &Palette, on: bool, name: &str) -> bool {
    let state = if on { Ticked::All } else { Ticked::None };
    tick_box(ui, p, state, &format!("Select {name}"))
}

/// A tick box that can also show "some ticked", e.g. for a group.
pub fn tick_state(ui: &mut egui::Ui, p: &Palette, state: Ticked, label: &str) -> bool {
    tick_box(ui, p, state, label)
}

fn tick_box(ui: &mut egui::Ui, p: &Palette, state: Ticked, label: &str) -> bool {
    let (rect, response) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), Sense::click());
    let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
    response.widget_info(|| {
        egui::WidgetInfo::selected(egui::Role::CheckBox, true, state == Ticked::All, label)
    });
    let painter = ui.painter();
    let corner = egui::CornerRadius::same(4);
    if state == Ticked::None {
        let stroke = if response.hovered() {
            p.accent
        } else {
            p.muted.gamma_multiply(0.6)
        };
        painter.rect_stroke(
            rect.shrink(0.5),
            corner,
            egui::Stroke::new(1.3, stroke),
            egui::StrokeKind::Inside,
        );
    } else {
        painter.rect_filled(rect, corner, p.accent);
        let white = egui::Stroke::new(2.0, p.on_accent);
        let c = rect.center();
        if state == Ticked::All {
            painter.line(
                vec![
                    c + egui::vec2(-4.0, 0.0),
                    c + egui::vec2(-1.0, 3.0),
                    c + egui::vec2(4.5, -3.5),
                ],
                white,
            );
        } else {
            painter.line_segment([c + egui::vec2(-4.0, 0.0), c + egui::vec2(4.0, 0.0)], white);
        }
    }
    response.clicked()
}

/// The row a step of `delta` lands on, if it moves at all.
fn step(current: Option<usize>, delta: i32, rows: usize) -> Option<usize> {
    if rows == 0 || delta == 0 {
        return None;
    }
    let Some(current) = current else {
        return Some(if delta > 0 { 0 } else { rows - 1 });
    };
    let next = (current as i64 + i64::from(delta)).clamp(0, rows as i64 - 1) as usize;
    (next != current).then_some(next)
}

/// Draws a table with `rows` rows. `add_row` fills in the cells of one row
/// (one `row.col(..)` per column); `label` names a row for screen readers.
/// Returns the index of a row that was clicked or stepped to with the
/// keyboard.
#[allow(clippy::too_many_arguments)]
pub fn show(
    ui: &mut egui::Ui,
    p: &Palette,
    id: &str,
    columns: Vec<Col>,
    rows: usize,
    is_selected: impl Fn(usize) -> bool,
    label: impl Fn(usize) -> String,
    mut add_row: impl FnMut(usize, &mut TableRow<'_, '_>),
) -> Option<usize> {
    let row_height = if is_compact(ui) {
        COMPACT_ROW_HEIGHT
    } else {
        ROW_HEIGHT
    };
    let requested = ui.ctx().data_mut(|d| d.remove_temp::<i32>(step_id()));
    let current = requested.and_then(|_| (0..rows).find(|&i| is_selected(i)));
    let stepped = requested.and_then(|delta| step(current, delta, rows));

    let mut clicked = stepped;
    let mut builder = TableBuilder::new(ui)
        .id_salt(id)
        .sense(Sense::click())
        .cell_layout(Layout::left_to_right(Align::Center));
    if let Some(row) = stepped.or(current) {
        builder = builder.scroll_to_row(row, None);
    }
    for col in &columns {
        builder = builder.column(col.width);
    }
    builder
        .header(26.0, |mut header| {
            for col in &columns {
                header.col(|ui| match col.ticked {
                    Some(state) => {
                        let label = if state == Ticked::All {
                            "Select none"
                        } else {
                            "Select all"
                        };
                        if tick_box(ui, p, state, label) {
                            ui.data_mut(|d| d.insert_temp(select_all_id(id), true));
                        }
                    }
                    None => {
                        ui.label(RichText::new(col.title).size(11.0).color(p.muted));
                    }
                });
            }
        })
        .body(|body| {
            body.rows(row_height, rows, |mut row| {
                let index = row.index();
                let selected = is_selected(index);
                row.set_selected(selected);
                add_row(index, &mut row);
                let response = row.response();
                // A row, not just a clickable area: its name, and whether
                // it's selected.
                response.ctx.accesskit_node_builder(response.id, |node| {
                    node.set_role(egui::accesskit::Role::Row);
                    node.set_label(label(index));
                    node.set_selected(selected);
                });
                if response.clicked() {
                    clicked = Some(index);
                }
            });
        });
    clicked
}

/// Like [`two_line`], with a coloured icon in front, e.g. a container
/// coloured by its state.
pub fn with_icon(
    ui: &mut egui::Ui,
    p: &Palette,
    icon: Icon,
    color: egui::Color32,
    primary: &str,
    secondary: &str,
) {
    let size = if is_compact(ui) { 18.0 } else { 30.0 };
    let (rect, _) = ui.allocate_exact_size(egui::vec2(size, size), Sense::hover());
    ui.painter().rect_filled(
        rect,
        egui::CornerRadius::same(7),
        color.gamma_multiply(0.12),
    );
    icons::paint(ui.painter(), rect.shrink(size * 0.22), icon, color);
    ui.add_space(4.0);
    two_line(ui, p, primary, secondary);
}

/// Primary text with a muted second line, e.g. name over image. In
/// compact mode both go on one line.
pub fn two_line(ui: &mut egui::Ui, p: &Palette, primary: &str, secondary: &str) {
    let font = egui::FontId::new(13.5, crate::theme::semibold());
    let primary_text = |ui: &egui::Ui| {
        RichText::new(fit_middle(ui, primary, &font))
            .font(font.clone())
            .color(p.text)
    };
    if is_compact(ui) {
        let primary_text = primary_text(ui);
        label(ui, primary_text);
        label(ui, RichText::new(secondary).size(12.0).color(p.muted));
        return;
    }
    ui.vertical(|ui| {
        ui.add_space(6.0);
        let primary_text = primary_text(ui);
        label(ui, primary_text);
        label(ui, RichText::new(secondary).size(12.0).color(p.muted));
    });
}

/// Shortens `text` in the middle until it fits the width left, keeping
/// more of the end: that's what tells `mirror.gcr.io/…/ubuntu:act-22.04`
/// from its neighbours, or `proj-web-1` from `proj-web-2`.
fn fit_middle(ui: &egui::Ui, text: &str, font: &egui::FontId) -> String {
    let width = ui.available_width();
    let measure = |s: String| {
        ui.fonts_mut(|f| f.layout_no_wrap(s, font.clone(), egui::Color32::PLACEHOLDER))
            .size()
            .x
    };
    if measure(text.to_owned()) <= width {
        return text.to_owned();
    }
    let chars: Vec<char> = text.chars().collect();
    // The most characters that still fit, by bisection.
    let (mut lo, mut hi) = (0, chars.len());
    while lo < hi {
        let mid = (lo + hi).div_ceil(2);
        if measure(squeeze(&chars, mid)) <= width {
            lo = mid;
        } else {
            hi = mid - 1;
        }
    }
    squeeze(&chars, lo)
}

/// `keep` characters of `chars`, a third from the start and the rest from
/// the end, with "…" between.
fn squeeze(chars: &[char], keep: usize) -> String {
    let head = keep / 3;
    let tail = keep - head;
    let mut out: String = chars[..head].iter().collect();
    out.push('…');
    out.extend(&chars[chars.len() - tail..]);
    out
}

/// Whether the pointer is over the row this cell belongs to.
pub fn row_hovered(ui: &egui::Ui) -> bool {
    let cell = ui.max_rect();
    ui.ctx().pointer_hover_pos().is_some_and(|pos| {
        ui.clip_rect().contains(pos) && pos.y >= cell.top() && pos.y < cell.bottom()
    })
}

pub fn text(ui: &mut egui::Ui, p: &Palette, value: &str) {
    label(ui, RichText::new(value).color(p.text));
}

pub fn muted(ui: &mut egui::Ui, p: &Palette, value: &str) {
    label(ui, RichText::new(value).color(p.muted));
}

pub fn mono(ui: &mut egui::Ui, p: &Palette, value: &str) {
    label(ui, RichText::new(value).monospace().color(p.muted));
}

/// Non-selectable, truncating label so clicks select the row instead.
fn label(ui: &mut egui::Ui, text: RichText) {
    ui.add(egui::Label::new(text).truncate().selectable(false));
}

#[cfg(test)]
mod tests {
    use super::{squeeze, step};

    #[test]
    fn squeezes_keeping_more_of_the_end() {
        let chars: Vec<char> = "mirror.gcr.io/catthehacker/ubuntu:act-22.04"
            .chars()
            .collect();
        assert_eq!(squeeze(&chars, 21), "mirror.…untu:act-22.04");
        assert_eq!(squeeze(&chars, 0), "…");
    }

    #[test]
    fn steps_through_rows() {
        assert_eq!(step(None, 1, 3), Some(0));
        assert_eq!(step(None, -1, 3), Some(2));
        assert_eq!(step(Some(0), 1, 3), Some(1));
        assert_eq!(step(Some(2), 1, 3), None);
        assert_eq!(step(Some(0), -1, 3), None);
        assert_eq!(step(Some(1), 0, 3), None);
        assert_eq!(step(None, 1, 0), None);
    }
}