maruzzella 0.1.2

GTK4 desktop shell prototype in Rust with persisted layouts and plugin-backed views.
Documentation
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::collections::HashSet;

use maruzzella_api::{MzContributionSurface, MzStartupTab, MzToolbarItem};

use crate::plugins::PluginRuntime;
use crate::spec::{
    make_workbench_tabs_closeable, plugin_tab_with_instance, BottomPanelLayout, CommandSpec,
    MenuItemSpec, MenuRootSpec, PanelResizePolicy, ShellSpec, SplitAxis, TabGroupSpec,
    ToolbarItemSpec, ToolbarOptionSpec, WorkbenchNodeSpec,
};

#[derive(Clone, Debug)]
pub struct BrandingSpec {
    pub title: String,
    pub search_placeholder: String,
    pub search_command_id: Option<String>,
    pub status_text: String,
}

#[derive(Clone, Debug)]
pub struct LayoutContribution {
    pub bottom_panel_layout: BottomPanelLayout,
    pub left_panel: TabGroupSpec,
    pub right_panel: TabGroupSpec,
    pub bottom_panel: TabGroupSpec,
    pub workbench: WorkbenchNodeSpec,
    pub left_panel_resize: PanelResizePolicy,
    pub right_panel_resize: PanelResizePolicy,
    pub bottom_panel_resize: PanelResizePolicy,
}

#[derive(Clone, Debug)]
pub struct ProductSpec {
    pub branding: BrandingSpec,
    pub menu_roots: Vec<MenuRootSpec>,
    pub menu_items: Vec<MenuItemSpec>,
    pub commands: Vec<CommandSpec>,
    pub toolbar_items: Vec<ToolbarItemSpec>,
    pub include_base_toolbar_items: bool,
    pub include_base_menu_items: bool,
    pub include_base_startup_tabs: bool,
    pub layout: LayoutContribution,
}

impl ProductSpec {
    pub fn shell_spec(&self) -> ShellSpec {
        let mut workbench = self.layout.workbench.clone();
        make_workbench_tabs_closeable(&mut workbench);

        ShellSpec {
            title: self.branding.title.clone(),
            search_placeholder: self.branding.search_placeholder.clone(),
            search_command_id: self.branding.search_command_id.clone(),
            status_text: self.branding.status_text.clone(),
            app_appearance_id: "app-shell".to_string(),
            topbar_appearance_id: "topbar".to_string(),
            menu_appearance_id: "menu".to_string(),
            toolbar_appearance_id: "toolbar".to_string(),
            search_input_appearance_id: "search".to_string(),
            status_appearance_id: "status".to_string(),
            button_appearance_id: "secondary".to_string(),
            text_appearance_id: "body".to_string(),
            bottom_panel_layout: self.layout.bottom_panel_layout,
            menu_roots: self.menu_roots.clone(),
            menu_items: self.menu_items.clone(),
            commands: self.commands.clone(),
            toolbar_items: self.toolbar_items.clone(),
            left_panel: self.layout.left_panel.clone(),
            right_panel: self.layout.right_panel.clone(),
            bottom_panel: self.layout.bottom_panel.clone(),
            workbench,
            left_panel_resize: self.layout.left_panel_resize,
            right_panel_resize: self.layout.right_panel_resize,
            bottom_panel_resize: self.layout.bottom_panel_resize,
        }
    }
}

pub fn merge_plugin_runtime(
    spec: &mut ShellSpec,
    runtime: &PluginRuntime,
    include_base_toolbar_items: bool,
    include_base_menu_items: bool,
) {
    merge_runtime_commands(spec, runtime);
    merge_runtime_menus(spec, runtime, include_base_menu_items);
    merge_runtime_toolbar(spec, runtime, include_base_toolbar_items);
}

