easywireguard 0.5.1

mesh, minus the mess - interfaces, keys and full-mesh configs in one CLI + TUI
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
//! Centered overlays: the wizard, a QR, an inspect pane and the confirms.

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use std::path::PathBuf;

use super::*;

/// A centered modal over the current tab: a QR to scan, or a scrollable text
/// pager (`Text`) showing a `.conf` - an interface's on disk, or a mesh node's
/// generated on the fly (even if it was never written out).
pub(super) enum Overlay {
    Qr {
        title: String,
        width: usize,
        dark: Vec<bool>,
    },
    Text {
        title: String,
        body: String,
        scroll: u16,
    },
    Confirm {
        prompt: String,
        action: ConfirmAction,
    },
    Menu {
        title: String,
        name: String,
        items: Vec<(String, ExportKind)>,
        idx: usize,
    },
    /// The saved buffer failed validation. Shows the reason and lets the user
    /// choose: correct (reopen the editor on the same content) or discard it.
    Invalid {
        reason: String,
        content: String,
        original: Option<PathBuf>,
        was_up: bool,
    },
}

/// What a `y`/Enter on a Confirm overlay carries out.
#[derive(Clone)]
pub(super) enum ConfirmAction {
    /// Remove a node from the mesh manifest.
    DeleteNode(String),
    /// Delete an interface `.conf` from disk (a `.bak` is kept first).
    DeleteIface(PathBuf),
}

/// Ways to export a node from the Export menu.
#[derive(Clone, Copy)]
pub(super) enum ExportKind {
    Conf,
    Install,
    Qr,
    Ansible,
}

pub(super) fn render_prompt(f: &mut Frame, area: Rect, p: &Prompt) {
    let height = p.fields.len() as u16 + 6;
    let rect = centered_pct(area, 72, height);
    f.render_widget(Clear, rect);
    let mut lines: Vec<Line> = vec![Line::raw("")];
    for (i, field) in p.fields.iter().enumerate() {
        let active = i == p.idx;
        let label_style = if active {
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().add_modifier(Modifier::DIM)
        };
        let arrow = Span::raw(if active { "" } else { "  " });
        match &field.kind {
            FieldKind::Type(kind) => {
                let dim = Style::default().add_modifier(Modifier::DIM);
                let opt = |k: NodeKind| {
                    let st = if k == *kind {
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD | Modifier::REVERSED)
                    } else {
                        dim
                    };
                    Span::styled(format!(" {} ", k.short()), st)
                };
                lines.push(Line::from(vec![
                    arrow,
                    Span::styled("Type: ", label_style),
                    opt(NodeKind::Spoke),
                    Span::styled("", dim),
                    opt(NodeKind::Hub),
                    Span::styled(if active { "   ←/→ toggle" } else { "" }, dim),
                ]));
            }
            FieldKind::Key(src) => {
                let dim = Style::default().add_modifier(Modifier::DIM);
                let opt = |k: KeySource| {
                    let st = if k == *src {
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD | Modifier::REVERSED)
                    } else {
                        dim
                    };
                    Span::styled(format!(" {} ", k.short()), st)
                };
                lines.push(Line::from(vec![
                    arrow,
                    Span::styled("Key:  ", label_style),
                    opt(KeySource::Generate),
                    Span::styled("", dim),
                    opt(KeySource::Paste),
                    Span::styled(if active { "   ←/→ toggle" } else { "" }, dim),
                ]));
            }
            FieldKind::Pick { options, idx } => {
                let dim = Style::default().add_modifier(Modifier::DIM);
                let chosen = if options.is_empty() {
                    Span::styled(" (no hubs yet - create one first) ", dim)
                } else {
                    Span::styled(
                        format!(" {} ", options[*idx]),
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD | Modifier::REVERSED),
                    )
                };
                let counter = if options.len() > 1 {
                    format!("  ({}/{})", idx + 1, options.len())
                } else {
                    String::new()
                };
                lines.push(Line::from(vec![
                    arrow,
                    Span::styled(format!("{}: ", field.label), label_style),
                    chosen,
                    Span::styled(counter, dim),
                    Span::styled(
                        if active && options.len() > 1 {
                            "   ←/→ choose"
                        } else {
                            ""
                        },
                        dim,
                    ),
                ]));
            }
            FieldKind::Text => {
                let head = if field.default.is_empty() {
                    format!("{}: ", field.label)
                } else {
                    format!("{} [{}]: ", field.label, field.default)
                };
                let cursor = if active { "" } else { "" };
                lines.push(Line::from(vec![
                    arrow,
                    Span::styled(head, label_style),
                    Span::raw(format!("{}{}", field.value, cursor)),
                ]));
            }
        }
    }
    lines.push(Line::raw(""));
    lines.push(Line::from(Span::styled(
        format!("  {CTRL_VIM_Y_MOVE} {Y_MOVE} move · {CTRL_VIM_X_MOVE} {X_MOVE} choose · enter next/submit · esc cancel"),
        Style::default().add_modifier(Modifier::DIM),
    )));
    let para = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" {} ", p.title))
                .border_style(Style::default().fg(Color::Cyan)),
        )
        .wrap(Wrap { trim: false });
    f.render_widget(para, rect);
}

