1use std::collections::BTreeMap;
8use std::fmt::Write as _;
9
10use super::{
11 CODES, ClaimKey, CodeKind, Dismiss, Display, Fit, FocusPolicy, HostDisplay, HostOffer,
12 HostSize, Instances, Keep, Keyboard, Lifetime, Mountable, Rule, Window, Workers, check,
13};
14
15pub const MOUNT_TESTS: &str = "crates/egui-pop-gallery/tests/it/mounts.rs";
17
18pub fn render(components: &[Mountable], hosts: &[HostOffer]) -> String {
20 let mut out = String::new();
21 let o = &mut out;
22 head(o);
23 hosts_section(o, hosts);
24 components_section(o, components);
25 let cells: Vec<Vec<Fit>> = components
26 .iter()
27 .map(|m| hosts.iter().map(|h| check(m, h)).collect())
28 .collect();
29 matrix(o, components, hosts, &cells);
30 counts(o, hosts, &cells);
31 rules(o);
32 codes(o);
33 notes(o);
34 out
35}
36
37fn head(o: &mut String) {
38 o.push_str(
39 "# Hosts and components: what can live where
40
41<!-- Generated by `cargo xtask hosts` from the declarations; do not edit. -->
42
43A **host** is a place egui-pop draws content in (a docked panel, a
44floating palette, a dialog). A **component** is something drawn there
45(the image viewport, the tree, the terminal). Each cell answers: can
46this component be mounted in this host, and if not, why not?
47
48This page is generated from the mount contract
49([ADR 0013](adr/0013-mount-contract.md)): each component declares what it
50needs (`Mountable`), each host what it offers (`HostOffer`), and each
51cell is the verdict of `egui_pop::model::mount::check` on the pair.
52`cargo xtask hosts` writes it, and a test fails when the committed page
53is stale. In an application, `AppHandle::where_can` gives the same
54verdicts and the debug bridge's `mounts` collector shows them to agents.
55
56## How to read a cell
57
58| Cell | Status | Meaning |
59|---|---|---|
60| `yes` | fits | Nothing in the way; mounted by the mount tests. |
61| `if c…` | fits under conditions | Fits, under every condition named (see [Conditions](#conditions)). |
62| `D…` | does not fit, by design | It would break a named rule on purpose; the rule says what to do instead. |
63| `E…` | does not fit, egui-pop limit | egui-pop does not do it yet; an estimated cost is given. |
64| `U…` | does not fit, upstream limit | egui, eframe or another dependency cannot do it; linked to [upstream.md](upstream.md). |
65| `…*` | not tried | Fits by the declarations, but no headless test can mount it there (see [Notes](#notes)): a gap, not a refusal. |
66
67\"Impossible\" is only ever a `D` or a `U`. An `E` is work not done yet.
68",
69 );
70}
71
72fn hosts_section(o: &mut String, hosts: &[HostOffer]) {
73 o.push_str(
74 "
75## The hosts
76
77| Column | Host | Where in the code | What it offers |
78|---|---|---|---|
79",
80 );
81 for h in hosts {
82 let _ = writeln!(
83 o,
84 "| **{}** | {} | {} | {} |",
85 h.code,
86 h.name,
87 code_list(&h.source),
88 offer(h)
89 );
90 }
91 o.push_str(
92 "
93Hosts that take **no component at all**, by design, and so have no column:
94
95- **Toast** (`toasts`): text, a level, actions and a job's progress;
96 data only. A component goes in the jobs centre or a panel the toast's
97 action opens.
98- **Menus and the command palette**: items, not content.
99- **A palette outside the main window** (a native utility window): not
100 built, and blocked upstream, U3.
101",
102 );
103}
104
105fn code_list(s: &str) -> String {
107 s.split(", ")
108 .filter(|p| !p.is_empty())
109 .map(|p| format!("`{p}`"))
110 .collect::<Vec<_>>()
111 .join(", ")
112}
113
114fn keys(keys: &[ClaimKey]) -> String {
115 keys.iter().map(|k| k.name()).collect::<Vec<_>>().join(", ")
116}
117
118fn offer(h: &HostOffer) -> String {
120 let mut parts: Vec<String> = Vec::new();
121 parts.push(
122 match h.size {
123 HostSize::Fill => "a whole rect",
124 HostSize::Given => "a size of its own declaration",
125 HostSize::Content => "a bounded width, the content's height",
126 HostSize::Row => "one row",
127 HostSize::NoUi => "**no `Ui`: data only**",
128 }
129 .to_string(),
130 );
131 if h.resizable {
132 parts.push("resized by the user".into());
133 } else if h.size != HostSize::NoUi {
134 parts.push("not resizable".into());
135 }
136 parts.push(
137 match h.focus {
138 FocusPolicy::Shared => "shared focus",
139 FocusPolicy::ClickInto => "the keyboard once clicked into",
140 FocusPolicy::ModalExclusive => "modal: the whole keyboard",
141 FocusPolicy::None => "no keyboard",
142 }
143 .to_string(),
144 );
145 if !h.owns_keys.is_empty() {
146 let honoured = if h.honours_claims {
147 " (given to a content claiming them)"
148 } else {
149 ""
150 };
151 parts.push(format!("owns {}{honoured}", keys(&h.owns_keys)));
152 }
153 if !h.dismissed_by.is_empty() {
154 let by: Vec<&str> = h
155 .dismissed_by
156 .iter()
157 .map(|d| match d {
158 Dismiss::Answer => "an answer",
159 Dismiss::Escape => "Escape",
160 Dismiss::OutsideClick => "a click outside",
161 })
162 .collect();
163 parts.push(format!("closed by {}", by.join(", ")));
164 }
165 parts.push(
166 match h.lifetime {
167 Lifetime::Persistent => "persistent",
168 Lifetime::Transient => "transient",
169 }
170 .into(),
171 );
172 parts.push(
173 match h.window {
174 Window::Main => "main window",
175 Window::Auxiliary => "an auxiliary window",
176 Window::FollowsPanel => "its panel's window",
177 }
178 .into(),
179 );
180 if h.size != HostSize::NoUi {
181 parts.push(if h.keymap {
182 "the keymap reaches it".into()
183 } else {
184 "**the keymap does not reach it**".into()
185 });
186 }
187 if h.projection {
188 parts.push("in the projection".into());
189 }
190 if !h.keeps.is_empty() {
191 let kept: Vec<&str> = h
192 .keeps
193 .iter()
194 .map(|k| match k {
195 Keep::Place => "place",
196 Keep::Size => "size",
197 Keep::ViewValues => "view values",
198 })
199 .collect();
200 parts.push(format!("keeps its {}", kept.join(", ")));
201 }
202 let mut gives = Vec::new();
203 if h.gives_ui {
204 gives.push("a `Ui`");
205 }
206 if h.gives_app {
207 gives.push("an `AppHandle`");
208 }
209 if h.scope {
210 gives.push("a focus scope");
211 }
212 if h.fault_boundary {
213 gives.push("a fault boundary");
214 }
215 if !gives.is_empty() {
216 parts.push(format!("gives {}", gives.join(", ")));
217 }
218 if h.gives_ui && !h.free_content {
219 parts.push("descriptor fields only".into());
220 }
221 parts.push(match h.display {
222 HostDisplay::Srgb => "sRGB".into(),
223 HostDisplay::Wide => "wide gamut".into(),
224 });
225 if h.gives_ui && !h.cursor_images {
226 parts.push("system cursors only".into());
227 }
228 if h.hides_content {
229 parts.push("may hide its content".into());
230 }
231 let mut line = parts.join("; ");
232 line.push('.');
233 capitalise(&line)
234}
235
236fn capitalise(s: &str) -> String {
237 let mut c = s.chars();
238 match c.next() {
239 Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),
240 None => String::new(),
241 }
242}
243
244fn components_section(o: &mut String, components: &[Mountable]) {
245 o.push_str(
246 "
247## The components
248
249| Row | Crate | What it needs |
250|---|---|---|
251",
252 );
253 for m in components {
254 let _ = writeln!(o, "| {} | `{}` | {} |", m.name, m.from, needs(m));
255 }
256}
257
258fn needs(m: &Mountable) -> String {
260 let mut parts: Vec<String> = Vec::new();
261 let mut k = match m.keyboard {
262 Keyboard::None => "no keyboard".to_string(),
263 Keyboard::Hover => "keys while hovered".into(),
264 Keyboard::Focus => "keys when focused".into(),
265 Keyboard::Exclusive => "**every key** while focused".into(),
266 };
267 if !m.claims.is_empty() {
268 let _ = write!(k, ", claims {}", keys(&m.claims));
269 }
270 parts.push(k);
271 match (&m.surface, m.keymap) {
272 (Some(s), _) => parts.push(format!("keymap surface `{s}`")),
273 (None, true) => parts.push("keymap bindings".into()),
274 (None, false) => {}
275 }
276 let mut pointer = Vec::new();
277 if m.pointer.drag {
278 pointer.push("drags");
279 }
280 if m.pointer.drag_out {
281 pointer.push("drags out");
282 }
283 if m.pointer.wheel {
284 pointer.push("wheel");
285 }
286 if m.pointer.cursor_images {
287 pointer.push("bitmap cursors");
288 }
289 if !pointer.is_empty() {
290 parts.push(pointer.join(", "));
291 }
292 let workers = match m.workers {
293 Workers::None => None,
294 Workers::DrainedWhenDrawn => Some("workers, drained when drawn"),
295 Workers::Bounded => Some("workers, bounded while hidden"),
296 };
297 if let Some(w) = workers {
298 parts.push(if m.keep_under_modal {
299 format!("{w}, kept under a modal")
300 } else {
301 w.into()
302 });
303 }
304 match m.display {
305 Display::Srgb => {}
306 Display::WideWanted => parts.push("wide gamut wanted".into()),
307 Display::WideRequired => parts.push("**wide gamut required**".into()),
308 }
309 let mut size = String::new();
310 let [w, h] = m.size.min;
311 if w > 0.0 || h > 0.0 {
312 let _ = write!(size, "at least {w} by {h}");
313 }
314 if let Some([w, h]) = m.size.preferred {
315 if !size.is_empty() {
316 size.push_str(", ");
317 }
318 let _ = write!(size, "{w} by {h} preferred");
319 }
320 if let Some([w, h]) = m.size.max {
321 if !size.is_empty() {
322 size.push_str(", ");
323 }
324 let _ = write!(size, "at most {w} by {h}");
325 }
326 if let Some(a) = m.size.aspect {
327 if !size.is_empty() {
328 size.push_str(", ");
329 }
330 let _ = write!(size, "aspect {a}");
331 }
332 if m.size.fills {
333 if !size.is_empty() {
334 size.push_str(", ");
335 }
336 size.push_str("fills");
337 }
338 if !size.is_empty() {
339 parts.push(size);
340 }
341 if m.instances == Instances::Single {
342 parts.push("**one per application**".into());
343 }
344 if let Some(key) = &m.view_state {
345 parts.push(format!("view state `{key}`"));
346 }
347 if m.app {
348 parts.push("an `AppHandle`".into());
349 }
350 if m.asks {
351 parts.push("asks a question".into());
352 }
353 if m.session {
354 parts.push("**holds a session**".into());
355 }
356 if m.popups {
357 parts.push("popups of its own".into());
358 }
359 if m.preview {
360 parts.push("a preview mode".into());
361 }
362 if m.descriptor_field {
363 parts.push("a descriptor field".into());
364 }
365 parts.push(format!("role `{}`", m.role));
366 let mut line = parts.join("; ");
367 line.push('.');
368 capitalise(&line)
369}
370
371fn cell(fit: &Fit, host: &HostOffer) -> String {
373 let star = if fit.fits() && !host.headless {
374 "*"
375 } else {
376 ""
377 };
378 format!("`{}{star}`", fit.cell())
379}
380
381fn matrix(o: &mut String, components: &[Mountable], hosts: &[HostOffer], cells: &[Vec<Fit>]) {
382 o.push_str("\n## The matrix\n\n| Component |");
383 for h in hosts {
384 let _ = write!(o, " {} |", h.code);
385 }
386 o.push_str("\n|---|");
387 for _ in hosts {
388 o.push_str("---|");
389 }
390 o.push('\n');
391 for (m, row) in components.iter().zip(cells) {
392 let _ = write!(o, "| {} |", m.name);
393 for (fit, h) in row.iter().zip(hosts) {
394 let _ = write!(o, " {} |", cell(fit, h));
395 }
396 o.push('\n');
397 }
398 let _ = writeln!(
399 o,
400 "\nColumns: {}.",
401 hosts
402 .iter()
403 .map(|h| format!("**{}** {}", h.code, h.name.to_lowercase()))
404 .collect::<Vec<_>>()
405 .join(", ")
406 );
407}
408
409fn counts(o: &mut String, hosts: &[HostOffer], cells: &[Vec<Fit>]) {
410 let (mut yes, mut under, mut not_tried) = (0, 0, 0);
411 let mut refused: BTreeMap<(u8, &'static str), usize> = BTreeMap::new();
412 let mut total = 0;
413 for row in cells {
414 for (fit, h) in row.iter().zip(hosts) {
415 total += 1;
416 if fit.fits() && !h.headless {
417 not_tried += 1;
418 }
419 match fit {
420 Fit::Yes => yes += 1,
421 Fit::Under { .. } => under += 1,
422 Fit::No { refusal, .. } => {
423 let rank = match refusal.kind {
424 CodeKind::Design => 0,
425 CodeKind::Limit => 1,
426 CodeKind::Upstream => 2,
427 CodeKind::Condition => 3,
428 };
429 *refused.entry((rank, refusal.code)).or_default() += 1;
430 }
431 }
432 }
433 }
434 let kind = |rank: u8| -> (usize, String) {
435 let by: Vec<String> = refused
436 .iter()
437 .filter(|((r, _), _)| *r == rank)
438 .map(|((_, code), n)| format!("`{code}` {n}"))
439 .collect();
440 let n = refused
441 .iter()
442 .filter(|((r, _), _)| *r == rank)
443 .map(|(_, n)| n)
444 .sum();
445 (n, by.join(", "))
446 };
447 let (design, design_by) = kind(0);
448 let (limit, limit_by) = kind(1);
449 let (upstream, upstream_by) = kind(2);
450 let with = |by: String| {
451 if by.is_empty() {
452 String::new()
453 } else {
454 format!(" ({by})")
455 }
456 };
457 let _ = write!(
458 o,
459 "
460## Counts
461
462| Status | Cells |
463|---|---|
464| fits (`yes`) | {yes} |
465| fits under conditions (`if`) | {under} |
466| does not fit, by design{} | {design} |
467| does not fit, egui-pop limit{} | {limit} |
468| does not fit, upstream{} | {upstream} |
469| **total** ({} components by {} hosts) | {total} |
470
471Of the cells that fit, {not_tried} are not tried (`*`): their host
472cannot be mounted headless.
473",
474 with(design_by),
475 with(limit_by),
476 with(upstream_by),
477 cells.len(),
478 hosts.len(),
479 );
480}
481
482fn rules(o: &mut String) {
483 o.push_str(
484 "
485## Rules
486
487Each rule looks at one need against one offer. The worst verdict wins,
488and every condition is kept.
489
490| Rule | Name | What it compares |
491|---|---|---|
492",
493 );
494 for r in Rule::ALL {
495 let _ = writeln!(o, "| {} | {} | {} |", r.number(), r.name(), r.compares());
496 }
497}
498
499fn codes(o: &mut String) {
500 o.push_str("\n## Conditions\n\n| Code | Condition |\n|---|---|\n");
501 for c in CODES.iter().filter(|c| c.kind == CodeKind::Condition) {
502 let _ = writeln!(o, "| {} | **{}.** {} |", c.code, c.title, c.text);
503 }
504 o.push_str("\n## Reasons\n\n### By design\n\n| Code | Rule | Do instead |\n|---|---|---|\n");
505 for c in CODES.iter().filter(|c| c.kind == CodeKind::Design) {
506 let _ = writeln!(
507 o,
508 "| {} | **{}.** {} | {} |",
509 c.code, c.title, c.text, c.then
510 );
511 }
512 o.push_str(
513 "
514D4 and D5 constrain how a component is used rather than where it fits:
515no component of today asks a question of its own, and a dialog's body
516draws a second choice inline.
517
518### egui-pop limits
519
520| Code | Limit | Estimated cost |
521|---|---|---|
522",
523 );
524 for c in CODES.iter().filter(|c| c.kind == CodeKind::Limit) {
525 let _ = writeln!(
526 o,
527 "| {} | **{}.** {} | {} |",
528 c.code, c.title, c.text, c.then
529 );
530 }
531 o.push_str(
532 "
533### Upstream limits
534
535| Code | Limit | Entry |
536|---|---|---|
537",
538 );
539 for c in CODES.iter().filter(|c| c.kind == CodeKind::Upstream) {
540 let _ = writeln!(
541 o,
542 "| {} | **{}.** {} | {} |",
543 c.code, c.title, c.text, c.then
544 );
545 }
546 o.push_str(
547 "
548U1 and U2 degrade a cell (condition c3) rather than refuse it: no
549component of today requires wide gamut. One that did (a mastering view)
550would be refused outside the main window with U2.
551",
552 );
553}
554
555fn notes(o: &mut String) {
556 let _ = write!(
557 o,
558 "
559## Notes
560
561- **Evidence.** `{MOUNT_TESTS}` mounts every component's gallery story
562 in a mock host built from each offer that accepts it (the panel and
563 the story by the gallery itself; the palette as an area of bounded
564 width; the raw modal and the popover through the overlay stack; the
565 custom dialog as a `Dialog::Custom`; the lines as one row), checks that
566 nothing faults, that every interactive node has a name and that no
567 diagnostic is raised, and checks that each refused mount is reported
568 with its rule.
569- **Workers.** Tile, thumbnail, tree and terminal sources run on the
570 application's threads and keep running whatever the host, a modal
571 included. Hidden, a component keeps bounded memory (c11 closed): the
572 terminal and the jobs take their input off-draw; the viewport folds
573 its source's changes past `source::NOTICES`, the tree reloads past
574 `tree::EDITS_WAITING` edits, the library keeps its `INBOX` latest
575 requests and a console its `CONSOLE_PENDING` latest bytes, each
576 counting what it dropped (docs/threading.md, section 2.2).
577- **Accessibility in an auxiliary window** is not tried: whether eframe
578 gives an immediate viewport its own AccessKit tree has not been
579 checked.
580- **Tests across windows.** egui_kittest draws an immediate viewport
581 inside the main one. The keys, overlays and focus of auxiliary windows
582 are tested with an immediate viewport renderer of the tests' own
583 (`crates/egui-pop-api/tests/it/windows.rs`), each window's pass run with
584 its own input, but no component is mounted in a real window there:
585 the cells stay `*`.
586- **Declarations can lie.** A component declared as reading keys when
587 focused that reads one globally (the node graph's Space) shows a fit
588 where it misbehaves; the mount tests are the guard.
589- **A plugin that goes** takes its components, its host offers and
590 their mounts with it, and the mounts made while its code ran (ADR
591 0028): the `mounts` collector no longer lists them, and its
592 `plugin.disconnected` event counts them (`components`, `hosts`,
593 `mounts`). Connected again, it declares them again.
594"
595 );
596}
597
598#[cfg(test)]
599mod tests {
600 use super::*;
601
602 #[test]
603 fn the_page_shows_every_host_component_and_cell_with_counts() {
604 let hosts = [
605 HostOffer::new("panel", "P", "Docked panel").source("Ctx::panel, workbench"),
606 HostOffer::new("popover", "O", "Popover")
607 .size(HostSize::Content)
608 .dismissed_by(&[Dismiss::OutsideClick])
609 .lifetime(Lifetime::Transient),
610 HostOffer::new("window", "W", "Auxiliary window").headless(false),
611 ];
612 let components = [
613 Mountable::new("viewport", "Image viewport")
614 .crate_name("egui-pop-viewport")
615 .fills(),
616 Mountable::new("terminal", "Terminal")
617 .crate_name("egui-pop-editors")
618 .session(),
619 ];
620 let page = render(&components, &hosts);
621 assert!(page.contains("| **P** | Docked panel | `Ctx::panel`, `workbench` |"));
622 assert!(
623 page.contains("| Image viewport | `yes` | `if c1` | `yes*` |"),
624 "{page}"
625 );
626 assert!(
627 page.contains("| Terminal | `yes` | `D3` | `yes*` |"),
628 "{page}"
629 );
630 assert!(
631 page.contains("| does not fit, by design (`D3` 1) | 1 |"),
632 "{page}"
633 );
634 assert!(page.contains("| **total** (2 components by 3 hosts) | 6 |"));
635 assert!(page.contains("2 are not tried"));
636 assert!(page.contains("| R11 | dialog content |"));
637 assert!(page.contains("| c1 | **Content-sized host.**"));
638 assert_eq!(page, render(&components, &hosts));
640 }
641}