1use std::collections::BTreeMap;
9use std::fmt;
10
11use egui::Ui;
12use egui_pop_model::diagnostics::Diagnostics;
13use egui_pop_model::ids::{BlockId, OwnerId, ZoneId};
14use serde::Serialize;
15
16use crate::app::AppHandle;
17
18pub const TITLE: ZoneId = ZoneId::from_static("app.title");
21pub const CAPTION: ZoneId = ZoneId::from_static("app.caption");
24pub const CAPTION_START: ZoneId = ZoneId::from_static("app.caption-start");
29pub const ACTIVITY_BAR: ZoneId = ZoneId::from_static("app.activity-bar");
32pub const TOP_BAR: ZoneId = ZoneId::from_static("app.top-bar");
34pub const TOP_BAR_END: ZoneId = ZoneId::from_static("app.top-bar-end");
43pub const SIDE_BAR: ZoneId = ZoneId::from_static("app.side-bar");
45pub const MAIN: ZoneId = ZoneId::from_static("app.main");
47pub const INSPECTOR: ZoneId = ZoneId::from_static("app.inspector");
49pub const STATUS_BAR: ZoneId = ZoneId::from_static("app.status-bar");
51
52pub const OVERLAYS: ZoneId = ZoneId::from_static("app.overlays");
57
58pub const WINDOW_OVERLAYS: ZoneId = ZoneId::from_static("app.window-overlays");
66
67pub const SHELL: [ZoneId; 8] = [
69 TITLE,
70 TOP_BAR,
71 ACTIVITY_BAR,
72 SIDE_BAR,
73 MAIN,
74 INSPECTOR,
75 STATUS_BAR,
76 OVERLAYS,
77];
78
79pub type DrawFn = Box<dyn FnMut(&mut Ui, &AppHandle)>;
81pub type WrapFn = Box<dyn FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui))>;
83
84#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
86pub enum Place {
87 Before(BlockId),
88 After(BlockId),
89}
90
91pub enum Block {
93 Add {
94 id: BlockId,
95 weight: i32,
96 draw: DrawFn,
97 },
98 Replace {
99 target: BlockId,
100 id: BlockId,
101 draw: DrawFn,
102 },
103 Extend {
104 place: Place,
105 id: BlockId,
106 draw: DrawFn,
107 },
108 Wrap {
109 target: BlockId,
110 id: BlockId,
111 wrap: WrapFn,
112 },
113}
114
115impl fmt::Debug for Block {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 match self {
118 Block::Add { id, weight, .. } => write!(f, "Add({id}, {weight})"),
119 Block::Replace { target, id, .. } => write!(f, "Replace({target} with {id})"),
120 Block::Extend { place, id, .. } => write!(f, "Extend({id} {place:?})"),
121 Block::Wrap { target, id, .. } => write!(f, "Wrap({target} in {id})"),
122 }
123 }
124}
125
126impl Block {
127 pub fn add(id: BlockId, weight: i32, draw: impl FnMut(&mut Ui, &AppHandle) + 'static) -> Block {
129 Block::Add {
130 id,
131 weight,
132 draw: Box::new(draw),
133 }
134 }
135
136 pub fn replace(
138 target: BlockId,
139 id: BlockId,
140 draw: impl FnMut(&mut Ui, &AppHandle) + 'static,
141 ) -> Block {
142 Block::Replace {
143 target,
144 id,
145 draw: Box::new(draw),
146 }
147 }
148
149 pub fn extend(
151 place: Place,
152 id: BlockId,
153 draw: impl FnMut(&mut Ui, &AppHandle) + 'static,
154 ) -> Block {
155 Block::Extend {
156 place,
157 id,
158 draw: Box::new(draw),
159 }
160 }
161
162 pub fn wrap(
164 target: BlockId,
165 id: BlockId,
166 wrap: impl FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui)) + 'static,
167 ) -> Block {
168 Block::Wrap {
169 target,
170 id,
171 wrap: Box::new(wrap),
172 }
173 }
174
175 pub fn id(&self) -> &BlockId {
176 match self {
177 Block::Add { id, .. }
178 | Block::Replace { id, .. }
179 | Block::Extend { id, .. }
180 | Block::Wrap { id, .. } => id,
181 }
182 }
183
184 fn op(&self) -> &'static str {
185 match self {
186 Block::Add { .. } => "add",
187 Block::Replace { .. } => "replace",
188 Block::Extend { .. } => "extend",
189 Block::Wrap { .. } => "wrap",
190 }
191 }
192}
193
194#[derive(Debug)]
196pub(crate) struct Contribution {
197 pub zone: ZoneId,
198 pub owner: OwnerId,
199 pub rank: usize,
201 pub seq: u64,
202 pub block: Option<Block>,
204}
205
206#[derive(Clone, Debug, PartialEq, Serialize)]
208pub struct Resolved {
209 pub id: BlockId,
210 pub owner: OwnerId,
211 pub weight: i32,
212 #[serde(skip)]
214 pub(crate) draw: usize,
215 #[serde(skip)]
217 pub(crate) wraps: Vec<usize>,
218 pub notes: Vec<String>,
220}
221
222#[derive(Clone, Debug, PartialEq, Serialize)]
224pub struct ZoneInfo {
225 pub id: ZoneId,
226 pub owner: OwnerId,
227 pub title: String,
228 pub blocks: Vec<Resolved>,
229}
230
231#[derive(Debug, Default)]
233pub(crate) struct ZoneTable {
234 pub zones: BTreeMap<ZoneId, (OwnerId, String)>,
235 pub contributions: Vec<Contribution>,
236 pub resolved: BTreeMap<ZoneId, Vec<Resolved>>,
237 next: u64,
238}
239
240impl ZoneTable {
241 pub fn declare(&mut self, owner: &OwnerId, zone: ZoneId, title: &str) -> Result<(), OwnerId> {
242 if let Some((by, _)) = self.zones.get(&zone) {
243 return Err(by.clone());
244 }
245 self.zones.insert(zone, (owner.clone(), title.into()));
246 Ok(())
247 }
248
249 pub fn contribute(&mut self, owner: &OwnerId, rank: usize, zone: ZoneId, block: Block) {
250 self.next += 1;
251 self.contributions.push(Contribution {
252 zone,
253 owner: owner.clone(),
254 rank,
255 seq: self.next,
256 block: Some(block),
257 });
258 }
259
260 pub fn remove_owner(&mut self, owner: &OwnerId) {
261 self.contributions.retain(|c| c.owner != *owner);
262 self.zones.retain(|_, (o, _)| o != owner);
263 }
264
265 pub fn set_rank(&mut self, owner: &OwnerId, rank: usize) {
267 for c in &mut self.contributions {
268 if c.owner == *owner {
269 c.rank = rank;
270 }
271 }
272 }
273
274 pub fn resolve(&mut self, d: &mut Diagnostics) {
276 self.resolved.clear();
277 let mut by_zone: BTreeMap<ZoneId, Vec<usize>> = BTreeMap::new();
278 for (i, c) in self.contributions.iter().enumerate() {
279 if !self.zones.contains_key(&c.zone) {
280 let op = c.block.as_ref().map_or("block", Block::op);
281 let id = c
282 .block
283 .as_ref()
284 .map(|b| b.id().to_string())
285 .unwrap_or_default();
286 d.error(
287 "unknown-zone",
288 Some(&c.owner),
289 &id,
290 format!(
291 "{op} `{id}` targets zone `{}`, which nobody declared: it is not shown",
292 c.zone
293 ),
294 );
295 continue;
296 }
297 by_zone.entry(c.zone.clone()).or_default().push(i);
298 }
299 for (zone, mut list) in by_zone {
300 list.sort_by_key(|&i| (self.contributions[i].rank, self.contributions[i].seq));
302 let out = self.resolve_zone(&zone, &list, d);
303 self.resolved.insert(zone, out);
304 }
305 for zone in self.zones.keys() {
306 self.resolved.entry(zone.clone()).or_default();
307 }
308 }
309
310 fn resolve_zone(&self, zone: &ZoneId, list: &[usize], d: &mut Diagnostics) -> Vec<Resolved> {
311 let c = &self.contributions;
312 let mut out: Vec<Resolved> = Vec::new();
313 let taken = |out: &Vec<Resolved>, id: &BlockId| out.iter().any(|r| r.id == *id);
314 let dup = |d: &mut Diagnostics, i: usize, id: &BlockId| {
315 d.error(
316 "duplicate-block",
317 Some(&c[i].owner),
318 id.as_str(),
319 format!("zone `{zone}` already has a block `{id}`: this one is not shown"),
320 );
321 };
322 let mut adds: Vec<(i32, usize)> = list
324 .iter()
325 .filter_map(|&i| match &c[i].block {
326 Some(Block::Add { weight, .. }) => Some((*weight, i)),
327 _ => None,
328 })
329 .collect();
330 adds.sort_by_key(|(w, i)| (*w, c[*i].rank, c[*i].seq));
331 for (weight, i) in adds {
332 let id = c[i].block.as_ref().expect("a block").id().clone();
333 if taken(&out, &id) {
334 dup(d, i, &id);
335 continue;
336 }
337 out.push(Resolved {
338 id,
339 owner: c[i].owner.clone(),
340 weight,
341 draw: i,
342 wraps: Vec::new(),
343 notes: Vec::new(),
344 });
345 }
346 let last_weight = |out: &Vec<Resolved>| out.last().map_or(0, |r| r.weight);
347 for &i in list {
349 if let Some(Block::Replace { target, id, .. }) = &c[i].block {
350 match out.iter().position(|r| r.id == *target) {
351 Some(p) => {
352 let old = out[p].owner.clone();
353 out[p].id = id.clone();
354 out[p].owner = c[i].owner.clone();
355 out[p].draw = i;
356 out[p].notes.push(format!("replaced `{target}` ({old})"));
357 }
358 None if taken(&out, id) => dup(d, i, id),
359 None => {
360 let weight = last_weight(&out);
361 d.warn(
362 "dangling-replace",
363 Some(&c[i].owner),
364 id.as_str(),
365 format!(
366 "`{id}` replaces `{target}` in zone `{zone}`, which has no such block: it is added as a new block at the end"
367 ),
368 );
369 out.push(Resolved {
370 id: id.clone(),
371 owner: c[i].owner.clone(),
372 weight,
373 draw: i,
374 wraps: Vec::new(),
375 notes: vec![format!("meant to replace missing `{target}`")],
376 });
377 }
378 }
379 }
380 }
381 for &i in list {
383 if let Some(Block::Extend { place, id, .. }) = &c[i].block {
384 if taken(&out, id) {
385 dup(d, i, id);
386 continue;
387 }
388 let (target, after) = match place {
389 Place::Before(t) => (t, false),
390 Place::After(t) => (t, true),
391 };
392 let at = out.iter().position(|r| r.id == *target);
393 let (pos, weight, note) = match at {
394 Some(p) => (
395 if after { p + 1 } else { p },
396 out[p].weight,
397 format!("{} `{target}`", if after { "after" } else { "before" }),
398 ),
399 None => {
400 d.warn(
401 "dangling-extend",
402 Some(&c[i].owner),
403 id.as_str(),
404 format!(
405 "`{id}` goes {} `{target}` in zone `{zone}`, which has no such block: it is added at the end",
406 if after { "after" } else { "before" }
407 ),
408 );
409 (
410 out.len(),
411 last_weight(&out),
412 format!("meant to go next to missing `{target}`"),
413 )
414 }
415 };
416 out.insert(
417 pos,
418 Resolved {
419 id: id.clone(),
420 owner: c[i].owner.clone(),
421 weight,
422 draw: i,
423 wraps: Vec::new(),
424 notes: vec![note],
425 },
426 );
427 }
428 }
429 for &i in list {
431 if let Some(Block::Wrap { target, id, .. }) = &c[i].block {
432 match out.iter_mut().find(|r| r.id == *target) {
433 Some(r) => {
434 r.wraps.push(i);
435 r.notes.push(format!("wrapped by `{id}` ({})", c[i].owner));
436 }
437 None => d.warn(
438 "dangling-wrap",
439 Some(&c[i].owner),
440 id.as_str(),
441 format!("`{id}` wraps `{target}` in zone `{zone}`, which has no such block: the wrap is skipped"),
442 ),
443 }
444 }
445 }
446 out
447 }
448
449 pub fn infos(&self) -> Vec<ZoneInfo> {
451 self.zones
452 .iter()
453 .map(|(id, (owner, title))| ZoneInfo {
454 id: id.clone(),
455 owner: owner.clone(),
456 title: title.clone(),
457 blocks: self.resolved.get(id).cloned().unwrap_or_default(),
458 })
459 .collect()
460 }
461}
462
463pub(crate) fn draw_chain(ui: &mut Ui, app: &AppHandle, draw: &mut DrawFn, wraps: &mut [WrapFn]) {
465 match wraps.split_last_mut() {
466 None => draw(ui, app),
467 Some((outer, inner)) => {
468 outer(ui, app, &mut |ui: &mut Ui| draw_chain(ui, app, draw, inner));
469 }
470 }
471}