pub(super) fn render_overlay(f: &mut Frame, ov: &Overlay) {
    match ov {
        Overlay::Qr { title, width, dark } => {
            const QZ: usize = 2; // light quiet zone around the code
            let n = width + 2 * QZ;
            let is_dark = |x: usize, y: usize| -> bool {
                x >= QZ
                    && y >= QZ
                    && x < width + QZ
                    && y < width + QZ
                    && dark[(y - QZ) * width + (x - QZ)]
            };
            let full = f.area();
            // Half-block packs 2 modules/row (best scan). Quadrant packs 2x2/cell -
            // half the width - as a fallback when half-block is too wide to fit.
            let half = (n as u16 + 2, n.div_ceil(2) as u16 + 2);
            let quad = (n.div_ceil(2) as u16 + 2, n.div_ceil(2) as u16 + 2);
            let fits = |wh: (u16, u16)| wh.0 <= full.width && wh.1 <= full.height;
            let (lines, wh) = if fits(half) {
                (qr_half(n, &is_dark), half)
            } else if fits(quad) {
                (qr_quad(n, &is_dark), quad)
            } else {
                // Even the densest rendering won't fit - don't show a clipped, un-
                // scannable QR; point at the file/PNG instead.
                let area = centered(full, 50.min(full.width), 4);
                f.render_widget(Clear, area);
                f.render_widget(
                    Paragraph::new(format!("QR needs a {}x{} terminal.\nMaximize the window, or use E -> out/<name>.conf / PNG.", quad.0, quad.1))
                        .block(Block::default().borders(Borders::ALL).title(title.clone()).border_style(Style::default().fg(Color::Yellow)))
                        .wrap(Wrap { trim: false }),
                    area,
                );
                return;
            };
            let area = centered(full, wh.0, wh.1);
            f.render_widget(Clear, area);
            f.render_widget(
                Paragraph::new(lines)
                    .block(Block::default().borders(Borders::ALL).title(title.clone())),
                area,
            );
        }
        Overlay::Text {
            title,
            body,
            scroll,
        } => {
            let full = f.area();
            let w = (body.lines().map(|l| l.chars().count()).max().unwrap_or(40) as u16 + 4)
                .min(full.width.saturating_sub(4))
                .max(24);
            let h = (body.lines().count() as u16 + 3)
                .min(full.height.saturating_sub(2))
                .max(6);
            let area = centered(full, w, h);
            f.render_widget(Clear, area);
            let foot = format!("  {VIM_Y_MOVE} {Y_MOVE} scroll · y copy · other key close");
            f.render_widget(
                Paragraph::new(body.clone())
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title(title.clone())
                            .title_bottom(Line::from(foot).right_aligned())
                            .border_style(Style::default().fg(Color::Cyan)),
                    )
                    .scroll((*scroll, 0)),
                area,
            );
        }
        Overlay::Confirm { prompt, .. } => {
            let w = prompt.chars().count() as u16 + 2;
            let area = centered(f.area(), w, 3);
            f.render_widget(Clear, area);
            f.render_widget(
                Paragraph::new(prompt.clone()).block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(Style::default().fg(Color::Red)),
                ),
                area,
            );
        }
        Overlay::Invalid { reason, .. } => {
            let full = f.area();
            let body = format!(
                "This config is not valid:\n\n{reason}\n\ne / ↵  correct (reopen editor)\nd / esc  discard"
            );
            let w = 64.min(full.width.saturating_sub(4)).max(28);
            let h = (body.lines().count() as u16 + 4)
                .min(full.height.saturating_sub(2))
                .max(7);
            let area = centered(full, w, h);
            f.render_widget(Clear, area);
            f.render_widget(
                Paragraph::new(body)
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title(" invalid config ")
                            .border_style(Style::default().fg(Color::Yellow)),
                    )
                    .wrap(Wrap { trim: false }),
                area,
            );
        }
        Overlay::Menu {
            title, items, idx, ..
        } => {
            let lines: Vec<Line> = items
                .iter()
                .enumerate()
                .map(|(i, (label, _))| {
                    let active = i == *idx;
                    Line::from(vec![
                        Span::raw(if active { "" } else { "  " }),
                        Span::styled(
                            label.clone(),
                            if active {
                                Style::default()
                                    .fg(Color::Cyan)
                                    .add_modifier(Modifier::BOLD)
                            } else {
                                Style::default().add_modifier(Modifier::DIM)
                            },
                        ),
                    ])
                })
                .collect();
            let w = items
                .iter()
                .map(|(l, _)| l.chars().count())
                .max()
                .unwrap_or(20) as u16
                + 6;
            let area = centered(
                f.area(),
                w.max(title.chars().count() as u16 + 2),
                items.len() as u16 + 2,
            );
            f.render_widget(Clear, area);
            f.render_widget(
                Paragraph::new(lines).block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title(title.clone())
                        .title_bottom(
                            Line::from(format!("  {VIM_Y_MOVE} {Y_MOVE} · ↵ select · esc"))
                                .right_aligned(),
                        )
                        .border_style(Style::default().fg(Color::Cyan)),
                ),
                area,
            );
        }
    }
}

