Add iced cosmic example

This commit is contained in:
Jeremy Soller 2022-09-30 08:55:37 -06:00
parent 167b92f084
commit 699e474427
No known key found for this signature in database
GPG key ID: 87F211AF2BE4C2FE
19 changed files with 532 additions and 121 deletions

View file

@ -4,26 +4,16 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
cascade = "1.0.0" freedesktop-icons = "0.2.1"
derivative = { version = "2", optional = true }
gtk4 = { git = "https://github.com/gtk-rs/gtk4-rs", features = ["v4_6"] }
adw = { git = "https://gitlab.gnome.org/World/Rust/libadwaita-rs", package = "libadwaita"}
adw-user-colors-lib = { git = "https://github.com/pop-os/user-color-editor" }
gdk4-wayland = { git = "https://github.com/gtk-rs/gtk4-rs", features = ["wayland_crate"], optional = true }
gdk4-x11 = { git = "https://github.com/gtk-rs/gtk4-rs", features = ["xlib"], optional = true }
x11 = { version = "2.19.1", features = ["xlib"], optional = true }
gobject-sys = { git = "https://github.com/gtk-rs/gtk-rs-core", optional = true }
wayland-client = { version = "0.29.4", optional = true }
wayland-protocols = { version = "0.29.4", features = ["client", "unstable_protocols"], optional = true }
once_cell = "1.13.0"
libcosmic-widgets = { path = "widgets", optional = true }
xdg = "2.4.1"
[features] [dependencies.iced]
default = ["widgets"] git = "https://github.com/pop-os/iced.git"
layer-shell = ["derivative", "gdk4-wayland", "wayland-client", "wayland-protocols", "gobject-sys"] branch = "cosmic-design-system"
x = ["x11", "gdk4-x11"] features = ["cosmic_theme", "svg"]
widgets = ["libcosmic-widgets"]
[workspace] [workspace]
members = ["widgets"] members = [
"examples/cosmic",
"gtk4",
"gtk4/widgets"
]

View file

@ -0,0 +1,14 @@
[package]
name = "cosmic"
version = "0.1.0"
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
edition = "2021"
publish = false
[dependencies]
freedesktop-icons = "0.2.1"
[dependencies.iced]
git = "https://github.com/pop-os/iced.git"
branch = "cosmic-design-system"
features = ["cosmic_theme", "svg"]

15
examples/cosmic/README.md Normal file
View file

@ -0,0 +1,15 @@
# Styling
An example showcasing custom styling with a light and dark theme.
All the example code is located in the __[`main`](src/main.rs)__ file.
<div align="center">
<a href="https://user-images.githubusercontent.com/518289/71867993-acff4300-310c-11ea-85a3-d01d8f884346.gif">
<img src="https://user-images.githubusercontent.com/518289/71867993-acff4300-310c-11ea-85a3-d01d8f884346.gif" height="400px">
</a>
</div>
You can run it with `cargo run`:
```
cargo run --package styling
```

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,48 @@
Digitized data copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A.
with Reserved Font Name < Fira >,
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

318
examples/cosmic/src/main.rs Normal file
View file

