Skip to main content

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::{Color, Length, Subscription, theme, window};
26pub use settings::Settings;
27use std::borrow::Cow;
28use std::cell::RefCell;
29use std::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());
393        #[cfg(wayland_platform)]
394        {
395            nav = nav
396                .window_id_maybe(self.core().main_window_id())
397                .on_surface_action(|m| crate::Action::Cosmic(crate::app::Action::Surface(m)))
398        }
399        let mut nav = nav
400            .into_container()
401            .width(iced::Length::Shrink)
402            .height(iced::Length::Fill);
403
404        if !self.core().is_condensed() {
405            nav = nav.max_width(280);
406        }
407
408        Some(Element::from(nav))
409    }
410
411    /// Shows a context menu for the active nav bar item.
412    fn nav_context_menu(&self) -> Option<Vec<menu::Tree<crate::Action<Self::Message>>>> {
413        None
414    }
415
416    /// Allows COSMIC to integrate with your application's [`nav_bar::Model`].
417    fn nav_model(&self) -> Option<&nav_bar::Model> {
418        None
419    }
420
421    /// Called before closing the application. Returning a message will override closing windows.
422    fn on_app_exit(&mut self) -> Option<Self::Message> {
423        None
424    }
425
426    /// Called when a window requests to be closed.
427    fn on_close_requested(&self, id: window::Id) -> Option<Self::Message> {
428        None
429    }
430
431    // Called when context drawer is toggled
432    fn on_context_drawer(&mut self) -> Task<Self::Message> {
433        Task::none()
434    }
435
436    /// Called when the escape key is pressed.
437    fn on_escape(&mut self) -> Task<Self::Message> {
438        Task::none()
439    }
440
441    /// Called when a navigation item is selected.
442    fn on_nav_select(&mut self, id: nav_bar::Id) -> Task<Self::Message> {
443        Task::none()
444    }
445
446    /// Called when a context menu is requested for a navigation item.
447    fn on_nav_context(&mut self, id: nav_bar::Id) -> Task<Self::Message> {
448        Task::none()
449    }
450
451    /// Called when the search function is requested.
452    fn on_search(&mut self) -> Task<Self::Message> {
453        Task::none()
454    }
455
456    /// Called when a window is resized.
457    fn on_window_resize(&mut self, id: window::Id, width: f32, height: f32) {}
458
459    /// Event sources that are to be listened to.
460    fn subscription(&self) -> Subscription<Self::Message> {
461        Subscription::none()
462    }
463
464    /// Respond to an application-specific message.
465    fn update(&mut self, message: Self::Message) -> Task<Self::Message> {
466        Task::none()
467    }
468
469    /// Respond to a system theme change
470    fn system_theme_update(
471        &mut self,
472        keys: &[&'static str],
473        new_theme: &cosmic_theme::Theme,
474    ) -> Task<Self::Message> {
475        Task::none()
476    }
477
478    /// Respond to a system theme mode change
479    fn system_theme_mode_update(
480        &mut self,
481        keys: &[&'static str],
482        new_theme: &cosmic_theme::ThemeMode,
483    ) -> Task<Self::Message> {
484        Task::none()
485    }
486
487    /// Constructs the view for the main window.
488    fn view(&self) -> Element<'_, Self::Message>;
489
490    /// Constructs views for other windows.
491    fn view_window(&self, id: window::Id) -> Element<'_, Self::Message> {
492        panic!("no view for window {id:?}");
493    }
494
495    /// Overrides the default style for applications
496    fn style(&self) -> Option<theme::Style> {
497        None
498    }
499
500    /// Handles dbus activation messages
501    #[cfg(feature = "single-instance")]
502    fn dbus_activation(&mut self, msg: crate::dbus_activation::Message) -> Task<Self::Message> {
503        Task::none()
504    }
505
506    /// Invoked on connect to dbus session socket used for dbus activation
507    ///
508    /// Can be used to expose custom interfaces on the same owned name.
509    #[cfg(feature = "single-instance")]
510    fn dbus_connection(&mut self, conn: zbus::Connection) -> Task<Self::Message> {
511        Task::none()
512    }
513}
514
515/// Methods automatically derived for all types implementing [`Application`].
516pub trait ApplicationExt: Application {
517    /// Initiates a window drag.
518    fn drag(&mut self) -> Task<Self::Message>;
519
520    /// Maximizes the window.
521    fn maximize(&mut self) -> Task<Self::Message>;
522
523    /// Minimizes the window.
524    fn minimize(&mut self) -> Task<Self::Message>;
525    /// Get the title of the main window.
526
527    #[cfg(not(feature = "multi-window"))]
528    fn title(&self) -> &str;
529
530    #[cfg(feature = "multi-window")]
531    /// Get the title of a window.
532    fn title(&self, id: window::Id) -> &str;
533
534    /// Set the context drawer visibility.
535    fn set_show_context(&mut self, show: bool) {
536        self.core_mut().set_show_context(show);
537    }
538
539    /// Set the header bar title.
540    fn set_header_title(&mut self, title: String) {
541        self.core_mut().set_header_title(title);
542    }
543
544    #[cfg(not(feature = "multi-window"))]
545    /// Set the title of the main window.
546    fn set_window_title(&mut self, title: String) -> Task<Self::Message>;
547
548    #[cfg(feature = "multi-window")]
549    /// Set the title of a window.
550    fn set_window_title(&mut self, title: String, id: window::Id) -> Task<Self::Message>;
551
552    /// View template for the main window.
553    fn view_main(&self) -> Element<'_, crate::Action<Self::Message>>;
554
555    fn watch_config<T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq>(
556        &self,
557        id: &'static str,
558    ) -> iced::Subscription<cosmic_config::Update<T>> {
559        self.core().watch_config(id)
560    }
561
562    fn watch_state<T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq>(
563        &self,
564        id: &'static str,
565    ) -> iced::Subscription<cosmic_config::Update<T>> {
566        self.core().watch_state(id)
567    }
568}
569
570impl<App: Application> ApplicationExt for App {
571    fn drag(&mut self) -> Task<Self::Message> {
572        self.core().drag(None)
573    }
574
575    fn maximize(&mut self) -> Task<Self::Message> {
576        self.core().maximize(None, true)
577    }
578
579    fn minimize(&mut self) -> Task<Self::Message> {
580        self.core().minimize(None)
581    }
582
583    #[cfg(feature = "multi-window")]
584    fn title(&self, id: window::Id) -> &str {
585        self.core().title.get(&id).map_or("", |s| s.as_str())
586    }
587
588    #[cfg(not(feature = "multi-window"))]
589    fn title(&self) -> &str {
590        self.core()
591            .main_window_id()
592            .and_then(|id| self.core().title.get(&id).map(std::string::String::as_str))
593            .unwrap_or("")
594    }
595
596    #[cfg(feature = "multi-window")]
597    fn set_window_title(&mut self, title: String, id: window::Id) -> Task<Self::Message> {
598        self.core_mut().title.insert(id, title.clone());
599        self.core().set_title(Some(id), title)
600    }
601
602    #[cfg(not(feature = "multi-window"))]
603    fn set_window_title(&mut self, title: String) -> Task<Self::Message> {
604        let Some(id) = self.core().main_window_id() else {
605            return Task::none();
606        };
607
608        self.core_mut().title.insert(id, title.clone());
609        Task::none()
610    }
611
612    #[allow(clippy::too_many_lines)]
613    /// Creates the view for the main window.
614    fn view_main(&self) -> Element<'_, crate::Action<Self::Message>> {
615        let core = self.core();
616        let is_condensed = core.is_condensed();
617        let sharp_corners = core.window.sharp_corners;
618        let maximized = core.window.is_maximized;
619        let content_container = core.window.content_container;
620        let show_context = core.window.show_context;
621        let nav_bar_active = core.nav_bar_active();
622        let focused = core
623            .focus_chain()
624            .iter()
625            .any(|i| Some(*i) == core.main_window_id());
626
627        let border_padding = core
628            .window
629            .border_padding
630            .unwrap_or(if maximized { 8 } else { 7 });
631
632        let main_content_padding = if content_container {
633            let right_padding = if show_context { 0 } else { border_padding };
634            let left_padding = if nav_bar_active { 0 } else { border_padding };
635
636            [0, right_padding, 0, left_padding]
637        } else {
638            [0, 0, 0, 0]
639        };
640
641        let content_row = crate::widget::row::with_children({
642            let mut widgets = Vec::with_capacity(3);
643
644            // Insert nav bar onto the left side of the window.
645            let has_nav = if let Some(nav) = self.nav_bar() {
646                let nav = id_container(nav, iced_core::id::Id::new("COSMIC_nav_bar"));
647                widgets.push(
648                    container(nav)
649                        .padding([
650                            0,
651                            if is_condensed { border_padding } else { 8 },
652                            border_padding,
653                            border_padding,
654                        ])
655                        .into(),
656                );
657                true
658            } else {
659                false
660            };
661
662            if self.nav_model().is_none() || core.show_content() {
663                let main_content = self.view();
664
665                //TODO: reduce duplication
666                let context_width = core.context_width(has_nav);
667                if core.window.context_is_overlay && show_context {
668                    if let Some(context) = self.context_drawer() {
669                        widgets.push(
670                            crate::widget::context_drawer(
671                                context.title,
672                                context.actions,
673                                context.header,
674                                context.footer,
675                                context.on_close,
676                                main_content,
677                                context.content,
678                                context_width,
679                            )
680                            .apply(|drawer| {
681                                Element::from(id_container(
682                                    drawer,
683                                    iced_core::id::Id::new("COSMIC_context_drawer"),
684                                ))
685                            })
686                            .apply(container)
687                            .padding([0, if content_container { border_padding } else { 0 }, 0, 0])
688                            .apply(Element::from)
689                            .map(crate::Action::App),
690                        );
691                    } else {
692                        widgets.push(
693                            container(main_content.map(crate::Action::App))
694                                .padding(main_content_padding)
695                                .into(),
696                        );
697                    }
698                } else {
699                    //TODO: hide content when out of space
700                    widgets.push(
701                        container(main_content.map(crate::Action::App))
702                            .padding(main_content_padding)
703                            .into(),
704                    );
705                    if let Some(context) = self.context_drawer() {
706                        widgets.push(
707                            crate::widget::ContextDrawer::new_inner(
708                                context.title,
709                                context.actions,
710                                context.header,
711                                context.footer,
712                                context.content,
713                                context.on_close,
714                                context_width,
715                            )
716                            .apply(Element::from)
717                            .map(crate::Action::App)
718                            .apply(container)
719                            .width(context_width)
720                            .apply(|drawer| {
721                                Element::from(id_container(
722                                    drawer,
723                                    iced_core::id::Id::new("COSMIC_context_drawer"),
724                                ))
725                            })
726                            .apply(container)
727                            .padding(if content_container {
728                                [0, border_padding, border_padding, border_padding]
729                            } else {
730                                [0, 0, 0, 0]
731                            })
732                            .into(),
733                        );
734                    } else {
735                        //TODO: this element is added to workaround state issues
736                        widgets.push(space::horizontal().width(Length::Shrink).into());
737                    }
738                }
739            }
740
741            widgets
742        });
743
744        let content_col = crate::widget::column::with_capacity(2)
745            .push(content_row)
746            .push_maybe(self.footer().map(|footer| {
747                container(footer.map(crate::Action::App)).padding([
748                    0,
749                    border_padding,
750                    border_padding,
751                    border_padding,
752                ])
753            }));
754        let content: Element<_> = if content_container {
755            content_col
756                .width(iced::Length::Fill)
757                .height(iced::Length::Fill)
758                .apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_content_container")))
759                .into()
760        } else {
761            content_col.into()
762        };
763
764        // Ensures visually aligned radii for content and window corners
765        let window_corner_radius = if sharp_corners {
766            crate::theme::active().cosmic().radius_0()
767        } else {
768            crate::theme::active()
769                .cosmic()
770                .radius_s()
771                .map(|x| if x < 4.0 { x } else { x + 4.0 })
772        };
773
774        let view_column = crate::widget::column::with_capacity(2)
775            .push_maybe(if core.window.show_headerbar {
776                Some({
777                    let mut header = crate::widget::header_bar()
778                        .focused(focused)
779                        .maximized(maximized)
780                        .sharp_corners(sharp_corners)
781                        .title(&core.window.header_title)
782                        .on_drag(crate::Action::Cosmic(Action::Drag))
783                        .on_right_click(crate::Action::Cosmic(Action::ShowWindowMenu))
784                        .on_double_click(crate::Action::Cosmic(Action::Maximize));
785
786                    if self.nav_model().is_some() {
787                        let toggle = crate::widget::nav_bar_toggle()
788                            .active(core.nav_bar_active())
789                            .selected(focused)
790                            .on_toggle(if is_condensed {
791                                crate::Action::Cosmic(Action::ToggleNavBarCondensed)
792                            } else {
793                                crate::Action::Cosmic(Action::ToggleNavBar)
794                            });
795
796                        header = header.start(toggle);
797                    }
798
799                    if core.window.show_close {
800                        header = header.on_close(crate::Action::Cosmic(Action::Close));
801                    }
802
803                    if core.window.show_maximize && crate::config::show_maximize() {
804                        header = header.on_maximize(crate::Action::Cosmic(Action::Maximize));
805                    }
806
807                    if core.window.show_minimize && crate::config::show_minimize() {
808                        header = header.on_minimize(crate::Action::Cosmic(Action::Minimize));
809                    }
810
811                    for element in self.header_start() {
812                        header = header.start(element.map(crate::Action::App));
813                    }
814
815                    for element in self.header_center() {
816                        header = header.center(element.map(crate::Action::App));
817                    }
818
819                    for element in self.header_end() {
820                        header = header.end(element.map(crate::Action::App));
821                    }
822
823                    if content_container {
824                        header.apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_header")))
825                    } else {
826                        // Needed to avoid header bar corner gaps for apps without a content container
827                        header
828                            .apply(container)
829                            .class(crate::theme::Container::custom(move |theme| {
830                                let cosmic = theme.cosmic();
831                                container::Style {
832                                    background: Some(iced::Background::Color(
833                                        cosmic.background(theme.transparent).base.into(),
834                                    )),
835                                    border: iced::Border {
836                                        radius: [
837                                            (window_corner_radius[0] - 1.0).max(0.0),
838                                            (window_corner_radius[1] - 1.0).max(0.0),
839                                            cosmic.radius_0()[2],
840                                            cosmic.radius_0()[3],
841                                        ]
842                                        .into(),
843                                        ..Default::default()
844                                    },
845                                    ..Default::default()
846                                }
847                            }))
848                            .apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_header")))
849                    }
850                })
851            } else {
852                None
853            })
854            // The content element contains every element beneath the header.
855            .push(content)
856            .apply(container)
857            .padding(if maximized { 0 } else { 1 })
858            .class(crate::theme::Container::custom(move |theme| {
859                container::Style {
860                    background: if content_container {
861                        Some(iced::Background::Color(
862                            theme.cosmic().background(theme.transparent).base.into(),
863                        ))
864                    } else {
865                        None
866                    },
867                    border: iced::Border {
868                        color: theme.cosmic().bg_divider().into(),
869                        width: if maximized { 0.0 } else { 1.0 },
870                        radius: window_corner_radius.into(),
871                    },
872                    ..Default::default()
873                }
874            }));
875
876        // Show any current dialog on top and centered over the view content
877        // We have to use a popover even without a dialog to keep the tree from changing
878        let mut popover = popover(view_column).modal(true);
879        if let Some(dialog) = self
880            .dialog()
881            .map(|w| Element::from(id_container(w, iced_core::id::Id::new("COSMIC_dialog"))))
882        {
883            popover = popover.popup(dialog.map(crate::Action::App));
884        }
885
886        let view_element: Element<_> = popover.into();
887        view_element.debug(core.debug)
888    }
889}
890
891const EMBEDDED_FONTS: &[&[u8]] = &[
892    include_bytes!("../../res/open-sans/OpenSans-Light.ttf"),
893    include_bytes!("../../res/open-sans/OpenSans-Regular.ttf"),
894    include_bytes!("../../res/open-sans/OpenSans-Semibold.ttf"),
895    include_bytes!("../../res/open-sans/OpenSans-Bold.ttf"),
896    include_bytes!("../../res/open-sans/OpenSans-ExtraBold.ttf"),
897    include_bytes!("../../res/noto/NotoSansMono-Regular.ttf"),
898    include_bytes!("../../res/noto/NotoSansMono-Bold.ttf"),
899];
900
901#[cold]
902fn preload_fonts() {
903    let mut font_system = iced::advanced::graphics::text::font_system()
904        .write()
905        .unwrap();
906
907    EMBEDDED_FONTS
908        .iter()
909        .for_each(move |font| font_system.load_font(Cow::Borrowed(font)));
910}