libcosmic updates

This commit is contained in:
Ashley Wulber 2024-10-16 20:36:46 -04:00 committed by Ashley Wulber
parent 9c62f19e4b
commit 0491c4baaa
91 changed files with 3550 additions and 2300 deletions

View file

@ -7,62 +7,88 @@ use iced::window;
use super::Message;
/// Commands for COSMIC applications.
pub type Command<M> = iced::Command<Message<M>>;
pub type Task<M> = iced::Task<Message<M>>;
/// Creates a command which yields a [`crate::app::Message`].
pub fn message<M: Send + 'static>(message: Message<M>) -> Command<M> {
pub fn message<M: Send + 'static>(message: Message<M>) -> Task<M> {
crate::command::message(message)
}
/// Convenience methods for building message-based commands.
pub mod message {
/// Creates a command which yields an application message.
pub fn app<M: Send + 'static>(message: M) -> crate::app::Command<M> {
pub fn app<M: Send + 'static>(message: M) -> crate::app::Task<M> {
super::message(super::Message::App(message))
}
/// Creates a command which yields a cosmic message.
pub fn cosmic<M: Send + 'static>(
message: crate::app::cosmic::Message,
) -> crate::app::Command<M> {
pub fn cosmic<M: Send + 'static>(message: crate::app::cosmic::Message) -> crate::app::Task<M> {
super::message(super::Message::Cosmic(message))
}
}
pub fn drag<M: Send + 'static>(id: Option<window::Id>) -> iced::Command<Message<M>> {
crate::command::drag(id).map(Message::Cosmic)
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.get().cloned()) else {
return iced::Task::none();
};
crate::command::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.get().cloned()) else {
return iced::Task::none();
};
crate::command::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.get().cloned()) else {
return iced::Task::none();
};
crate::command::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.get().cloned()) else {
return iced::Task::none();
};
crate::command::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.get().cloned()) else {
return iced::Task::none();
};
crate::command::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.get().cloned()) else {
return iced::Task::none();
};
crate::command::toggle_maximize(id).map(Message::Cosmic)
}
}
pub fn maximize<M: Send + 'static>(
id: Option<window::Id>,
maximized: bool,
) -> iced::Command<Message<M>> {
crate::command::maximize(id, maximized).map(Message::Cosmic)
}
pub fn minimize<M: Send + 'static>(id: Option<window::Id>) -> iced::Command<Message<M>> {
crate::command::minimize(id).map(Message::Cosmic)
}
pub fn set_scaling_factor<M: Send + 'static>(factor: f32) -> iced::Command<Message<M>> {
message::cosmic(super::cosmic::Message::ScaleFactor(factor))
}
pub fn set_theme<M: Send + 'static>(theme: crate::Theme) -> iced::Command<Message<M>> {
pub fn set_theme<M: Send + 'static>(theme: crate::Theme) -> iced::Task<Message<M>> {
message::cosmic(super::cosmic::Message::AppThemeChange(theme))
}
pub fn set_title<M: Send + 'static>(
id: Option<window::Id>,
title: String,
) -> iced::Command<Message<M>> {
crate::command::set_title(id, title).map(Message::Cosmic)
}
pub fn set_windowed<M: Send + 'static>(id: Option<window::Id>) -> iced::Command<Message<M>> {
crate::command::set_windowed(id).map(Message::Cosmic)
}
pub fn toggle_maximize<M: Send + 'static>(id: Option<window::Id>) -> iced::Command<Message<M>> {
crate::command::toggle_maximize(id).map(Message::Cosmic)
}

View file

@ -1,7 +1,7 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use std::collections::HashMap;
use std::{cell::OnceCell, collections::HashMap};
use crate::widget::nav_bar;
use cosmic_config::CosmicConfigEntry;
@ -40,8 +40,8 @@ pub struct Window {
pub show_close: bool,
pub show_maximize: bool,
pub show_minimize: bool,
height: u32,
width: u32,
height: f32,
width: f32,
}
/// COSMIC-specific application settings
@ -93,6 +93,10 @@ pub struct Core {
#[cfg(feature = "dbus-config")]
pub(crate) settings_daemon: Option<cosmic_settings_daemon::CosmicSettingsDaemonProxy<'static>>,
pub(crate) main_window: OnceCell<window::Id>,
pub(crate) exit_on_main_window_closed: bool,
}
impl Default for Core {
@ -135,10 +139,10 @@ impl Default for Core {
show_maximize: true,
show_minimize: true,
show_window_menu: false,
height: 0,
width: 0,
height: 0.,
width: 0.,
},
focused_window: Some(window::Id::MAIN),
focused_window: None,
#[cfg(feature = "applet")]
applet: crate::applet::Context::default(),
#[cfg(feature = "single-instance")]
@ -148,6 +152,8 @@ impl Default for Core {
portal_is_dark: None,
portal_accent: None,
portal_is_high_contrast: None,
main_window: OnceCell::new(),
exit_on_main_window_closed: true,
}
}
}
@ -297,12 +303,12 @@ impl Core {
}
/// Set the height of the main window.
pub(crate) fn set_window_height(&mut self, new_height: u32) {
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: u32) {
pub(crate) fn set_window_width(&mut self, new_width: f32) {
self.window.width = new_width;
self.is_condensed_update();
}
@ -364,4 +370,12 @@ impl Core {
self.portal_is_dark
.unwrap_or(self.system_theme_mode.is_dark)
}
/// The [`Id`] of the main window
pub fn main_window_id(&self) -> Option<window::Id> {
self.main_window
.get()
.filter(|id| iced::window::Id::NONE != **id)
.cloned()
}
}

View file

