feat: Tooltips and Better Surface Management

This commit is contained in:
Ashley Wulber 2025-03-14 11:56:21 -04:00 committed by GitHub
parent c7edd37b03
commit 337b80d4ca
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
90 changed files with 3651 additions and 977 deletions

75
src/app/action.rs Normal file
View file

@ -0,0 +1,75 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use crate::surface;
use crate::theme::Theme;
use crate::widget::nav_bar;
use crate::{config::CosmicTk, keyboard_nav};
#[cfg(feature = "wayland")]
use cctk::sctk::reexports::csd_frame::{WindowManagerCapabilities, WindowState};
use cosmic_theme::ThemeMode;
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
use iced::Application as IcedApplication;
/// A message managed internally by COSMIC.
#[derive(Clone, Debug)]
pub enum Action {
/// Activate the application
Activate(String),
/// Application requests theme change.
AppThemeChange(Theme),
/// Requests to close the window.
Close,
/// Closes or shows the context drawer.
ContextDrawer(bool),
/// Requests to drag the window.
Drag,
/// Window focus changed
Focus(iced::window::Id),
/// Keyboard shortcuts managed by libcosmic.
KeyboardNav(keyboard_nav::Action),
/// Requests to maximize the window.
Maximize,
/// Requests to minimize the window.
Minimize,
/// Activates a navigation element from the nav bar.
NavBar(nav_bar::Id),
/// Activates a context menu for an item from the nav bar.
NavBarContext(nav_bar::Id),
/// Set scaling factor
ScaleFactor(f32),
/// Show the window menu
ShowWindowMenu,
/// Tracks updates to window suggested size.
#[cfg(feature = "applet")]
SuggestedBounds(Option<iced::Size>),
/// Internal surface message
Surface(surface::Action),
/// Notifies that a surface was closed.
/// Any data relating to the surface should be cleaned up.
SurfaceClosed(iced::window::Id),
/// Notification of system theme changes.
SystemThemeChange(Vec<&'static str>, Theme),
/// Notification of system theme mode changes.
SystemThemeModeChange(Vec<&'static str>, ThemeMode),
/// Toggles visibility of the nav bar.
ToggleNavBar,
/// Toggles the condensed status of the nav bar.
ToggleNavBarCondensed,
/// Toolkit configuration update
ToolkitConfig(CosmicTk),
/// Window focus lost
Unfocus(iced::window::Id),
/// Updates the window maximized state
WindowMaximized(iced::window::Id, bool),
/// Updates the tracked window geometry.
WindowResize(iced::window::Id, f32, f32),
/// Tracks updates to window state.
#[cfg(feature = "wayland")]
WindowState(iced::window::Id, WindowState),
/// Capabilities the window manager supports
#[cfg(feature = "wayland")]
WmCapabilities(iced::window::Id, WindowManagerCapabilities),
#[cfg(feature = "xdg-portal")]
DesktopSettings(crate::theme::portal::Desktop),
}

View file

@ -1,94 +0,0 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use iced::window;
/// Asynchronous actions for COSMIC applications.
use super::Message;
/// Commands for COSMIC applications.
pub type Task<M> = iced::Task<Message<M>>;
/// Creates a task which yields a [`crate::app::Message`].
pub fn message<M: Send + 'static>(message: Message<M>) -> Task<M> {
crate::task::message(message)
}
/// Convenience methods for building message-based commands.
pub mod message {
/// Creates a task which yields an application message.
pub fn app<M: Send + 'static>(message: M) -> crate::app::Task<M> {
super::message(super::Message::App(message))
}
/// Creates a task which yields a cosmic message.
pub fn cosmic<M: Send + 'static>(message: crate::app::cosmic::Message) -> crate::app::Task<M> {
super::message(super::Message::Cosmic(message))
}
}
impl crate::app::Core {
pub fn drag<M: Send + 'static>(&self, id: Option<window::Id>) -> iced::Task<Message<M>> {
let Some(id) = id.or(self.main_window) else {
return iced::Task::none();
};
crate::task::drag(id).map(Message::Cosmic)
}
pub fn maximize<M: Send + 'static>(
&self,
id: Option<window::Id>,
maximized: bool,
) -> iced::Task<Message<M>> {
let Some(id) = id.or(self.main_window) else {
return iced::Task::none();
};
crate::task::maximize(id, maximized).map(Message::Cosmic)
}
pub fn minimize<M: Send + 'static>(&self, id: Option<window::Id>) -> iced::Task<Message<M>> {
let Some(id) = id.or(self.main_window) else {
return iced::Task::none();
};
crate::task::minimize(id).map(Message::Cosmic)
}
pub fn set_scaling_factor<M: Send + 'static>(&self, factor: f32) -> iced::Task<Message<M>> {
message::cosmic(super::cosmic::Message::ScaleFactor(factor))
}
pub fn set_title<M: Send + 'static>(
&self,
id: Option<window::Id>,
title: String,
) -> iced::Task<Message<M>> {
let Some(id) = id.or(self.main_window) else {
return iced::Task::none();
};
crate::task::set_title(id, title).map(Message::Cosmic)
}
pub fn set_windowed<M: Send + 'static>(
&self,
id: Option<window::Id>,
) -> iced::Task<Message<M>> {
let Some(id) = id.or(self.main_window) else {
return iced::Task::none();
};
crate::task::set_windowed(id).map(Message::Cosmic)
}
pub fn toggle_maximize<M: Send + 'static>(
&self,
id: Option<window::Id>,
) -> iced::Task<Message<M>> {
let Some(id) = id.or(self.main_window) else {
return iced::Task::none();
};
crate::task::toggle_maximize(id).map(Message::Cosmic)
}
}
pub fn set_theme<M: Send + 'static>(theme: crate::Theme) -> iced::Task<Message<M>> {
message::cosmic(super::cosmic::Message::AppThemeChange(theme))
}

View file

@ -1,3 +1,6 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
//
use std::borrow::Cow;
use crate::Element;
@ -12,11 +15,11 @@ pub struct ContextDrawer<'a, Message: Clone + 'static> {
}
#[cfg(feature = "about")]
pub fn about<'a, Message: Clone + 'static>(
about: &'a crate::widget::about::About,
pub fn about<Message: Clone + 'static>(
about: &crate::widget::about::About,
on_url_press: impl Fn(String) -> Message,
on_close: Message,
) -> ContextDrawer<'a, Message> {
) -> ContextDrawer<'_, Message> {
context_drawer(crate::widget::about(about, on_url_press), on_close)
}

View file

