ferrodock 1.8.0

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
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
//! The container list, optionally grouped by Compose project under
//! collapsible headers.

use eframe::egui;

use super::{ContainersPage, actions, ports, status};
use crate::app::components::icons::Icon;
use std::collections::VecDeque;

use crate::app::components::{sparkline, table, widgets};
use crate::app::page::{PageCtx, toggle_selection};
use crate::app::pages::{confirm_removal, remove_task};
use crate::docker::{Action, ContainerInfo, Resource, StatsSample, Task, format_size};
use crate::theme::Palette;

/// One line of the list.
enum Row<'a> {
    /// A Compose project (None: containers in no project) and its
    /// containers.
    Group {
        project: Option<&'a str>,
        containers: Vec<&'a ContainerInfo>,
    },
    /// A container; `grouped` indents it under its project.
    Item {
        container: &'a ContainerInfo,
        grouped: bool,
    },
}

fn grouping_id() -> egui::Id {
    egui::Id::unique("containers-grouped-by-project")
}

/// Whether the list is grouped by Compose project (remembered between runs).
fn grouped(ui: &egui::Ui) -> bool {
    ui.data_mut(|d| d.get_persisted::<bool>(grouping_id()))
        .unwrap_or(false)
}

/// The "Group by project" switch.
pub(super) fn grouping_toggle(ui: &mut egui::Ui) {
    let mut on = grouped(ui);
    if ui
        .toggle_value(&mut on, "Group by project")
        .on_hover_text("Show containers under their Compose project")
        .changed()
    {
        ui.data_mut(|d| d.insert_persisted(grouping_id(), on));
    }
}

/// The rows to show: containers as they are, or grouped by project with
/// folded projects' containers left out.
fn rows<'a>(
    visible: &[&'a ContainerInfo],
    grouped: bool,
    collapsed: &std::collections::BTreeSet<String>,
) -> Vec<Row<'a>> {
    if !grouped {
        return visible
            .iter()
            .map(|c| Row::Item {
                container: c,
                grouped: false,
            })
            .collect();
    }
    let mut projects: std::collections::BTreeMap<&str, Vec<&ContainerInfo>> = Default::default();
    let mut loose = Vec::new();
    for c in visible {
        match &c.compose {
            Some(labels) => projects.entry(labels.project.as_str()).or_default().push(c),
            None => loose.push(*c),
        }
    }
    let mut groups: Vec<(Option<&str>, Vec<&ContainerInfo>)> =
        projects.into_iter().map(|(p, cs)| (Some(p), cs)).collect();
    if !loose.is_empty() {
        groups.push((None, loose));
    }
    let mut rows = Vec::new();
    for (project, containers) in groups {
        let folded = collapsed.contains(project.unwrap_or(""));
        let items: Vec<Row> = if folded {
            Vec::new()
        } else {
            containers
                .iter()
                .map(|c| Row::Item {
                    container: c,
                    grouped: true,
                })
                .collect()
        };
        rows.push(Row::Group {
            project,
            containers,
        });
        rows.extend(items);
    }
    rows
}

