1use serde::{Deserialize, Serialize};
6
7use crate::ids::{CommandId, OwnerId, PanelId};
8use crate::mount::{self, HostOffer, Mountable};
9use crate::registry::Registry;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Area {
16 Center,
18 StartSide,
20 EndSide,
22 Bottom,
23}
24
25impl Area {
26 pub const ALL: [Area; 4] = [Area::Center, Area::StartSide, Area::EndSide, Area::Bottom];
27
28 pub fn name(self) -> &'static str {
30 match self {
31 Area::Center => "the centre",
32 Area::StartSide => "the start side bar",
33 Area::EndSide => "the end side bar",
34 Area::Bottom => "the bottom panel",
35 }
36 }
37}
38
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum PanelKind {
46 #[default]
49 View,
50 Control,
52 Mixed,
55}
56
57impl PanelKind {
58 pub const ALL: [PanelKind; 3] = [PanelKind::View, PanelKind::Control, PanelKind::Mixed];
59
60 pub fn as_str(self) -> &'static str {
62 match self {
63 PanelKind::View => "view",
64 PanelKind::Control => "control",
65 PanelKind::Mixed => "mixed",
66 }
67 }
68
69 pub fn edits(self) -> bool {
71 self != PanelKind::View
72 }
73}
74
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum Instances {
79 #[default]
81 Single,
82 Multiple,
87}
88
89#[derive(Clone, Debug, PartialEq, Serialize)]
94pub struct PanelSpec {
95 pub id: PanelId,
96 pub title: String,
97 pub area: Area,
99 pub areas: Vec<Area>,
101 pub commands: Vec<CommandId>,
104 pub min_size: f32,
107 pub default_size: Option<f32>,
109 pub detachable: bool,
111 pub icon: String,
114 pub bare: bool,
117 pub open: bool,
119 pub palette: bool,
122 pub floatable: bool,
125 pub content: Option<Mountable>,
128 pub kind: PanelKind,
131 pub instances: Instances,
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
138#[serde(rename_all = "snake_case")]
139pub enum Place {
140 Area(Area),
141 Floating,
142 Window,
143}
144
145#[derive(Clone, Debug, PartialEq, Serialize)]
148pub struct PanelHost {
149 pub place: Place,
150 pub offer: HostOffer,
151}
152
153impl PanelSpec {
154 pub fn new(id: PanelId, title: &str, area: Area) -> Self {
155 Self {
156 id,
157 title: title.into(),
158 area,
159 areas: Vec::new(),
160 commands: Vec::new(),
161 min_size: 120.0,
162 default_size: None,
163 detachable: true,
164 icon: String::new(),
165 bare: false,
166 open: true,
167 palette: false,
168 floatable: true,
169 content: None,
170 kind: PanelKind::View,
171 instances: Instances::Single,
172 }
173 }
174
175 pub fn instances(mut self, instances: Instances) -> Self {
179 self.instances = instances;
180 self
181 }
182
183 pub fn instance_spec(&self, id: &PanelId, title: Option<&str>) -> PanelSpec {
187 let mut spec = self.clone();
188 spec.title = match title {
189 Some(t) => t.to_string(),
190 None => format!("{} {}", self.title, id.instance_number()),
191 };
192 spec.id = id.clone();
193 spec.open = true;
194 spec
195 }
196
197 pub fn kind(mut self, kind: PanelKind) -> Self {
201 self.kind = kind;
202 self
203 }
204
205 pub fn content(mut self, needs: Mountable) -> Self {
207 self.content = Some(needs);
208 self
209 }
210
211 pub fn min_size(mut self, points: f32) -> Self {
213 self.min_size = points.max(0.0);
214 self
215 }
216
217 pub fn default_size(mut self, points: f32) -> Self {
219 self.default_size = Some(points.max(self.min_size));
220 self
221 }
222
223 pub fn detachable(mut self, on: bool) -> Self {
225 self.detachable = on;
226 self
227 }
228
229 pub fn icon(mut self, name: &str) -> Self {
231 self.icon = name.into();
232 self
233 }
234
235 pub fn closed(mut self) -> Self {
238 self.open = false;
239 self
240 }
241
242 pub fn palette(mut self) -> Self {
245 self.palette = true;
246 self.floatable = true;
247 self
248 }
249
250 pub fn floatable(mut self, on: bool) -> Self {
254 self.floatable = on || self.palette;
255 self
256 }
257
258 pub fn bare(mut self) -> Self {
260 self.bare = true;
261 self
262 }
263
264 pub fn refuses(&self, host: &PanelHost) -> Option<String> {
268 let place = match host.place {
269 Place::Area(area) => {
270 (!self.allows(area)).then(|| format!("{} stays out of {}", self.title, area.name()))
271 }
272 Place::Floating => (!self.floatable).then(|| format!("{} cannot float", self.title)),
273 Place::Window => {
274 (!self.detachable).then(|| format!("{} cannot be detached", self.title))
275 }
276 };
277 place.or_else(|| {
278 let needs = self.content.as_ref()?;
279 let fit = mount::check(needs, &host.offer);
280 let refusal = fit.refusal()?;
281 Some(format!(
282 "{} cannot go in {}: {}",
283 self.title,
284 host.offer.name.to_lowercase(),
285 refusal.reason()
286 ))
287 })
288 }
289
290 pub fn only_in(mut self, areas: &[Area]) -> Self {
292 self.areas = areas.to_vec();
293 self
294 }
295
296 pub fn allows(&self, area: Area) -> bool {
298 self.areas.is_empty() || area == self.area || self.areas.contains(&area)
299 }
300}
301
302#[derive(Debug, Default)]
304pub struct Panels {
305 specs: Registry<PanelId, PanelSpec>,
306}
307
308impl Panels {
309 pub fn new() -> Self {
310 Self::default()
311 }
312
313 pub fn declare(&mut self, owner: &OwnerId, spec: PanelSpec) -> Result<(), String> {
314 let id = spec.id.clone();
315 self.specs
316 .insert(owner, id, spec)
317 .map_err(|t| format!("panel `{}` is already declared by `{}`", t.id, t.by))
318 }
319
320 pub fn get(&self, id: &str) -> Option<&PanelSpec> {
321 PanelId::new(id).ok().and_then(|id| self.specs.get(&id))
322 }
323
324 pub fn all(&self) -> Vec<&PanelSpec> {
326 self.specs
327 .in_order()
328 .into_iter()
329 .map(|(_, s)| &s.item)
330 .collect()
331 }
332
333 pub fn owner(&self, id: &PanelId) -> Option<&OwnerId> {
336 self.specs.owner(id)
337 }
338
339 pub fn owned(&self) -> Vec<(&PanelSpec, &OwnerId)> {
341 self.specs
342 .in_order()
343 .into_iter()
344 .map(|(_, s)| (&s.item, &s.owner))
345 .collect()
346 }
347
348 pub fn remove_owner(&mut self, owner: &OwnerId) -> Vec<PanelId> {
349 self.specs
350 .remove_owner(owner)
351 .into_iter()
352 .map(|(id, _)| id)
353 .collect()
354 }
355
356 pub fn shell_commands(&self) -> Vec<(CommandId, String)> {
359 self.all()
360 .into_iter()
361 .flat_map(|p| {
362 let focus = p.id.as_str().to_string() + ".focus";
363 let toggle = p.id.as_str().to_string() + ".toggle";
364 [
365 (CommandId::new(focus), format!("Focus {}", p.title)),
366 (CommandId::new(toggle), format!("Show or hide {}", p.title)),
367 ]
368 })
369 .filter_map(|(id, t)| id.ok().map(|id| (id, t)))
370 .collect()
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377 use crate::mount::{HostSize, Mountable};
378
379 fn host(place: Place) -> PanelHost {
380 PanelHost {
381 place,
382 offer: HostOffer::new("panel", "P", "Docked panel"),
383 }
384 }
385
386 #[test]
387 fn a_panel_is_a_view_unless_declared() {
388 let id = PanelId::new("demo.params").unwrap();
389 let spec = PanelSpec::new(id.clone(), "Parameters", Area::EndSide);
390 assert_eq!(spec.kind, PanelKind::View);
391 assert!(!spec.kind.edits());
392 let spec = spec.kind(PanelKind::Mixed);
393 assert!(spec.kind.edits());
394 assert_eq!(serde_json::to_value(spec.kind).unwrap(), "mixed");
395 for k in PanelKind::ALL {
396 assert_eq!(serde_json::to_value(k).unwrap(), k.as_str());
397 }
398 }
399
400 #[test]
401 fn a_panel_refuses_areas_floating_and_windows_it_is_not_allowed() {
402 let id = PanelId::new("demo.log").unwrap();
403 let spec = PanelSpec::new(id, "Log", Area::Bottom)
404 .only_in(&[Area::Center])
405 .floatable(false)
406 .detachable(false);
407 assert_eq!(spec.refuses(&host(Place::Area(Area::Bottom))), None);
408 assert_eq!(
409 spec.refuses(&host(Place::Area(Area::StartSide))).as_deref(),
410 Some("Log stays out of the start side bar")
411 );
412 assert_eq!(
413 spec.refuses(&host(Place::Floating)).as_deref(),
414 Some("Log cannot float")
415 );
416 assert_eq!(
417 spec.refuses(&host(Place::Window)).as_deref(),
418 Some("Log cannot be detached")
419 );
420 }
421
422 #[test]
423 fn a_panel_floats_unless_it_opts_out() {
424 let id = PanelId::new("demo.log").unwrap();
425 let spec = PanelSpec::new(id, "Log", Area::Bottom);
426 assert_eq!(spec.refuses(&host(Place::Floating)), None);
427 let spec = spec.floatable(false);
428 assert_eq!(
429 spec.refuses(&host(Place::Floating)).as_deref(),
430 Some("Log cannot float")
431 );
432 assert!(spec.palette().floatable(false).floatable);
434 }
435
436 #[test]
437 fn a_panel_refuses_a_host_its_content_does_not_fit() {
438 let id = PanelId::new("demo.view").unwrap();
439 let spec = PanelSpec::new(id, "View", Area::Center)
440 .floatable(true)
441 .content(Mountable::new("viewport", "Viewport").fills());
442 let row = PanelHost {
443 place: Place::Floating,
444 offer: HostOffer::new("line", "L", "Line zone").size(HostSize::Row),
445 };
446 let why = spec.refuses(&row).unwrap();
447 assert!(why.starts_with("View cannot go in line zone: "), "{why}");
448 assert!(why.contains("R1, D1"), "{why}");
449 assert_eq!(spec.refuses(&host(Place::Floating)), None);
450 }
451}