pub fn merge_runtime_startup_tabs(
    spec: &mut ShellSpec,
    runtime: &PluginRuntime,
    include_base_startup_tabs: bool,
) {
    for contribution in runtime
        .surface_contributions()
        .iter()
        .filter(|contribution| contribution.surface == Some(MzContributionSurface::StartupTabs))
    {
        if !include_base_startup_tabs && contribution.plugin_id == "maruzzella.base" {
            continue;
        }

        let Ok(tab) = MzStartupTab::from_bytes(&contribution.payload) else {
            runtime.push_diagnostic(
                Some(contribution.plugin_id.clone()),
                format!(
                    "invalid startup tab contribution payload: {}",
                    contribution.contribution_id
                ),
            );
            continue;
        };
        let closable = tab.closable || find_group_in_workbench(&spec.workbench, &tab.group_id);
        let Some(group) = find_group_mut(spec, &tab.group_id) else {
            continue;
        };
        if !group.tabs.is_empty() {
            continue;
        }
        if group.tabs.iter().any(|existing| existing.id == tab.tab_id) {
            continue;
        }
        group.tabs.push(plugin_tab_with_instance(
            &tab.tab_id,
            &tab.group_id,
            &tab.title,
            &tab.plugin_view_id,
            tab.instance_key.as_deref(),
            tab.payload,
            &tab.placeholder,
            closable,
        ));
        if tab.active {
            group.active_tab_id = Some(tab.tab_id);
        }
    }
}

fn merge_runtime_commands(spec: &mut ShellSpec, runtime: &PluginRuntime) {
    let mut known_command_ids = spec
        .commands
        .iter()
        .map(|command| command.id.clone())
        .collect::<HashSet<_>>();
    for command in runtime.commands() {
        if known_command_ids.insert(command.command_id.clone()) {
            spec.commands.push(CommandSpec {
                id: command.command_id.clone(),
                title: command.title.clone(),
            });
        }
    }
}

fn merge_runtime_menus(
    spec: &mut ShellSpec,
    runtime: &PluginRuntime,
    include_base_menu_items: bool,
) {
    let mut known_root_ids = spec
        .menu_roots
        .iter()
        .map(|root| root.id.clone())
        .collect::<HashSet<_>>();
    let mut known_menu_ids = spec
        .menu_items
        .iter()
        .map(|item| item.id.clone())
        .collect::<HashSet<_>>();

    for item in runtime.menu_items() {
        if !include_base_menu_items && item.plugin_id == "maruzzella.base" {
            continue;
        }

        let Some(parent_surface) = item.parent_surface else {
            if !known_root_ids.contains(&item.parent_id) {
                continue;
            }
            if known_menu_ids.insert(item.menu_id.clone()) {
                spec.menu_items.push(MenuItemSpec {
                    id: item.menu_id.clone(),
                    root_id: item.parent_id.clone(),
                    label: item.title.clone(),
                    command_id: item.command_id.clone(),
                    payload: item.payload.clone(),
                });
            }
            continue;
        };

        let root_id = parent_surface.root_id();
        let root_label = parent_surface.root_label();

        if known_root_ids.insert(root_id.to_string()) {
            spec.menu_roots.push(MenuRootSpec {
                id: root_id.to_string(),
                label: root_label.to_string(),
            });
        }

        if known_menu_ids.insert(item.menu_id.clone()) {
            spec.menu_items.push(MenuItemSpec {
                id: item.menu_id.clone(),
                root_id: root_id.to_string(),
                label: item.title.clone(),
                command_id: item.command_id.clone(),
                payload: item.payload.clone(),
            });
        }
    }
}

fn merge_runtime_toolbar(
    spec: &mut ShellSpec,
    runtime: &PluginRuntime,
    include_base_toolbar_items: bool,
) {
    let mut known_toolbar_ids = spec
        .toolbar_items
        .iter()
        .map(|item| item.id.clone())
        .collect::<HashSet<_>>();

    for contribution in runtime
        .surface_contributions()
        .iter()
        .filter(|contribution| contribution.surface == Some(MzContributionSurface::ToolbarItems))
    {
        if !include_base_toolbar_items && contribution.plugin_id == "maruzzella.base" {
            continue;
        }
        let Ok(item) = MzToolbarItem::from_bytes(&contribution.payload) else {
            runtime.push_diagnostic(
                Some(contribution.plugin_id.clone()),
                format!(
                    "invalid toolbar contribution payload: {}",
                    contribution.contribution_id
                ),
            );
            continue;
        };
        if known_toolbar_ids.insert(item.item_id.clone()) {
            spec.toolbar_items.push(ToolbarItemSpec {
                id: item.item_id,
                icon_name: item.icon_name,
                label: item.label,
                command_id: item.command_id,
                payload: item.payload,
                secondary: item.secondary,
                display_mode: match item.display_mode {
                    maruzzella_api::MzToolbarDisplayMode::IconOnly => {
                        crate::spec::ToolbarDisplayMode::IconOnly
                    }
                    maruzzella_api::MzToolbarDisplayMode::IconAndText => {
                        crate::spec::ToolbarDisplayMode::IconAndText
                    }
                    maruzzella_api::MzToolbarDisplayMode::TextOnly => {
                        crate::spec::ToolbarDisplayMode::TextOnly
                    }
                    maruzzella_api::MzToolbarDisplayMode::Dropdown => {
                        crate::spec::ToolbarDisplayMode::Dropdown
                    }
                },
                appearance_id: if item.appearance_id.is_empty() {
                    if item.secondary {
                        "ghost".to_string()
                    } else {
                        "primary".to_string()
                    }
                } else {
                    item.appearance_id
                },
                options: item
                    .options
                    .into_iter()
                    .map(|option| ToolbarOptionSpec {
                        label: option.label,
                        payload: option.payload,
                    })
                    .collect(),
                selected_index: item.selected_index,
            });
        }
    }
}