pub(super) fn show(
    page: &mut ContainersPage,
    ui: &mut egui::Ui,
    ctx: &mut PageCtx,
    visible: &[&ContainerInfo],
) {
    let p = ctx.palette;
    let store = ctx.store;

    // Drop the less important columns when space is tight (e.g. with the
    // details pane open); both are still shown in the details pane.
    let width = ui.available_width();
    let show_ports = width >= 700.0;
    let show_id = width >= 560.0;
    let show_usage = width >= 860.0;
    let mut columns = vec![table::Col::fill("NAME"), table::Col::fixed("STATUS", 150.0)];
    if show_id {
        columns.push(table::Col::fixed("ID", 110.0));
    }
    if show_usage {
        columns.push(table::Col::fixed("CPU", 104.0));
        columns.push(table::Col::fixed("MEMORY", 90.0));
    }
    if show_ports {
        columns.push(table::Col::fixed("PORTS", 140.0));
    }
    columns.push(table::Col::fixed("", 100.0));

    if !page.marked.is_empty() {
        bulk_bar(page, ui, ctx, visible);
    }

    let selected = page.selected.clone();
    let marked = page.marked.clone();
    let rows = rows(visible, grouped(ui), &page.collapsed);
    let columns_count = columns.len();
    let clicked = table::show(
        ui,
        p,
        "containers",
        columns,
        rows.len(),
        |i| match &rows[i] {
            Row::Item { container: c, .. } => {
                selected.as_deref() == Some(c.id.as_str()) || marked.contains(&c.id)
            }
            Row::Group { .. } => false,
        },
        |i, row| {
            let (c, indented) = match &rows[i] {
                Row::Item { container, grouped } => (*container, *grouped),
                Row::Group {
                    project,
                    containers,
                } => {
                    let folded = page.collapsed.contains(project.unwrap_or(""));
                    group_row(row, ctx, *project, containers, folded, columns_count);
                    return;
                }
            };
            row.col(|ui| {
                if indented {
                    ui.add_space(18.0);
                }
                let color = status::color(p, &c.state);
                table::with_icon(ui, p, Icon::Container, color, &c.name, &c.image)
            });
            row.col(|ui| status::cell(ui, p, c, store.pending.get(&c.id).copied()));
            if show_id {
                row.col(|ui| table::mono(ui, p, c.short_id()));
            }
            if show_usage {
                let history = store.usage.get(&c.id);
                row.col(|ui| cpu_cell(ui, p, history));
                row.col(|ui| {
                    let memory = history
                        .and_then(|h| h.back())
                        .map(|s| format_size(s.memory_used as i64));
                    table::muted(ui, p, memory.as_deref().unwrap_or("—"));
                });
            }
            if show_ports {
                row.col(|ui| ports::cell(ui, p, &c.ports));
            }
            let selected_row = selected.as_deref() == Some(c.id.as_str());
            row.col(|ui| {
                ui.spacing_mut().item_spacing.x = 2.0;
                let busy = store.pending.contains_key(&c.id);
                // Actions show on the hovered or selected row only, so idle
                // rows stay calm.
                if (busy || selected_row || table::row_hovered(ui))
                    && let Some(action) = actions::buttons(ui, c, busy, false)
                {
                    ctx.request(actions::intent(action, c));
                }
            });
        },
    );
    let clicked = match clicked.map(|i| &rows[i]) {
        Some(Row::Group { project, .. }) => {
            // Fold or unfold the project.
            let key = project.unwrap_or("").to_owned();
            if !page.collapsed.remove(&key) {
                page.collapsed.insert(key);
            }
            None
        }
        Some(Row::Item { container, .. }) => visible.iter().position(|c| c.id == container.id),
        None => None,
    };
    if let Some(i) = clicked {
        let modifiers = ui.input(|input| input.modifiers);
        let id = visible[i].id.clone();
        if modifiers.shift && !page.marked.is_empty() {
            // Mark everything between the last marked row and this one.
            let anchor = page
                .anchor
                .as_ref()
                .and_then(|a| visible.iter().position(|c| c.id == *a))
                .unwrap_or(i);
            let (from, to) = (anchor.min(i), anchor.max(i));
            page.marked
                .extend(visible[from..=to].iter().map(|c| c.id.clone()));
        } else if modifiers.command {
            if !page.marked.remove(&id) {
                // Start the selection with the row that was open, if any.
                if let Some(open) = page.selected.take() {
                    page.marked.insert(open);
                }
                page.marked.insert(id.clone());
            }
            page.anchor = Some(id);
        } else {
            page.marked.clear();
            toggle_selection(&mut page.selected, id.clone());
            page.anchor = Some(id);
        }
    }
}

/// A project's header: fold arrow, name, how many run, and actions for
/// all of its containers.
fn group_row(
    row: &mut egui_extras::TableRow<'_, '_>,
    ctx: &mut PageCtx,
    project: Option<&str>,
    containers: &[&ContainerInfo],
    folded: bool,
    columns: usize,
) {
    let p = ctx.palette;
    let running = containers.iter().filter(|c| c.is_active()).count();
    row.col(|ui| {
        let chevron = if folded {
            Icon::ChevronRight
        } else {
            Icon::ChevronDown
        };
        let (rect, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover());
        crate::app::components::icons::paint(ui.painter(), rect, chevron, p.muted);
        let name = project.unwrap_or("Other containers");
        ui.label(
            egui::RichText::new(name)
                .font(egui::FontId::new(14.0, crate::theme::semibold()))
                .color(p.text),
        );
        let count = if project.is_some() {
            format!("{running}/{} running", containers.len())
        } else {
            format!("{running} running")
        };
        ui.label(egui::RichText::new(count).size(12.0).color(p.muted));
    });
    // Empty cells up to the actions column.
    for _ in 1..columns - 1 {
        row.col(|_| {});
    }
    row.col(|ui| {
        if project.is_none() {
            return;
        }
        ui.spacing_mut().item_spacing.x = 2.0;
        let tasks = |action: Action, wanted: bool| -> Vec<Task> {
            containers
                .iter()
                .filter(|c| c.is_active() == wanted)
                .map(|c| Task {
                    action,
                    id: c.id.clone(),
                    name: c.name.clone(),
                })
                .collect()
        };
        let mut run = Vec::new();
        if running < containers.len() && widgets::icon_button(ui, Icon::Play, "Start all").clicked()
        {
            run = tasks(Action::Start, false);
        }
        if running > 0 {
            if widgets::icon_button(ui, Icon::Stop, "Stop all").clicked() {
                run = tasks(Action::Stop, true);
            }
            if widgets::icon_button(ui, Icon::Restart, "Restart all").clicked() {
                run = tasks(Action::Restart, true);
            }
        }
        for task in run {
            ctx.request(crate::app::page::Intent::Run(task));
        }
    });
}

