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