pub fn default_product_spec() -> ProductSpec {
    let branding = BrandingSpec {
        title: "Maruzzella".to_string(),
        search_placeholder: "Search Maruzzella".to_string(),
        search_command_id: None,
        status_text: "Neutral GTK workspace shell".to_string(),
    };
    let commands = vec![CommandSpec {
        id: "shell.reload_theme".to_string(),
        title: "Reload Theme".to_string(),
    }];
    let toolbar_items = Vec::new();
    let menu_roots = Vec::new();
    let menu_items = Vec::new();
    let layout = LayoutContribution {
        bottom_panel_layout: BottomPanelLayout::CenterOnly,
        left_panel: TabGroupSpec::new("panel-left", None, Vec::new())
            .with_panel_appearance("primary")
            .with_panel_header_appearance("secondary")
            .with_tab_strip_appearance("utility"),
        right_panel: TabGroupSpec::new("panel-right", None, Vec::new())
            .with_panel_appearance("secondary")
            .with_panel_header_appearance("secondary")
            .with_tab_strip_appearance("utility"),
        bottom_panel: TabGroupSpec::new("panel-bottom", None, Vec::new())
            .with_panel_appearance("console")
            .with_panel_header_appearance("secondary")
            .with_tab_strip_appearance("console")
            .with_text_appearance("code"),
        workbench: WorkbenchNodeSpec::Split {
            axis: SplitAxis::Horizontal,
            children: vec![
                WorkbenchNodeSpec::Group(
                    TabGroupSpec::new("workbench-main", None, Vec::new())
                        .with_panel_appearance("workbench")
                        .with_panel_header_appearance("secondary")
                        .with_tab_strip_appearance("editor"),
                ),
                WorkbenchNodeSpec::Group(
                    TabGroupSpec::new("workbench-secondary", None, Vec::new())
                        .with_panel_appearance("workbench")
                        .with_panel_header_appearance("secondary")
                        .with_tab_strip_appearance("editor"),
                ),
            ],
        },
        left_panel_resize: PanelResizePolicy::default(),
        right_panel_resize: PanelResizePolicy::default(),
        bottom_panel_resize: PanelResizePolicy::default(),
    };

    ProductSpec {
        branding,
        menu_roots,
        menu_items,
        commands,
        toolbar_items,
        include_base_toolbar_items: true,
        include_base_menu_items: true,
        include_base_startup_tabs: true,
        layout,
    }
}

fn find_group_mut<'a>(spec: &'a mut ShellSpec, group_id: &str) -> Option<&'a mut TabGroupSpec> {
    if spec.left_panel.id == group_id {
        return Some(&mut spec.left_panel);
    }
    if spec.right_panel.id == group_id {
        return Some(&mut spec.right_panel);
    }
    if spec.bottom_panel.id == group_id {
        return Some(&mut spec.bottom_panel);
    }
    find_group_mut_in_workbench(&mut spec.workbench, group_id)
}

fn find_group_mut_in_workbench<'a>(
    node: &'a mut WorkbenchNodeSpec,
    group_id: &str,
) -> Option<&'a mut TabGroupSpec> {
    match node {
        WorkbenchNodeSpec::Group(group) => (group.id == group_id).then_some(group),
        WorkbenchNodeSpec::Split { children, .. } => children
            .iter_mut()
            .find_map(|child| find_group_mut_in_workbench(child, group_id)),
    }
}

