Skip to main content

cosmic/app/
cosmic.rs

1// Copyright 2023 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4use std::borrow::Borrow;
5use std::collections::HashMap;
6use std::sync::Arc;
7
8use super::{Action, Application, ApplicationExt, Subscription};
9#[cfg(wayland_platform)]
10use crate::core::Auto;
11#[cfg(wayland_platform)]
12use crate::surface::action::LiveSettings;
13use crate::theme::{THEME, Theme, ThemeType};
14use crate::{Core, Element, keyboard_nav};
15#[cfg(wayland_platform)]
16use cctk::sctk::reexports::csd_frame::{WindowManagerCapabilities, WindowState};
17use cosmic_theme::ThemeMode;
18#[cfg(wayland_platform)]
19use enumflags2::BitFlags;
20#[cfg(not(any(feature = "multi-window", wayland_platform)))]
21use iced::Application as IcedApplication;
22#[cfg(wayland_platform)]
23use iced::event::wayland;
24use iced::{Task, theme, window};
25use iced_futures::event::listen_with;
26#[cfg(feature = "winit")]
27use iced_winit::SurfaceIdWrapper;
28use palette::color_difference::EuclideanDistance;
29
30#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
31#[non_exhaustive]
32pub enum WindowingSystem {
33    UiKit,
34    AppKit,
35    Orbital,
36    OhosNdk,
37    Xlib,
38    Xcb,
39    Wayland,
40    Drm,
41    Gbm,
42    Win32,
43    WinRt,
44    Web,
45    WebCanvas,
46    WebOffscreenCanvas,
47    AndroidNdk,
48    Haiku,
49}
50
51pub(crate) static WINDOWING_SYSTEM: std::sync::OnceLock<WindowingSystem> =
52    std::sync::OnceLock::new();
53
54pub fn windowing_system() -> Option<WindowingSystem> {
55    WINDOWING_SYSTEM.get().copied()
56}
57
58fn init_windowing_system<M>(handle: window::raw_window_handle::WindowHandle) -> crate::Action<M> {
59    let raw = handle.as_ref();
60    let system = match raw {
61        window::raw_window_handle::RawWindowHandle::UiKit(_) => WindowingSystem::UiKit,
62        window::raw_window_handle::RawWindowHandle::AppKit(_) => WindowingSystem::AppKit,
63        window::raw_window_handle::RawWindowHandle::Orbital(_) => WindowingSystem::Orbital,
64        window::raw_window_handle::RawWindowHandle::OhosNdk(_) => WindowingSystem::OhosNdk,
65        window::raw_window_handle::RawWindowHandle::Xlib(_) => WindowingSystem::Xlib,
66        window::raw_window_handle::RawWindowHandle::Xcb(_) => WindowingSystem::Xcb,
67        window::raw_window_handle::RawWindowHandle::Wayland(_) => WindowingSystem::Wayland,
68        window::raw_window_handle::RawWindowHandle::Web(_) => WindowingSystem::Web,
69        window::raw_window_handle::RawWindowHandle::WebCanvas(_) => WindowingSystem::WebCanvas,
70        window::raw_window_handle::RawWindowHandle::WebOffscreenCanvas(_) => {
71            WindowingSystem::WebOffscreenCanvas
72        }
73        window::raw_window_handle::RawWindowHandle::AndroidNdk(_) => WindowingSystem::AndroidNdk,
74        window::raw_window_handle::RawWindowHandle::Haiku(_) => WindowingSystem::Haiku,
75        window::raw_window_handle::RawWindowHandle::Drm(_) => WindowingSystem::Drm,
76        window::raw_window_handle::RawWindowHandle::Gbm(_) => WindowingSystem::Gbm,
77        window::raw_window_handle::RawWindowHandle::Win32(_) => WindowingSystem::Win32,
78        window::raw_window_handle::RawWindowHandle::WinRt(_) => WindowingSystem::WinRt,
79        _ => {
80            tracing::warn!("Unknown windowing system: {raw:?}");
81            return crate::Action::Cosmic(Action::WindowingSystemInitialized);
82        }
83    };
84
85    _ = WINDOWING_SYSTEM.set(system);
86    crate::Action::Cosmic(Action::WindowingSystemInitialized)
87}
88
89#[derive(Default)]
90pub struct Cosmic<App: Application> {
91    pub app: App,
92    pub surface_views: HashMap<
93        window::Id,
94        (
95            Option<window::Id>,
96            SurfaceIdWrapper,
97            Box<dyn for<'a> Fn(&'a App) -> crate::surface::action::LiveSettings>,
98            Option<
99                Box<
100                    dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>>
101                        + Send
102                        + Sync
103                        + 'static,
104                >,
105            >,
106        ),
107    >,
108    pub opened_surfaces: HashMap<window::Id, u32>,
109    blur_enabled: bool,
110}
111
112impl<T: Application> Cosmic<T>
113where
114    T::Message: Send + 'static,
115{
116    pub fn init(
117        (mut core, flags): (Core, T::Flags),
118    ) -> (Self, iced::Task<crate::Action<T::Message>>) {
119        #[cfg(all(feature = "dbus-config", target_os = "linux"))]
120        {
121            use iced_futures::futures::executor::block_on;
122            core.settings_daemon = block_on(cosmic_config::dbus::settings_daemon_proxy()).ok();
123        }
124        let id = core.main_window_id().unwrap_or(window::Id::RESERVED);
125
126        let (model, command) = T::init(core, flags);
127        let existing_theme = THEME.lock().unwrap();
128        let blur = existing_theme.transparent;
129        drop(existing_theme);
130
131        let mut cmds = vec![
132            iced_runtime::window::run_with_handle(id, init_windowing_system),
133            command,
134        ];
135
136        if blur {
137            cmds.push(crate::task::message(crate::action::cosmic(
138                Action::BlurEnabled,
139            )));
140        }
141        (Self::new(model), Task::batch(cmds))
142    }
143
144    #[cfg(not(feature = "multi-window"))]
145    pub fn title(&self) -> String {
146        self.app.title().to_string()
147    }
148
149    #[cfg(feature = "multi-window")]
150    pub fn title(&self, id: window::Id) -> String {
151        self.app.title(id).to_string()
152    }
153
154    #[allow(clippy::too_many_lines)]
155    pub fn surface_update(
156        &mut self,
157        _surface_message: crate::surface::Action<T::Message>,
158    ) -> iced::Task<crate::Action<T::Message>> {
159        #[cfg(feature = "surface-message")]
160        match _surface_message {
161            #[cfg(wayland_platform)]
162            crate::surface::Action::AppSubsurface(settings, _live_settings, view) => {
163                let Some(settings) = std::sync::Arc::try_unwrap(settings)
164                    .ok()
165                    .and_then(|s| s.downcast::<Box<dyn Fn(&mut T) -> iced_runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings + Send + Sync>>().ok()) else {
166                    tracing::error!("Invalid settings for subsurface");
167                    return Task::none();
168                    };
169
170                let settings = settings(&mut self.app);
171
172                let view = view.and_then(|view| {
173                    match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
174                        dyn for<'a> Fn(&'a T) -> Element<'a, crate::Action<T::Message>>
175                            + Send
176                            + Sync,
177                    >>() {
178                        Ok(v) => Some(v),
179                        Err(err) => {
180                            tracing::error!("Invalid view for subsurface view: {err:?}");
181
182                            None
183                        }
184                    }
185                });
186                self.get_subsurface(settings, view.map(|v| *v))
187            }
188            #[cfg(wayland_platform)]
189            crate::surface::Action::Subsurface(settings, _live_settings, view) => {
190                let Some(settings) = std::sync::Arc::try_unwrap(settings)
191                    .ok()
192                    .and_then(|s| s.downcast::<Box<dyn Fn() -> iced_runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings + Send + Sync>>().ok()) else {
193                    tracing::error!("Invalid settings for subsurface");
194                    return Task::none();
195                };
196                let settings = settings();
197
198                if let Some(view) = view {
199                    self.get_subsurface(settings, Some(Box::new(move |_| view())))
200                } else {
201                    self.get_subsurface(settings, None)
202                }
203            }
204            #[cfg(wayland_platform)]
205            crate::surface::Action::AppPopup(settings, live_settings, view) => {
206                let Some(settings) = std::sync::Arc::try_unwrap(settings)
207                    .ok()
208                    .and_then(|s| s.downcast::<Box<dyn Fn(&mut T) -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings + Send + Sync>>().ok()) else {
209                    tracing::error!("Invalid settings for popup");
210                    return Task::none();
211                };
212                let Some(live_settings) =
213                    std::sync::Arc::try_unwrap(live_settings)
214                        .ok()
215                        .and_then(|s| {
216                            s.downcast::<Box<dyn Fn(&T) -> LiveSettings + Send + Sync>>()
217                                .ok()
218                        })
219                else {
220                    tracing::error!("Invalid live settings for popup");
221                    return Task::none();
222                };
223
224                let view = view.and_then(|view| {
225                    match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
226                        dyn for<'a> Fn(&'a T) -> Element<'a, crate::Action<T::Message>>
227                            + Send
228                            + Sync,
229                    >>() {
230                        Ok(v) => Some(v),
231                        Err(err) => {
232                            tracing::error!("Invalid view for subsurface view: {err:?}");
233                            None
234                        }
235                    }
236                });
237                let settings = settings(&mut self.app);
238
239                self.get_popup(settings, *live_settings, view.map(|v| *v))
240            }
241            #[cfg(wayland_platform)]
242            crate::surface::Action::DestroyPopup(id) => {
243                iced_winit::commands::popup::destroy_popup(id)
244            }
245            #[cfg(wayland_platform)]
246            crate::surface::Action::DestroyTooltipPopup => {
247                #[cfg(feature = "applet")]
248                {
249                    iced_winit::commands::popup::destroy_popup(*crate::applet::TOOLTIP_WINDOW_ID)
250                }
251                #[cfg(not(feature = "applet"))]
252                {
253                    Task::none()
254                }
255            }
256            #[cfg(wayland_platform)]
257            crate::surface::Action::DestroySubsurface(id) => {
258                iced_winit::commands::subsurface::destroy_subsurface(id)
259            }
260            #[cfg(wayland_platform)]
261            crate::surface::Action::DestroyWindow(id) => iced::window::close(id),
262            crate::surface::Action::ResponsiveMenuBar {
263                menu_bar,
264                limits,
265                size,
266            } => {
267                let core = self.app.core_mut();
268                core.menu_bars.insert(menu_bar, (limits, size));
269                iced::Task::none()
270            }
271            #[cfg(wayland_platform)]
272            crate::surface::Action::Popup(settings, live_settings, view) => {
273                let Some(settings) = std::sync::Arc::try_unwrap(settings)
274                    .ok()
275                    .and_then(|s| s.downcast::<Box<dyn Fn() -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings + Send + Sync>>().ok()) else {
276                    tracing::error!("Invalid settings for popup");
277                    return Task::none();
278                };
279
280                let Some(live_settings) =
281                    std::sync::Arc::try_unwrap(live_settings)
282                        .ok()
283                        .and_then(|s| {
284                            s.downcast::<Box<dyn Fn() -> LiveSettings + Send + Sync>>()
285                                .ok()
286                        })
287                else {
288                    tracing::error!("Invalid live settings for popup");
289                    return Task::none();
290                };
291                let settings = settings();
292                let live_settings = Box::new(move |_: &T| live_settings());
293
294                if let Some(view) = view {
295                    self.get_popup(settings, live_settings, Some(Box::new(move |_| view())))
296                } else {
297                    self.get_popup(settings, live_settings, None)
298                }
299            }
300            #[cfg(wayland_platform)]
301            crate::surface::Action::AppWindow(id, settings, live_settings, view) => {
302                let Some(settings) = std::sync::Arc::try_unwrap(settings).ok().and_then(|s| {
303                    s.downcast::<Box<dyn Fn(&mut T) -> iced::window::Settings + Send + Sync>>()
304                        .ok()
305                }) else {
306                    tracing::error!("Invalid settings for AppWindow");
307                    return Task::none();
308                };
309                let Some(live_settings) =
310                    std::sync::Arc::try_unwrap(live_settings)
311                        .ok()
312                        .and_then(|s| {
313                            s.downcast::<Box<dyn Fn(&T) -> LiveSettings + Send + Sync>>()
314                                .ok()
315                        })
316                else {
317                    tracing::error!("Invalid live settings for popup");
318                    return Task::none();
319                };
320
321                let view = view.and_then(|view| {
322                    match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
323                        dyn for<'a> Fn(&'a T) -> Element<'a, crate::Action<T::Message>>
324                            + Send
325                            + Sync,
326                    >>() {
327                        Ok(v) => Some(v),
328                        Err(err) => {
329                            tracing::error!("Invalid view for AppWindow: {err:?}");
330                            None
331                        }
332                    }
333                });
334                let settings = settings(&mut self.app);
335
336                self.get_window(id, settings, *live_settings, view.map(|v| *v))
337            }
338            #[cfg(wayland_platform)]
339            crate::surface::Action::Window(id, settings, live_settings, view) => {
340                let Some(settings) = std::sync::Arc::try_unwrap(settings).ok().and_then(|s| {
341                    s.downcast::<Box<dyn Fn() -> iced::window::Settings + Send + Sync>>()
342                        .ok()
343                }) else {
344                    tracing::error!("Invalid settings for Window");
345                    return Task::none();
346                };
347
348                let Some(live_settings) =
349                    std::sync::Arc::try_unwrap(live_settings)
350                        .ok()
351                        .and_then(|s| {
352                            s.downcast::<Box<dyn Fn() -> LiveSettings + Send + Sync>>()
353                                .ok()
354                        })
355                else {
356                    tracing::error!("Invalid live settings for popup");
357                    return Task::none();
358                };
359
360                if let Some(view) = view {
361                    let settings = settings();
362
363                    self.get_window(
364                        id,
365                        settings,
366                        Box::new(move |_| live_settings()),
367                        Some(Box::new(move |_| view())),
368                    )
369                } else {
370                    let settings = settings();
371
372                    iced_runtime::task::oneshot(|channel| {
373                        iced_runtime::Action::Window(iced_runtime::window::Action::Open(
374                            id, settings, channel,
375                        ))
376                    })
377                    .discard()
378                }
379            }
380
381            crate::surface::Action::Ignore => iced::Task::none(),
382            crate::surface::Action::Task(f) => f().map(crate::Action::Surface),
383            #[cfg(wayland_platform)]
384            crate::surface::Action::AppLayerShell(settings, live_settings, view) => {
385                let Some(settings) = std::sync::Arc::try_unwrap(settings)
386                    .ok()
387                    .and_then(|s| s.downcast::<Box<dyn Fn(&mut T) -> iced_runtime::platform_specific::wayland::layer_surface::SctkLayerSurfaceSettings + Send + Sync>>().ok()) else {
388                    tracing::error!("Invalid settings for layer surface");
389                    return Task::none();
390                };
391                let Some(live_settings) =
392                    std::sync::Arc::try_unwrap(live_settings)
393                        .ok()
394                        .and_then(|s| {
395                            s.downcast::<Box<dyn Fn(&T) -> LiveSettings + Send + Sync>>()
396                                .ok()
397                        })
398                else {
399                    tracing::error!("Invalid live settings for popup");
400                    return Task::none();
401                };
402
403                let view = view.and_then(|view| {
404                    match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
405                        dyn for<'a> Fn(&'a T) -> Element<'a, crate::Action<T::Message>>
406                            + Send
407                            + Sync,
408                    >>() {
409                        Ok(v) => Some(v),
410                        Err(err) => {
411                            tracing::error!("Invalid view for layer surface: {err:?}");
412                            None
413                        }
414                    }
415                });
416
417                let settings = settings(&mut self.app);
418
419                self.get_layer_shell(settings, *live_settings, view.map(|v| *v))
420            }
421            #[cfg(wayland_platform)]
422            crate::surface::Action::LayerShell(settings, live_settings, view) => {
423                let Some(settings) = std::sync::Arc::try_unwrap(settings)
424                    .ok()
425                    .and_then(|s| s.downcast::<Box<dyn Fn() -> iced_runtime::platform_specific::wayland::layer_surface::SctkLayerSurfaceSettings + Send + Sync>>().ok()) else {
426                    tracing::error!("Invalid settings for layer surface");
427                    return Task::none();
428                };
429
430                let Some(live_settings) =
431                    std::sync::Arc::try_unwrap(live_settings)
432                        .ok()
433                        .and_then(|s| {
434                            s.downcast::<Box<dyn Fn() -> LiveSettings + Send + Sync>>()
435                                .ok()
436                        })
437                else {
438                    tracing::error!("Invalid live settings for popup");
439                    return Task::none();
440                };
441                let settings = settings();
442                let live_settings = live_settings();
443                let live_settings = Box::new(move |_app: &T| live_settings);
444
445                if let Some(view) = view {
446                    self.get_layer_shell(settings, live_settings, Some(Box::new(move |_| view())))
447                } else {
448                    self.get_layer_shell(settings, live_settings, None)
449                }
450            }
451            #[cfg(wayland_platform)]
452            crate::surface::Action::DestroyLayerShell(id) => {
453                iced_winit::commands::layer_surface::destroy_layer_surface(id)
454            }
455            #[cfg(wayland_platform)]
456            crate::surface::Action::Lock(id, output, live_settings, view) => {
457                let Some(live_settings) =
458                    std::sync::Arc::try_unwrap(live_settings)
459                        .ok()
460                        .and_then(|s| {
461                            s.downcast::<Box<dyn Fn() -> LiveSettings + Send + Sync>>()
462                                .ok()
463                        })
464                else {
465                    tracing::error!("Invalid live settings for popup");
466                    return Task::none();
467                };
468
469                let live_settings = live_settings();
470                let live_settings = Box::new(move |_app: &T| live_settings);
471
472                if let Some(view) = view {
473                    self.get_lock(id, output, live_settings, Some(Box::new(move |_| view())))
474                } else {
475                    self.get_lock(id, output, live_settings, None)
476                }
477            }
478            #[cfg(wayland_platform)]
479            crate::surface::Action::DestroyLock(id) => {
480                iced_winit::commands::session_lock::destroy_lock_surface(id)
481            }
482            crate::surface::Action::SyncLiveSettings(id) => {
483                if let Some((_, id, live_settings, _)) = self.surface_views.get(&id) {
484                    let live_settings = live_settings(&self.app);
485                    return self.apply_live_settings(*id, &live_settings);
486                }
487                Task::none()
488            }
489            // Off wayland every arm above is compiled out, so this keeps the match valid.
490            #[cfg(not(wayland_platform))]
491            _ => iced::Task::none(),
492        }
493
494        #[cfg(not(feature = "surface-message"))]
495        iced::Task::none()
496    }
497
498    pub fn update(
499        &mut self,
500        message: crate::Action<T::Message>,
501    ) -> iced::Task<crate::Action<T::Message>> {
502        let mut task = match message {
503            crate::Action::App(message) => self.app.update(message),
504            crate::Action::Cosmic(message) => self.cosmic_update(message),
505            crate::Action::Surface(action) => self.surface_update(action),
506            crate::Action::None => iced::Task::none(),
507            #[cfg(feature = "single-instance")]
508            crate::Action::DbusActivation(message) => {
509                let mut task = self.app.dbus_activation(message);
510
511                if let Some(id) = self.app.core().main_window_id() {
512                    let unminimize = iced_runtime::window::minimize::<()>(id, false);
513                    task = task.chain(unminimize.discard());
514                }
515
516                task
517            }
518        };
519
520        // Drain any text context-menu popup teardown requests queued by
521        // widgets during `app.update()` and destroy them through the normal
522        // popup pipeline. Drained before the creation queue so a
523        // destroy-then-recreate (a second right-click reusing the same id)
524        // keeps its order.
525        #[cfg(all(wayland_platform, target_os = "linux"))]
526        for id in crate::widget::text_context_menu::take_popup_destroys() {
527            task = task.chain(iced_winit::commands::popup::destroy_popup(id));
528        }
529
530        // Drain any text context-menu popup requests queued by widgets during
531        // `app.update()` and create them through the normal popup pipeline.
532        #[cfg(all(wayland_platform, target_os = "linux"))]
533        for req in crate::widget::text_context_menu::take_popup_requests() {
534            let (live_settings, settings, view) =
535                crate::widget::text_context_menu::into_popup_view::<T::Message>(req);
536            task = task.chain(self.get_popup(
537                settings,
538                Box::new(move |_| live_settings),
539                Some(Box::new(move |_| view())),
540            ));
541        }
542
543        #[cfg(all(target_env = "gnu", not(target_os = "windows")))]
544        crate::malloc::trim(0);
545
546        task
547    }
548
549    #[cfg(not(feature = "multi-window"))]
550    pub fn scale_factor(&self) -> f64 {
551        f64::from(self.app.core().scale_factor())
552    }
553
554    #[cfg(feature = "multi-window")]
555    pub fn scale_factor(&self, _id: window::Id) -> f64 {
556        f64::from(self.app.core().scale_factor())
557    }
558
559    pub fn style(&self, _theme: &Theme) -> theme::Style {
560        if let Some(style) = self.app.style() {
561            style
562        } else {
563            let theme = THEME.lock().unwrap();
564            if self.app.core().window.is_maximized && !theme.cosmic().frosted_maximized_apps {
565                crate::style::iced::application::style(theme.borrow())
566            } else {
567                theme::Style {
568                    background_color: iced_core::Color::TRANSPARENT,
569                    icon_color: theme.cosmic().on_bg_color().into(),
570                    text_color: theme.cosmic().on_bg_color().into(),
571                }
572            }
573        }
574    }
575
576    #[allow(clippy::too_many_lines)]
577    #[cold]
578    pub fn subscription(&self) -> Subscription<crate::Action<T::Message>> {
579        let window_events = listen_with(|event, _, id| {
580            match event {
581                iced::Event::Window(window::Event::Resized(iced::Size { width, height })) => {
582                    return Some(Action::WindowResize(id, width, height));
583                }
584                iced::Event::Window(window::Event::Opened { .. }) => {
585                    return Some(Action::Opened(id));
586                }
587                iced::Event::Window(window::Event::Closed) => {
588                    return Some(Action::SurfaceClosed(id));
589                }
590                iced::Event::Window(window::Event::Focused) => return Some(Action::Focus(id)),
591                iced::Event::Window(window::Event::Unfocused) => return Some(Action::Unfocus(id)),
592                #[cfg(wayland_platform)]
593                iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland(event)) => {
594                    match event {
595                        wayland::Event::Popup(wayland::PopupEvent::Done, _, popup) => {
596                            if popup == id {
597                                return Some(Action::SurfaceClosed(popup));
598                            }
599                        }
600                        wayland::Event::Layer(wayland::LayerEvent::Done, _, layer) => {
601                            return Some(Action::SurfaceClosed(layer));
602                        }
603                        #[cfg(feature = "applet")]
604                        wayland::Event::Window(
605                            iced::event::wayland::WindowEvent::SuggestedBounds(b),
606                        ) => {
607                            return Some(Action::SuggestedBounds(b));
608                        }
609                        #[cfg(wayland_platform)]
610                        wayland::Event::Window(iced::event::wayland::WindowEvent::WindowState(
611                            s,
612                        )) => {
613                            return Some(Action::WindowState(id, s));
614                        }
615                        wayland::Event::BlurEnabled => {
616                            return Some(Action::BlurEnabled);
617                        }
618                        _ => (),
619                    }
620                }
621                _ => (),
622            }
623
624            None
625        });
626
627        let mut subscriptions = vec![
628            self.app.subscription().map(crate::Action::App),
629            self.app
630                .core()
631                .watch_config::<crate::config::CosmicTk>(crate::config::ID)
632                .map(|update| {
633                    for why in update
634                        .errors
635                        .into_iter()
636                        .filter(cosmic_config::Error::is_err)
637                    {
638                        if let cosmic_config::Error::GetKey(_, err) = &why
639                            && err.kind() == std::io::ErrorKind::NotFound
640                        {
641                            // No system default config installed; don't error
642                            continue;
643                        }
644                        tracing::error!(?why, "cosmic toolkit config update error");
645                    }
646
647                    crate::Action::Cosmic(Action::ToolkitConfig(update.config))
648                }),
649            self.app
650                .core()
651                .watch_config::<cosmic_theme::Theme>(
652                    if if let ThemeType::System { prefer_dark, .. } =
653                        THEME.lock().unwrap().theme_type
654                    {
655                        prefer_dark
656                    } else {
657                        None
658                    }
659                    .unwrap_or_else(|| self.app.core().system_theme_mode.is_dark)
660                    {
661                        cosmic_theme::DARK_THEME_ID
662                    } else {
663                        cosmic_theme::LIGHT_THEME_ID
664                    },
665                )
666                .map(|update| {
667                    for why in update
668                        .errors
669                        .into_iter()
670                        .filter(cosmic_config::Error::is_err)
671                    {
672                        tracing::error!(?why, "cosmic theme config update error");
673                    }
674                    Action::SystemThemeChange(
675                        update.keys,
676                        crate::theme::Theme::system(Arc::new(update.config)),
677                    )
678                })
679                .map(crate::Action::Cosmic),
680            self.app
681                .core()
682                .watch_config::<ThemeMode>(cosmic_theme::THEME_MODE_ID)
683                .map(|update| {
684                    for error in update
685                        .errors
686                        .into_iter()
687                        .filter(cosmic_config::Error::is_err)
688                    {
689                        tracing::error!(?error, "error reading system theme mode update");
690                    }
691                    Action::SystemThemeModeChange(update.keys, update.config)
692                })
693                .map(crate::Action::Cosmic),
694            window_events.map(crate::Action::Cosmic),
695            #[cfg(xdg_portal)]
696            crate::theme::portal::desktop_settings()
697                .map(Action::DesktopSettings)
698                .map(crate::Action::Cosmic),
699        ];
700
701        if self.app.core().keyboard_nav {
702            subscriptions.push(
703                keyboard_nav::subscription()
704                    .map(Action::KeyboardNav)
705                    .map(crate::Action::Cosmic),
706            );
707        }
708
709        #[cfg(feature = "single-instance")]
710        if self.app.core().single_instance {
711            subscriptions.push(crate::dbus_activation::subscription::<T>());
712        }
713
714        // Drives the text context-menu popup queues: a right-click queues a
715        // popup but publishes no message, so this re-emits `Action::None` to
716        // make `update()` run and drain the queue.
717        #[cfg(all(wayland_platform, target_os = "linux"))]
718        subscriptions.push(crate::widget::text_context_menu::wake_subscription::<
719            T::Message,
720        >());
721
722        Subscription::batch(subscriptions)
723    }
724
725    #[cfg(not(feature = "multi-window"))]
726    pub fn theme(&self) -> Theme {
727        crate::theme::active()
728    }
729
730    #[cfg(feature = "multi-window")]
731    pub fn theme(&self, _id: window::Id) -> Theme {
732        crate::theme::active()
733    }
734
735    #[cfg(feature = "multi-window")]
736    pub fn view(&self, id: window::Id) -> Element<'_, crate::Action<T::Message>> {
737        crate::widget::text_context_menu::set_current_window_id(id);
738        #[cfg(all(wayland_platform, target_os = "linux"))]
739        if let Some((_, _, _, Some(v))) = self.surface_views.get(&id) {
740            return v(&self.app);
741        }
742        if self
743            .app
744            .core()
745            .main_window_id()
746            .is_none_or(|main_id| main_id != id)
747        {
748            return self.app.view_window(id).map(crate::Action::App);
749        }
750
751        let view = if self.app.core().window.use_template {
752            self.app.view_main()
753        } else {
754            self.app.view().map(crate::Action::App)
755        };
756
757        #[cfg(all(target_env = "gnu", not(target_os = "windows")))]
758        crate::malloc::trim(0);
759
760        view
761    }
762
763    #[cfg(not(feature = "multi-window"))]
764    pub fn view(&self) -> Element<crate::Action<T::Message>> {
765        if let Some(id) = self.app.core().main_window_id() {
766            crate::widget::text_context_menu::set_current_window_id(id);
767        }
768        let view = self.app.view_main();
769
770        #[cfg(all(target_env = "gnu", not(target_os = "windows")))]
771        crate::malloc::trim(0);
772
773        view
774    }
775}
776
777impl<T: Application> Cosmic<T> {
778    #[allow(clippy::unused_self)]
779    #[cold]
780    pub fn close(&mut self) -> iced::Task<crate::Action<T::Message>> {
781        if let Some(id) = self.app.core().main_window_id() {
782            iced::window::close(id)
783        } else {
784            iced::Task::none()
785        }
786    }
787
788    #[allow(clippy::too_many_lines)]
789    fn cosmic_update(&mut self, message: Action) -> iced::Task<crate::Action<T::Message>> {
790        match message {
791            #[cfg(not(wayland_platform))]
792            Action::WindowMaximized(id, maximized) => {
793                if self
794                    .app
795                    .core()
796                    .main_window_id()
797                    .is_some_and(|main_id| main_id == id)
798                {
799                    self.app.core_mut().window.sharp_corners = maximized;
800                }
801            }
802
803            Action::WindowResize(id, width, height) => {
804                if self
805                    .app
806                    .core()
807                    .main_window_id()
808                    .is_some_and(|main_id| main_id == id)
809                {
810                    self.app.core_mut().set_window_width(width);
811                    self.app.core_mut().set_window_height(height);
812                }
813
814                self.app.on_window_resize(id, width, height);
815
816                //TODO: more efficient test of maximized (winit has no event for maximize if set by the OS)
817                return iced::window::is_maximized(id).map(move |maximized| {
818                    crate::Action::Cosmic(Action::WindowMaximized(id, maximized))
819                });
820            }
821
822            #[cfg(wayland_platform)]
823            Action::WindowState(id, state) => {
824                if self
825                    .app
826                    .core()
827                    .main_window_id()
828                    .is_some_and(|main_id| main_id == id)
829                {
830                    self.app.core_mut().window.sharp_corners = state.intersects(
831                        WindowState::MAXIMIZED
832                            | WindowState::FULLSCREEN
833                            | WindowState::TILED
834                            | WindowState::TILED_RIGHT
835                            | WindowState::TILED_LEFT
836                            | WindowState::TILED_TOP
837                            | WindowState::TILED_BOTTOM,
838                    );
839                    self.app.core_mut().window.is_maximized =
840                        state.intersects(WindowState::MAXIMIZED | WindowState::FULLSCREEN);
841                }
842                {
843                    use iced_winit::platform_specific::commands::corner_radius::corner_radius;
844
845                    let theme = THEME.lock().unwrap();
846                    let rounded = !self.app.core().window.sharp_corners
847                        && self.app.core().sync_window_border_radii_to_theme();
848
849                    let cur_rad = self.app.core().corners(&theme, rounded);
850                    return Task::batch([corner_radius(id, cur_rad).discard()]);
851                }
852            }
853
854            #[cfg(wayland_platform)]
855            Action::WmCapabilities(id, capabilities) => {
856                if self
857                    .app
858                    .core()
859                    .main_window_id()
860                    .is_some_and(|main_id| main_id == id)
861                {
862                    self.app.core_mut().window.show_maximize =
863                        capabilities.contains(WindowManagerCapabilities::MAXIMIZE);
864                    self.app.core_mut().window.show_minimize =
865                        capabilities.contains(WindowManagerCapabilities::MINIMIZE);
866                    self.app.core_mut().window.show_window_menu =
867                        capabilities.contains(WindowManagerCapabilities::WINDOW_MENU);
868                }
869            }
870
871            Action::KeyboardNav(message) => match message {
872                keyboard_nav::Action::FocusNext => {
873                    return iced::widget::operation::focus_next().map(crate::Action::Cosmic);
874                }
875                keyboard_nav::Action::FocusPrevious => {
876                    return iced::widget::operation::focus_previous().map(crate::Action::Cosmic);
877                }
878                keyboard_nav::Action::Escape => return self.app.on_escape(),
879                keyboard_nav::Action::Search => return self.app.on_search(),
880
881                keyboard_nav::Action::Fullscreen => return self.app.core().toggle_maximize(None),
882            },
883
884            Action::ContextDrawer(show) => {
885                self.app.core_mut().set_show_context(show);
886                return self.app.on_context_drawer();
887            }
888
889            Action::Drag => return self.app.core().drag(None),
890
891            Action::Minimize => return self.app.core().minimize(None),
892
893            Action::Maximize => return self.app.core().toggle_maximize(None),
894
895            Action::NavBar(key) => {
896                self.app.core_mut().nav_bar_set_toggled_condensed(false);
897                return self.app.on_nav_select(key);
898            }
899
900            Action::NavBarContext(key) => {
901                self.app.core_mut().nav_bar_set_context(key);
902                return self.app.on_nav_context(key);
903            }
904
905            Action::ToggleNavBar => {
906                self.app.core_mut().nav_bar_toggle();
907            }
908
909            Action::ToggleNavBarCondensed => {
910                self.app.core_mut().nav_bar_toggle_condensed();
911            }
912
913            Action::AppThemeChange(mut theme) => {
914                if let ThemeType::System { .. } = theme.theme_type {
915                    self.app.core_mut().theme_sub_counter += 1;
916
917                    let portal_accent = self.app.core().portal_accent;
918                    if let Some(a) = portal_accent {
919                        let t_inner = theme.cosmic();
920                        if a.distance_squared(*t_inner.accent_color()) > 0.00001 {
921                            theme = Theme::system(Arc::new(t_inner.with_accent(a)));
922                        }
923                    }
924                }
925
926                let new_blur = self.blur_enabled && self.app.core().frosted(theme.cosmic());
927
928                theme.transparent = new_blur;
929                let mut guard = THEME.lock().unwrap();
930                guard.set_theme(theme.theme_type.clone());
931                guard.transparent = new_blur;
932                drop(guard);
933
934                #[cfg(wayland_platform)]
935                {
936                    let core = self.app.core();
937                    let mut cmds = Vec::with_capacity(1 + self.surface_views.len());
938                    let blur = if new_blur {
939                        iced::window::enable_blur
940                    } else {
941                        iced::window::disable_blur
942                    };
943                    if core.blur(&theme, None) {
944                        cmds.push(blur(
945                            self.app
946                                .core()
947                                .main_window_id()
948                                .unwrap_or(window::Id::RESERVED),
949                        ));
950                    }
951                    for (id, wrapper, ..) in &self.surface_views {
952                        let overriden = wrapper.2(&self.app);
953                        if core.blur(&theme, Some(wrapper.1)) && overriden.blur.unwrap_or(true) {
954                            cmds.push(blur(*id));
955                        } else if overriden.blur.is_some_and(|b| !b) {
956                            cmds.push(iced::window::disable_blur(*id));
957                        }
958                    }
959                    return Task::batch(cmds);
960                }
961            }
962
963            Action::SystemThemeChange(keys, mut theme) => {
964                let cur_is_dark = self.app.core().system_theme_mode.is_dark;
965                // Ignore updates if the current theme mode does not match.
966                if cur_is_dark != theme.cosmic().is_dark {
967                    return iced::Task::none();
968                }
969                // update transparent
970                let new_blur = self.blur_enabled && self.app.core().frosted(theme.cosmic());
971                theme.transparent = new_blur;
972
973                let cmd = self.app.system_theme_update(&keys, theme.cosmic());
974                // Record the last-known system theme in event that the current theme is custom.
975                self.app.core_mut().system_theme = theme.clone();
976                let portal_accent = self.app.core().portal_accent;
977                {
978                    let mut cosmic_theme = THEME.lock().unwrap();
979
980                    // Only apply update if the theme is set to load a system theme
981                    if let ThemeType::System {
982                        theme: _,
983                        prefer_dark,
984                    } = cosmic_theme.theme_type
985                    {
986                        let mut new_theme = if let Some(a) = portal_accent {
987                            let t_inner = theme.cosmic();
988                            if a.distance_squared(*t_inner.accent_color()) > 0.00001 {
989                                Theme::system(Arc::new(t_inner.with_accent(a)))
990                            } else {
991                                theme
992                            }
993                        } else {
994                            theme
995                        };
996                        new_theme.transparent = new_blur;
997                        new_theme.theme_type.prefer_dark(prefer_dark);
998
999                        cosmic_theme.set_theme(new_theme.theme_type);
1000                        cosmic_theme.transparent = new_blur;
1001
1002                        #[cfg(wayland_platform)]
1003                        {
1004                            use iced_winit::platform_specific::commands::corner_radius::corner_radius;
1005
1006                            let rounded = self.app.core().sync_window_border_radii_to_theme()
1007                                && !self.app.core().window.sharp_corners;
1008
1009                            let cur_rad = self.app.core().corners(&cosmic_theme, rounded);
1010
1011                            // Update radius for the main window
1012                            let main_window_id = self
1013                                .app
1014                                .core()
1015                                .main_window_id()
1016                                .unwrap_or(window::Id::RESERVED);
1017                            let mut cmds =
1018                                vec![cmd, corner_radius(main_window_id, cur_rad).discard()];
1019                            // Update radius for each tracked view with the window surface type
1020                            for (id, (_, surface_type, live_settings, _)) in &self.surface_views {
1021                                let overriden = live_settings(&self.app);
1022                                let cur_rad = if let Some(c) = overriden.corners {
1023                                    Some(c)
1024                                } else {
1025                                    corners(
1026                                        *surface_type,
1027                                        rounded,
1028                                        &cosmic_theme,
1029                                        self.app.core().auto_corner_radius,
1030                                    )
1031                                };
1032                                if cur_rad.is_none() {
1033                                    continue;
1034                                }
1035                                cmds.push(corner_radius(*id, cur_rad).discard());
1036                            }
1037
1038                            let blur = if new_blur {
1039                                iced::window::enable_blur
1040                            } else {
1041                                iced::window::disable_blur
1042                            };
1043
1044                            cmds.push(blur(
1045                                self.app
1046                                    .core()
1047                                    .main_window_id()
1048                                    .unwrap_or(window::Id::RESERVED),
1049                            ));
1050
1051                            for (id, wrapper, ..) in &self.surface_views {
1052                                let overriden = wrapper.2(&self.app);
1053                                if self.app.core().blur(&cosmic_theme, Some(wrapper.1))
1054                                    && overriden.blur.unwrap_or(true)
1055                                {
1056                                    cmds.push(blur(*id));
1057                                } else if overriden.blur.is_some_and(|b| !b) {
1058                                    cmds.push(iced::window::disable_blur(*id));
1059                                }
1060                            }
1061                            return Task::batch(cmds);
1062                        }
1063                    }
1064                }
1065
1066                return cmd;
1067            }
1068
1069            Action::ScaleFactor(factor) => {
1070                self.app.core_mut().set_scale_factor(factor);
1071            }
1072
1073            Action::Close => {
1074                return match self.app.on_app_exit() {
1075                    Some(message) => self.app.update(message),
1076                    None => self.close(),
1077                };
1078            }
1079            Action::SystemThemeModeChange(keys, mode) => {
1080                if match THEME.lock().unwrap().theme_type {
1081                    ThemeType::System {
1082                        theme: _,
1083                        prefer_dark,
1084                    } => prefer_dark.is_some(),
1085                    _ => false,
1086                } {
1087                    return iced::Task::none();
1088                }
1089
1090                let mut cmds = vec![self.app.system_theme_mode_update(&keys, &mode)];
1091
1092                let core = self.app.core_mut();
1093                core.system_theme_mode = mode;
1094                let is_dark = core.system_is_dark();
1095                let changed = core.system_theme_mode.is_dark != is_dark
1096                    || core.portal_is_dark != Some(is_dark)
1097                    || core.system_theme.cosmic().is_dark != is_dark;
1098                if changed {
1099                    core.theme_sub_counter += 1;
1100                    let mut new_theme = if is_dark {
1101                        crate::theme::system_dark()
1102                    } else {
1103                        crate::theme::system_light()
1104                    };
1105                    cmds.push(self.app.system_theme_update(&[], new_theme.cosmic()));
1106
1107                    let core = self.app.core_mut();
1108                    new_theme = if let Some(a) = core.portal_accent {
1109                        let t_inner = new_theme.cosmic();
1110                        if a.distance_squared(*t_inner.accent_color()) > 0.00001 {
1111                            Theme::system(Arc::new(t_inner.with_accent(a)))
1112                        } else {
1113                            new_theme
1114                        }
1115                    } else {
1116                        new_theme
1117                    };
1118                    let new_blur = self.blur_enabled && core.frosted(new_theme.cosmic());
1119                    new_theme.transparent = new_blur;
1120
1121                    core.system_theme = new_theme.clone();
1122                    {
1123                        let mut cosmic_theme = THEME.lock().unwrap();
1124
1125                        // Only apply update if the theme is set to load a system theme
1126                        if let ThemeType::System { .. } = cosmic_theme.theme_type {
1127                            cosmic_theme.set_theme(new_theme.theme_type);
1128                            cosmic_theme.transparent = new_blur;
1129                            #[cfg(wayland_platform)]
1130                            {
1131                                use iced_winit::platform_specific::commands::corner_radius::corner_radius;
1132
1133                                let rounded = self.app.core().sync_window_border_radii_to_theme()
1134                                    && !self.app.core().window.sharp_corners;
1135                                let cur_rad = self.app.core().corners(&cosmic_theme, rounded);
1136
1137                                // Update radius for the main window
1138                                let main_window_id = self
1139                                    .app
1140                                    .core()
1141                                    .main_window_id()
1142                                    .unwrap_or(window::Id::RESERVED);
1143                                cmds.push(corner_radius(main_window_id, cur_rad).discard());
1144                                // Update radius for each tracked view with the window surface type
1145                                for (id, (_, surface_type, live_settings, _)) in &self.surface_views
1146                                {
1147                                    let overriden = live_settings(&self.app);
1148                                    let cur_rad = if let Some(c) = overriden.corners {
1149                                        Some(c)
1150                                    } else {
1151                                        corners(
1152                                            *surface_type,
1153                                            rounded,
1154                                            &cosmic_theme,
1155                                            self.app.core().auto_corner_radius,
1156                                        )
1157                                    };
1158                                    if cur_rad.is_none() {
1159                                        continue;
1160                                    }
1161                                    cmds.push(corner_radius(*id, cur_rad).discard());
1162                                }
1163
1164                                let core = self.app.core();
1165                                let blur = if cosmic_theme.transparent {
1166                                    iced::window::enable_blur
1167                                } else {
1168                                    iced::window::disable_blur
1169                                };
1170
1171                                if core.blur(&cosmic_theme, None) {
1172                                    cmds.push(blur(
1173                                        self.app
1174                                            .core()
1175                                            .main_window_id()
1176                                            .unwrap_or(window::Id::RESERVED),
1177                                    ));
1178                                }
1179                                for (id, wrapper, ..) in &self.surface_views {
1180                                    let overriden = wrapper.2(&self.app);
1181                                    if core.blur(&cosmic_theme, Some(wrapper.1))
1182                                        && overriden.blur.unwrap_or(true)
1183                                    {
1184                                        cmds.push(blur(*id));
1185                                    } else if overriden.blur.is_some_and(|b| !b) {
1186                                        cmds.push(iced::window::disable_blur(*id));
1187                                    }
1188                                }
1189
1190                                return Task::batch(cmds);
1191                            }
1192                        }
1193                    }
1194                }
1195                return Task::batch(cmds);
1196            }
1197            Action::Activate(_token) => {
1198                if let Some(id) = self.app.core().main_window_id() {
1199                    // Unminimize window before requesting to activate it.
1200                    let mut task = iced_runtime::window::minimize(id, false);
1201
1202                    #[cfg(wayland_platform)]
1203                    {
1204                        task = task.chain(
1205                            iced_winit::platform_specific::commands::activation::activate(
1206                                id,
1207                                #[allow(clippy::used_underscore_binding)]
1208                                _token,
1209                            ),
1210                        );
1211                    }
1212
1213                    #[cfg(not(wayland_platform))]
1214                    {
1215                        task = task.chain(iced_runtime::window::gain_focus(id));
1216                    }
1217
1218                    return task;
1219                }
1220            }
1221
1222            Action::SurfaceClosed(id) => {
1223                if self.opened_surfaces.get_mut(&id).is_some_and(|v| {
1224                    *v = v.saturating_sub(1);
1225                    *v == 0
1226                }) {
1227                    self.opened_surfaces.remove(&id);
1228                    self.surface_views.remove(&id);
1229                }
1230                self.surface_views.shrink_to(self.surface_views.len() * 2);
1231
1232                let mut ret = if let Some(msg) = self.app.on_close_requested(id) {
1233                    self.app.update(msg)
1234                } else {
1235                    Task::none()
1236                };
1237                let core = self.app.core();
1238                if core.exit_on_main_window_closed
1239                    && core.main_window_id().is_some_and(|m_id| id == m_id)
1240                {
1241                    ret = Task::batch([iced::exit::<crate::Action<T::Message>>()]);
1242                }
1243                return ret;
1244            }
1245
1246            Action::ShowWindowMenu => {
1247                if let Some(id) = self.app.core().main_window_id() {
1248                    return iced::window::show_system_menu(id);
1249                }
1250            }
1251
1252            #[cfg(feature = "single-instance")]
1253            Action::DbusConnection(conn) => {
1254                return self.app.dbus_connection(conn);
1255            }
1256
1257            #[cfg(xdg_portal)]
1258            Action::DesktopSettings(crate::theme::portal::Desktop::ColorScheme(s)) => {
1259                use ashpd::desktop::settings::ColorScheme;
1260                if match THEME.lock().unwrap().theme_type {
1261                    ThemeType::System {
1262                        theme: _,
1263                        prefer_dark,
1264                    } => prefer_dark.is_some(),
1265                    _ => false,
1266                } {
1267                    return iced::Task::none();
1268                }
1269                let is_dark = match s {
1270                    ColorScheme::NoPreference => None,
1271                    ColorScheme::PreferDark => Some(true),
1272                    ColorScheme::PreferLight => Some(false),
1273                };
1274                let core = self.app.core_mut();
1275
1276                core.portal_is_dark = is_dark;
1277                let is_dark = core.system_is_dark();
1278                let changed = core.system_theme_mode.is_dark != is_dark
1279                    || core.portal_is_dark != Some(is_dark)
1280                    || core.system_theme.cosmic().is_dark != is_dark;
1281
1282                if changed {
1283                    core.theme_sub_counter += 1;
1284                    let mut new_theme = if is_dark {
1285                        crate::theme::system_dark()
1286                    } else {
1287                        crate::theme::system_light()
1288                    };
1289                    if let ThemeType::System { .. } = new_theme.theme_type {
1290                        let new_blur = self.blur_enabled && core.frosted(new_theme.cosmic());
1291                        new_theme.transparent = new_blur;
1292                    }
1293                    core.system_theme = new_theme.clone();
1294                    let core = self.app.core();
1295                    {
1296                        let mut cosmic_theme = THEME.lock().unwrap();
1297
1298                        // Only apply update if the theme is set to load a system theme
1299                        if let ThemeType::System { .. } = cosmic_theme.theme_type {
1300                            let mut cmds = Vec::with_capacity(1);
1301                            #[cfg(wayland_platform)]
1302                            {
1303                                let blur = if cosmic_theme.transparent {
1304                                    iced::window::enable_blur
1305                                } else {
1306                                    iced::window::disable_blur
1307                                };
1308
1309                                if core.blur(&cosmic_theme, None) {
1310                                    cmds.push(blur(
1311                                        core.main_window_id().unwrap_or(window::Id::RESERVED),
1312                                    ));
1313                                }
1314
1315                                for (id, wrapper, ..) in &self.surface_views {
1316                                    let overriden = wrapper.2(&self.app);
1317                                    if core.blur(&cosmic_theme, Some(wrapper.1))
1318                                        && overriden.blur.unwrap_or(true)
1319                                    {
1320                                        cmds.push(blur(*id));
1321                                    } else if overriden.blur.is_some_and(|b| !b) {
1322                                        cmds.push(iced::window::disable_blur(*id));
1323                                    }
1324                                }
1325                            }
1326                            cosmic_theme.set_theme(new_theme.theme_type);
1327                            return Task::batch(cmds);
1328                        }
1329                    }
1330                }
1331            }
1332            #[cfg(xdg_portal)]
1333            Action::DesktopSettings(crate::theme::portal::Desktop::Accent(c)) => {
1334                use palette::Srgba;
1335                let c = Srgba::new(c.red() as f32, c.green() as f32, c.blue() as f32, 1.0);
1336                let core = self.app.core_mut();
1337                core.portal_accent = Some(c);
1338                let cur_accent = core.system_theme.cosmic().accent_color();
1339
1340                if cur_accent.distance_squared(*c) < 0.00001 {
1341                    // skip calculations if we already have the same color
1342                    return iced::Task::none();
1343                }
1344
1345                {
1346                    let mut cosmic_theme = THEME.lock().unwrap();
1347
1348                    // Only apply update if the theme is set to load a system theme
1349                    if let ThemeType::System {
1350                        theme: t,
1351                        prefer_dark,
1352                    } = cosmic_theme.theme_type.clone()
1353                    {
1354                        cosmic_theme.set_theme(ThemeType::System {
1355                            theme: Arc::new(t.with_accent(c)),
1356                            prefer_dark,
1357                        });
1358                    }
1359                }
1360            }
1361            #[cfg(xdg_portal)]
1362            Action::DesktopSettings(crate::theme::portal::Desktop::Contrast(_)) => {
1363                // TODO when high contrast is integrated in settings and all custom themes
1364            }
1365
1366            Action::ToolkitConfig(config) => {
1367                *crate::config::COSMIC_TK.write().unwrap() = config;
1368            }
1369
1370            Action::Focus(f) => {
1371                #[cfg(wayland_platform)]
1372                if let Some((
1373                    parent,
1374                    SurfaceIdWrapper::Subsurface(_) | SurfaceIdWrapper::Popup(_),
1375                    _,
1376                    _,
1377                )) = self.surface_views.get(&f)
1378                {
1379                    // If the parent is already focused, push the new focus
1380                    // to the end of the focus chain.
1381                    if parent.is_some_and(|p| self.app.core().focused_window.last() == Some(&p)) {
1382                        self.app.core_mut().focused_window.push(f);
1383                        return iced::Task::none();
1384                    } else {
1385                        // set the whole parent chain to the focus chain
1386                        let mut parent_chain = vec![f];
1387                        let mut cur = *parent;
1388                        while let Some(p) = cur {
1389                            parent_chain.push(p);
1390                            cur = self
1391                                .surface_views
1392                                .get(&p)
1393                                .and_then(|(parent, _, _, _)| *parent);
1394                        }
1395                        parent_chain.reverse();
1396                        self.app.core_mut().focused_window = parent_chain;
1397                        return iced::Task::none();
1398                    }
1399                }
1400                self.app.core_mut().focused_window = vec![f];
1401            }
1402
1403            Action::Unfocus(id) => {
1404                let core = self.app.core_mut();
1405                if core.focused_window().as_ref().is_some_and(|cur| *cur == id) {
1406                    core.focused_window.pop();
1407                }
1408            }
1409            #[cfg(feature = "applet")]
1410            Action::SuggestedBounds(b) => {
1411                tracing::info!("Suggested bounds: {b:?}");
1412                let core = self.app.core_mut();
1413                core.applet.suggested_bounds = b;
1414            }
1415            Action::Opened(id) => {
1416                #[cfg(wayland_platform)]
1417                {
1418                    use iced_winit::platform_specific::commands::corner_radius::corner_radius;
1419
1420                    let theme = THEME.lock().unwrap();
1421
1422                    // TODO do we need per window sharp corners?
1423                    let rounded = (!self.app.core().window.sharp_corners
1424                        && self.app.core().sync_window_border_radii_to_theme())
1425                        || self
1426                            .surface_views
1427                            .get(&id)
1428                            .is_some_and(|(_, surface_type, _, _)| {
1429                                matches!(
1430                                    surface_type,
1431                                    SurfaceIdWrapper::Popup(_) | SurfaceIdWrapper::LayerSurface(_)
1432                                )
1433                            });
1434                    let new_blur = self.blur_enabled && self.app.core().frosted(theme.cosmic());
1435
1436                    let wrapper = self.surface_views.get(&id).map(|s| s.1);
1437
1438                    // this will blur untracked windows as if they were the main window
1439                    let blur_cmd = if self.app.core().blur(&theme, wrapper)
1440                        && self
1441                            .surface_views
1442                            .get(&id)
1443                            .and_then(|s| s.2(&self.app).blur)
1444                            .unwrap_or(true)
1445                    {
1446                        let blur = if new_blur {
1447                            iced::window::enable_blur
1448                        } else {
1449                            iced::window::disable_blur
1450                        };
1451                        let mut cmds = Vec::with_capacity(1 + self.surface_views.len());
1452                        cmds.push(blur(id));
1453
1454                        Task::batch(cmds)
1455                    } else {
1456                        Task::none()
1457                    };
1458
1459                    let corner_task = if let Some((_, cur_rad)) =
1460                        self.surface_views.get(&id).map(|s| (s.1, &s.2)).and_then(
1461                            |(s, overriden)| {
1462                                let overriden = overriden(&self.app);
1463                                if let Some(c) = overriden.corners {
1464                                    Some((s, c))
1465                                } else {
1466                                    corners(s, rounded, &theme, self.app.core().auto_corner_radius)
1467                                        .map(|c| (s, c))
1468                                }
1469                            },
1470                        ) {
1471                        corner_radius(id, Some(cur_rad)).discard()
1472                    } else if id
1473                        == self
1474                            .app
1475                            .core()
1476                            .main_window_id()
1477                            .unwrap_or(window::Id::RESERVED)
1478                    {
1479                        corner_radius(id, self.app.core().corners(&theme, rounded)).discard()
1480                    } else {
1481                        Task::none()
1482                    };
1483
1484                    return Task::batch([
1485                        blur_cmd,
1486                        corner_task,
1487                        iced_runtime::window::run_with_handle(id, init_windowing_system),
1488                    ]);
1489                }
1490                #[cfg(not(wayland_platform))]
1491                return iced_runtime::window::run_with_handle(id, init_windowing_system);
1492            }
1493            #[cfg(wayland_platform)]
1494            Action::BlurEnabled => {
1495                // TODO do this after blur event confirms support instead of for all wayland windows
1496                self.blur_enabled = true;
1497                let mut t = THEME.lock().unwrap();
1498
1499                let new_blur = self.blur_enabled && self.app.core().frosted(t.cosmic());
1500
1501                t.transparent = new_blur;
1502
1503                self.app.core_mut().system_theme.transparent = new_blur;
1504                {
1505                    let blur = if new_blur {
1506                        iced::window::enable_blur
1507                    } else {
1508                        iced::window::disable_blur
1509                    };
1510                    let mut cmds = Vec::with_capacity(1 + self.surface_views.len());
1511                    if self.app.core().blur(&t, None) {
1512                        cmds.push(blur(
1513                            self.app
1514                                .core()
1515                                .main_window_id()
1516                                .unwrap_or(window::Id::RESERVED),
1517                        ));
1518                    }
1519                    for (id, wrapper, ..) in &self.surface_views {
1520                        let overriden = wrapper.2(&self.app);
1521                        if self.app.core().blur(&t, Some(wrapper.1))
1522                            && overriden.blur.unwrap_or(true)
1523                        {
1524                            cmds.push(blur(*id));
1525                        } else if overriden.blur.is_some_and(|b| !b) {
1526                            cmds.push(iced::window::disable_blur(*id));
1527                        }
1528                    }
1529                    return Task::batch(cmds);
1530                }
1531            }
1532            _ => (),
1533        }
1534
1535        iced::Task::none()
1536    }
1537}
1538
1539impl<App: Application> Cosmic<App> {
1540    pub fn new(app: App) -> Self {
1541        Self {
1542            app,
1543            surface_views: HashMap::new(),
1544            opened_surfaces: HashMap::new(),
1545            blur_enabled: false,
1546        }
1547    }
1548
1549    #[cfg(feature = "surface-message")]
1550    /// Apply live setting overrides for a surface
1551    pub fn apply_live_settings(
1552        &mut self,
1553        id_wrapper: SurfaceIdWrapper,
1554        live_settings: &crate::surface::action::LiveSettings,
1555    ) -> Task<crate::Action<App::Message>> {
1556        let id = id_wrapper.inner();
1557
1558        let mut cmds = Vec::with_capacity(2);
1559        let t = THEME.lock().unwrap();
1560
1561        if let Some(blur) = live_settings.blur {
1562            let blur_cmd = if blur {
1563                if matches!(id_wrapper, SurfaceIdWrapper::Window(_)) {
1564                    window::enable_blur(id)
1565                } else {
1566                    #[cfg(wayland_platform)]
1567                    {
1568                        iced_winit::commands::blur::blur(
1569                            id,
1570                            Some(vec![iced::Rectangle::new(
1571                                iced::Point::ORIGIN,
1572                                iced::Size::INFINITE,
1573                            )]),
1574                        )
1575                        .discard()
1576                    }
1577                    #[cfg(not(wayland_platform))]
1578                    {
1579                        iced::window::enable_blur(id)
1580                    }
1581                }
1582            } else if matches!(id_wrapper, SurfaceIdWrapper::Window(_)) {
1583                window::disable_blur(id)
1584            } else {
1585                #[cfg(wayland_platform)]
1586                {
1587                    iced_winit::commands::blur::blur(id, None).discard()
1588                }
1589                #[cfg(not(wayland_platform))]
1590                {
1591                    iced::window::disable_blur(id)
1592                }
1593            };
1594            cmds.push(blur_cmd);
1595        } else if self.app.core().blur(&t, Some(id_wrapper)) {
1596            cmds.push(if matches!(id_wrapper, SurfaceIdWrapper::Window(_)) {
1597                window::enable_blur(id)
1598            } else {
1599                #[cfg(wayland_platform)]
1600                {
1601                    iced_winit::commands::blur::blur(
1602                        id,
1603                        Some(vec![iced::Rectangle::new(
1604                            iced::Point::ORIGIN,
1605                            iced::Size::INFINITE,
1606                        )]),
1607                    )
1608                    .discard()
1609                }
1610                #[cfg(not(wayland_platform))]
1611                {
1612                    iced::window::enable_blur(id)
1613                }
1614            });
1615        }
1616        #[cfg(wayland_platform)]
1617        if let Some(corners) = live_settings.corners {
1618            cmds.push(
1619                iced_winit::commands::corner_radius::corner_radius(id, Some(corners)).discard(),
1620            );
1621        } else {
1622            let rounded = !self.app.core().window.sharp_corners
1623                && self.app.core().sync_window_border_radii_to_theme();
1624            if let Some(cur_rad) =
1625                corners(id_wrapper, rounded, &t, self.app.core().auto_corner_radius)
1626            {
1627                cmds.push(
1628                    iced_winit::commands::corner_radius::corner_radius(id, Some(cur_rad)).discard(),
1629                );
1630            }
1631        }
1632        #[cfg(wayland_platform)]
1633        if let (SurfaceIdWrapper::LayerSurface(id), Some(padding)) =
1634            (id_wrapper, live_settings.padding)
1635        {
1636            cmds.push(iced_winit::commands::layer_surface::set_padding(
1637                id, padding,
1638            ));
1639        }
1640        Task::batch(cmds)
1641    }
1642
1643    #[cfg(wayland_platform)]
1644    /// Create a subsurface
1645    pub fn get_subsurface(
1646        &mut self,
1647        settings: iced_runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings,
1648        view: Option<
1649            Box<dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync>,
1650        >,
1651    ) -> Task<crate::Action<App::Message>> {
1652        use iced_winit::commands::subsurface::get_subsurface;
1653
1654        *self.opened_surfaces.entry(settings.id).or_insert_with(|| 0) += 1;
1655        let live_settings_task = self.apply_live_settings(
1656            SurfaceIdWrapper::Subsurface(settings.id),
1657            &LiveSettings {
1658                blur: None,
1659                corners: None,
1660                padding: None,
1661            },
1662        );
1663        self.surface_views.insert(
1664            settings.id,
1665            (
1666                Some(settings.parent),
1667                SurfaceIdWrapper::Subsurface(settings.id),
1668                Box::new(|_| LiveSettings::default()),
1669                view,
1670            ),
1671        );
1672        live_settings_task.chain(get_subsurface(settings))
1673    }
1674
1675    #[cfg(wayland_platform)]
1676    /// Create a subsurface
1677    pub fn get_popup(
1678        &mut self,
1679        settings: iced_runtime::platform_specific::wayland::popup::SctkPopupSettings,
1680        live_settings: Box<dyn for<'a> Fn(&'a App) -> LiveSettings + Send + Sync>,
1681        view: Option<
1682            Box<dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync>,
1683        >,
1684    ) -> Task<crate::Action<App::Message>> {
1685        use iced_winit::commands::popup::get_popup;
1686        *self.opened_surfaces.entry(settings.id).or_insert_with(|| 0) += 1;
1687        let live_settings_task = self.apply_live_settings(
1688            SurfaceIdWrapper::Popup(settings.id),
1689            &live_settings(&self.app),
1690        );
1691        self.surface_views.insert(
1692            settings.id,
1693            (
1694                Some(settings.parent),
1695                SurfaceIdWrapper::Popup(settings.id),
1696                live_settings,
1697                view,
1698            ),
1699        );
1700        live_settings_task.chain(get_popup(settings)).discard()
1701    }
1702
1703    #[cfg(wayland_platform)]
1704    /// Create a window surface
1705    pub fn get_window(
1706        &mut self,
1707        id: iced::window::Id,
1708        settings: iced::window::Settings,
1709        live_settings: Box<dyn for<'a> Fn(&'a App) -> LiveSettings + Send + Sync>,
1710
1711        view: Option<
1712            Box<dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync>,
1713        >,
1714    ) -> Task<crate::Action<App::Message>> {
1715        use iced_winit::SurfaceIdWrapper;
1716        *self.opened_surfaces.entry(id).or_insert(0) += 1;
1717        let live_settings_task =
1718            self.apply_live_settings(SurfaceIdWrapper::Window(id), &live_settings(&self.app));
1719        self.surface_views.insert(
1720            id,
1721            (
1722                None, // TODO parent for window, platform specific option maybe?
1723                SurfaceIdWrapper::Window(id),
1724                live_settings,
1725                view,
1726            ),
1727        );
1728
1729        // We don't control window creation in the same way
1730        iced_runtime::task::oneshot(|channel| {
1731            iced_runtime::Action::Window(iced_runtime::window::Action::Open(id, settings, channel))
1732        })
1733        .discard()
1734        .chain(live_settings_task)
1735    }
1736
1737    #[cfg(wayland_platform)]
1738    pub fn get_layer_shell(
1739        &mut self,
1740        settings: iced_runtime::platform_specific::wayland::layer_surface::SctkLayerSurfaceSettings,
1741        live_settings: Box<dyn for<'a> Fn(&'a App) -> LiveSettings + Send + Sync>,
1742        view: Option<
1743            Box<dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync>,
1744        >,
1745    ) -> Task<crate::Action<App::Message>> {
1746        use iced_winit::SurfaceIdWrapper;
1747        use iced_winit::platform_specific::commands::layer_surface::get_layer_surface;
1748        *self.opened_surfaces.entry(settings.id).or_insert(0) += 1;
1749        let live_settings_task = self.apply_live_settings(
1750            SurfaceIdWrapper::LayerSurface(settings.id),
1751            &live_settings(&self.app),
1752        );
1753        self.surface_views.insert(
1754            settings.id,
1755            (
1756                None, // TODO parent for layer shell, platform specific option maybe?
1757                SurfaceIdWrapper::LayerSurface(settings.id),
1758                live_settings,
1759                view,
1760            ),
1761        );
1762        live_settings_task.chain(get_layer_surface(settings))
1763    }
1764
1765    #[cfg(wayland_platform)]
1766    pub fn get_lock(
1767        &mut self,
1768        id: window::Id,
1769        output: cctk::wayland_client::protocol::wl_output::WlOutput,
1770        live_settings: Box<dyn for<'a> Fn(&'a App) -> LiveSettings + Send + Sync>,
1771        view: Option<
1772            Box<dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync>,
1773        >,
1774    ) -> Task<crate::Action<App::Message>> {
1775        use iced_winit::SurfaceIdWrapper;
1776        use iced_winit::platform_specific::commands::session_lock::get_lock_surface;
1777        *self.opened_surfaces.entry(id).or_insert(0) += 1;
1778        let live_settings_task =
1779            self.apply_live_settings(SurfaceIdWrapper::SessionLock(id), &live_settings(&self.app));
1780        self.surface_views.insert(
1781            id,
1782            (
1783                None, // TODO parent for layer shell, platform specific option maybe?
1784                SurfaceIdWrapper::SessionLock(id),
1785                live_settings,
1786                view,
1787            ),
1788        );
1789
1790        live_settings_task.chain(get_lock_surface(id, output))
1791    }
1792}
1793
1794#[cfg(wayland_platform)]
1795fn corners(
1796    surface_type: SurfaceIdWrapper,
1797    rounded: bool,
1798    theme: &Theme,
1799    auto_corner_radius: BitFlags<Auto>,
1800) -> Option<iced_runtime::platform_specific::wayland::CornerRadius> {
1801    if !match surface_type {
1802        SurfaceIdWrapper::Window(_) => auto_corner_radius.contains(Auto::Window),
1803        SurfaceIdWrapper::LayerSurface(_) => auto_corner_radius.contains(Auto::System),
1804        SurfaceIdWrapper::Popup(_) => auto_corner_radius.contains(Auto::Popup),
1805        _ => false,
1806    } {
1807        return None;
1808    }
1809    let theme = theme.cosmic();
1810    Some(if let SurfaceIdWrapper::Popup(_) = surface_type {
1811        let radius_m = theme.radius_m();
1812        iced_runtime::platform_specific::wayland::CornerRadius {
1813            top_left: radius_m[0].round() as u32,
1814            top_right: radius_m[1].round() as u32,
1815            bottom_right: radius_m[2].round() as u32,
1816            bottom_left: radius_m[3].round() as u32,
1817        }
1818    } else if let SurfaceIdWrapper::Window(_) = surface_type
1819        && !rounded
1820    {
1821        let radius_0 = theme.radius_0();
1822        iced_runtime::platform_specific::wayland::CornerRadius {
1823            top_left: radius_0[0].round() as u32,
1824            top_right: radius_0[1].round() as u32,
1825            bottom_right: radius_0[2].round() as u32,
1826            bottom_left: radius_0[3].round() as u32,
1827        }
1828    } else {
1829        let radius_s = theme.radius_s().map(|x| if x < 4.0 { x } else { x + 4.0 });
1830        iced_runtime::platform_specific::wayland::CornerRadius {
1831            top_left: radius_s[0].round() as u32,
1832            top_right: radius_s[1].round() as u32,
1833            bottom_right: radius_s[2].round() as u32,
1834            bottom_left: radius_s[3].round() as u32,
1835        }
1836    })
1837}