/// A rect centered in `area`, exactly `w`x`h` (capped to the screen).
/// Shrink a `.conf` for QR encoding without changing meaning: drop the alignment
/// padding around `=`, the client-irrelevant `ListenPort`, `[Peer]` name comments,
/// and blank lines. WireGuard parses `Key=Value` fine, so fewer bytes = smaller QR.
pub(super) fn compact_for_qr(config: &str) -> String {
    let mut out = String::new();
    for line in config.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with("ListenPort") {
            continue;
        }
        if let Some(h) = line.find('#') {
            let head = line[..h].trim(); // e.g. "[Peer]  # name" -> "[Peer]"
            if !head.is_empty() {
                out.push_str(head);
                out.push('\n');
            }
            continue;
        }
        match line.split_once('=') {
            Some((k, v)) => out.push_str(&format!("{}={}\n", k.trim(), v.trim())),
            None => out.push_str(&format!("{line}\n")),
        }
    }
    out
}

/// QR as upper-half blocks: 1 module/col, 2 modules/row (fg=top, bg=bottom).
/// Square-ish modules, best for scanning. `n` = side incl. quiet zone.
pub(super) fn qr_half(n: usize, is_dark: &dyn Fn(usize, usize) -> bool) -> Vec<Line<'static>> {
    (0..n)
        .step_by(2)
        .map(|y| {
            Line::from(
                (0..n)
                    .map(|x| {
                        let fg = if is_dark(x, y) {
                            Color::Black
                        } else {
                            Color::White
                        };
                        let bg = if y + 1 < n && is_dark(x, y + 1) {
                            Color::Black
                        } else {
                            Color::White
                        };
                        Span::styled("", Style::default().fg(fg).bg(bg))
                    })
                    .collect::<Vec<_>>(),
            )
        })
        .collect()
}

/// QR as quadrant blocks: each cell packs a 2x2 module block (black on white), so
/// it's half the width of the half-block form - denser, at the cost of scan margin.
pub(super) fn qr_quad(n: usize, is_dark: &dyn Fn(usize, usize) -> bool) -> Vec<Line<'static>> {
    // Glyph per 2x2 pattern, bit order TL=1, TR=2, BL=4, BR=8.
    const G: [char; 16] = [
        ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
    ];
    let cell = Style::default().fg(Color::Black).bg(Color::White);
    (0..n)
        .step_by(2)
        .map(|y| {
            Line::from(
                (0..n)
                    .step_by(2)
                    .map(|x| {
                        let d = |dx: usize, dy: usize| {
                            x + dx < n && y + dy < n && is_dark(x + dx, y + dy)
                        };
                        let bits = d(0, 0) as usize
                            | (d(1, 0) as usize) << 1
                            | (d(0, 1) as usize) << 2
                            | (d(1, 1) as usize) << 3;
                        Span::styled(G[bits].to_string(), cell)
                    })
                    .collect::<Vec<_>>(),
            )
        })
        .collect()
}