/// CPU now, with a small trend line; amber above 80%.
fn cpu_cell(ui: &mut egui::Ui, p: &Palette, history: Option<&VecDeque<StatsSample>>) {
    let Some(latest) = history.and_then(|h| h.back()) else {
        table::muted(ui, p, "—");
        return;
    };
    let busy = latest.cpu_percent >= 80.0;
    let color = if busy { p.warning } else { p.accent };
    ui.add(
        egui::Label::new(
            egui::RichText::new(format!("{:.1}%", latest.cpu_percent)).color(if busy {
                p.warning
            } else {
                p.text
            }),
        )
        .selectable(false),
    );
    let values: Vec<f64> = history
        .into_iter()
        .flatten()
        .map(|s| s.cpu_percent)
        .collect();
    let max = values.iter().copied().fold(10.0, f64::max);
    sparkline::tiny(ui, &values, max, color, egui::vec2(36.0, 14.0));
}

/// "3 selected" with the actions that apply to them.
fn bulk_bar(
    page: &mut ContainersPage,
    ui: &mut egui::Ui,
    ctx: &mut PageCtx,
    visible: &[&ContainerInfo],
) {
    let p = ctx.palette;
    let chosen: Vec<&ContainerInfo> = visible
        .iter()
        .copied()
        .filter(|c| page.marked.contains(&c.id))
        .collect();
    egui::Frame::new()
        .fill(p.accent.gamma_multiply(0.08))
        .stroke(egui::Stroke::new(1.0, p.accent.gamma_multiply(0.3)))
        .corner_radius(egui::CornerRadius::same(10))
        .inner_margin(egui::Margin::symmetric(12, 6))
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new(format!("{} selected", chosen.len()))
                        .font(egui::FontId::new(13.5, crate::theme::semibold()))
                        .color(p.text),
                );
                ui.add_space(8.0);
                let groups = [
                    (Action::Start, Icon::Play, "Start"),
                    (Action::Stop, Icon::Stop, "Stop"),
                    (Action::Restart, Icon::Restart, "Restart"),
                ];
                for (action, icon, label) in groups {
                    let targets: Vec<&ContainerInfo> = chosen
                        .iter()
                        .copied()
                        .filter(|c| match action {
                            Action::Start => !c.is_active(),
                            Action::Stop => c.is_active(),
                            _ => true,
                        })
                        .collect();
                    let response = ui
                        .add_enabled_ui(!targets.is_empty(), |ui| widgets::button(ui, icon, label))
                        .inner;
                    if response.clicked() {
                        for c in targets {
                            ctx.request(actions::intent(action, c));
                        }
                    }
                }
                let stopped: Vec<Task> = chosen
                    .iter()
                    .filter(|c| !c.is_active())
                    .map(|c| remove_task(Resource::Containers, &c.id, &c.name))
                    .collect();
                let remove = ui
                    .add_enabled_ui(!stopped.is_empty(), |ui| {
                        widgets::danger_button(ui, p, "Remove…")
                    })
                    .inner
                    .on_disabled_hover_text("Stop them first");
                if remove.clicked() {
                    ctx.request(confirm_removal("container", stopped));
                }
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if ui.button("Clear").clicked() {
                        page.marked.clear();
                    }
                });
            });
        });
    ui.add_space(6.0);
}

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

    fn container(name: &str, project: Option<&str>) -> ContainerInfo {
        ContainerInfo {
            id: name.into(),
            name: name.into(),
            compose: project.map(|p| ComposeLabels {
                project: p.into(),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    fn shape(rows: &[Row]) -> Vec<String> {
        rows.iter()
            .map(|r| match r {
                Row::Group { project, .. } => format!("# {}", project.unwrap_or("other")),
                Row::Item { container, .. } => container.name.clone(),
            })
            .collect()
    }

    #[test]
    fn groups_and_folds_projects() {
        let all = [
            container("api", Some("shop")),
            container("lone", None),
            container("blog-web", Some("blog")),
            container("db", Some("shop")),
        ];
        let visible: Vec<&ContainerInfo> = all.iter().collect();
        let mut folded = std::collections::BTreeSet::new();
        assert_eq!(shape(&rows(&visible, false, &folded)).len(), 4);
        assert_eq!(
            shape(&rows(&visible, true, &folded)),
            [
                "# blog", "blog-web", "# shop", "api", "db", "# other", "lone"
            ]
        );
        folded.insert("shop".to_owned());
        assert_eq!(
            shape(&rows(&visible, true, &folded)),
            ["# blog", "blog-web", "# shop", "# other", "lone"]
        );
    }
}