fn find_group_in_workbench(node: &WorkbenchNodeSpec, group_id: &str) -> bool {
    match node {
        WorkbenchNodeSpec::Group(group) => group.id == group_id,
        WorkbenchNodeSpec::Split { children, .. } => children
            .iter()
            .any(|child| find_group_in_workbench(child, group_id)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugins::{
        PluginRuntime, RegisteredCommand, RegisteredMenuItem, RegisteredSurfaceContribution,
    };
    use maruzzella_api::{MzContributionSurface, MzMenuSurface, MzStartupTab};

    #[test]
    fn merges_plugin_commands_and_surface_backed_menu_roots() {
        let mut runtime = PluginRuntime::empty_for_tests();
        runtime.activation_order = vec!["maruzzella.base".to_string()];
        runtime.commands = vec![RegisteredCommand {
            plugin_id: "maruzzella.base".to_string(),
            command_id: "shell.plugins".to_string(),
            title: "Plugins".to_string(),
            invoke: None,
            can_invoke: None,
        }];
        runtime.menu_items = vec![RegisteredMenuItem {
            plugin_id: "maruzzella.base".to_string(),
            menu_id: "plugins".to_string(),
            parent_id: "maruzzella.menu.file.items".to_string(),
            parent_surface: Some(MzMenuSurface::FileItems),
            title: "Plugins".to_string(),
            command_id: "shell.plugins".to_string(),
            payload: Vec::new(),
        }];
        runtime.surface_contributions = vec![RegisteredSurfaceContribution {
            plugin_id: "maruzzella.base".to_string(),
            surface_id: "maruzzella.about.sections".to_string(),
            surface: Some(maruzzella_api::MzContributionSurface::AboutSections),
            contribution_id: "base.about".to_string(),
            payload: Vec::new(),
        }];

        let mut spec = default_product_spec().shell_spec();
        merge_plugin_runtime(&mut spec, &runtime, true, true);

        assert!(spec
            .commands
            .iter()
            .any(|command| command.id == "shell.plugins"));
        assert!(spec.menu_roots.iter().any(|root| root.id == "file"));
        assert!(spec
            .menu_items
            .iter()
            .any(|item| item.id == "plugins" && item.root_id == "file"));
    }
    #[test]
    fn can_skip_base_menu_contributions() {
        let mut runtime = PluginRuntime::empty_for_tests();
        runtime.commands = vec![RegisteredCommand {
            plugin_id: "maruzzella.base".to_string(),
            command_id: "shell.plugins".to_string(),
            title: "Plugins".to_string(),
            invoke: None,
            can_invoke: None,
        }];
        runtime.menu_items = vec![RegisteredMenuItem {
            plugin_id: "maruzzella.base".to_string(),
            menu_id: "plugins".to_string(),
            parent_id: "maruzzella.menu.file.items".to_string(),
            parent_surface: Some(MzMenuSurface::FileItems),
            title: "Plugins".to_string(),
            command_id: "shell.plugins".to_string(),
            payload: Vec::new(),
        }];

        let mut spec = default_product_spec().shell_spec();
        merge_plugin_runtime(&mut spec, &runtime, true, false);

        assert!(spec
            .commands
            .iter()
            .any(|command| command.id == "shell.plugins"));
        assert!(!spec.menu_roots.iter().any(|root| root.id == "file"));
        assert!(!spec.menu_items.iter().any(|item| item.id == "plugins"));
    }
    #[test]
    fn can_skip_base_startup_tabs() {
        let mut runtime = PluginRuntime::empty_for_tests();
        runtime.surface_contributions = vec![RegisteredSurfaceContribution {
            plugin_id: "maruzzella.base".to_string(),
            surface_id: "maruzzella.startup.tabs".to_string(),
            surface: Some(MzContributionSurface::StartupTabs),
            contribution_id: "base.activity".to_string(),
            payload: MzStartupTab::new(
                "panel-bottom",
                "runtime-activity",
                "Activity",
                "maruzzella.base.activity",
            )
            .to_bytes()
            .expect("startup tab should serialize"),
        }];

        let mut spec = default_product_spec().shell_spec();
        merge_runtime_startup_tabs(&mut spec, &runtime, false);

        assert!(spec.bottom_panel.tabs.is_empty());
    }
}