@ -1,377 +0,0 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use std::{cell::OnceCell, collections::HashMap};
use crate::widget::nav_bar;
use cosmic_config::CosmicConfigEntry;
use cosmic_theme::ThemeMode;
use iced::window;
use iced_core::window::Id;
use palette::Srgba;
use slotmap::Key;
use crate::Theme;
/// Status of the nav bar and its panels.
#[derive(Clone)]
pub struct NavBar {
active: bool,
context_id: crate::widget::nav_bar::Id,
toggled: bool,
toggled_condensed: bool,
}
/// COSMIC-specific settings for windows.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone)]
pub struct Window {
/// Label to display as header bar title.
pub header_title: String,
pub use_template: bool,
pub content_container: bool,
pub context_is_overlay: bool,
pub sharp_corners: bool,
pub show_context: bool,
pub show_headerbar: bool,
pub show_window_menu: bool,
pub show_close: bool,
pub show_maximize: bool,
pub show_minimize: bool,
height: f32,
width: f32,
}
/// COSMIC-specific application settings
#[derive(Clone)]
pub struct Core {
/// Enables debug features in cosmic/iced.
pub debug: bool,
/// Disables loading the icon theme from cosmic-config.
pub(super) icon_theme_override: bool,
/// Whether the window is too small for the nav bar + main content.
is_condensed: bool,
/// Enables built in keyboard navigation
pub(super) keyboard_nav: bool,
/// Current status of the nav bar panel.
nav_bar: NavBar,
/// Scaling factor used by the application
scale_factor: f32,
/// Window focus state
pub(super) focused_window: Option<window::Id>,
pub(super) theme_sub_counter: u64,
/// Last known system theme
pub(super) system_theme: Theme,
/// Configured theme mode
pub(super) system_theme_mode: ThemeMode,
pub(super) portal_is_dark: Option<bool>,
pub(super) portal_accent: Option<Srgba>,
pub(super) portal_is_high_contrast: Option<bool>,
pub(super) title: HashMap<Id, String>,
pub window: Window,
#[cfg(feature = "applet")]
pub applet: crate::applet::Context,
#[cfg(feature = "single-instance")]
pub(crate) single_instance: bool,
#[cfg(feature = "dbus-config")]
pub(crate) settings_daemon: Option<cosmic_settings_daemon::CosmicSettingsDaemonProxy<'static>>,
pub(crate) main_window: Option<window::Id>,
pub(crate) exit_on_main_window_closed: bool,
}
impl Default for Core {
fn default() -> Self {
Self {
debug: false,
icon_theme_override: false,
is_condensed: false,
keyboard_nav: true,
nav_bar: NavBar {
active: true,
context_id: crate::widget::nav_bar::Id::null(),
toggled: true,
toggled_condensed: false,
},
scale_factor: 1.0,
title: HashMap::new(),
theme_sub_counter: 0,
system_theme: crate::theme::active(),
system_theme_mode: ThemeMode::config()
.map(|c| {
ThemeMode::get_entry(&c).unwrap_or_else(|(errors, mode)| {
for why in errors.into_iter().filter(cosmic_config::Error::is_err) {
tracing::error!(?why, "ThemeMode config entry error");
}
mode
})
})
.unwrap_or_default(),
window: Window {
header_title: String::new(),
use_template: true,
content_container: true,
context_is_overlay: true,
sharp_corners: false,
show_context: false,
show_headerbar: true,
show_close: true,
show_maximize: true,
show_minimize: true,
show_window_menu: false,
height: 0.,
width: 0.,
},
focused_window: None,
#[cfg(feature = "applet")]
applet: crate::applet::Context::default(),
#[cfg(feature = "single-instance")]
single_instance: false,
#[cfg(feature = "dbus-config")]
settings_daemon: None,
portal_is_dark: None,
portal_accent: None,
portal_is_high_contrast: None,
main_window: None,
exit_on_main_window_closed: true,
}
}
}
impl Core {
/// Whether the window is too small for the nav bar + main content.
#[must_use]
pub fn is_condensed(&self) -> bool {
self.is_condensed
}
/// The scaling factor used by the application.
#[must_use]
pub fn scale_factor(&self) -> f32 {
self.scale_factor
}
/// Enable or disable keyboard navigation
pub fn set_keyboard_nav(&mut self, enabled: bool) {
self.keyboard_nav = enabled;
}
#[must_use]
/// Enable or disable keyboard navigation
pub fn keyboard_nav(&self) -> bool {
self.keyboard_nav
}
/// Changes the scaling factor used by the application.
pub(crate) fn set_scale_factor(&mut self, factor: f32) {
self.scale_factor = factor;
self.is_condensed_update();
}
/// Set header bar title
pub fn set_header_title(&mut self, title: String) {
self.window.header_title = title;
}
/// Whether to show or hide the main window's content.
pub(crate) fn show_content(&self) -> bool {
!self.is_condensed || !self.nav_bar.toggled_condensed
}
/// Call this whenever the scaling factor or window width has changed.
#[allow(clippy::cast_precision_loss)]
fn is_condensed_update(&mut self) {
// Nav bar (280px) + padding (8px) + content (360px)
let mut breakpoint = 280.0 + 8.0 + 360.0;
//TODO: the app may return None from the context_drawer function even if show_context is true
if self.window.show_context && !self.window.context_is_overlay {
// Context drawer min width (344px) + padding (8px)
breakpoint += 344.0 + 8.0;
};
self.is_condensed = (breakpoint * self.scale_factor) > self.window.width as f32;
self.nav_bar_update();
}
fn condensed_conflict(&self) -> bool {
// There is a conflict if the view is condensed and both the nav bar and context drawer are open on the same layer
self.is_condensed
&& self.nav_bar.toggled_condensed
&& self.window.show_context
&& !self.window.context_is_overlay
}
pub(crate) fn context_width(&self, has_nav: bool) -> f32 {
let window_width = (self.window.width as f32) / self.scale_factor;
// Content width (360px) + padding (8px)
let mut reserved_width = 360.0 + 8.0;
if has_nav {
// Navbar width (280px) + padding (8px)
reserved_width += 280.0 + 8.0;
}
// This logic is to ensure the context drawer does not take up too much of the content's space
// The minimum width is 344px and the maximum with is 480px
// We want to keep the content at least 360px until going down to the minimum width
(window_width - reserved_width).min(480.0).max(344.0)
}
pub fn set_show_context(&mut self, show: bool) {
self.window.show_context = show;
self.is_condensed_update();
// Ensure nav bar is closed if condensed view and context drawer is opened
if self.condensed_conflict() {
self.nav_bar.toggled_condensed = false;
self.is_condensed_update();
}
}
/// Whether the nav panel is visible or not
#[must_use]
pub fn nav_bar_active(&self) -> bool {
self.nav_bar.active
}
pub fn nav_bar_toggle(&mut self) {
self.nav_bar.toggled = !self.nav_bar.toggled;
self.nav_bar_set_toggled_condensed(self.nav_bar.toggled);
}
pub fn nav_bar_toggle_condensed(&mut self) {
self.nav_bar_set_toggled_condensed(!self.nav_bar.toggled_condensed);
}
pub(crate) fn nav_bar_context(&self) -> nav_bar::Id {
self.nav_bar.context_id
}
pub(crate) fn nav_bar_set_context(&mut self, id: nav_bar::Id) {
self.nav_bar.context_id = id;
}
pub fn nav_bar_set_toggled(&mut self, toggled: bool) {
self.nav_bar.toggled = toggled;
self.nav_bar_set_toggled_condensed(self.nav_bar.toggled);
}
pub(crate) fn nav_bar_set_toggled_condensed(&mut self, toggled: bool) {
self.nav_bar.toggled_condensed = toggled;
self.nav_bar_update();
// Ensure context drawer is closed if condensed view and nav bar is opened
if self.condensed_conflict() {
self.window.show_context = false;
self.is_condensed_update();
// Sync nav bar state if the view is no longer condensed after closing the context drawer
if !self.is_condensed {
self.nav_bar.toggled = toggled;
self.nav_bar_update();
}
}
}
pub(crate) fn nav_bar_update(&mut self) {
self.nav_bar.active = if self.is_condensed {
self.nav_bar.toggled_condensed
} else {
self.nav_bar.toggled
};
}
/// Set the height of the main window.
pub(crate) fn set_window_height(&mut self, new_height: f32) {
self.window.height = new_height;
}
/// Set the width of the main window.
pub(crate) fn set_window_width(&mut self, new_width: f32) {
self.window.width = new_width;
self.is_condensed_update();
}
/// Get the current system theme
pub fn system_theme(&self) -> &Theme {
&self.system_theme
}
#[must_use]
/// Get the current system theme mode
pub fn system_theme_mode(&self) -> ThemeMode {
self.system_theme_mode
}
pub fn watch_config<
T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq,
>(
&self,
config_id: &'static str,
) -> iced::Subscription<cosmic_config::Update<T>> {
#[cfg(feature = "dbus-config")]
if let Some(settings_daemon) = self.settings_daemon.clone() {
return cosmic_config::dbus::watcher_subscription(settings_daemon, config_id, false);
}
cosmic_config::config_subscription(
std::any::TypeId::of::<T>(),
std::borrow::Cow::Borrowed(config_id),
T::VERSION,
)
}
pub fn watch_state<
T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq,
>(
&self,
state_id: &'static str,
) -> iced::Subscription<cosmic_config::Update<T>> {
#[cfg(feature = "dbus-config")]
if let Some(settings_daemon) = self.settings_daemon.clone() {
return cosmic_config::dbus::watcher_subscription(settings_daemon, state_id, true);
}
cosmic_config::config_subscription(
std::any::TypeId::of::<T>(),
std::borrow::Cow::Borrowed(state_id),
T::VERSION,
)
}
/// Get the current focused window if it exists
#[must_use]
pub fn focused_window(&self) -> Option<window::Id> {
self.focused_window.clone()
}
/// Whether the application should use a dark theme, according to the system
#[must_use]
pub fn system_is_dark(&self) -> bool {
self.portal_is_dark
.unwrap_or(self.system_theme_mode.is_dark)
}
/// The [`Id`] of the main window
#[must_use]
pub fn main_window_id(&self) -> Option<window::Id> {
self.main_window.filter(|id| iced::window::Id::NONE != *id)
}
/// Reset the tracked main window to a new value
pub fn set_main_window_id(&mut self, mut id: Option<window::Id>) -> Option<window::Id> {
std::mem::swap(&mut self.main_window, &mut id);
id
}
}