@ -0,0 +1,318 @@
use iced::widget::{
button, checkbox, column, container, horizontal_rule, horizontal_space, progress_bar, radio,
row, slider, svg, text, toggler,
vertical_space,
};
use iced::{theme, Alignment, Background, Color, Element, Font, Length, Sandbox, Settings, Theme};
const FONT: Font = Font::External {
name: "Fira Sans Regular",
bytes: include_bytes!("../res/Fira/Sans/Regular.otf"),
};
const FONT_LIGHT: Font = Font::External {
name: "Fira Sans Light",
bytes: include_bytes!("../res/Fira/Sans/Light.otf"),
};
const FONT_SEMIBOLD: Font = Font::External {
name: "Fira Sans SemiBold",
bytes: include_bytes!("../res/Fira/Sans/SemiBold.otf"),
};
pub fn main() -> iced::Result {
let mut settings = Settings::default();
settings.default_font = match FONT {
Font::Default => None,
Font::External { bytes, .. } => Some(bytes),
};
settings.default_text_size = 18;
Window::run(settings)
}
fn icon(name: &str, size: u16) -> svg::Svg {
let handle = match freedesktop_icons::lookup(name)
.with_size(size)
.with_theme("Pop")
.with_cache()
.force_svg()
.find()
{
Some(path) => svg::Handle::from_path(path),
None => {
eprintln!("icon '{}' size {} not found", name, size);
svg::Handle::from_memory(Vec::new())
},
};
svg::Svg::new(handle)
}
fn sidebar_style(theme: &Theme) -> container::Appearance {
container::Appearance {
text_color: None,
background: Some(Background::Color(
match theme {
Theme::Dark => Color::from_rgb8(0x29, 0x29, 0x29),
Theme::Light => Color::from_rgb8(0xfd, 0xfd, 0xfd),
}
)),
border_radius: 8.0,
border_width: 0.0,
border_color: Color::TRANSPARENT,
}
}
fn listview_style(theme: &Theme) -> container::Appearance {
container::Appearance {
text_color: None,
background: Some(Background::Color(
match theme {
Theme::Dark => Color::from_rgb8(0x27, 0x27, 0x27),
Theme::Light => Color::from_rgb8(0xf7, 0xf7, 0xf7),
}
)),
border_radius: 8.0,
border_width: 0.0,
border_color: Color::TRANSPARENT,
}
}
#[derive(Default)]
struct Window {
page: u8,
debug: bool,
theme: Theme,
slider_value: f32,
checkbox_value: bool,
toggler_value: bool,
}
#[derive(Debug, Clone)]
enum Message {
Page(u8),
Debug(bool),
ThemeChanged(Theme),
ButtonPressed,
SliderChanged(f32),
CheckboxToggled(bool),
TogglerToggled(bool),
}
impl Sandbox for Window {
type Message = Message;
fn new() -> Self {
let mut window = Window::default();
window.slider_value = 50.0;
window
}
fn title(&self) -> String {
String::from("COSMIC Design System - Iced")
}
fn update(&mut self, message: Message) {
match message {
Message::Page(page) => self.page = page,
Message::Debug(debug) => self.debug = debug,
Message::ThemeChanged(theme) => self.theme = theme,
Message::ButtonPressed => {}
Message::SliderChanged(value) => self.slider_value = value,
Message::CheckboxToggled(value) => self.checkbox_value = value,
Message::TogglerToggled(value) => self.toggler_value = value,
}
}
fn view(&self) -> Element<Message> {
let sidebar: Element<_> = container(
column![
//TODO: Support symbolic icons
button(
row![
icon("network-wireless", 16).width(Length::Units(16)),
text("Wi-Fi"),
horizontal_space(Length::Fill),
]
.padding([4, 12])
.spacing(8)
)
.on_press(Message::Page(0))
.style(if self.page == 0 { theme::Button::Primary } else { theme::Button::Text })
,
button(
row![
icon("preferences-desktop", 16).width(Length::Units(16)),
text("Desktop"),
horizontal_space(Length::Fill),
]
.padding([4, 12])
.spacing(8)
)
.on_press(Message::Page(1))
.style(if self.page == 1 { theme::Button::Primary } else { theme::Button::Text })
,
button(
row![
icon("system-software-update", 16).width(Length::Units(16)),
text("OS Upgrade & Recovery"),
horizontal_space(Length::Fill),
]
.padding([4, 12])
.spacing(8)
)
.on_press(Message::Page(2))
.style(if self.page == 2 { theme::Button::Primary } else { theme::Button::Text })
,
vertical_space(Length::Fill),
]
.spacing(12)
.padding(12)
.max_width(300)
)
.style(theme::Container::Custom(sidebar_style))
.into();
let choose_theme = [Theme::Light, Theme::Dark].iter().fold(
row![text("Theme:")].spacing(10).align_items(Alignment::Center),
|row, theme| {
row.push(radio(
format!("{:?}", theme),
*theme,
Some(self.theme),
Message::ThemeChanged,
))
},
);
let content: Element<_> = column![
choose_theme,
vertical_space(Length::Units(16)),
toggler(
String::from("Debug layout"),
self.debug,
Message::Debug,
)
.width(Length::Shrink)
.size(24)
.spacing(12)
,
vertical_space(Length::Units(16)),
text("Buttons").font(FONT_SEMIBOLD),
container(
column![
row![
button("Primary")
.style(theme::Button::Primary)
.padding([8, 16])
.on_press(Message::ButtonPressed)
,
button("Secondary")
.style(theme::Button::Secondary)
.padding([8, 16])
.on_press(Message::ButtonPressed)
,
button("Positive")
.style(theme::Button::Positive)
.padding([8, 16])
.on_press(Message::ButtonPressed)
,
button("Destructive")
.style(theme::Button::Destructive)
.padding([8, 16])
.on_press(Message::ButtonPressed)
,
button("Text")
.style(theme::Button::Text)
.padding([8, 16])
.on_press(Message::ButtonPressed)
,
].spacing(12),
horizontal_rule(12),
row![
button("Primary")
.style(theme::Button::Primary)
.padding([8, 16])
,
button("Secondary")
.style(theme::Button::Secondary)
.padding([8, 16])
,
button("Positive")
.style(theme::Button::Positive)
.padding([8, 16])
,
button("Destructive")
.style(theme::Button::Destructive)
.padding([8, 16])
,
button("Text")
.style(theme::Button::Text)
.padding([8, 16])
,
].spacing(12),
]
.padding([12, 16])
.spacing(12)
)
.style(theme::Container::Custom(listview_style))
,
vertical_space(Length::Units(16)),
text("Controls").font(FONT_SEMIBOLD),
container(
column![
row![
text("Toggler"),
horizontal_space(Length::Fill),
toggler(None, self.toggler_value, Message::TogglerToggled)
.size(24)
.width(Length::Shrink),
]
.padding([0, 8])
,
horizontal_rule(12),
row![
text("Slider"),
horizontal_space(Length::Fill),
slider(0.0..=100.0, self.slider_value, Message::SliderChanged)
.width(Length::Units(250)),
]
.padding([0, 8])
,
horizontal_rule(12),
row![
text("Progress"),
horizontal_space(Length::Fill),
progress_bar(0.0..=100.0, self.slider_value).height(Length::Units(4))
.width(Length::Units(250)),
]
.padding([0, 8])
,
horizontal_rule(12),
checkbox("Checkbox", self.checkbox_value, Message::CheckboxToggled),
]
.padding([12, 16])
.spacing(12)
)
.style(theme::Container::Custom(listview_style))
]
.spacing(8)
.padding(24)
.max_width(600)
.into();
container(row![
if self.debug { sidebar.explain(Color::WHITE) } else { sidebar },
horizontal_space(Length::Fill),
if self.debug { content.explain(Color::WHITE) } else { content },
horizontal_space(Length::Fill),
])
.padding([16, 8])
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn theme(&self) -> Theme {
self.theme
}
}

26
gtk4/Cargo.toml Normal file
View file

@ -0,0 +1,26 @@
[package]
name = "libcosmic-gtk4"
version = "0.1.0"
edition = "2021"
[dependencies]
cascade = "1.0.0"
derivative = { version = "2", optional = true }
gtk4 = { git = "https://github.com/gtk-rs/gtk4-rs", features = ["v4_6"] }
adw = { git = "https://gitlab.gnome.org/World/Rust/libadwaita-rs", package = "libadwaita"}
adw-user-colors-lib = { git = "https://github.com/pop-os/user-color-editor" }
gdk4-wayland = { git = "https://github.com/gtk-rs/gtk4-rs", features = ["wayland_crate"], optional = true }
gdk4-x11 = { git = "https://github.com/gtk-rs/gtk4-rs", features = ["xlib"], optional = true }
x11 = { version = "2.19.1", features = ["xlib"], optional = true }
gobject-sys = { git = "https://github.com/gtk-rs/gtk-rs-core", optional = true }
wayland-client = { version = "0.29.4", optional = true }
wayland-protocols = { version = "0.29.4", features = ["client", "unstable_protocols"], optional = true }
once_cell = "1.13.0"
libcosmic-widgets = { path = "widgets", optional = true }
xdg = "2.4.1"
[features]
default = ["widgets"]
layer-shell = ["derivative", "gdk4-wayland", "wayland-client", "wayland-protocols", "gobject-sys"]
x = ["x11", "gdk4-x11"]
widgets = ["libcosmic-widgets"]

101
gtk4/src/lib.rs Normal file
View file

@ -0,0 +1,101 @@
mod deref_cell;
#[cfg(feature = "layer-shell")]
pub mod wayland;
#[cfg(feature = "layer-shell")]
mod wayland_custom_surface;
#[cfg(feature = "x")]
pub mod x;
#[cfg(feature = "widgets")]
pub use libcosmic_widgets as widgets;
use adw::StyleManager;
use gtk4::{
gdk,
gio::{self, FileMonitor, FileMonitorEvent, FileMonitorFlags},
glib,
prelude::*,
};
pub fn init() -> (Option<FileMonitor>, Option<FileMonitor>) {
let _ = gtk4::init();
adw::init();
let gtk_user_provider = gtk4::CssProvider::new();
if let Some(display) = gdk::Display::default() {
gtk4::StyleContext::add_provider_for_display(
&display,
&gtk_user_provider,
gtk4::STYLE_PROVIDER_PRIORITY_USER,
);
}
let cosmic_user_provider = gtk4::CssProvider::new();
if let Some(display) = gdk::Display::default() {
gtk4::StyleContext::add_provider_for_display(
&display,
&cosmic_user_provider,
gtk4::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
let path = xdg::BaseDirectories::with_prefix("gtk-4.0")
.ok()
.and_then(|xdg_dirs| xdg_dirs.find_config_file("gtk.css"))
.unwrap_or_else(|| "~/.config/gtk-4.0/gtk.css".into());
let gtk_file = gio::File::for_path(path);
let gtk_css_monitor = gtk_file.monitor(FileMonitorFlags::all(), None::<&gio::Cancellable>).ok().map(|monitor| {
monitor.connect_changed(glib::clone!(@strong gtk_user_provider => move |_monitor, file, _other_file, event| {
match event {
FileMonitorEvent::Deleted | FileMonitorEvent::MovedOut | FileMonitorEvent::Renamed => {
if adw::is_initialized() {
let manager = StyleManager::default();
let css = if manager.is_dark() {
adw_user_colors_lib::colors::ColorOverrides::dark_default().as_gtk_css()
} else {
adw_user_colors_lib::colors::ColorOverrides::light_default().as_gtk_css()
};
gtk_user_provider
.load_from_data(css.as_bytes());
}
},
FileMonitorEvent::ChangesDoneHint | FileMonitorEvent::Created | FileMonitorEvent::MovedIn => {
gtk_user_provider.load_from_file(file);
},
_ => {} // ignored
}
}));
monitor
});
let path = xdg::BaseDirectories::with_prefix("gtk-4.0")
.ok()
.and_then(|xdg_dirs| xdg_dirs.find_config_file("cosmic.css"))
.unwrap_or_else(|| "~/.config/gtk-4.0/cosmic.css".into());
let cosmic_file = gio::File::for_path(path);
cosmic_user_provider.load_from_file(&cosmic_file);
let cosmic_css_monitor = cosmic_file.monitor(FileMonitorFlags::all(), None::<&gio::Cancellable>).ok().map(|monitor| {
monitor.connect_changed(glib::clone!(@strong cosmic_user_provider => move |_monitor, file, _other_file, event| {
match event {
FileMonitorEvent::Deleted | FileMonitorEvent::MovedOut | FileMonitorEvent::Renamed => {
if adw::is_initialized() {
let manager = StyleManager::default();
let css = if manager.is_dark() {
adw_user_colors_lib::colors::ColorOverrides::dark_default().as_gtk_css()
} else {
adw_user_colors_lib::colors::ColorOverrides::light_default().as_gtk_css()
};
cosmic_user_provider
.load_from_data(css.as_bytes());
}
},
FileMonitorEvent::ChangesDoneHint | FileMonitorEvent::Created | FileMonitorEvent::MovedIn => {
cosmic_user_provider.load_from_file(file);
},
_ => {} // ignored
}
}));
monitor
});
(gtk_css_monitor, cosmic_css_monitor)
}

View file

@ -1,101 +0,0 @@
mod deref_cell;
#[cfg(feature = "layer-shell")]
pub mod wayland;
#[cfg(feature = "layer-shell")]
mod wayland_custom_surface;
#[cfg(feature = "x")]
pub mod x;
#[cfg(feature = "widgets")]
pub use libcosmic_widgets as widgets;
use adw::StyleManager;
use gtk4::{
gdk,
gio::{self, FileMonitor, FileMonitorEvent, FileMonitorFlags},
glib,
prelude::*,
};
pub fn init() -> (Option<FileMonitor>, Option<FileMonitor>) {
let _ = gtk4::init();
adw::init();
let gtk_user_provider = gtk4::CssProvider::new();
if let Some(display) = gdk::Display::default() {
gtk4::StyleContext::add_provider_for_display(
&display,
&gtk_user_provider,
gtk4::STYLE_PROVIDER_PRIORITY_USER,
);
}
let cosmic_user_provider = gtk4::CssProvider::new();
if let Some(display) = gdk::Display::default() {
gtk4::StyleContext::add_provider_for_display(
&display,
&cosmic_user_provider,
gtk4::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
let path = xdg::BaseDirectories::with_prefix("gtk-4.0")
.ok()
.and_then(|xdg_dirs| xdg_dirs.find_config_file("gtk.css"))
.unwrap_or_else(|| "~/.config/gtk-4.0/gtk.css".into());
let gtk_file = gio::File::for_path(path);
let gtk_css_monitor = gtk_file.monitor(FileMonitorFlags::all(), None::<&gio::Cancellable>).ok().map(|monitor| {
monitor.connect_changed(glib::clone!(@strong gtk_user_provider => move |_monitor, file, _other_file, event| {
match event {
FileMonitorEvent::Deleted | FileMonitorEvent::MovedOut | FileMonitorEvent::Renamed => {
if adw::is_initialized() {
let manager = StyleManager::default();
let css = if manager.is_dark() {
adw_user_colors_lib::colors::ColorOverrides::dark_default().as_gtk_css()
} else {
adw_user_colors_lib::colors::ColorOverrides::light_default().as_gtk_css()
};
gtk_user_provider
.load_from_data(css.as_bytes());
}
},
FileMonitorEvent::ChangesDoneHint | FileMonitorEvent::Created | FileMonitorEvent::MovedIn => {
gtk_user_provider.load_from_file(file);
},
_ => {} // ignored
}
}));
monitor
});
let path = xdg::BaseDirectories::with_prefix("gtk-4.0")
.ok()
.and_then(|xdg_dirs| xdg_dirs.find_config_file("cosmic.css"))
.unwrap_or_else(|| "~/.config/gtk-4.0/cosmic.css".into());
let cosmic_file = gio::File::for_path(path);
cosmic_user_provider.load_from_file(&cosmic_file);
let cosmic_css_monitor = cosmic_file.monitor(FileMonitorFlags::all(), None::<&gio::Cancellable>).ok().map(|monitor| {
monitor.connect_changed(glib::clone!(@strong cosmic_user_provider => move |_monitor, file, _other_file, event| {
match event {
FileMonitorEvent::Deleted | FileMonitorEvent::MovedOut | FileMonitorEvent::Renamed => {
if adw::is_initialized() {
let manager = StyleManager::default();
let css = if manager.is_dark() {
adw_user_colors_lib::colors::ColorOverrides::dark_default().as_gtk_css()
} else {
adw_user_colors_lib::colors::ColorOverrides::light_default().as_gtk_css()
};
cosmic_user_provider
.load_from_data(css.as_bytes());
}
},
FileMonitorEvent::ChangesDoneHint | FileMonitorEvent::Created | FileMonitorEvent::MovedIn => {
cosmic_user_provider.load_from_file(file);
},
_ => {} // ignored
}
}));
monitor
});
(gtk_css_monitor, cosmic_css_monitor)
}