@ -1,32 +1,23 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use std::borrow::Borrow;
use std::sync::Arc;
use super::{command, Application, ApplicationExt, Core, Subscription};
use super::{Application, ApplicationExt, Core, Subscription};
use crate::config::CosmicTk;
use crate::theme::{self, Theme, ThemeType, THEME};
use crate::theme::{Theme, ThemeType, THEME};
use crate::widget::nav_bar;
use crate::{keyboard_nav, Element};
#[cfg(feature = "wayland")]
use cctk::sctk::reexports::csd_frame::{WindowManagerCapabilities, WindowState};
use cosmic_theme::ThemeMode;
#[cfg(feature = "wayland")]
use iced::event::wayland::{self, WindowEvent};
#[cfg(feature = "wayland")]
use iced::event::PlatformSpecific;
#[cfg(all(feature = "winit", feature = "multi-window"))]
use iced::multi_window::Application as IcedApplication;
#[cfg(feature = "wayland")]
use iced::wayland::Application as IcedApplication;
use iced::event::wayland;
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
use iced::Application as IcedApplication;
use iced::{window, Command};
use iced::{window, Task};
use iced_futures::event::listen_with;
#[cfg(not(feature = "wayland"))]
use iced_runtime::command::Action;
#[cfg(not(feature = "wayland"))]
use iced_runtime::window::Action as WindowAction;
use palette::color_difference::EuclideanDistance;
/// A message managed internally by COSMIC.
@ -65,7 +56,7 @@ pub enum Message {
/// Updates the window maximized state
WindowMaximized(window::Id, bool),
/// Updates the tracked window geometry.
WindowResize(window::Id, u32, u32),
WindowResize(window::Id, f32, f32),
/// Tracks updates to window state.
#[cfg(feature = "wayland")]
WindowState(window::Id, WindowState),
@ -86,7 +77,9 @@ pub enum Message {
Unfocus(window::Id),
/// Tracks updates to window suggested size.
#[cfg(feature = "applet")]
Configure(cctk::sctk::shell::xdg::window::WindowConfigure),
SuggestedBounds(Option<iced::Size>),
/// Window Created
MainWindowCreated(window::Id),
}
#[derive(Default)]
@ -94,109 +87,104 @@ pub struct Cosmic<App> {
pub app: App,
}
impl<T: Application> IcedApplication for Cosmic<T>
impl<T: Application> Cosmic<T>
where
T::Message: Send + 'static,
{
type Executor = T::Executor;
type Flags = (Core, T::Flags);
type Message = super::Message<T::Message>;
type Theme = Theme;
fn new((mut core, flags): Self::Flags) -> (Self, iced::Command<Self::Message>) {
pub fn init(
(mut core, flags, window_settings): (Core, T::Flags, iced::window::Settings),
) -> (Self, iced::Task<super::Message<T::Message>>) {
#[cfg(feature = "dbus-config")]
{
use iced_futures::futures::executor::block_on;
core.settings_daemon = block_on(cosmic_config::dbus::settings_daemon_proxy()).ok();
}
let (model, command) = T::init(core, flags);
let (model, mut command) = T::init(core, flags);
(Self::new(model), command)
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
fn title(&self) -> String {
#[cfg(not(feature = "multi-window"))]
pub fn title(&self) -> String {
self.app.title().to_string()
}
#[cfg(any(feature = "multi-window", feature = "wayland"))]
fn title(&self, id: window::Id) -> String {
#[cfg(feature = "multi-window")]
pub fn title(&self, id: window::Id) -> String {
self.app.title(id).to_string()
}
fn update(&mut self, message: Self::Message) -> iced::Command<Self::Message> {
pub fn update(
&mut self,
message: super::Message<T::Message>,
) -> iced::Task<super::Message<T::Message>> {
match message {
super::Message::App(message) => self.app.update(message),
super::Message::Cosmic(message) => self.cosmic_update(message),
super::Message::None => iced::Command::none(),
super::Message::None => iced::Task::none(),
#[cfg(feature = "single-instance")]
super::Message::DbusActivation(message) => self.app.dbus_activation(message),
}
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
fn scale_factor(&self) -> f64 {
#[cfg(not(feature = "multi-window"))]
pub fn scale_factor(&self) -> f64 {
f64::from(self.app.core().scale_factor())
}
#[cfg(any(feature = "multi-window", feature = "wayland"))]
fn scale_factor(&self, _id: window::Id) -> f64 {
#[cfg(feature = "multi-window")]
pub fn scale_factor(&self, _id: window::Id) -> f64 {
f64::from(self.app.core().scale_factor())
}
fn style(&self) -> <Self::Theme as iced_style::application::StyleSheet>::Style {
pub fn style(&self, theme: &Theme) -> iced_runtime::Appearance {
if let Some(style) = self.app.style() {
style
} else if self.app.core().window.sharp_corners {
theme::Application::default()
let theme = THEME.lock().unwrap();
crate::style::iced::application::appearance(theme.borrow())
} else {
theme::Application::Custom(Box::new(|theme| iced_style::application::Appearance {
let theme = THEME.lock().unwrap();
iced_runtime::Appearance {
background_color: iced_core::Color::TRANSPARENT,
icon_color: theme.cosmic().on_bg_color().into(),
text_color: theme.cosmic().on_bg_color().into(),
}))
}
}
}
#[allow(clippy::too_many_lines)]
fn subscription(&self) -> Subscription<Self::Message> {
let window_events = listen_with(|event, _| {
pub fn subscription(&self) -> Subscription<super::Message<T::Message>> {
let window_events = listen_with(|event, _, id| {
match event {
iced::Event::Window(id, window::Event::Resized { width, height }) => {
iced::Event::Window(window::Event::Resized(iced::Size { width, height })) => {
return Some(Message::WindowResize(id, width, height));
}
iced::Event::Window(id, window::Event::Closed) => {
iced::Event::Window(window::Event::Closed) => {
return Some(Message::SurfaceClosed(id))
}
iced::Event::Window(id, window::Event::Focused) => return Some(Message::Focus(id)),
iced::Event::Window(id, window::Event::Unfocused) => {
return Some(Message::Unfocus(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::Opened { .. }) => {
return Some(Message::MainWindowCreated(id));
}
#[cfg(feature = "wayland")]
iced::Event::PlatformSpecific(PlatformSpecific::Wayland(event)) => match event {
wayland::Event::Window(WindowEvent::State(state), _surface, id) => {
return Some(Message::WindowState(id, state));
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));
}
#[cfg(feature = "applet")]
wayland::Event::Window(
iced::event::wayland::WindowEvent::SuggestedBounds(b),
) => {
return Some(Message::SuggestedBounds(b));
}
_ => (),
}
wayland::Event::Window(
WindowEvent::WmCapabilities(capabilities),
_surface,
id,
) => {
return Some(Message::WmCapabilities(id, capabilities));
}
wayland::Event::Popup(wayland::PopupEvent::Done, _, id)
| wayland::Event::Layer(wayland::LayerEvent::Done, _, id) => {
return Some(Message::SurfaceClosed(id));
}
#[cfg(feature = "applet")]
wayland::Event::Window(WindowEvent::Configure(conf), _surface, id)
if id == window::Id::MAIN =>
{
return Some(Message::Configure(conf));
}
_ => (),
},
}
_ => (),
}
@ -275,19 +263,24 @@ where
Subscription::batch(subscriptions)
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
fn theme(&self) -> Self::Theme {
#[cfg(not(feature = "multi-window"))]
pub fn theme(&self) -> Theme {
crate::theme::active()
}
#[cfg(any(feature = "multi-window", feature = "wayland"))]
fn theme(&self, _id: window::Id) -> Self::Theme {
#[cfg(feature = "multi-window")]
pub fn theme(&self, _id: window::Id) -> Theme {
crate::theme::active()
}
#[cfg(any(feature = "multi-window", feature = "wayland"))]
fn view(&self, id: window::Id) -> Element<Self::Message> {
if id != self.app.main_window_id() {
#[cfg(feature = "multi-window")]
pub fn view(&self, id: window::Id) -> Element<super::Message<T::Message>> {
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);
}
@ -298,37 +291,43 @@ where
}
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
fn view(&self) -> Element<Self::Message> {
#[cfg(not(feature = "multi-window"))]
pub fn view(&self) -> Element<super::Message<T::Message>> {
self.app.view_main()
}
}
impl<T: Application> Cosmic<T> {
#[cfg(feature = "wayland")]
pub fn close(&mut self) -> iced::Command<super::Message<T::Message>> {
iced_sctk::commands::window::close_window(self.app.main_window_id())
}
#[cfg(not(feature = "wayland"))]
#[allow(clippy::unused_self)]
pub fn close(&mut self) -> iced::Command<super::Message<T::Message>> {
iced::Command::single(Action::Window(WindowAction::Close(
self.app.main_window_id(),
)))
pub fn close(&mut self) -> iced::Task<super::Message<T::Message>> {
if let Some(id) = self.app.core().main_window_id() {
iced::window::close(id)
} else {
iced::Task::none()
}
}
#[allow(clippy::too_many_lines)]
fn cosmic_update(&mut self, message: Message) -> iced::Command<super::Message<T::Message>> {
fn cosmic_update(&mut self, message: Message) -> iced::Task<super::Message<T::Message>> {
match message {
Message::WindowMaximized(id, maximized) => {
if self.app.main_window_id() == id {
if self
.app
.core()
.main_window_id()
.is_some_and(|main_id| main_id == id)
{
self.app.core_mut().window.sharp_corners = maximized;
}
}
Message::WindowResize(id, width, height) => {
if self.app.main_window_id() == id {
if self
.app
.core()
.main_window_id()
.is_some_and(|main_id| main_id == id)
{
self.app.core_mut().set_window_width(width);
self.app.core_mut().set_window_height(height);
}
@ -336,15 +335,19 @@ impl<T: Application> Cosmic<T> {
self.app.on_window_resize(id, width, height);
//TODO: more efficient test of maximized (winit has no event for maximize if set by the OS)
#[cfg(not(feature = "wayland"))]
return iced::window::fetch_maximized(id, move |maximized| {
return iced::window::get_maximized(id).map(move |maximized| {
super::Message::Cosmic(Message::WindowMaximized(id, maximized))
});
}
#[cfg(feature = "wayland")]
Message::WindowState(id, state) => {
if self.app.main_window_id() == id {
if self
.app
.core()
.main_window_id()
.is_some_and(|main_id| main_id == id)
{
self.app.core_mut().window.sharp_corners = state.intersects(
WindowState::MAXIMIZED
| WindowState::FULLSCREEN
@ -359,7 +362,12 @@ impl<T: Application> Cosmic<T> {
#[cfg(feature = "wayland")]
Message::WmCapabilities(id, capabilities) => {
if self.app.main_window_id() == id {
if self
.app
.core()
.main_window_id()
.is_some_and(|main_id| main_id == id)
{
self.app.core_mut().window.show_maximize =
capabilities.contains(WindowManagerCapabilities::MAXIMIZE);
self.app.core_mut().window.show_minimize =
@ -379,9 +387,7 @@ impl<T: Application> Cosmic<T> {
keyboard_nav::Message::Escape => return self.app.on_escape(),
keyboard_nav::Message::Search => return self.app.on_search(),
keyboard_nav::Message::Fullscreen => {
return command::toggle_maximize(Some(self.app.main_window_id()))
}
keyboard_nav::Message::Fullscreen => return self.app.core().toggle_maximize(None),
},
Message::ContextDrawer(show) => {
@ -389,11 +395,11 @@ impl<T: Application> Cosmic<T> {
return self.app.on_context_drawer();
}
Message::Drag => return command::drag(Some(self.app.main_window_id())),
Message::Drag => return self.app.core().drag(None),
Message::Minimize => return command::minimize(Some(self.app.main_window_id())),
Message::Minimize => return self.app.core().minimize(None),
Message::Maximize => return command::toggle_maximize(Some(self.app.main_window_id())),
Message::Maximize => return self.app.core().toggle_maximize(None),
Message::NavBar(key) => {
self.app.core_mut().nav_bar_set_toggled_condensed(false);
@ -433,7 +439,7 @@ impl<T: Application> Cosmic<T> {
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 {
return iced::Command::none();
return iced::Task::none();
}
let cmd = self.app.system_theme_update(&keys, theme.cosmic());
// Record the last-known system theme in event that the current theme is custom.
@ -479,7 +485,7 @@ impl<T: Application> Cosmic<T> {
}
Message::SystemThemeModeChange(keys, mode) => {
if !keys.contains(&"is_dark") {
return iced::Command::none();
return iced::Task::none();
}
if match THEME.lock().unwrap().theme_type {
ThemeType::System {
@ -488,7 +494,7 @@ impl<T: Application> Cosmic<T> {
} => prefer_dark.is_some(),
_ => false,
} {
return iced::Command::none();
return iced::Task::none();
}
let mut cmds = vec![self.app.system_theme_mode_update(&keys, &mode)];
@ -527,23 +533,37 @@ impl<T: Application> Cosmic<T> {
}
}
}
return Command::batch(cmds);
return Task::batch(cmds);
}
Message::Activate(_token) => {
Message::Activate(_token) =>
{
#[cfg(feature = "wayland")]
return iced_sctk::commands::activation::activate(
self.app.main_window_id(),
#[allow(clippy::used_underscore_binding)]
_token,
);
}
Message::SurfaceClosed(id) => {
if let Some(msg) = self.app.on_close_requested(id) {
return self.app.update(msg);
if let Some(id) = self.app.core().main_window_id() {
return iced_winit::platform_specific::commands::activation::activate(
id,
#[allow(clippy::used_underscore_binding)]
_token,
);
}
}
Message::SurfaceClosed(id) => {
let mut ret = if let Some(msg) = self.app.on_close_requested(id) {
self.app.update(msg)
} else {
Task::none()
};
let core = self.app.core();
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>>()]);
}
return ret;
}
Message::ShowWindowMenu => {
return window::show_window_menu(window::Id::MAIN);
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)) => {
@ -555,7 +575,7 @@ impl<T: Application> Cosmic<T> {
} => prefer_dark.is_some(),
_ => false,
} {
return iced::Command::none();
return iced::Task::none();
}
let is_dark = match s {
ColorScheme::NoPreference => None,
@ -595,7 +615,7 @@ impl<T: Application> Cosmic<T> {
if cur_accent.distance_squared(*c) < 0.00001 {
// skip calculations if we already have the same color
return iced::Command::none();
return iced::Task::none();
}
{
@ -640,19 +660,20 @@ impl<T: Application> Cosmic<T> {
core.focused_window = None;
}
}
#[cfg(feature = "applet")]
Message::Configure(configure) => {
if let Some(w) = configure.new_size.0 {
self.app.core_mut().set_window_width(w.get());
}
if let Some(h) = configure.new_size.1 {
self.app.core_mut().set_window_height(h.get());
}
self.app.core_mut().applet.configure = Some(configure);
Message::MainWindowCreated(id) => {
let core = self.app.core_mut();
_ = core.main_window.set(id);
}
#[cfg(feature = "applet")]
Message::SuggestedBounds(b) => {
tracing::info!("Suggested bounds: {b:?}");
let core = self.app.core_mut();
core.applet.suggested_bounds = b;
}
_ => {}
}
iced::Command::none()
iced::Task::none()
}
}

View file

@ -9,6 +9,8 @@
pub mod command;
mod core;
pub mod cosmic;
#[cfg(all(feature = "winit", feature = "multi-window"))]
pub(crate) mod multi_window;
pub mod settings;
pub mod message {
@ -47,17 +49,14 @@ pub mod message {
use std::borrow::Cow;
pub use self::command::Command;
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::{context_drawer, horizontal_space, id_container, menu, nav_bar, popover};
use apply::Apply;
#[cfg(all(feature = "winit", feature = "multi-window"))]
use iced::{multi_window::Application as IcedApplication, window};
#[cfg(any(not(feature = "winit"), not(feature = "multi-window")))]
use iced::{window, Application as IcedApplication};
use iced::window;
use iced::{Length, Subscription};
pub use message::Message;
use url::Url;
@ -73,15 +72,15 @@ use {
pub(crate) fn iced_settings<App: Application>(
settings: Settings,
flags: App::Flags,
) -> iced::Settings<(Core, App::Flags)> {
) -> (iced::Settings, (Core, App::Flags, iced::window::Settings)) {
preload_fonts();
let mut core = Core::default();
core.debug = settings.debug;
core.icon_theme_override = settings.default_icon_theme.is_some();
core.set_scale_factor(settings.scale_factor);
core.set_window_width(settings.size.width as u32);
core.set_window_height(settings.size.height as u32);
core.set_window_width(settings.size.width);
core.set_window_height(settings.size.height);
if let Some(icon_theme) = settings.default_icon_theme {
crate::icon_theme::set_default(icon_theme);
@ -91,65 +90,40 @@ pub(crate) fn iced_settings<App: Application>(
THEME.lock().unwrap().set_theme(settings.theme.theme_type);
let mut iced = iced::Settings::with_flags((core, flags));
if settings.no_main_window {
core.main_window.set(iced::window::Id::NONE).unwrap();
}
let mut iced = iced::Settings::default();
iced.antialiasing = settings.antialiasing;
iced.default_font = settings.default_font;
iced.default_text_size = iced::Pixels(settings.default_text_size);
iced.exit_on_close_request = settings.exit_on_close;
#[cfg(not(feature = "wayland"))]
{
let exit_on_close = settings.exit_on_close;
iced.window.exit_on_close_request = exit_on_close;
}
let exit_on_close = settings.exit_on_close;
iced.exit_on_close_request = exit_on_close;
let mut window_settings = iced::window::Settings::default();
window_settings.exit_on_close_request = exit_on_close;
iced.id = Some(App::APP_ID.to_owned());
#[cfg(all(not(feature = "wayland"), target_os = "linux"))]
{
iced.window.platform_specific.application_id = App::APP_ID.to_string();
window_settings.platform_specific.application_id = App::APP_ID.to_string();
core.exit_on_main_window_closed = exit_on_close;
if let Some(border_size) = settings.resizable {
window_settings.resize_border = border_size as u32;
window_settings.resizable = true;
}
window_settings.decorations = !settings.client_decorations;
window_settings.size = settings.size;
let min_size = settings.size_limits.min();
if min_size != iced::Size::ZERO {
window_settings.min_size = Some(min_size);
}
let max_size = settings.size_limits.max();
if max_size != iced::Size::INFINITY {
window_settings.max_size = Some(max_size);
}
#[cfg(feature = "wayland")]
{
use iced::wayland::actions::window::SctkWindowSettings;
use iced_sctk::settings::InitialSurface;
iced.initial_surface = if settings.no_main_window {
InitialSurface::None
} else {
InitialSurface::XdgWindow(SctkWindowSettings {
app_id: Some(App::APP_ID.to_owned()),
autosize: settings.autosize,
client_decorations: settings.client_decorations,
resizable: settings.resizable,
size: (settings.size.width as u32, settings.size.height as u32).into(),
size_limits: settings.size_limits,
title: None,
transparent: settings.transparent,
xdg_activation_token: std::env::var("XDG_ACTIVATION_TOKEN").ok(),
..SctkWindowSettings::default()
})
};
}
#[cfg(not(feature = "wayland"))]
{
if let Some(border_size) = settings.resizable {
iced.window.resize_border = border_size as u32;
iced.window.resizable = true;
}
iced.window.decorations = !settings.client_decorations;
iced.window.size = settings.size;
let min_size = settings.size_limits.min();
if min_size != iced::Size::ZERO {
iced.window.min_size = Some(min_size);
}
let max_size = settings.size_limits.max();
if max_size != iced::Size::INFINITY {
iced.window.max_size = Some(max_size);
}
iced.window.transparent = settings.transparent;
}
iced
window_settings.transparent = settings.transparent;
(iced, (core, flags, window_settings))
}
/// Launch a COSMIC application with the given [`Settings`].
@ -158,9 +132,40 @@ pub(crate) fn iced_settings<App: Application>(
///
/// Returns error on application failure.
pub fn run<App: Application>(settings: Settings, flags: App::Flags) -> iced::Result {
let settings = iced_settings::<App>(settings, flags);
cosmic::Cosmic::<App>::run(settings)
let default_font = settings.default_font;
let (settings, flags) = iced_settings::<App>(settings, flags);
#[cfg(not(feature = "multi-window"))]
{
iced::application(
cosmic::Cosmic::title,
cosmic::Cosmic::update,
cosmic::Cosmic::view,
)
.subscription(cosmic::Cosmic::subscription)
.style(cosmic::Cosmic::style)
.theme(cosmic::Cosmic::theme)
.window_size((500.0, 800.0))
.settings(settings)
.window(flags.2.clone())
.run_with(move || cosmic::Cosmic::<App>::init(flags))
}
#[cfg(feature = "multi-window")]
{
let mut app = multi_window::multi_window(
cosmic::Cosmic::title,
cosmic::Cosmic::update,
cosmic::Cosmic::view,
);
if flags.0.main_window.get().is_none() {
app = app.window(flags.2.clone());
_ = flags.0.main_window.set(iced_core::window::Id::RESERVED);
}
app.subscription(cosmic::Cosmic::subscription)
.style(cosmic::Cosmic::style)
.theme(cosmic::Cosmic::theme)
.settings(settings)
.run_with(move || cosmic::Cosmic::<App>::init(flags))
}
}
#[cfg(feature = "single-instance")]
@ -362,9 +367,41 @@ where
tracing::info!("Another instance is running");
Ok(())
} else {
let mut settings = iced_settings::<App>(settings, flags);
settings.flags.0.single_instance = true;
cosmic::Cosmic::<App>::run(settings)
let (settings, mut flags) = iced_settings::<App>(settings, flags);
flags.0.single_instance = true;
#[cfg(not(feature = "multi-window"))]
{
iced::application(
cosmic::Cosmic::title,
cosmic::Cosmic::update,
cosmic::Cosmic::view,
)
.subscription(cosmic::Cosmic::subscription)
.style(cosmic::Cosmic::style)
.theme(cosmic::Cosmic::theme)
.window_size((500.0, 800.0))
.settings(settings)
.window(flags.2.clone())
.run_with(move || cosmic::Cosmic::<App>::init(flags))
}
#[cfg(feature = "multi-window")]
{
let mut app = multi_window::multi_window(
cosmic::Cosmic::title,
cosmic::Cosmic::update,
cosmic::Cosmic::view,
);
if flags.0.main_window.get().is_none() {
app = app.window(flags.2.clone());
_ = flags.0.main_window.set(iced_core::window::Id::RESERVED);
}
app.subscription(cosmic::Cosmic::subscription)
.style(cosmic::Cosmic::style)
.theme(cosmic::Cosmic::theme)
.settings(settings)
.run_with(move || cosmic::Cosmic::<App>::init(flags))
}
}
}
@ -409,7 +446,7 @@ where
fn core_mut(&mut self) -> &mut Core;
/// Creates the application, and optionally emits command on initialize.
fn init(core: Core, flags: Self::Flags) -> (Self, Command<Self::Message>);
fn init(core: Core, flags: Self::Flags) -> (Self, Task<Self::Message>);
/// Displays a context drawer on the side of the application window when `Some`.
fn context_drawer(&self) -> Option<Element<Self::Message>> {
@ -441,11 +478,6 @@ where
Vec::new()
}
/// Get the main [`window::Id`], which is [`window::Id::MAIN`] by default
fn main_window_id(&self) -> window::Id {
window::Id::MAIN
}
/// Allows overriding the default nav bar widget.
fn nav_bar(&self) -> Option<Element<Message<Self::Message>>> {
if !self.core().nav_bar_active() {
@ -491,32 +523,32 @@ where
}
// Called when context drawer is toggled
fn on_context_drawer(&mut self) -> Command<Self::Message> {
Command::none()
fn on_context_drawer(&mut self) -> Task<Self::Message> {
Task::none()
}
/// Called when the escape key is pressed.
fn on_escape(&mut self) -> Command<Self::Message> {
Command::none()
fn on_escape(&mut self) -> Task<Self::Message> {
Task::none()
}
/// Called when a navigation item is selected.
fn on_nav_select(&mut self, id: nav_bar::Id) -> Command<Self::Message> {
Command::none()
fn on_nav_select(&mut self, id: nav_bar::Id) -> Task<Self::Message> {
Task::none()
}
/// Called when a context menu is requested for a navigation item.
fn on_nav_context(&mut self, id: nav_bar::Id) -> Command<Self::Message> {
Command::none()
fn on_nav_context(&mut self, id: nav_bar::Id) -> Task<Self::Message> {
Task::none()
}
/// Called when the search function is requested.
fn on_search(&mut self) -> Command<Self::Message> {
Command::none()
fn on_search(&mut self) -> Task<Self::Message> {
Task::none()
}
/// Called when a window is resized.
fn on_window_resize(&mut self, id: window::Id, width: u32, height: u32) {}
fn on_window_resize(&mut self, id: window::Id, width: f32, height: f32) {}
/// Event sources that are to be listened to.
fn subscription(&self) -> Subscription<Self::Message> {
@ -524,8 +556,8 @@ where
}
/// Respond to an application-specific message.
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
Command::none()
fn update(&mut self, message: Self::Message) -> Task<Self::Message> {
Task::none()
}
/// Respond to a system theme change
@ -533,8 +565,8 @@ where
&mut self,
keys: &[&'static str],
new_theme: &cosmic_theme::Theme,
) -> Command<Self::Message> {
Command::none()
) -> Task<Self::Message> {
Task::none()
}
/// Respond to a system theme mode change
@ -542,8 +574,8 @@ where
&mut self,
keys: &[&'static str],
new_theme: &cosmic_theme::ThemeMode,
) -> Command<Self::Message> {
Command::none()
) -> Task<Self::Message> {
Task::none()
}
/// Constructs the view for the main window.
@ -555,33 +587,33 @@ where
}
/// Overrides the default style for applications
fn style(&self) -> Option<<crate::Theme as iced_style::application::StyleSheet>::Style> {
fn style(&self) -> Option<iced_runtime::Appearance> {
None
}
/// Handles dbus activation messages
#[cfg(feature = "single-instance")]
fn dbus_activation(&mut self, msg: DbusActivationMessage) -> Command<Self::Message> {
Command::none()
fn dbus_activation(&mut self, msg: DbusActivationMessage) -> Task<Self::Message> {
Task::none()
}
}
/// Methods automatically derived for all types implementing [`Application`].
pub trait ApplicationExt: Application {
/// Initiates a window drag.
fn drag(&mut self) -> Command<Self::Message>;
fn drag(&mut self) -> Task<Self::Message>;
/// Maximizes the window.
fn maximize(&mut self) -> Command<Self::Message>;
fn maximize(&mut self) -> Task<Self::Message>;
/// Minimizes the window.
fn minimize(&mut self) -> Command<Self::Message>;
fn minimize(&mut self) -> Task<Self::Message>;
/// Get the title of the main window.
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
#[cfg(not(feature = "multi-window"))]
fn title(&self) -> &str;
#[cfg(any(feature = "multi-window", feature = "wayland"))]
#[cfg(feature = "multi-window")]
/// Get the title of a window.
fn title(&self, id: window::Id) -> &str;
@ -600,56 +632,58 @@ pub trait ApplicationExt: Application {
self.core_mut().set_header_title(title);
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
#[cfg(not(feature = "multi-window"))]
/// Set the title of the main window.
fn set_window_title(&mut self, title: String) -> Command<Self::Message>;
fn set_window_title(&mut self, title: String) -> Task<Self::Message>;
#[cfg(any(feature = "multi-window", feature = "wayland"))]
#[cfg(feature = "multi-window")]
/// Set the title of a window.
fn set_window_title(&mut self, title: String, id: window::Id) -> Command<Self::Message>;
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>>;
}
impl<App: Application> ApplicationExt for App {
fn drag(&mut self) -> Command<Self::Message> {
command::drag(Some(self.main_window_id()))
fn drag(&mut self) -> Task<Self::Message> {
self.core().drag(None)
}
fn maximize(&mut self) -> Command<Self::Message> {
command::maximize(Some(self.main_window_id()), true)
fn maximize(&mut self) -> Task<Self::Message> {
self.core().maximize(None, true)
}
fn minimize(&mut self) -> Command<Self::Message> {
command::minimize(Some(self.main_window_id()))
fn minimize(&mut self) -> Task<Self::Message> {
self.core().minimize(None)
}
#[cfg(any(feature = "multi-window", feature = "wayland"))]
#[cfg(feature = "multi-window")]
fn title(&self, id: window::Id) -> &str {
self.core().title.get(&id).map_or("", |s| s.as_str())
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
#[cfg(not(feature = "multi-window"))]
fn title(&self) -> &str {
self.core()
.title
.get(&self.main_window_id())
.map_or("", |s| s.as_str())
.main_window_id()
.and_then(|id| self.core().title.get(&id).map(std::string::String::as_str))
.unwrap_or("")
}
#[cfg(any(feature = "multi-window", feature = "wayland"))]
fn set_window_title(&mut self, title: String, id: window::Id) -> Command<Self::Message> {
#[cfg(feature = "multi-window")]
fn set_window_title(&mut self, title: String, id: window::Id) -> Task<Self::Message> {
self.core_mut().title.insert(id, title.clone());
command::set_title(Some(id), title)
self.core().set_title(Some(id), title)
}
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
fn set_window_title(&mut self, title: String) -> Command<Self::Message> {
let id = self.main_window_id();
#[cfg(not(feature = "multi-window"))]
fn set_window_title(&mut self, title: String) -> Task<Self::Message> {
let Some(id) = self.core().main_window_id() else {
return Task::none();
};
self.core_mut().title.insert(id, title.clone());
Command::none()
Task::none()
}
#[allow(clippy::too_many_lines)]
@ -659,7 +693,7 @@ impl<App: Application> ApplicationExt for App {
let is_condensed = core.is_condensed();
let focused = core
.focused_window()
.is_some_and(|i| i == self.main_window_id());
.is_some_and(|i| Some(i) == self.core().main_window_id());
let content_row = crate::widget::row::with_children({
let mut widgets = Vec::with_capacity(4);
@ -678,7 +712,7 @@ impl<App: Application> ApplicationExt for App {
if self.nav_model().is_none() || core.show_content() {
// Manual spacing must be used due to state workarounds below
if has_nav {
widgets.push(horizontal_space(Length::Fixed(8.0)).into());
widgets.push(horizontal_space().width(Length::Fixed(8.0)).into());
}
let main_content = self.view().map(Message::App);
@ -727,7 +761,7 @@ impl<App: Application> ApplicationExt for App {
);
} else {
//TODO: this element is added to workaround state issues
widgets.push(horizontal_space(Length::Shrink).into());
widgets.push(horizontal_space().width(Length::Shrink).into());
}
}
}
@ -744,7 +778,7 @@ impl<App: Application> ApplicationExt for App {
.padding([0, 8, 8, 8])
.width(iced::Length::Fill)
.height(iced::Length::Fill)
.style(crate::theme::Container::WindowBackground)
.class(crate::theme::Container::WindowBackground)
.apply(|w| id_container(w, iced_core::id::Id::new("COSMIC_content_container")))
.into()
} else {
@ -770,7 +804,7 @@ impl<App: Application> ApplicationExt for App {
} else {
Message::Cosmic(cosmic::Message::ToggleNavBar)
})
.style(crate::theme::Button::HeaderBar);
.class(crate::theme::Button::HeaderBar);
header = header.start(toggle);
}
@ -825,11 +859,9 @@ 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::subscription::channel(
iced_futures::Subscription::run_with_id(
TypeId::of::<DbusActivation>(),
10,
move |mut output| async move {
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() {
@ -888,7 +920,7 @@ fn single_instance_subscription<App: ApplicationExt>() -> Subscription<Message<A
loop {
iced::futures::pending!();
}
},
}),
)
}

238
src/app/multi_window.rs Normal file
View file

@ -0,0 +1,238 @@
//! Create and run daemons that run in the background.
//! Copied from iced 0.13, but adds optional initial window
use iced::application;
use iced::window;
use iced::{
self,
program::{self, with_style, with_subscription, with_theme, with_title},
runtime::{Appearance, DefaultStyle},
Program,
};
use iced::{Element, Result, Settings, Subscription, Task};
use std::marker::PhantomData;
pub(crate) struct Instance<State, Message, Theme, Renderer, Update, View> {
update: Update,
view: View,
_state: PhantomData<State>,
_message: PhantomData<Message>,
_theme: PhantomData<Theme>,
_renderer: PhantomData<Renderer>,
}
/// Creates an iced [`MultiWindow`] given its title, update, and view logic.
pub fn multi_window<State, Message, Theme, Renderer>(
title: impl Title<State>,
update: impl application::Update<State, Message>,
view: impl for<'a> self::View<'a, State, Message, Theme, Renderer>,
) -> MultiWindow<impl Program<State = State, Message = Message, Theme = Theme>>
where
State: 'static,
Message: Send + std::fmt::Debug + 'static,
Theme: Default + DefaultStyle,
Renderer: program::Renderer,
{
use std::marker::PhantomData;
impl<State, Message, Theme, Renderer, Update, View> Program
for Instance<State, Message, Theme, Renderer, Update, View>
where
Message: Send + std::fmt::Debug + 'static,
Theme: Default + DefaultStyle,
Renderer: program::Renderer,
Update: application::Update<State, Message>,
View: for<'a> self::View<'a, State, Message, Theme, Renderer>,
{
type State = State;
type Message = Message;
type Theme = Theme;
type Renderer = Renderer;
type Executor = iced_futures::backend::default::Executor;
fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> {
self.update.update(state, message).into()
}
fn view<'a>(
&self,
state: &'a Self::State,
window: window::Id,
) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
self.view.view(state, window).into()
}
}
MultiWindow {
raw: Instance {
update,
view,
_state: PhantomData,
_message: PhantomData,
_theme: PhantomData,
_renderer: PhantomData,
},
settings: Settings::default(),
window: None,
}
.title(title)
}
/// The underlying definition and configuration of an iced daemon.
///
/// You can use this API to create and run iced applications
/// step by step—without coupling your logic to a trait
/// or a specific type.
///
/// You can create a [`MultiWindow`] with the [`daemon`] helper.
#[derive(Debug)]
pub struct MultiWindow<P: Program> {
raw: P,
settings: Settings,
window: Option<window::Settings>,
}
impl<P: Program> MultiWindow<P> {
#[cfg(any(feature = "winit", feature = "wayland"))]
/// Runs the [`MultiWindow`].
///
/// The state of the [`MultiWindow`] must implement [`Default`].
/// If your state does not implement [`Default`], use [`run_with`]
/// instead.
///
/// [`run_with`]: Self::run_with
pub fn run(self) -> Result
where
Self: 'static,
P::State: Default,
{
self.raw.run(self.settings, self.window)
}
#[cfg(any(feature = "winit", feature = "wayland"))]
/// Runs the [`MultiWindow`] with a closure that creates the initial state.
pub fn run_with<I>(self, initialize: I) -> Result
where
Self: 'static,
I: FnOnce() -> (P::State, Task<P::Message>) + 'static,
{
self.raw.run_with(self.settings, self.window, initialize)
}
/// Sets the [`Settings`] that will be used to run the [`MultiWindow`].
pub fn settings(self, settings: Settings) -> Self {
Self { settings, ..self }
}
/// Sets the [`Title`] of the [`MultiWindow`].
pub(crate) fn title(
self,
title: impl Title<P::State>,
) -> MultiWindow<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> {
MultiWindow {
raw: with_title(self.raw, move |state, window| title.title(state, window)),
settings: self.settings,
window: self.window,
}
}
/// Sets the subscription logic of the [`MultiWindow`].
pub fn subscription(
self,
f: impl Fn(&P::State) -> Subscription<P::Message>,
) -> MultiWindow<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> {
MultiWindow {
raw: with_subscription(self.raw, f),
settings: self.settings,
window: self.window,
}
}
/// Sets the theme logic of the [`MultiWindow`].
pub fn theme(
self,
f: impl Fn(&P::State, window::Id) -> P::Theme,
) -> MultiWindow<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> {
MultiWindow {
raw: with_theme(self.raw, f),
settings: self.settings,
window: self.window,
}
}
/// Sets the style logic of the [`MultiWindow`].
pub fn style(
self,
f: impl Fn(&P::State, &P::Theme) -> Appearance,
) -> MultiWindow<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> {
MultiWindow {
raw: with_style(self.raw, f),
settings: self.settings,
window: self.window,
}
}
/// Sets the window settings of the [`MultiWindow`].
pub fn window(self, window: window::Settings) -> Self {
Self {
raw: self.raw,
settings: self.settings,
window: Some(window),
}
}
}
/// The title logic of some [`MultiWindow`].
///
/// This trait is implemented both for `&static str` and
/// any closure `Fn(&State, window::Id) -> String`.
///
/// This trait allows the [`daemon`] builder to take any of them.
pub trait Title<State> {
/// Produces the title of the [`MultiWindow`].
fn title(&self, state: &State, window: window::Id) -> String;
}
impl<State> Title<State> for &'static str {
fn title(&self, _state: &State, _window: window::Id) -> String {
(*self).to_string()
}
}
impl<T, State> Title<State> for T
where
T: Fn(&State, window::Id) -> String,
{
fn title(&self, state: &State, window: window::Id) -> String {
self(state, window)
}
}
/// The view logic of some [`MultiWindow`].
///
/// This trait allows the [`daemon`] builder to take any closure that
/// returns any `Into<Element<'_, Message>>`.
pub trait View<'a, State, Message, Theme, Renderer> {
/// Produces the widget of the [`MultiWindow`].
fn view(
&self,
state: &'a State,
window: window::Id,
) -> impl Into<Element<'a, Message, Theme, Renderer>>;
}
impl<'a, T, State, Message, Theme, Renderer, Widget> View<'a, State, Message, Theme, Renderer> for T
where
T: Fn(&'a State, window::Id) -> Widget,
State: 'static,
Widget: Into<Element<'a, Message, Theme, Renderer>>,
{
fn view(
&self,
state: &'a State,
window: window::Id,
) -> impl Into<Element<'a, Message, Theme, Renderer>> {
self(state, window)
}
}

View file

@ -20,7 +20,6 @@ pub struct Settings {
pub(crate) autosize: bool,
/// Set the application to not create a main window
#[cfg(feature = "wayland")]
pub(crate) no_main_window: bool,
/// Whether the window should have a border, a title bar, etc. or not.
@ -77,7 +76,6 @@ impl Default for Settings {
antialiasing: true,
#[cfg(feature = "wayland")]
autosize: false,
#[cfg(feature = "wayland")]
no_main_window: false,
client_decorations: true,
debug: false,