View file

@ -2,13 +2,12 @@
// SPDX-License-Identifier: MPL-2.0
use std::borrow::Borrow;
use std::collections::HashMap;
use std::sync::Arc;
use super::{Application, ApplicationExt, Core, Subscription};
use crate::config::CosmicTk;
use super::{Action, Application, ApplicationExt, Subscription};
use crate::theme::{Theme, ThemeType, THEME};
use crate::widget::nav_bar;
use crate::{keyboard_nav, Element};
use crate::{keyboard_nav, Core, Element};
#[cfg(feature = "wayland")]
use cctk::sctk::reexports::csd_frame::{WindowManagerCapabilities, WindowState};
use cosmic_theme::ThemeMode;
@ -20,69 +19,14 @@ use iced::{window, Task};
use iced_futures::event::listen_with;
use palette::color_difference::EuclideanDistance;
/// A message managed internally by COSMIC.
#[derive(Clone, Debug)]
pub enum Message {
/// Application requests theme change.
AppThemeChange(Theme),
/// Requests to close the window.
Close,
/// Closes or shows the context drawer.
ContextDrawer(bool),
/// Requests to drag the window.
Drag,
/// Keyboard shortcuts managed by libcosmic.
KeyboardNav(keyboard_nav::Message),
/// Requests to maximize the window.
Maximize,
/// Requests to minimize the window.
Minimize,
/// Activates a navigation element from the nav bar.
NavBar(nav_bar::Id),
/// Activates a context menu for an item from the nav bar.
NavBarContext(nav_bar::Id),
/// Set scaling factor
ScaleFactor(f32),
/// Notification of system theme changes.
SystemThemeChange(Vec<&'static str>, Theme),
/// Notification of system theme mode changes.
SystemThemeModeChange(Vec<&'static str>, ThemeMode),
/// Toggles visibility of the nav bar.
ToggleNavBar,
/// Toggles the condensed status of the nav bar.
ToggleNavBarCondensed,
/// Toolkit configuration update
ToolkitConfig(CosmicTk),
/// Updates the window maximized state
WindowMaximized(window::Id, bool),
/// Updates the tracked window geometry.
WindowResize(window::Id, f32, f32),
/// Tracks updates to window state.
#[cfg(feature = "wayland")]
WindowState(window::Id, WindowState),
/// Capabilities the window manager supports
#[cfg(feature = "wayland")]
WmCapabilities(window::Id, WindowManagerCapabilities),
/// Notifies that a surface was closed.
/// Any data relating to the surface should be cleaned up.
SurfaceClosed(window::Id),
/// Activate the application
Activate(String),
ShowWindowMenu,
#[cfg(feature = "xdg-portal")]
DesktopSettings(crate::theme::portal::Desktop),
/// Window focus changed
Focus(window::Id),
/// Window focus lost
Unfocus(window::Id),
/// Tracks updates to window suggested size.
#[cfg(feature = "applet")]
SuggestedBounds(Option<iced::Size>),
}
#[derive(Default)]
pub struct Cosmic<App> {
pub struct Cosmic<App: Application> {
pub app: App,
#[cfg(feature = "wayland")]
pub surface_views: HashMap<
window::Id,
Box<dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>>>,
>,
}
impl<T: Application> Cosmic<T>
@ -91,7 +35,7 @@ where
{
pub fn init(
(mut core, flags): (Core, T::Flags),
) -> (Self, iced::Task<super::Message<T::Message>>) {
) -> (Self, iced::Task<crate::Action<T::Message>>) {
#[cfg(feature = "dbus-config")]
{
use iced_futures::futures::executor::block_on;
@ -113,16 +57,157 @@ where
self.app.title(id).to_string()
}
pub fn surface_update(
&mut self,
_surface_message: crate::surface::Action,
) -> iced::Task<crate::Action<T::Message>> {
#[cfg(feature = "wayland")]
match _surface_message {
crate::surface::Action::AppSubsurface(settings, view) => {
let Some(settings) = std::sync::Arc::try_unwrap(settings)
.ok()
.and_then(|s| s.downcast::<Box<dyn Fn(&mut T) -> iced_runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings + Send + Sync>>().ok()) else {
tracing::error!("Invalid settings for subsurface");
return Task::none();
};
if let Some(view) = view.and_then(|view| {
match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
dyn for<'a> Fn(&'a T) -> Element<'a, crate::Action<T::Message>>
+ Send
+ Sync,
>>() {
Ok(v) => Some(v),
Err(err) => {
tracing::error!("Invalid view for subsurface view: {err:?}");
None
}
}
}) {
let settings = settings(&mut self.app);
self.get_subsurface(settings, *view)
} else {
iced_winit::commands::subsurface::get_subsurface(settings(&mut self.app))
}
}
crate::surface::Action::Subsurface(settings, view) => {
let Some(settings) = std::sync::Arc::try_unwrap(settings)
.ok()
.and_then(|s| s.downcast::<Box<dyn Fn() -> iced_runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings + Send + Sync>>().ok()) else {
tracing::error!("Invalid settings for subsurface");
return Task::none();
};
if let Some(view) = view.and_then(|view| {
match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
dyn Fn() -> Element<'static, crate::Action<T::Message>> + Send + Sync,
>>() {
Ok(v) => Some(v),
Err(err) => {
tracing::error!("Invalid view for subsurface view: {err:?}");
None
}
}
}) {
let settings = settings();
self.get_subsurface(settings, Box::new(move |_| view()))
} else {
iced_winit::commands::subsurface::get_subsurface(settings())
}
}
crate::surface::Action::AppPopup(settings, view) => {
let Some(settings) = std::sync::Arc::try_unwrap(settings)
.ok()
.and_then(|s| s.downcast::<Box<dyn Fn(&mut T) -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings + Send + Sync>>().ok()) else {
tracing::error!("Invalid settings for popup");
return Task::none();
};
if let Some(view) = view.and_then(|view| {
match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
dyn for<'a> Fn(&'a T) -> Element<'a, crate::Action<T::Message>>
+ Send
+ Sync,
>>() {
Ok(v) => Some(v),
Err(err) => {
tracing::error!("Invalid view for subsurface view: {err:?}");
None
}
}
}) {
let settings = settings(&mut self.app);
self.get_popup(settings, *view)
} else {
iced_winit::commands::popup::get_popup(settings(&mut self.app))
}
}
#[cfg(feature = "wayland")]
crate::surface::Action::DestroyPopup(id) => {
iced_winit::commands::popup::destroy_popup(id)
}
#[cfg(feature = "wayland")]
crate::surface::Action::DestroySubsurface(id) => {
iced_winit::commands::subsurface::destroy_subsurface(id)
}
crate::surface::Action::ResponsiveMenuBar {
menu_bar,
limits,
size,
} => {
let core = self.app.core_mut();
core.menu_bars.insert(menu_bar, (limits, size));
iced::Task::none()
}
crate::surface::Action::Popup(settings, view) => {
let Some(settings) = std::sync::Arc::try_unwrap(settings)
.ok()
.and_then(|s| s.downcast::<Box<dyn Fn() -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings + Send + Sync>>().ok()) else {
tracing::error!("Invalid settings for popup");
return Task::none();
};
if let Some(view) = view.and_then(|view| {
match std::sync::Arc::try_unwrap(view).ok()?.downcast::<Box<
dyn Fn() -> Element<'static, crate::Action<T::Message>> + Send + Sync,
>>() {
Ok(v) => Some(v),
Err(err) => {
tracing::error!("Invalid view for subsurface view: {err:?}");
None
}
}
}) {
let settings = settings();
self.get_popup(settings, Box::new(move |_| view()))
} else {
iced_winit::commands::popup::get_popup(settings())
}
}
crate::surface::Action::Ignore => iced::Task::none(),
crate::surface::Action::Task(f) => {
f().map(|sm| crate::Action::Cosmic(Action::Surface(sm)))
}
}
#[cfg(not(feature = "wayland"))]
iced::Task::none()
}
pub fn update(
&mut self,
message: super::Message<T::Message>,
) -> iced::Task<super::Message<T::Message>> {
message: crate::Action<T::Message>,
) -> iced::Task<crate::Action<T::Message>> {
let message = match message {
super::Message::App(message) => self.app.update(message),
super::Message::Cosmic(message) => self.cosmic_update(message),
super::Message::None => iced::Task::none(),
crate::Action::App(message) => self.app.update(message),
crate::Action::Cosmic(message) => self.cosmic_update(message),
crate::Action::None => iced::Task::none(),
#[cfg(feature = "single-instance")]
super::Message::DbusActivation(message) => self.app.dbus_activation(message),
crate::Action::DbusActivation(message) => self.app.dbus_activation(message),
};
#[cfg(target_env = "gnu")]
@ -158,29 +243,29 @@ where
}
#[allow(clippy::too_many_lines)]
pub fn subscription(&self) -> Subscription<super::Message<T::Message>> {
pub fn subscription(&self) -> Subscription<crate::Action<T::Message>> {
let window_events = listen_with(|event, _, id| {
match event {
iced::Event::Window(window::Event::Resized(iced::Size { width, height })) => {
return Some(Message::WindowResize(id, width, height));
return Some(Action::WindowResize(id, width, height));
}
iced::Event::Window(window::Event::Closed) => {
return Some(Message::SurfaceClosed(id));
return Some(Action::SurfaceClosed(id));
}
iced::Event::Window(window::Event::Focused) => return Some(Message::Focus(id)),
iced::Event::Window(window::Event::Unfocused) => return Some(Message::Unfocus(id)),
iced::Event::Window(window::Event::Focused) => return Some(Action::Focus(id)),
iced::Event::Window(window::Event::Unfocused) => return Some(Action::Unfocus(id)),
#[cfg(feature = "wayland")]
iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland(event)) => {
match event {
wayland::Event::Popup(wayland::PopupEvent::Done, _, id)
| wayland::Event::Layer(wayland::LayerEvent::Done, _, id) => {
return Some(Message::SurfaceClosed(id));
return Some(Action::SurfaceClosed(id));
}
#[cfg(feature = "applet")]
wayland::Event::Window(
iced::event::wayland::WindowEvent::SuggestedBounds(b),
) => {
return Some(Message::SuggestedBounds(b));
return Some(Action::SuggestedBounds(b));
}
_ => (),
}
@ -192,7 +277,7 @@ where
});
let mut subscriptions = vec![
self.app.subscription().map(super::Message::App),
self.app.subscription().map(crate::Action::App),
self.app
.core()
.watch_config::<crate::config::CosmicTk>(crate::config::ID)
@ -205,7 +290,7 @@ where
tracing::error!(?why, "cosmic toolkit config update error");
}
super::Message::Cosmic(Message::ToolkitConfig(update.config))
crate::Action::Cosmic(Action::ToolkitConfig(update.config))
}),
self.app
.core()
@ -232,12 +317,12 @@ where
{
tracing::error!(?why, "cosmic theme config update error");
}
Message::SystemThemeChange(
Action::SystemThemeChange(
update.keys,
crate::theme::Theme::system(Arc::new(update.config)),
)
})
.map(super::Message::Cosmic),
.map(crate::Action::Cosmic),
self.app
.core()
.watch_config::<ThemeMode>(cosmic_theme::THEME_MODE_ID)
@ -249,27 +334,27 @@ where
{
tracing::error!(?error, "error reading system theme mode update");
}
Message::SystemThemeModeChange(update.keys, update.config)
Action::SystemThemeModeChange(update.keys, update.config)
})
.map(super::Message::Cosmic),
window_events.map(super::Message::Cosmic),
.map(crate::Action::Cosmic),
window_events.map(crate::Action::Cosmic),
#[cfg(feature = "xdg-portal")]
crate::theme::portal::desktop_settings()
.map(Message::DesktopSettings)
.map(super::Message::Cosmic),
.map(Action::DesktopSettings)
.map(crate::Action::Cosmic),
];
if self.app.core().keyboard_nav {
subscriptions.push(
keyboard_nav::subscription()
.map(Message::KeyboardNav)
.map(super::Message::Cosmic),
.map(Action::KeyboardNav)
.map(crate::Action::Cosmic),
);
}
#[cfg(feature = "single-instance")]
if self.app.core().single_instance {
subscriptions.push(super::single_instance_subscription::<T>());
subscriptions.push(crate::dbus_activation::subscription::<T>());
}
Subscription::batch(subscriptions)
@ -286,20 +371,24 @@ where
}
#[cfg(feature = "multi-window")]
pub fn view(&self, id: window::Id) -> Element<super::Message<T::Message>> {
pub fn view(&self, id: window::Id) -> Element<crate::Action<T::Message>> {
#[cfg(feature = "wayland")]
if let Some(v) = self.surface_views.get(&id) {
return v(&self.app);
}
if !self
.app
.core()
.main_window_id()
.is_some_and(|main_id| main_id == id)
{
return self.app.view_window(id).map(super::Message::App);
return self.app.view_window(id).map(crate::Action::App);
}
let view = if self.app.core().window.use_template {
self.app.view_main()
} else {
self.app.view().map(super::Message::App)
self.app.view().map(crate::Action::App)
};
#[cfg(target_env = "gnu")]
@ -309,7 +398,7 @@ where
}
#[cfg(not(feature = "multi-window"))]
pub fn view(&self) -> Element<super::Message<T::Message>> {
pub fn view(&self) -> Element<crate::Action<T::Message>> {
let view = self.app.view_main();
#[cfg(target_env = "gnu")]
@ -321,7 +410,7 @@ where
impl<T: Application> Cosmic<T> {
#[allow(clippy::unused_self)]
pub fn close(&mut self) -> iced::Task<super::Message<T::Message>> {
pub fn close(&mut self) -> iced::Task<crate::Action<T::Message>> {
if let Some(id) = self.app.core().main_window_id() {
iced::window::close(id)
} else {
@ -330,9 +419,9 @@ impl<T: Application> Cosmic<T> {
}
#[allow(clippy::too_many_lines)]
fn cosmic_update(&mut self, message: Message) -> iced::Task<super::Message<T::Message>> {
fn cosmic_update(&mut self, message: Action) -> iced::Task<crate::Action<T::Message>> {
match message {
Message::WindowMaximized(id, maximized) => {
Action::WindowMaximized(id, maximized) => {
if self
.app
.core()
@ -343,7 +432,7 @@ impl<T: Application> Cosmic<T> {
}
}
Message::WindowResize(id, width, height) => {
Action::WindowResize(id, width, height) => {
if self
.app
.core()
@ -358,12 +447,12 @@ impl<T: Application> Cosmic<T> {
//TODO: more efficient test of maximized (winit has no event for maximize if set by the OS)
return iced::window::get_maximized(id).map(move |maximized| {
super::Message::Cosmic(Message::WindowMaximized(id, maximized))
crate::Action::Cosmic(Action::WindowMaximized(id, maximized))
});
}
#[cfg(feature = "wayland")]
Message::WindowState(id, state) => {
Action::WindowState(id, state) => {
if self
.app
.core()
@ -383,7 +472,7 @@ impl<T: Application> Cosmic<T> {
}
#[cfg(feature = "wayland")]
Message::WmCapabilities(id, capabilities) => {
Action::WmCapabilities(id, capabilities) => {
if self
.app
.core()
@ -399,49 +488,49 @@ impl<T: Application> Cosmic<T> {
}
}
Message::KeyboardNav(message) => match message {
keyboard_nav::Message::FocusNext => {
return iced::widget::focus_next().map(super::Message::Cosmic)
Action::KeyboardNav(message) => match message {
keyboard_nav::Action::FocusNext => {
return iced::widget::focus_next().map(crate::Action::Cosmic)
}
keyboard_nav::Message::FocusPrevious => {
return iced::widget::focus_previous().map(super::Message::Cosmic)
keyboard_nav::Action::FocusPrevious => {
return iced::widget::focus_previous().map(crate::Action::Cosmic)
}
keyboard_nav::Message::Escape => return self.app.on_escape(),
keyboard_nav::Message::Search => return self.app.on_search(),
keyboard_nav::Action::Escape => return self.app.on_escape(),
keyboard_nav::Action::Search => return self.app.on_search(),
keyboard_nav::Message::Fullscreen => return self.app.core().toggle_maximize(None),
keyboard_nav::Action::Fullscreen => return self.app.core().toggle_maximize(None),
},
Message::ContextDrawer(show) => {
Action::ContextDrawer(show) => {
self.app.core_mut().set_show_context(show);
return self.app.on_context_drawer();
}
Message::Drag => return self.app.core().drag(None),
Action::Drag => return self.app.core().drag(None),
Message::Minimize => return self.app.core().minimize(None),
Action::Minimize => return self.app.core().minimize(None),
Message::Maximize => return self.app.core().toggle_maximize(None),
Action::Maximize => return self.app.core().toggle_maximize(None),
Message::NavBar(key) => {
Action::NavBar(key) => {
self.app.core_mut().nav_bar_set_toggled_condensed(false);
return self.app.on_nav_select(key);
}
Message::NavBarContext(key) => {
Action::NavBarContext(key) => {
self.app.core_mut().nav_bar_set_context(key);
return self.app.on_nav_context(key);
}
Message::ToggleNavBar => {
Action::ToggleNavBar => {
self.app.core_mut().nav_bar_toggle();
}
Message::ToggleNavBarCondensed => {
Action::ToggleNavBarCondensed => {
self.app.core_mut().nav_bar_toggle_condensed();
}
Message::AppThemeChange(mut theme) => {
Action::AppThemeChange(mut theme) => {
if let ThemeType::System { theme: _, .. } = theme.theme_type {
self.app.core_mut().theme_sub_counter += 1;
@ -457,7 +546,7 @@ impl<T: Application> Cosmic<T> {
THEME.lock().unwrap().set_theme(theme.theme_type);
}
Message::SystemThemeChange(keys, theme) => {
Action::SystemThemeChange(keys, theme) => {
let cur_is_dark = THEME.lock().unwrap().theme_type.is_dark();
// Ignore updates if the current theme mode does not match.
if cur_is_dark != theme.cosmic().is_dark {
@ -495,17 +584,17 @@ impl<T: Application> Cosmic<T> {
return cmd;
}
Message::ScaleFactor(factor) => {
Action::ScaleFactor(factor) => {
self.app.core_mut().set_scale_factor(factor);
}
Message::Close => {
Action::Close => {
return match self.app.on_app_exit() {
Some(message) => self.app.update(message),
None => self.close(),
};
}
Message::SystemThemeModeChange(keys, mode) => {
Action::SystemThemeModeChange(keys, mode) => {
if !keys.contains(&"is_dark") {
return iced::Task::none();
}
@ -557,7 +646,7 @@ impl<T: Application> Cosmic<T> {
}
return Task::batch(cmds);
}
Message::Activate(_token) =>
Action::Activate(_token) =>
{
#[cfg(feature = "wayland")]
if let Some(id) = self.app.core().main_window_id() {
@ -568,7 +657,10 @@ impl<T: Application> Cosmic<T> {
);
}
}
Message::SurfaceClosed(id) => {
Action::Surface(action) => return self.surface_update(action),
Action::SurfaceClosed(id) => {
let mut ret = if let Some(msg) = self.app.on_close_requested(id) {
self.app.update(msg)
} else {
@ -578,17 +670,19 @@ impl<T: Application> Cosmic<T> {
if core.exit_on_main_window_closed
&& core.main_window_id().is_some_and(|m_id| id == m_id)
{
ret = Task::batch(vec![iced::exit::<super::Message<T::Message>>()]);
ret = Task::batch(vec![iced::exit::<crate::Action<T::Message>>()]);
}
return ret;
}
Message::ShowWindowMenu => {
Action::ShowWindowMenu => {
if let Some(id) = self.app.core().main_window_id() {
return iced::window::show_system_menu(id);
}
}
#[cfg(feature = "xdg-portal")]
Message::DesktopSettings(crate::theme::portal::Desktop::ColorScheme(s)) => {
Action::DesktopSettings(crate::theme::portal::Desktop::ColorScheme(s)) => {
use ashpd::desktop::settings::ColorScheme;
if match THEME.lock().unwrap().theme_type {
ThemeType::System {
@ -628,7 +722,7 @@ impl<T: Application> Cosmic<T> {
}
}
#[cfg(feature = "xdg-portal")]
Message::DesktopSettings(crate::theme::portal::Desktop::Accent(c)) => {
Action::DesktopSettings(crate::theme::portal::Desktop::Accent(c)) => {
use palette::Srgba;
let c = Srgba::new(c.red() as f32, c.green() as f32, c.blue() as f32, 1.0);
let core = self.app.core_mut();
@ -657,11 +751,11 @@ impl<T: Application> Cosmic<T> {
}
}
#[cfg(feature = "xdg-portal")]
Message::DesktopSettings(crate::theme::portal::Desktop::Contrast(_)) => {
Action::DesktopSettings(crate::theme::portal::Desktop::Contrast(_)) => {
// TODO when high contrast is integrated in settings and all custom themes
}
Message::ToolkitConfig(config) => {
Action::ToolkitConfig(config) => {
// Change the icon theme if not defined by the application.
if !self.app.core().icon_theme_override
&& crate::icon_theme::default() != config.icon_theme
@ -672,18 +766,18 @@ impl<T: Application> Cosmic<T> {
*crate::config::COSMIC_TK.write().unwrap() = config;
}
Message::Focus(f) => {
Action::Focus(f) => {
self.app.core_mut().focused_window = Some(f);
}
Message::Unfocus(id) => {
Action::Unfocus(id) => {
let core = self.app.core_mut();
if core.focused_window.as_ref().is_some_and(|cur| *cur == id) {
core.focused_window = None;
}
}
#[cfg(feature = "applet")]
Message::SuggestedBounds(b) => {
Action::SuggestedBounds(b) => {
tracing::info!("Suggested bounds: {b:?}");
let core = self.app.core_mut();
core.applet.suggested_bounds = b;
@ -697,6 +791,40 @@ impl<T: Application> Cosmic<T> {
impl<App: Application> Cosmic<App> {
pub fn new(app: App) -> Self {
Self { app }
Self {
app,
#[cfg(feature = "wayland")]
surface_views: HashMap::new(),
}
}
#[cfg(feature = "wayland")]
/// Create a subsurface
pub fn get_subsurface(
&mut self,
settings: iced_runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings,
view: Box<
dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync,
>,
) -> Task<crate::Action<App::Message>> {
use iced_winit::commands::subsurface::get_subsurface;
self.surface_views.insert(settings.id, view);
get_subsurface(settings)
}
#[cfg(feature = "wayland")]
/// Create a subsurface
pub fn get_popup(
&mut self,
settings: iced_runtime::platform_specific::wayland::popup::SctkPopupSettings,
view: Box<
dyn for<'a> Fn(&'a App) -> Element<'a, crate::Action<App::Message>> + Send + Sync,
>,
) -> Task<crate::Action<App::Message>> {
use iced_winit::commands::popup::get_popup;
self.surface_views.insert(settings.id, view);
get_popup(settings)
}
}

View file

@ -6,70 +6,27 @@
//! Check out our [application](https://github.com/pop-os/libcosmic/tree/master/examples/application)
//! example in our repository.
pub mod command;
mod action;
pub use action::Action;
use cosmic_config::CosmicConfigEntry;
pub mod context_drawer;
mod core;
pub mod cosmic;
#[cfg(all(feature = "winit", feature = "multi-window"))]
pub(crate) mod multi_window;
pub mod settings;
pub mod message {
#[derive(Clone, Debug)]
#[must_use]
pub enum Message<M> {
/// Messages from the application, for the application.
App(M),
/// Internal messages to be handled by libcosmic.
Cosmic(super::cosmic::Message),
#[cfg(feature = "single-instance")]
/// Dbus activation messages
DbusActivation(super::DbusActivationMessage),
/// Do nothing
None,
}
pub type Task<M> = iced::Task<crate::Action<M>>;
pub const fn app<M>(message: M) -> Message<M> {
Message::App(message)
}
pub const fn cosmic<M>(message: super::cosmic::Message) -> Message<M> {
Message::Cosmic(message)
}
pub const fn none<M>() -> Message<M> {
Message::None
}
impl<M> From<M> for Message<M> {
fn from(value: M) -> Self {
Self::App(value)
}
}
}
use std::borrow::Cow;
pub use self::command::Task;
pub use self::core::Core;
pub use self::settings::Settings;
use crate::prelude::*;
use crate::theme::THEME;
use crate::widget::{container, horizontal_space, id_container, menu, nav_bar, popover};
pub use crate::Core;
use apply::Apply;
use context_drawer::ContextDrawer;
use iced::window;
use iced::{Length, Subscription};
pub use message::Message;
use url::Url;
#[cfg(feature = "single-instance")]
use {
iced_futures::futures::channel::mpsc::{Receiver, Sender},
iced_futures::futures::SinkExt,
std::any::TypeId,
std::collections::HashMap,
zbus::{interface, proxy, zvariant::Value},
};
pub use settings::Settings;
use std::borrow::Cow;
pub(crate) fn iced_settings<App: Application>(
settings: Settings,
@ -143,6 +100,7 @@ pub fn run<App: Application>(settings: Settings, flags: App::Flags) -> iced::Res
crate::malloc::limit_mmap_threshold(threshold);
}
let default_font = settings.default_font;
let (settings, mut flags, window_settings) = iced_settings::<App>(settings, flags);
#[cfg(not(feature = "multi-window"))]
{
@ -179,142 +137,6 @@ pub fn run<App: Application>(settings: Settings, flags: App::Flags) -> iced::Res
}
}
#[cfg(feature = "single-instance")]
#[derive(Debug, Clone)]
pub struct DbusActivationMessage<Action = String, Args = Vec<String>> {
pub activation_token: Option<String>,
pub desktop_startup_id: Option<String>,
pub msg: DbusActivationDetails<Action, Args>,
}
#[derive(Debug, Clone)]
pub enum DbusActivationDetails<Action = String, Args = Vec<String>> {
Activate,
Open {
url: Vec<Url>,
},
/// action can be deserialized as Flags
ActivateAction {
action: Action,
args: Args,
},
}
#[cfg(feature = "single-instance")]
#[derive(Debug, Default)]
pub struct DbusActivation(Option<Sender<DbusActivationMessage>>);
#[cfg(feature = "single-instance")]
impl DbusActivation {
#[must_use]
pub fn new() -> Self {
Self(None)
}
pub fn rx(&mut self) -> Receiver<DbusActivationMessage> {
let (tx, rx) = iced_futures::futures::channel::mpsc::channel(10);
self.0 = Some(tx);
rx
}
}
#[cfg(feature = "single-instance")]
#[proxy(interface = "org.freedesktop.DbusActivation", assume_defaults = true)]
pub trait DbusActivationInterface {
/// Activate the application.
fn activate(&mut self, platform_data: HashMap<&str, Value<'_>>) -> zbus::Result<()>;
/// Open the given URIs.
fn open(
&mut self,
uris: Vec<&str>,
platform_data: HashMap<&str, Value<'_>>,
) -> zbus::Result<()>;
/// Activate the given action.
fn activate_action(
&mut self,
action_name: &str,
parameter: Vec<&str>,
platform_data: HashMap<&str, Value<'_>>,
) -> zbus::Result<()>;
}
#[cfg(feature = "single-instance")]
#[interface(name = "org.freedesktop.DbusActivation")]
impl DbusActivation {
async fn activate(&mut self, platform_data: HashMap<&str, Value<'_>>) {
if let Some(tx) = &mut self.0 {
let _ = tx
.send(DbusActivationMessage {
activation_token: platform_data.get("activation-token").and_then(|t| match t {
Value::Str(t) => Some(t.to_string()),
_ => None,
}),
desktop_startup_id: platform_data.get("desktop-startup-id").and_then(
|t| match t {
Value::Str(t) => Some(t.to_string()),
_ => None,
},
),
msg: DbusActivationDetails::Activate,
})
.await;
}
}
async fn open(&mut self, uris: Vec<&str>, platform_data: HashMap<&str, Value<'_>>) {
if let Some(tx) = &mut self.0 {
let _ = tx
.send(DbusActivationMessage {
activation_token: platform_data.get("activation-token").and_then(|t| match t {
Value::Str(t) => Some(t.to_string()),
_ => None,
}),
desktop_startup_id: platform_data.get("desktop-startup-id").and_then(
|t| match t {
Value::Str(t) => Some(t.to_string()),
_ => None,
},
),
msg: DbusActivationDetails::Open {
url: uris.iter().filter_map(|u| Url::parse(u).ok()).collect(),
},
})
.await;
}
}
async fn activate_action(
&mut self,
action_name: &str,
parameter: Vec<&str>,
platform_data: HashMap<&str, Value<'_>>,
) {
if let Some(tx) = &mut self.0 {
let _ = tx
.send(DbusActivationMessage {
activation_token: platform_data.get("activation-token").and_then(|t| match t {
Value::Str(t) => Some(t.to_string()),
_ => None,
}),
desktop_startup_id: platform_data.get("desktop-startup-id").and_then(
|t| match t {
Value::Str(t) => Some(t.to_string()),
_ => None,
},
),
msg: DbusActivationDetails::ActivateAction {
action: action_name.to_string(),
args: parameter
.iter()
.map(std::string::ToString::to_string)
.collect(),
},
})
.await;
}
}
}
#[cfg(feature = "single-instance")]
/// Launch a COSMIC application with the given [`Settings`].
/// If the application is already running, the arguments will be passed to the
@ -326,6 +148,8 @@ where
App::Flags: CosmicFlags,
App::Message: Clone + std::fmt::Debug + Send + 'static,
{
use std::collections::HashMap;
let activation_token = std::env::var("XDG_ACTIVATION_TOKEN").ok();
let override_single = std::env::var("COSMIC_SINGLE_INSTANCE")
@ -342,14 +166,14 @@ where
return run::<App>(settings, flags);
};
if DbusActivationInterfaceProxyBlocking::builder(&conn)
if crate::dbus_activation::DbusActivationInterfaceProxyBlocking::builder(&conn)
.destination(App::APP_ID)
.ok()
.and_then(|b| b.path(path).ok())
.and_then(|b| b.destination(App::APP_ID).ok())
.and_then(|b| b.build().ok())
.is_some_and(|mut p| {
match {
let res = {
let mut platform_data = HashMap::new();
if let Some(activation_token) = activation_token {
platform_data.insert("activation-token", activation_token.into());
@ -363,7 +187,8 @@ where
} else {
p.activate(platform_data)
}
} {
};
match res {
Ok(()) => {
tracing::info!("Successfully activated another instance");
true
@ -491,7 +316,7 @@ where
}
/// Allows overriding the default nav bar widget.
fn nav_bar(&self) -> Option<Element<Message<Self::Message>>> {
fn nav_bar(&self) -> Option<Element<crate::Action<Self::Message>>> {
if !self.core().nav_bar_active() {
return None;
}
@ -499,8 +324,8 @@ where
let nav_model = self.nav_model()?;
let mut nav =
crate::widget::nav_bar(nav_model, |id| Message::Cosmic(cosmic::Message::NavBar(id)))
.on_context(|id| Message::Cosmic(cosmic::Message::NavBarContext(id)))
crate::widget::nav_bar(nav_model, |id| crate::Action::Cosmic(Action::NavBar(id)))
.on_context(|id| crate::Action::Cosmic(Action::NavBarContext(id)))
.context_menu(self.nav_context_menu(self.core().nav_bar_context()))
.into_container()
// XXX both must be shrink to avoid flex layout from ignoring it
@ -515,7 +340,10 @@ where
}
/// Shows a context menu for the active nav bar item.
fn nav_context_menu(&self, id: nav_bar::Id) -> Option<Vec<menu::Tree<Message<Self::Message>>>> {
fn nav_context_menu(
&self,
id: nav_bar::Id,
) -> Option<Vec<menu::Tree<crate::Action<Self::Message>>>> {
None
}
@ -605,7 +433,7 @@ where
/// Handles dbus activation messages
#[cfg(feature = "single-instance")]
fn dbus_activation(&mut self, msg: DbusActivationMessage) -> Task<Self::Message> {
fn dbus_activation(&mut self, msg: crate::dbus_activation::Message) -> Task<Self::Message> {
Task::none()
}
}
@ -648,7 +476,21 @@ pub trait ApplicationExt: Application {
fn set_window_title(&mut self, title: String, id: window::Id) -> Task<Self::Message>;
/// View template for the main window.
fn view_main(&self) -> Element<Message<Self::Message>>;
fn view_main(&self) -> Element<crate::Action<Self::Message>>;
fn watch_config<T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq>(
&self,
id: &'static str,
) -> iced::Subscription<cosmic_config::Update<T>> {
self.core().watch_config(id)
}
fn watch_state<T: CosmicConfigEntry + Send + Sync + Default + 'static + Clone + PartialEq>(
&self,
id: &'static str,
) -> iced::Subscription<cosmic_config::Update<T>> {
self.core().watch_state(id)
}
}
impl<App: Application> ApplicationExt for App {
@ -695,7 +537,7 @@ impl<App: Application> ApplicationExt for App {
#[allow(clippy::too_many_lines)]
/// Creates the view for the main window.
fn view_main(&self) -> Element<Message<Self::Message>> {
fn view_main(&self) -> Element<crate::Action<Self::Message>> {
let core = self.core();
let is_condensed = core.is_condensed();
// TODO: More granularity might be needed for different resize border
@ -762,13 +604,13 @@ impl<App: Application> ApplicationExt for App {
[0, 0, 0, 0]
})
.apply(Element::from)
.map(Message::App),
.map(crate::Action::App),
);
} else {
//TODO: container and padding are temporary, until
//the `resize_border` is moved to not cover window content
widgets.push(
container(main_content.map(Message::App))
container(main_content.map(crate::Action::App))
.padding(main_content_padding)
.into(),
);
@ -778,7 +620,7 @@ impl<App: Application> ApplicationExt for App {
//TODO: container and padding are temporary, until
//the `resize_border` is moved to not cover window content
widgets.push(
container(main_content.map(Message::App))
container(main_content.map(crate::Action::App))
.padding(main_content_padding)
.into(),
);
@ -794,7 +636,7 @@ impl<App: Application> ApplicationExt for App {
context_width,
)
.apply(Element::from)
.map(Message::App)
.map(crate::Action::App)
.apply(container)
.width(context_width)
.apply(|drawer| {
@ -824,7 +666,7 @@ impl<App: Application> ApplicationExt for App {
.push(content_row)
.push_maybe(
self.footer()
.map(|footer| container(footer.map(Message::App)).padding([0, 8, 8, 8])),
.map(|footer| container(footer.map(crate::Action::App)).padding([0, 8, 8, 8])),
);
let content: Element<_> = if core.window.content_container {
content_col
@ -851,45 +693,45 @@ impl<App: Application> ApplicationExt for App {
let mut header = crate::widget::header_bar()
.focused(focused)
.title(&core.window.header_title)
.on_drag(Message::Cosmic(cosmic::Message::Drag))
.on_right_click(Message::Cosmic(cosmic::Message::ShowWindowMenu))
.on_double_click(Message::Cosmic(cosmic::Message::Maximize));
.on_drag(crate::Action::Cosmic(Action::Drag))
.on_right_click(crate::Action::Cosmic(Action::ShowWindowMenu))
.on_double_click(crate::Action::Cosmic(Action::Maximize));
if self.nav_model().is_some() {
let toggle = crate::widget::nav_bar_toggle()
.active(core.nav_bar_active())
.selected(focused)
.on_toggle(if is_condensed {
Message::Cosmic(cosmic::Message::ToggleNavBarCondensed)
crate::Action::Cosmic(Action::ToggleNavBarCondensed)
} else {
Message::Cosmic(cosmic::Message::ToggleNavBar)
crate::Action::Cosmic(Action::ToggleNavBar)
});
header = header.start(toggle);
}
if core.window.show_close {
header = header.on_close(Message::Cosmic(cosmic::Message::Close));
header = header.on_close(crate::Action::Cosmic(Action::Close));
}
if core.window.show_maximize && crate::config::show_maximize() {
header = header.on_maximize(Message::Cosmic(cosmic::Message::Maximize));
header = header.on_maximize(crate::Action::Cosmic(Action::Maximize));
}
if core.window.show_minimize && crate::config::show_minimize() {
header = header.on_minimize(Message::Cosmic(cosmic::Message::Minimize));
header = header.on_minimize(crate::Action::Cosmic(Action::Minimize));
}
for element in self.header_start() {
header = header.start(element.map(Message::App));
header = header.start(element.map(crate::Action::App));
}
for element in self.header_center() {
header = header.center(element.map(Message::App));
header = header.center(element.map(crate::Action::App));
}
for element in self.header_end() {
header = header.end(element.map(Message::App));
header = header.end(element.map(crate::Action::App));
}
if content_container {
@ -951,7 +793,7 @@ impl<App: Application> ApplicationExt for App {
.dialog()
.map(|w| Element::from(id_container(w, iced_core::id::Id::new("COSMIC_dialog"))))
{
popover = popover.popup(dialog.map(Message::App));
popover = popover.popup(dialog.map(crate::Action::App));
}
let view_element: Element<_> = popover.into();
@ -959,74 +801,6 @@ impl<App: Application> ApplicationExt for App {
}
}
#[cfg(feature = "single-instance")]
fn single_instance_subscription<App: ApplicationExt>() -> Subscription<Message<App::Message>> {
use iced_futures::futures::StreamExt;
iced_futures::Subscription::run_with_id(
TypeId::of::<DbusActivation>(),
iced::stream::channel(10, move |mut output| async move {
let mut single_instance: DbusActivation = DbusActivation::new();
let mut rx = single_instance.rx();
if let Ok(builder) = zbus::ConnectionBuilder::session() {
let path: String = format!("/{}", App::APP_ID.replace('.', "/"));
if let Ok(conn) = builder.build().await {
// XXX Setup done this way seems to be more reliable.
//
// the docs for serve_at seem to imply it will replace the
// existing interface at the requested path, but it doesn't
// seem to work that way all the time. The docs for
// object_server().at() imply it won't replace the existing
// interface.
//
// request_name is used either way, with the builder or
// with the connection, but it must be done after the
// object server is setup.
if conn.object_server().at(path, single_instance).await != Ok(true) {
tracing::error!("Failed to serve dbus");
std::process::exit(1);
}
if conn.request_name(App::APP_ID).await.is_err() {
tracing::error!("Failed to serve dbus");
std::process::exit(1);
}
#[cfg(feature = "smol")]
let handle = {
std::thread::spawn(move || {
let conn_clone = _conn.clone();
zbus::block_on(async move {
loop {
conn_clone.executor().tick().await;
}
})
})
};
while let Some(mut msg) = rx.next().await {
if let Some(token) = msg.activation_token.take() {
if let Err(err) = output
.send(Message::Cosmic(cosmic::Message::Activate(token)))
.await
{
tracing::error!(?err, "Failed to send message");
}
}
if let Err(err) = output.send(Message::DbusActivation(msg)).await {
tracing::error!(?err, "Failed to send message");
}
}
}
} else {
tracing::warn!("Failed to connect to dbus for single instance");
}
loop {
iced::futures::pending!();
}
}),
)
}
const EMBEDDED_FONTS: &[&[u8]] = &[
include_bytes!("../../res/open-sans/OpenSans-Light.ttf"),
include_bytes!("../../res/open-sans/OpenSans-Regular.ttf"),
@ -1043,6 +817,6 @@ fn preload_fonts() {
.unwrap();
EMBEDDED_FONTS
.into_iter()
.iter()
.for_each(move |font| font_system.load_font(Cow::Borrowed(font)));
}

View file

@ -1,3 +1,6 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
//! Create and run daemons that run in the background.
//! Copied from iced 0.13, but adds optional initial window