cosmic/app/
mod.rs

1// Copyright 2023 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4//! Build interactive cross-platform COSMIC applications.
5//!
6//! Check out our [application](https://github.com/pop-os/libcosmic/tree/master/examples/application)
7//! example in our repository.
8
9mod action;
10pub use action::Action;
11use cosmic_config::CosmicConfigEntry;
12pub mod context_drawer;
13pub use context_drawer::{ContextDrawer, context_drawer};
14use iced::application::BootFn;
15pub mod cosmic;
16pub mod settings;
17
18pub type Task<M> = iced::Task<crate::Action<M>>;
19
20pub use crate::Core;
21use crate::prelude::*;
22use crate::theme::THEME;
23use crate::widget::{container, id_container, menu, nav_bar, popover, space};
24use apply::Apply;
25use iced::{Length, Subscription};
26use iced::{theme, window};
27pub use settings::Settings;
28use std::borrow::Cow;
29use std::{cell::RefCell, rc::Rc};
30
31#[cold]
32pub(crate) fn iced_settings<App: Application>(
33    settings: Settings,
34    flags: App::Flags,
35) -> (iced::Settings, (Core, App::Flags), iced::window::Settings) {
36    preload_fonts();
37
38    let mut core = Core::default();
39    core.debug = settings.debug;
40    core.icon_theme_override = settings.default_icon_theme.is_some();
41    core.set_scale_factor(settings.scale_factor);
42    core.set_window_width(settings.size.width);
43    core.set_window_height(settings.size.height);
44
45    if let Some(icon_theme) = settings.default_icon_theme {
46        crate::icon_theme::set_default(icon_theme);
47    } else {
48        crate::icon_theme::set_default(crate::config::icon_theme());
49    }
50
51    THEME.lock().unwrap().set_theme(settings.theme.theme_type);
52
53    if settings.no_main_window {
54        core.main_window = Some(iced::window::Id::NONE);
55    }
56
57    let mut iced = iced::Settings::default();
58
59    iced.antialiasing = settings.antialiasing;
60    iced.default_font = settings.default_font;
61    iced.default_text_size = iced::Pixels(settings.default_text_size);
62    let exit_on_close = settings.exit_on_close;
63    iced.is_daemon = false;
64    iced.exit_on_close_request = settings.is_daemon;
65    let mut window_settings = iced::window::Settings::default();
66    window_settings.exit_on_close_request = exit_on_close;
67    iced.id = Some(App::APP_ID.to_owned());
68    #[cfg(target_os = "linux")]
69    {
70        window_settings.platform_specific.application_id = App::APP_ID.to_string();
71    }
72    core.exit_on_main_window_closed = exit_on_close;
73
74    if let Some(border_size) = settings.resizable {
75        window_settings.resize_border = border_size as u32;
76        window_settings.resizable = true;
77    }
78    window_settings.decorations = !settings.client_decorations;
79    window_settings.size = settings.size;
80    let min_size = settings.size_limits.min();
81    if min_size != iced::Size::ZERO {
82        window_settings.min_size = Some(min_size);
83    }
84    let max_size = settings.size_limits.max();
85    if max_size != iced::Size::INFINITE {
86        window_settings.max_size = Some(max_size);
87    }
88
89    window_settings.transparent = settings.transparent;
90    (iced, (core, flags), window_settings)
91}
92
93pub(crate) struct BootDataInner<A: crate::app::Application> {
94    pub flags: A::Flags,
95    pub core: Core,
96    pub settings: window::Settings,
97}
98
99pub(crate) struct BootData<A: crate::app::Application>(pub Rc<RefCell<Option<BootDataInner<A>>>>);
100
101impl<A: crate::app::Application> BootFn<cosmic::Cosmic<A>, crate::Action<A::Message>>
102    for BootData<A>
103{
104    fn boot(&self) -> (cosmic::Cosmic<A>, iced::Task<crate::Action<A::Message>>) {
105        let mut data = self.0.borrow_mut();
106        let mut data = data.take().unwrap();
107        let mut tasks = Vec::new();
108        #[cfg(feature = "multi-window")]
109        if data.core.main_window_id().is_some() {
110            let window_task = iced_runtime::task::oneshot(|channel| {
111                iced_runtime::Action::Window(iced_runtime::window::Action::Open(
112                    window::Id::RESERVED,
113                    data.settings,
114                    channel,
115                ))
116            });
117            data.core.set_main_window_id(Some(window::Id::RESERVED));
118            tasks.push(window_task.discard());
119        }
120        let (a, t) = cosmic::Cosmic::<A>::init((data.core, data.flags));
121        tasks.push(t);
122        (a, Task::batch(tasks))
123    }
124}
125/// Launch a COSMIC application with the given [`Settings`].
126///
127/// # Errors
128///
129/// Returns error on application failure.
130pub fn run<App: Application>(settings: Settings, flags: App::Flags) -> iced::Result {
131    #[cfg(feature = "desktop")]
132    image_extras::register();
133
134    #[cfg(all(target_env = "gnu", not(target_os = "windows")))]
135    if let Some(threshold) = settings.default_mmap_threshold {
136        crate::malloc::limit_mmap_threshold(threshold);
137    }
138
139    let default_font = settings.default_font;
140    let (settings, (mut core, flags), window_settings) = iced_settings::<App>(settings, flags);
141    #[cfg(not(feature = "multi-window"))]
142    {
143        core.main_window = Some(iced::window::Id::RESERVED);
144
145        iced::application(
146            BootData(Rc::new(RefCell::new(Some(BootDataInner::<App> {
147                flags,
148                core,
149                settings: window_settings.clone(),
150            })))),
151            cosmic::Cosmic::update,
152            cosmic::Cosmic::view,
153        )
154        .subscription(cosmic::Cosmic::subscription)
155        .title(cosmic::Cosmic::title)
156        .style(cosmic::Cosmic::style)
157        .theme(cosmic::Cosmic::theme)
158        .window_size((500.0, 800.0))
159        .settings(settings)
160        .window(window_settings)
161        .run()
162    }
163    #[cfg(feature = "multi-window")]
164    {
165        let no_main_window = core.main_window.is_none();
166        if no_main_window {
167            // app = app.window(window_settings);
168            core.main_window = Some(iced_core::window::Id::RESERVED);
169        }
170        let app = iced::daemon(
171            BootData(Rc::new(RefCell::new(Some(BootDataInner::<App> {
172                flags,
173                core,
174                settings: window_settings,
175            })))),
176            cosmic::Cosmic::update,
177            cosmic::Cosmic::view,
178        );
179
180        app.subscription(cosmic::Cosmic::subscription)
181            .title(cosmic::Cosmic::title)
182            .style(cosmic::Cosmic::style)
183            .theme(cosmic::Cosmic::theme)
184            .settings(settings)
185            .run()
186    }
187}
188
189#[cfg(feature = "single-instance")]
190/// Launch a COSMIC application with the given [`Settings`].
191/// If the application is already running, the arguments will be passed to the
192/// running instance.
193/// # Errors
194/// Returns error on application failure.
195pub fn run_single_instance<App: Application>(settings: Settings, flags: App::Flags) -> iced::Result
196where
197    App::Flags: CosmicFlags,
198    App::Message: Clone + std::fmt::Debug + Send + 'static,
199{
200    #[cfg(feature = "desktop")]
201    image_extras::register();
202
203    use std::collections::HashMap;
204
205    let activation_token = std::env::var("XDG_ACTIVATION_TOKEN").ok();
206
207    let override_single = std::env::var("COSMIC_SINGLE_INSTANCE")
208        .map(|v| &v.to_lowercase() == "false" || &v == "0")
209        .unwrap_or_default();
210    if override_single {
211        return run::<App>(settings, flags);
212    }
213
214    let path: String = format!("/{}", App::APP_ID.replace('.', "/"));
215
216    let Ok(conn) = zbus::blocking::Connection::session() else {
217        tracing::warn!("Failed to connect to dbus");
218        return run::<App>(settings, flags);
219    };
220
221    if crate::dbus_activation::DbusActivationInterfaceProxyBlocking::builder(&conn)
222        .destination(App::APP_ID)
223        .ok()
224        .and_then(|b| b.path(path).ok())
225        .and_then(|b| b.destination(App::APP_ID).ok())
226        .and_then(|b| b.build().ok())
227        .is_some_and(|mut p| {
228            let res = {
229                let mut platform_data = HashMap::new();
230                if let Some(activation_token) = activation_token {
231                    platform_data.insert("activation-token", activation_token.into());
232                }
233                if let Ok(startup_id) = std::env::var("DESKTOP_STARTUP_ID") {
234                    platform_data.insert("desktop-startup-id", startup_id.into());
235                }
236                if let Some(action) = flags.action() {
237                    let action = action.to_string();
238                    p.activate_action(&action, flags.args(), platform_data)
239                } else {
240                    p.activate(platform_data)
241                }
242            };
243            match res {
244                Ok(()) => {
245                    tracing::info!("Successfully activated another instance");
246                    true
247                }
248                Err(err) => {
249                    tracing::warn!(?err, "Failed to activate another instance");
250                    false
251                }
252            }
253        })
254    {
255        tracing::info!("Another instance is running");
256        Ok(())
257    } else {
258        let (settings, (mut core, flags), window_settings) = iced_settings::<App>(settings, flags);
259        core.single_instance = true;
260
261        #[cfg(not(feature = "multi-window"))]
262        {
263            iced::application(
264                BootData(Rc::new(RefCell::new(Some(BootDataInner::<App> {
265                    flags,
266                    core,
267                    settings: window_settings.clone(),
268                })))),
269                cosmic::Cosmic::update,
270                cosmic::Cosmic::view,
271            )
272            .subscription(cosmic::Cosmic::subscription)
273            .style(cosmic::Cosmic::style)
274            .theme(cosmic::Cosmic::theme)
275            .window_size((500.0, 800.0))
276            .settings(settings)
277            .window(window_settings)
278            .run()
279        }
280        #[cfg(feature = "multi-window")]
281        {
282            let no_main_window = core.main_window.is_none();
283            if no_main_window {
284                // app = app.window(window_settings);
285                core.main_window = Some(iced_core::window::Id::RESERVED);
286            }
287            let mut app = iced::daemon(
288                BootData(Rc::new(RefCell::new(Some(BootDataInner::<App> {
289                    flags,
290                    core,
291                    settings: window_settings,
292                })))),
293                cosmic::Cosmic::update,
294                cosmic::Cosmic::view,
295            );
296
297            app.subscription(cosmic::Cosmic::subscription)
298                .style(cosmic::Cosmic::style)
299                .title(cosmic::Cosmic::title)
300                .theme(cosmic::Cosmic::theme)
301                .settings(settings)
302                .run()
303        }
304    }
305}
306
307pub trait CosmicFlags {
308    type SubCommand: ToString + std::fmt::Debug + Clone + Send + 'static;
309    type Args: Into<Vec<String>> + std::fmt::Debug + Clone + Send + 'static;
310    #[must_use]
311    fn action(&self) -> Option<&Self::SubCommand> {
312        None
313    }
314
315    #[must_use]
316    fn args(&self) -> Vec<&str> {
317        Vec::new()
318    }
319}
320
321/// An interactive cross-platform COSMIC application.
322#[allow(unused_variables)]
323pub trait Application
324where
325    Self: Sized + 'static,
326{
327    /// Default async executor to use with the app.
328    type Executor: iced_futures::Executor;
329
330    /// Argument received [`Application::new`].
331    type Flags;
332
333    /// Message type specific to our app.
334    type Message: Clone + std::fmt::Debug + Send + 'static;
335
336    /// An ID that uniquely identifies the application.
337    /// The standard is to pick an ID based on a reverse-domain name notation.
338    /// IE: `com.system76.Settings`
339    const APP_ID: &'static str;
340
341    /// Grants access to the COSMIC Core.
342    fn core(&self) -> &Core;
343
344    /// Grants access to the COSMIC Core.
345    fn core_mut(&mut self) -> &mut Core;
346
347    /// Creates the application, and optionally emits task on initialize.
348    fn init(core: Core, flags: Self::Flags) -> (Self, Task<Self::Message>);
349
350    /// Displays a context drawer on the side of the application window when `Some`.
351    /// Use the [`ApplicationExt::set_show_context`] function for this to take effect.
352    fn context_drawer(&self) -> Option<ContextDrawer<'_, Self::Message>> {
353        None
354    }
355
356    /// Displays a dialog in the center of the application window when `Some`.
357    fn dialog(&self) -> Option<Element<'_, Self::Message>> {
358        None
359    }
360
361    /// Displays a footer at the bottom of the application window when `Some`.
362    fn footer(&self) -> Option<Element<'_, Self::Message>> {
363        None
364    }
365
366    /// Attaches elements to the start section of the header.
367    fn header_start(&self) -> Vec<Element<'_, Self::Message>> {
368        Vec::new()
369    }
370
371    /// Attaches elements to the center of the header.
372    fn header_center(&self) -> Vec<Element<'_, Self::Message>> {
373        Vec::new()
374    }
375
376    /// Attaches elements to the end section of the header.
377    fn header_end(&self) -> Vec<Element<'_, Self::Message>> {
378        Vec::new()
379    }
380
381    /// Allows overriding the default nav bar widget.
382    fn nav_bar(&self) -> Option<Element<'_, crate::Action<Self::Message>>> {
383        if !self.core().nav_bar_active() {
384            return None;
385        }
386
387        let nav_model = self.nav_model()?;
388
389        let mut nav =
390            crate::widget::nav_bar(nav_model, |id| crate::Action::Cosmic(Action::NavBar(id)))
391                .on_context(|id| crate::Action::Cosmic(Action::NavBarContext(id)))
392                .context_menu(self.nav_context_menu(self.core().nav_bar_context()))
393                .into_container()
394                .width(iced::Length::Shrink)
395                .height(iced::Length::Fill);
396
397        if !self.core().is_condensed() {
398            nav = nav.max_width(280);
399        }
400
401        Some(Element::from(nav))
402    }
403
404    /// Shows a context menu for the active nav bar item.
405    fn nav_context_menu(
406        &self,
407        id: nav_bar::Id,
408    ) -> Option<Vec<menu::Tree<crate::Action<Self::Message>>>> {
409        None
410    }
411
412    /// Allows COSMIC to integrate with your application's [`nav_bar::Model`].
413    fn nav_model(&self) -> Option<&nav_bar::Model> {
414        None
415    }
416
417    /// Called before closing the application. Returning a message will override closing windows.
418    fn on_app_exit(&mut self) -> Option<Self::Message> {
419        None
420    }
421
422    /// Called when a window requests to be closed.
423    fn on_close_requested(&self, id: window::Id) -> Option<Self::Message> {
424        None
425    }
426
427    // Called when context drawer is toggled
428    fn on_context_drawer(&mut self) -> Task<Self::Message> {
429        Task::none()
430    }
431
432    /// Called when the escape key is pressed.
433    fn on_escape(&mut self) -> Task<Self::Message> {
434        Task::none()
435    }
436
437    /// Called when a navigation item is selected.
438    fn on_nav_select(&mut self, id: nav_bar::Id) -> Task<Self::Message> {
439        Task::none()
440    }
441
442    /// Called when a context menu is requested for a navigation item.
443    fn on_nav_context(&mut self, id: nav_bar::Id) -> Task<Self::Message> {
444        Task::none()
445    }
446
447    /// Called when the search function is requested.
448    fn on_search(&mut self) -> Task<Self::Message> {
449        Task::none()
450    }
451
452    /// Called when a window is resized.
453    fn on_window_resize(&mut self, id: window::Id, width: f32, height: f32) {}
454
455    /// Event sources that are to be listened to.
456    fn subscription(&self) -> Subscription<Self::Message> {
457        Subscription::none()
458    }
459
460    /// Respond to an application-specific message.
461    fn update(&mut self, message: Self::Message) -> Task<Self::Message> {
462        Task::none()
463    }
464
465    /// Respond to a system theme change
466    fn system_theme_update(
467        &mut self,
468        keys: &[&'static str],
469        new_theme: &cosmic_theme::Theme,
470    ) -> Task<Self::Message> {
471        Task::none()
472    }
473
474    /// Respond to a system theme mode change
475    fn system_theme_mode_update(
476        &mut self,
477        keys: &[&'static str],
478        new_theme: &cosmic_theme::ThemeMode,
479    ) -> Task<Self::Message> {
480        Task::none()
481    }
482
483    /// Constructs the view for the main window.
484    fn view(&self) -> Element<'_, Self::Message>;
485
486    /// Constructs views for other windows.
487    fn view_window(&self, id: window::Id) -> Element<'_, Self::Message> {
488        panic!("no view for window {id:?}");
489    }
490
491    /// Overrides the default style for applications
492    fn style(&self) -> Option<theme::Style> {
493        None
494    }
495
496    /// Handles dbus activation messages
497    #[cfg(feature = "single-instance")]
498    fn dbus_activation(&mut self, msg: crate::dbus_activation::Message) -> Task<Self::Message> {
499        Task::none()
500    }
501
502    /// Invoked on connect to dbus session socket used for dbus activation
503    ///
504    /// Can be used to expose custom interfaces on the same owned name.
505    #[cfg(feature = "single-instance")]
506    fn dbus_connection(&mut self, conn: zbus::Connection) -> Task<Self::Message> {
507        Task::none()
508    }
509}
510
511/// Methods automatically derived for all types implementing [`Application`].
512pub trait ApplicationExt: Application {
513    /// Initiates a window drag.
514    fn drag(&mut self) -> Task<Self::Message>;
515
516    /// Maximizes the window.
517    fn maximize(&mut self) -> Task<Self::Message>;
518
519    /// Minimizes the window.
520    fn minimize(&mut self) -> Task<Self::Message>;
521    /// Get the title of the main window.
522
523    #[cfg(not(feature = "multi-window"))]
524    fn title(&self) -> &str;
525
526    #[cfg(feature = "multi-window")]
527    /// Get the title of a window.
528    fn title(&self, id: window::Id) -> &str;
529
530    /// Set the context drawer visibility.
531    fn set_show_context(&mut self, show: bool) {
532        self.core_mut().set_show_context(show);
533    }
534
535    /// Set the header bar title.
536    fn set_header_title(&mut self, title: String) {
537        self.core_mut().set_header_title(title);
538    }
539
540    #[cfg(not(feature = "multi-window"))]
541    /// Set the title of the main window.
542    fn set_window_title(&mut self, title: String) -> Task<Self::Message>;
543
544    #[cfg(feature = "multi-window")]
545    /// Set the title of a window.
546    fn set_window_title(&mut self, title: String, id: window::Id) -> Task<Self::Message>;
547
548    /// View template for the main window.
549    fn view_main(&self) -> Element<'_, crate::Action<Self::Message>>;
550
551    fn watch_config<T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq>(
552        &self,
553        id: &'static str,
554    ) -> iced::Subscription<cosmic_config::Update<T>> {
555        self.core().watch_config(id)
556    }
557
558    fn watch_state<T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq>(
559        &self,
560        id: &'static str,
561    ) -> iced::Subscription<cosmic_config::Update<T>> {
562        self.core().watch_state(id)
563    }
564}
565
566impl<App: Application> ApplicationExt for App {
567    fn drag(&mut self) -> Task<Self::Message> {
568        self.core().drag(None)
569    }
570
571    fn maximize(&mut self) -> Task<Self::Message> {
572        self.core().maximize(None, true)
573    }
574
575    fn minimize(&mut self) -> Task<Self::Message> {
576        self.core().minimize(None)
577    }
578
579    #[cfg(feature = "multi-window")]
580    fn title(&self, id: window::Id) -> &str {
581        self.core().title.get(&id).map_or("", |s| s.as_str())
582    }
583
584    #[cfg(not(feature = "multi-window"))]
585    fn title(&self) -> &str {
586        self.core()
587            .main_window_id()
588            .and_then(|id| self.core().title.get(&id).map(std::string::String::as_str))
589            .unwrap_or("")
590    }
591
592    #[cfg(feature = "multi-window")]
593    fn set_window_title(&mut self, title: String, id: window::Id) -> Task<Self::Message> {
594        self.core_mut().title.insert(id, title.clone());
595        self.core().set_title(Some(id), title)
596    }
597
598    #[cfg(not(feature = "multi-window"))]
599    fn set_window_title(&mut self, title: String) -> Task<Self::Message> {
600        let Some(id) = self.core().main_window_id() else {
601            return Task::none();
602        };
603
604        self.core_mut().title.insert(id, title.clone());
605        Task::none()
606    }
607
608    #[allow(clippy::too_many_lines)]
609    /// Creates the view for the main window.
610    fn view_main(&self) -> Element<'_, crate::Action<Self::Message>> {
611        let core = self.core();
612        let is_condensed = core.is_condensed();
613        let sharp_corners = core.window.sharp_corners;
614        let maximized = core.window.is_maximized;
615        let content_container = core.window.content_container;
616        let show_context = core.window.show_context;
617        let nav_bar_active = core.nav_bar_active();
618        let focused = core
619            .focus_chain()
620            .iter()
621            .any(|i| Some(*i) == self.core().main_window_id());
622
623        let border_padding = if maximized { 8 } else { 7 };
624
625        let main_content_padding = if !content_container {
626            [0, 0, 0, 0]
627        } else {
628            let right_padding = if show_context { 0 } else { border_padding };
629            let left_padding = if nav_bar_active { 0 } else { border_padding };
630
631            [0, right_padding, 0, left_padding]
632        };
633
634        let content_row = crate::widget::row::with_children({
635            let mut widgets = Vec::with_capacity(3);
636
637            // Insert nav bar onto the left side of the window.
638            let has_nav = if let Some(nav) = self
639                .nav_bar()
640                .map(|nav| id_container(nav, iced_core::id::Id::new("COSMIC_nav_bar")))
641            {
642                widgets.push(
643                    container(nav)
644                        .padding([
645                            0,
646                            if is_condensed { border_padding } else { 8 },
647                            border_padding,
648                            border_padding,
649                        ])
650                        .into(),
651                );
652                true
653            } else {
654                false
655            };
656
657            if self.nav_model().is_none() || core.show_content() {
658                let main_content = self.view();
659
660                //TODO: reduce duplication
661                let context_width = core.context_width(has_nav);
662                if core.window.context_is_overlay && show_context {
663                    if let Some(context) = self.context_drawer() {
664                        widgets.push(
665                            crate::widget::context_drawer(
666                                context.title,
667                                context.actions,
668                                context.header,
669                                context.footer,
670                                context.on_close,
671                                main_content,
672                                context.content,
673                                context_width,
674                            )
675                            .apply(|drawer| {
676                                Element::from(id_container(
677                                    drawer,
678                                    iced_core::id::Id::new("COSMIC_context_drawer"),
679                                ))
680                            })
681                            .apply(container)
682                            .padding([0, if content_container { border_padding } else { 0 }, 0, 0])
683                            .apply(Element::from)
684                            .map(crate::Action::App),
685                        );
686                    } else {
687                        widgets.push(
688                            container(main_content.map(crate::Action::App))
689                                .padding(main_content_padding)
690                                .into(),
691                        );
692                    }
693                } else {
694                    //TODO: hide content when out of space
695                    widgets.push(
696                        container(main_content.map(crate::Action::App))
697                            .padding(main_content_padding)
698                            .into(),
699                    );
700                    if let Some(context) = self.context_drawer() {
701                        widgets.push(
702                            crate::widget::ContextDrawer::new_inner(
703                                context.title,
704                                context.actions,
705                                context.header,
706                                context.footer,
707                                context.content,
708                                context.on_close,
709                                context_width,
710                            )
711                            .apply(Element::from)
712                            .map(crate::Action::App)
713                            .apply(container)
714                            .width(context_width)
715                            .apply(|drawer| {
716                                Element::from(id_container(
717                                    drawer,
718                                    iced_core::id::Id::new("COSMIC_context_drawer"),
719                                ))
720                            })
721                            .apply(container)
722                            .padding(if content_container {
723                                [0, border_padding, border_padding, border_padding]
724                            } else {
725                                [0, 0, 0, 0]
726                            })
727                            .into(),
728                        );
729                    } else {
730                        //TODO: this element is added to workaround state issues
731                        widgets.push(space::horizontal().width(Length::Shrink).into());
732                    }
733                }
734            }
735
736            widgets
737        });
738
739        let content_col = crate::widget::column::with_capacity(2)
740            .push(content_row)
741            .push_maybe(self.footer().map(|footer| {
742                container(footer.map(crate::Action::App)).padding([
743                    0,
744                    border_padding,
745                    border_padding,
746                    border_padding,
747                ])
748            }));
749        let content: Element<_> = if content_container {
750            content_col
751                .width(iced::Length::Fill)
752                .height(iced::Length::Fill)
753                .apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_content_container")))
754                .into()
755        } else {
756            content_col.into()
757        };
758
759        // Ensures visually aligned radii for content and window corners
760        let window_corner_radius = if sharp_corners {
761            crate::theme::active().cosmic().radius_0()
762        } else {
763            crate::theme::active()
764                .cosmic()
765                .radius_s()
766                .map(|x| if x < 4.0 { x } else { x + 4.0 })
767        };
768
769        let view_column = crate::widget::column::with_capacity(2)
770            .push_maybe(if core.window.show_headerbar {
771                Some({
772                    let mut header = crate::widget::header_bar()
773                        .focused(focused)
774                        .maximized(maximized)
775                        .sharp_corners(sharp_corners)
776                        .transparent(content_container)
777                        .title(&core.window.header_title)
778                        .on_drag(crate::Action::Cosmic(Action::Drag))
779                        .on_right_click(crate::Action::Cosmic(Action::ShowWindowMenu))
780                        .on_double_click(crate::Action::Cosmic(Action::Maximize));
781
782                    if self.nav_model().is_some() {
783                        let toggle = crate::widget::nav_bar_toggle()
784                            .active(core.nav_bar_active())
785                            .selected(focused)
786                            .on_toggle(if is_condensed {
787                                crate::Action::Cosmic(Action::ToggleNavBarCondensed)
788                            } else {
789                                crate::Action::Cosmic(Action::ToggleNavBar)
790                            });
791
792                        header = header.start(toggle);
793                    }
794
795                    if core.window.show_close {
796                        header = header.on_close(crate::Action::Cosmic(Action::Close));
797                    }
798
799                    if core.window.show_maximize && crate::config::show_maximize() {
800                        header = header.on_maximize(crate::Action::Cosmic(Action::Maximize));
801                    }
802
803                    if core.window.show_minimize && crate::config::show_minimize() {
804                        header = header.on_minimize(crate::Action::Cosmic(Action::Minimize));
805                    }
806
807                    for element in self.header_start() {
808                        header = header.start(element.map(crate::Action::App));
809                    }
810
811                    for element in self.header_center() {
812                        header = header.center(element.map(crate::Action::App));
813                    }
814
815                    for element in self.header_end() {
816                        header = header.end(element.map(crate::Action::App));
817                    }
818
819                    if content_container {
820                        header.apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_header")))
821                    } else {
822                        // Needed to avoid header bar corner gaps for apps without a content container
823                        header
824                            .apply(container)
825                            .class(crate::theme::Container::custom(move |theme| {
826                                let cosmic = theme.cosmic();
827                                container::Style {
828                                    background: Some(iced::Background::Color(
829                                        cosmic.background.base.into(),
830                                    )),
831                                    border: iced::Border {
832                                        radius: [
833                                            (window_corner_radius[0] - 1.0).max(0.0),
834                                            (window_corner_radius[1] - 1.0).max(0.0),
835                                            cosmic.radius_0()[2],
836                                            cosmic.radius_0()[3],
837                                        ]
838                                        .into(),
839                                        ..Default::default()
840                                    },
841                                    ..Default::default()
842                                }
843                            }))
844                            .apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_header")))
845                    }
846                })
847            } else {
848                None
849            })
850            // The content element contains every element beneath the header.
851            .push(content)
852            .apply(container)
853            .padding(if maximized { 0 } else { 1 })
854            .class(crate::theme::Container::custom(move |theme| {
855                container::Style {
856                    background: if content_container {
857                        Some(iced::Background::Color(
858                            theme.cosmic().background.base.into(),
859                        ))
860                    } else {
861                        None
862                    },
863                    border: iced::Border {
864                        color: theme.cosmic().bg_divider().into(),
865                        width: if maximized { 0.0 } else { 1.0 },
866                        radius: window_corner_radius.into(),
867                    },
868                    ..Default::default()
869                }
870            }));
871
872        // Show any current dialog on top and centered over the view content
873        // We have to use a popover even without a dialog to keep the tree from changing
874        let mut popover = popover(view_column).modal(true);
875        if let Some(dialog) = self
876            .dialog()
877            .map(|w| Element::from(id_container(w, iced_core::id::Id::new("COSMIC_dialog"))))
878        {
879            popover = popover.popup(dialog.map(crate::Action::App));
880        }
881
882        let view_element: Element<_> = popover.into();
883        view_element.debug(core.debug)
884    }
885}
886
887const EMBEDDED_FONTS: &[&[u8]] = &[
888    include_bytes!("../../res/open-sans/OpenSans-Light.ttf"),
889    include_bytes!("../../res/open-sans/OpenSans-Regular.ttf"),
890    include_bytes!("../../res/open-sans/OpenSans-Semibold.ttf"),
891    include_bytes!("../../res/open-sans/OpenSans-Bold.ttf"),
892    include_bytes!("../../res/open-sans/OpenSans-ExtraBold.ttf"),
893    include_bytes!("../../res/noto/NotoSansMono-Regular.ttf"),
894    include_bytes!("../../res/noto/NotoSansMono-Bold.ttf"),
895];
896
897#[cold]
898fn preload_fonts() {
899    let mut font_system = iced::advanced::graphics::text::font_system()
900        .write()
901        .unwrap();
902
903    EMBEDDED_FONTS
904        .iter()
905        .for_each(move |font| font_system.load_font(Cow::Borrowed(font)));
906}