Compare commits

..

1 commit

Author SHA1 Message Date
Votre Nom
52ce463a59 window-management: toggle for macOS-style window controls position
Adds a new toggler "Place buttons on the left (macOS style)" in
*Desktop → Window Management → Window controls*, next to the existing
show_maximize / show_minimize controls. When enabled, writes
`WindowControlsPosition::Start` into the `CosmicTk` config
(com.system76.CosmicTk); when disabled, writes `End` (default).

All libcosmic-based applications rebuilt against a libcosmic that
exposes `WindowControlsPosition` pick up the change live through the
existing cosmic-config subscription.

Includes:
- new Message variant WindowControlsPositionStart(bool) + handler
- `window-controls.position-start` fluent key added in en + fr locales
- Cargo.toml: activate local [patch] override to libcosmic (dev only,
  not suitable for upstream merge)

Requires: libcosmic >= 5c331935 (header_bar WindowControlsPosition).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 15:09:01 +02:00
283 changed files with 9822 additions and 16725 deletions

View file

@ -26,7 +26,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: install system dependencies
run: sudo apt-get update && sudo apt-get install lld cmake libclang-dev libdav1d-dev libexpat1-dev libfontconfig-dev libfreetype-dev libpipewire-0.3-dev libpulse-dev pkg-config libxkbcommon-dev libudev-dev libinput-dev libwayland-dev
run: sudo apt-get update && sudo apt-get install lld cmake libclang-dev libexpat1-dev libfontconfig-dev libfreetype-dev libpipewire-0.3-dev libpulse-dev pkg-config libxkbcommon-dev libudev-dev libinput-dev libwayland-dev
- uses: actions/checkout@v6
- name: install toolchain
run: rustup toolchain install 1.90.0 --component clippy
@ -38,7 +38,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: install system dependencies
run: sudo apt-get update && sudo apt-get install lld cmake libclang-dev libdav1d-dev libexpat1-dev libfontconfig-dev libfreetype-dev libpipewire-0.3-dev libpulse-dev pkg-config libxkbcommon-dev libudev-dev libinput-dev libwayland-dev
run: sudo apt-get update && sudo apt-get install lld cmake libclang-dev libexpat1-dev libfontconfig-dev libfreetype-dev libpipewire-0.3-dev libpulse-dev pkg-config libxkbcommon-dev libudev-dev libinput-dev libwayland-dev
- uses: actions/checkout@v6
- name: install toolchain
run: rustup show
@ -50,7 +50,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: install system dependencies
run: sudo apt-get update && sudo apt-get install lld cmake libclang-dev libdav1d-dev libexpat1-dev libfontconfig-dev libfreetype-dev libpipewire-0.3-dev libpulse-dev pkg-config libxkbcommon-dev libudev-dev libinput-dev libwayland-dev just
run: sudo apt-get update && sudo apt-get install lld cmake libclang-dev libexpat1-dev libfontconfig-dev libfreetype-dev libpipewire-0.3-dev libpulse-dev pkg-config libxkbcommon-dev libudev-dev libinput-dev libwayland-dev just
- uses: actions/checkout@v6
- name: install toolchain
run: rustup show

View file

@ -1,15 +0,0 @@
{
"format_on_save": "on",
"lsp": {
"rust-analyzer": {
"initialization_options": {
"check": {
"command": "clippy",
},
"rustfmt": {
"extraArgs": ["+nightly"],
},
},
},
},
}

3667
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,25 +1,17 @@
[workspace]
members = ["cosmic-settings", "page", "pages/*", "subscriptions/*"]
members = ["cosmic-settings", "crates/*", "page", "pages/*", "subscriptions/*"]
default-members = ["cosmic-settings"]
resolver = "3"
[workspace.package]
rust-version = "1.93"
rust-version = "1.90"
[workspace.dependencies]
cosmic-randr = { path = "../cosmic-randr/lib" }
tokio = { version = "1.53.1", features = ["macros"] }
iced_winit = { path = "/home/lionel/Projets/COSMIC/libcosmic/iced/winit", default-features = false }
image = { version = "0.25.10", default-features = false, features = [
"jpeg",
"png",
"rayon",
"webp",
"hdr",
] }
cosmic-randr = { git = "https://github.com/pop-os/cosmic-randr" }
tokio = { version = "1.49.0", features = ["macros"] }
iced_winit = { git = "https://github.com/pop-os/libcosmic", default-features = false }
[workspace.dependencies.cosmic]
package = "libcosmic-yoda"
[workspace.dependencies.libcosmic]
features = [
"dbus-config",
"desktop",
@ -28,29 +20,29 @@ features = [
"tokio",
"qr_code",
]
path = "/home/lionel/Projets/COSMIC/libcosmic"
git = "https://github.com/pop-os/libcosmic"
[workspace.dependencies.cosmic-config]
path = "/home/lionel/Projets/COSMIC/libcosmic/cosmic-config"
git = "https://github.com/pop-os/libcosmic"
[workspace.dependencies.cosmic-bg-config]
path = "../cosmic-bg/config"
git = "https://github.com/pop-os/cosmic-bg"
[workspace.dependencies.cosmic-comp-config]
path = "../cosmic-comp/cosmic-comp-config"
git = "https://github.com/pop-os/cosmic-comp"
features = ["output"]
[workspace.dependencies.cosmic-idle-config]
path = "../cosmic-idle/cosmic-idle-config"
git = "https://github.com/pop-os/cosmic-idle"
[workspace.dependencies.cosmic-panel-config]
path = "../cosmic-panel/cosmic-panel-config"
git = "https://github.com/pop-os/cosmic-panel"
[workspace.dependencies.cosmic-randr-shell]
path = "../cosmic-randr/shell"
git = "https://github.com/pop-os/cosmic-randr"
[workspace.dependencies.sctk]
version = "0.20.0"
version = "0.20"
package = "smithay-client-toolkit"
[profile.dev]
@ -67,18 +59,34 @@ inherits = "release"
lto = "off"
debug = true
# [patch.'https://github.com/pop-os/cosmic-text']
# cosmic-text = { git = "https://github.com/pop-os/cosmic-text//", rev = "b017d7c" }
[patch.'https://github.com/pop-os/cosmic-protocols']
cosmic-protocols = { path = "../cosmic-protocols" }
cosmic-client-toolkit = { path = "../cosmic-protocols/client-toolkit" }
cosmic-protocols = { git = "https://github.com/pop-os/cosmic-protocols//", rev = "d0e95be" }
cosmic-client-toolkit = { git = "https://github.com/pop-os/cosmic-protocols//", rev = "d0e95be" }
# [patch.'https://github.com/pop-os/cosmic-settings-daemon']
# cosmic-settings-config = { git = "https://github.com/pop-os/cosmic-settings-daemon//", branch = "input_nobuild" }
# For development and testing purposes
[patch.'https://github.com/pop-os/libcosmic']
cosmic-config = { path = "/home/lionel/Projets/COSMIC/libcosmic/cosmic-config" }
cosmic-theme = { path = "/home/lionel/Projets/COSMIC/libcosmic/cosmic-theme" }
iced_futures = { path = "/home/lionel/Projets/COSMIC/libcosmic/iced/futures" }
iced_winit = { path = "/home/lionel/Projets/COSMIC/libcosmic/iced/winit" }
libcosmic = { path = "../libcosmic" }
cosmic-config = { path = "../libcosmic/cosmic-config" }
cosmic-theme = { path = "../libcosmic/cosmic-theme" }
iced_futures = { path = "../libcosmic/iced/futures" }
iced_winit = { path = "../libcosmic/iced/winit" }
[patch.'https://github.com/pop-os/cosmic-text.git']
cosmic-text = { path = "../cosmic-text" }
# libcosmic = { git = "https://github.com/pop-os/libcosmic//" }
# cosmic-config = { git = "https://github.com/pop-os/libcosmic//" }
# cosmic-theme = { git = "https://github.com/pop-os/libcosmic//" }
# iced_futures = { git = "https://github.com/pop-os/libcosmic//" }
# iced_winit = { git = "https://github.com/pop-os/libcosmic//" }
# [patch.'https://github.com/pop-os/dbus-settings-bindings']
# cosmic-dbus-networkmanager = { path = "../dbus-settings-bindings/networkmanager" }
# upower_dbus = { path = "../dbus-settings-bindings/upower" }
# nm-secret-agent-manager = { git = "https://github.com/pop-os/dbus-settings-bindings//", branch = "nm-secret-agent" }
[patch.crates-io]
atspi = { git = "https://github.com/wash2/atspi" }

View file

@ -48,13 +48,7 @@ This document provides a regression testing checklist for COSMIC Settings and th
### Sound
- [ ] Output & Input volume sliders work independently
- [ ] Output balance slider works & doesn't get reset by volume slider
- [ ] Amplification toggles work as expected
- [ ] Device profiles can be changed & reflect as expected on the main Sound page
- [ ] Applications using sound appear on the Applications sub-page
- [ ] Application volume and mute controls only affect the selected playback stream
- [ ] Closing an playback stream removes it from the Applications sub-page
TBD after devices/profiles are fixed.
### Power & Battery

View file

@ -1,25 +1,20 @@
cargo-target-dir := env('CARGO_TARGET_DIR', 'target')
# Compile with debug profile
[no-cd]
build-debug *args:
cargo build {{args}}
cargo build {{ args }}
# Compile with release profile
[no-cd]
build-release *args: (build-debug '--release' args)
# Compile with a vendored tarball
[no-cd]
build-vendored *args: vendor-extract (build-release '--frozen --offline' args)
# Check for errors and linter warnings
[no-cd]
check *args:
cargo clippy --all-features {{args}} -- -W clippy::pedantic
cargo clippy --all-features {{ args }} -- -W clippy::pedantic
# Runs a check with JSON message format for IDE integration
[no-cd]
check-json: (check '--message-format=json')
# Remove Cargo build artifacts
@ -33,38 +28,25 @@ clean-dist: clean
rm -rf .cargo vendor vendor.tar target
# Run the application for testing purposes
[no-cd]
run *args:
cargo run {{args}}
env RUST_LOG=debug RUST_BACKTRACE=full cargo run {{ args }} --release
# Run `cargo test`
[no-cd]
test *args:
cargo test {{args}}
cargo test {{ args }}
# Vendor Cargo dependencies locally
[no-cd]
vendor:
#!/usr/bin/env bash
mkdir -p .cargo
cargo vendor --locked | head -n -1 > .cargo/config.toml
echo 'directory = "vendor"' >> .cargo/config.toml
echo >> .cargo/config.toml
echo '[env]' >> .cargo/config.toml
if [ -n "${SOURCE_DATE_EPOCH}" ]
then
source_date="$(date -d "@${SOURCE_DATE_EPOCH}" "+%Y-%m-%d")"
echo "VERGEN_GIT_COMMIT_DATE = \"${source_date}\"" >> .cargo/config.toml
fi
if [ -n "${SOURCE_GIT_HASH}" ]
then
echo "VERGEN_GIT_SHA = \"${SOURCE_GIT_HASH}\"" >> .cargo/config.toml
fi
tar pcf vendor.tar .cargo vendor
rm -rf .cargo vendor
tar pcf vendor.tar vendor
rm -rf vendor
# Extracts vendored dependencies
[no-cd]
[private]
vendor-extract:
rm -rf vendor
tar pxf vendor.tar

View file

@ -1,6 +1,6 @@
[package]
name = "cosmic-settings"
version = "1.7.0"
version = "1.0.7"
edition = "2024"
license = "GPL-3.0-only"
publish = false
@ -16,11 +16,13 @@ ashpd = { version = "0.12", default-features = false, features = [
], optional = true }
chrono = "0.4"
jiff = "0.2"
clap = { version = "4.6.4", features = ["derive"] }
clap = { version = "4.5.59", features = ["derive"] }
color-eyre = "0.6.5"
cosmic-bg-config.workspace = true
cosmic-comp-config = { workspace = true, optional = true }
cosmic-config.workspace = true
cosmic-dbus-networkmanager = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
nm-secret-agent-manager = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
cosmic-idle-config.workspace = true
cosmic-panel-config = { workspace = true, optional = true }
cosmic-protocols = { git = "https://github.com/pop-os/cosmic-protocols", optional = true }
@ -32,78 +34,73 @@ cosmic-settings-accessibility-subscription = { path = "../subscriptions/accessib
cosmic-settings-a11y-manager-subscription = { path = "../subscriptions/a11y-manager", optional = true }
cosmic-settings-airplane-mode-subscription = { path = "../subscriptions/airplane-mode", optional = true }
cosmic-settings-bluetooth-subscription = { path = "../subscriptions/bluetooth", optional = true }
cosmic-settings-sound = { path = "../pages/sound", optional = true }
cosmic-settings-network-manager-subscription = { path = "../subscriptions/network-manager", optional = true }
cosmic-settings-upower-subscription = { path = "../subscriptions/upower", optional = true }
cosmic-settings-sound-subscription = { path = "../subscriptions/sound", optional = true, features = [
"auto-profile-init",
] }
cosmic-settings-wallpaper = { path = "../pages/wallpapers" }
cosmic-settings-daemon-config = { git = "https://github.com/pop-os/cosmic-settings-daemon", optional = true }
cups_rs = { version = "0.3.0", optional = true }
derive_setters = "0.1.9"
dirs = "6.0.0"
eyre = "0.6.12"
freedesktop-desktop-entry = "0.8.1"
futures = "0.3.33"
futures = "0.3.32"
hostname-validator = "1.1.1"
hostname1-zbus = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
i18n-embed-fl = "0.10.1"
image.workspace = true
indexmap = "2.14.0"
i18n-embed-fl = "0.10.0"
image = { version = "0.25", default-features = false, features = [
"jpeg",
"png",
"rayon",
"webp",
"hdr",
] }
indexmap = "2.13.0"
itertools = "0.14.0"
itoa = "1.0.18"
cosmic.workspace = true
itoa = "1.0.17"
libcosmic.workspace = true
iced_winit.workspace = true
locale1 = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
sysinfo = { version = "=0.38.0", optional = true }
mime-apps = { package = "cosmic-mime-apps", git = "https://github.com/pop-os/cosmic-mime-apps", features = ["tokio"], optional = true }
# Intégration OpenLogi (page Logitech des périphériques d'entrée).
openlogi-core = { path = "../../OpenLogi/crates/openlogi-core" }
openlogi-ipc = { path = "../../OpenLogi/crates/openlogi-ipc" }
tarpc = { version = "0.38", features = ["serde1", "tokio1"] }
mime-apps = { package = "cosmic-mime-apps", git = "https://github.com/pop-os/cosmic-mime-apps", optional = true }
notify = "8.2.0"
nmrs = { version = "3.5.2", optional = true }
regex = "1.13.1"
regex = "1.12.3"
ron = "0.12"
rust-embed = "8.12.0"
rust-embed = "8.11.0"
sctk = { workspace = true, optional = true }
secure-string = "0.3.0"
secret-service = { version = "5.1.0", features = ["rt-tokio-crypto-rust"], optional = true }
serde = { version = "1.0.229", features = ["derive"] }
serde = { version = "1.0.228", features = ["derive"] }
slab = "0.4.12"
slotmap = "1.1.1"
static_init = "1.0.4"
sunrise = "3.0.0"
timedate-zbus = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
tokio = { workspace = true, features = ["fs", "io-util", "process", "sync", "time"] }
tokio = { workspace = true, features = ["fs", "io-util", "process", "sync"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }
udev = { version = "0.9.3", optional = true }
upower_dbus = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
bluez-zbus = { git = "https://github.com/pop-os/dbus-settings-bindings", optional = true }
url = "2.5.8"
xkb-data = "0.2.2"
xkeysym = { version = "0.2.1", optional = true }
zbus = { version = "5.18.0", default-features = false, features = [
zbus = { version = "5.13.2", default-features = false, features = [
"tokio",
], optional = true }
zbus_polkit = { version = "5.0.0", optional = true }
fontdb = "0.23.0"
mime = "0.3.17"
rustix = { version = "1.1.4", features = ["process"] }
rustix = { version = "1.1.3", features = ["process"] }
gettext-rs = { version = "0.7.7", features = [
"gettext-system",
], optional = true }
num-traits = "0.2"
pwhash = "1"
which = "8.0.5"
zlink = "0.5.0"
intmap = "3.1.3"
[dependencies.cosmic-settings-audio-client]
git = "https://github.com/pop-os/cosmic-settings-daemon"
features = ["codec"]
optional = true
which = "8.0.0"
[dependencies.icu]
version = "2.2.0"
version = "2.1.1"
features = ["compiled_data"]
[dependencies.i18n-embed]
@ -116,11 +113,8 @@ git = "https://github.com/AerynOS/locales-rs"
optional = true
[features]
default = ["a11y", "avif", "linux", "single-instance", "wgpu", "systemd"]
avif = ["image/avif-native"]
default = ["a11y", "linux", "single-instance", "wgpu"]
gettext = ["dep:gettext-rs"]
systemd = []
openrc = []
# Default features for Linux
linux = [
@ -135,7 +129,6 @@ linux = [
"page-legacy-applications",
"page-networking",
"page-power",
"page-printers",
"page-region",
"page-sound",
"page-users",
@ -174,13 +167,13 @@ page-input = [
]
page-legacy-applications = ["cosmic-comp-config", "dep:cosmic-randr"]
page-networking = [
"dep:cosmic-settings-network-manager-subscription",
"xdg-portal",
"dep:nmrs",
"dep:secret-service",
"dep:cosmic-dbus-networkmanager",
"dep:nm-secret-agent-manager",
"dep:zbus",
]
page-power = ["dep:upower_dbus", "dep:zbus"]
page-printers = ["dep:cups_rs"]
page-region = [
"gettext",
"dep:locales-rs",
@ -188,18 +181,18 @@ page-region = [
"dep:zbus",
"dep:accounts-zbus",
]
page-sound = ["dep:cosmic-settings-audio-client", "dep:cosmic-settings-sound"]
page-sound = ["dep:cosmic-settings-sound-subscription"]
page-users = ["xdg-portal", "dep:accounts-zbus", "dep:zbus", "dep:zbus_polkit"]
page-window-management = ["cosmic-comp-config", "dep:cosmic-settings-config"]
page-workspaces = ["cosmic-comp-config"]
# Other features
a11y = ["cosmic/a11y"]
a11y = ["libcosmic/a11y"]
ashpd = ["dep:ashpd"]
cosmic-comp-config = ["dep:cosmic-comp-config"]
dbus-config = ["cosmic/dbus-config", "cosmic-config/dbus"]
single-instance = ["cosmic/single-instance"]
dbus-config = ["libcosmic/dbus-config", "cosmic-config/dbus"]
single-instance = ["libcosmic/single-instance"]
test = []
wayland = ["cosmic/wayland", "dep:cosmic-panel-config", "dep:cosmic-randr", "iced_winit/wayland"]
wgpu = ["cosmic/wgpu"]
xdg-portal = ["ashpd", "cosmic/xdg-portal"]
wayland = ["libcosmic/wayland", "dep:cosmic-panel-config", "dep:cosmic-randr", "iced_winit/cctk"]
wgpu = ["libcosmic/wgpu"]
xdg-portal = ["ashpd", "libcosmic/xdg-portal"]

View file

@ -1,5 +1,4 @@
use std::path::PathBuf;
use std::{env, fs};
use std::{env, fs, path::PathBuf};
use xdgen::{App, Context, FluentString};
fn main() {

View file

@ -5,6 +5,7 @@ use crate::PageCommands;
use crate::config::Config;
#[cfg(feature = "page-accessibility")]
use crate::pages::accessibility;
use crate::pages::applications;
#[cfg(feature = "page-bluetooth")]
use crate::pages::bluetooth;
use crate::pages::desktop::{self, appearance};
@ -16,25 +17,28 @@ use crate::pages::input;
use crate::pages::networking;
#[cfg(feature = "page-power")]
use crate::pages::power;
#[cfg(feature = "page-printers")]
use crate::pages::printers;
#[cfg(feature = "page-sound")]
use crate::pages::sound;
use crate::pages::{self, applications, system, time};
use crate::pages::{self, system, time};
use crate::subscription::desktop_files;
use crate::widget::{page_title, search_header};
use cosmic::app::context_drawer::ContextDrawer;
use cosmic::app::{Core, Task};
#[cfg(feature = "wayland")]
use cosmic::cctk::{sctk::output::OutputInfo, wayland_client::protocol::wl_output::WlOutput};
use cosmic::iced::event::{self, PlatformSpecific};
use cosmic::iced::{self, Length, Subscription, keyboard, window};
use cosmic::prelude::*;
use cosmic::widget::{
button, column, container, icon, id_container, nav_bar, row, scrollable, segmented_button,
settings, text_input,
use cosmic::{
Element,
app::{Core, Task, context_drawer::ContextDrawer},
iced::{
self, Length, Subscription,
event::{self, PlatformSpecific},
keyboard, window,
},
prelude::*,
surface,
widget::{
button, column, container, icon, id_container, nav_bar, row, scrollable, segmented_button,
settings, text_input,
},
};
use cosmic::{Element, surface};
#[cfg(feature = "cosmic-comp-config")]
use cosmic_comp_config::CosmicCompConfig;
#[cfg(feature = "wayland")]
@ -48,9 +52,8 @@ use desktop::{
#[cfg(feature = "wayland")]
use event::wayland;
use page::Entity;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::str::FromStr;
use std::{borrow::Cow, str::FromStr};
#[allow(clippy::struct_excessive_bools)]
#[allow(clippy::module_name_repetitions)]
@ -65,7 +68,6 @@ pub struct SettingsApp {
pages: page::Binder<crate::pages::Message>,
search_active: bool,
search_id: cosmic::widget::Id,
search_scroll_id: cosmic::iced::id::Id,
search_input: String,
search_selections: Vec<(page::Entity, section::Entity)>,
context_title: Option<String>,
@ -119,8 +121,6 @@ impl SettingsApp {
}
#[cfg(feature = "page-power")]
PageCommands::Power => self.pages.page_id::<power::Page>(),
#[cfg(feature = "page-printers")]
PageCommands::Printers => self.pages.page_id::<printers::Page>(),
#[cfg(feature = "page-region")]
PageCommands::RegionLanguage => self.pages.page_id::<time::region::Page>(),
#[cfg(feature = "page-sound")]
@ -210,7 +210,6 @@ impl cosmic::Application for SettingsApp {
pages: page::Binder::default(),
search_active: false,
search_id: cosmic::widget::Id::unique(),
search_scroll_id: cosmic::iced::id::Id::new("COSMIC_search_results_scrollable"),
search_input: String::new(),
search_selections: Vec::default(),
context_title: None,
@ -231,8 +230,6 @@ impl cosmic::Application for SettingsApp {
app.insert_page::<power::Page>();
#[cfg(feature = "page-input")]
app.insert_page::<input::Page>();
#[cfg(feature = "page-printers")]
app.insert_page::<printers::Page>();
app.insert_page::<applications::Page>();
app.insert_page::<time::Page>();
app.insert_page::<system::Page>();
@ -515,13 +512,6 @@ impl cosmic::Application for SettingsApp {
}
}
#[cfg(feature = "page-input")]
crate::pages::Message::Logitech(message) => {
if let Some(page) = self.pages.page_mut::<input::logitech::Page>() {
return page.update(message).map(Into::into);
}
}
#[cfg(feature = "page-input")]
crate::pages::Message::KeyboardShortcuts(message) => {
if let Some(page) = self.pages.page_mut::<input::keyboard::shortcuts::Page>() {
@ -593,13 +583,6 @@ impl cosmic::Application for SettingsApp {
}
}
#[cfg(feature = "page-sound")]
crate::pages::Message::SoundApplications(message) => {
if let Some(page) = self.pages.page_mut::<sound::applications::Page>() {
return page.update(message).map(Into::into);
}
}
#[cfg(feature = "page-sound")]
crate::pages::Message::SoundDeviceProfiles(message) => {
if let Some(page) = self.pages.page_mut::<sound::device_profiles::Page>() {
@ -676,13 +659,6 @@ impl cosmic::Application for SettingsApp {
}
}
#[cfg(feature = "page-printers")]
crate::pages::Message::Printers(message) => {
if let Some(page) = self.pages.page_mut::<printers::Page>() {
return page.update(message).map(Into::into);
}
}
#[cfg(feature = "page-networking")]
crate::pages::Message::Vpn(message) => {
if let Some(page) = self.pages.page_mut::<networking::vpn::Page>() {
@ -1174,9 +1150,6 @@ impl SettingsApp {
}
for page in unload {
if page == self.active_page {
continue;
}
self.loaded_pages.remove(&page);
self.pages.on_leave(page);
}
@ -1230,7 +1203,6 @@ impl SettingsApp {
self.page_container(settings::view_column(sections))
.apply(scrollable)
.apply(|w| id_container(w, self.search_scroll_id.clone()))
.into()
}

View file

@ -1,8 +1,10 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use cosmic::cosmic_config::{self, ConfigGet, ConfigSet};
use cosmic::cosmic_theme::palette::Srgba;
use cosmic::{
cosmic_config::{self, ConfigGet, ConfigSet},
cosmic_theme::palette::Srgba,
};
const NAME: &str = "com.system76.CosmicSettings";

View file

@ -1,8 +1,10 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use i18n_embed::fluent::{FluentLanguageLoader, fluent_language_loader};
use i18n_embed::{DefaultLocalizer, LanguageLoader, Localizer};
use i18n_embed::{
DefaultLocalizer, LanguageLoader, Localizer,
fluent::{FluentLanguageLoader, fluent_language_loader},
};
use rust_embed::RustEmbed;
use std::sync::LazyLock;

View file

@ -7,12 +7,6 @@
#![allow(clippy::cast_lossless)]
#![allow(clippy::too_many_lines)]
#[cfg(not(any(feature = "systemd", feature = "openrc")))]
compile_error!(
"At least one service manager feature must be enabled. \
Enable 'systemd' or 'openrc' for bluetooth service management."
);
pub mod app;
use std::str::FromStr;
@ -22,7 +16,6 @@ pub mod config;
#[macro_use]
pub mod localize;
pub mod pages;
pub mod service_manager;
pub mod subscription;
pub mod theme;
pub mod utils;
@ -31,8 +24,7 @@ pub mod widget;
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use cosmic::app::CosmicFlags;
use cosmic::iced::Limits;
use cosmic::{app::CosmicFlags, iced::Limits};
use i18n_embed::DesktopLanguageRequester;
use ron::error::SpannedError;
use serde::{Deserialize, Serialize};
@ -122,9 +114,6 @@ pub enum PageCommands {
/// Power settings page
#[cfg(feature = "page-power")]
Power,
/// Printers settings page
#[cfg(feature = "page-printers")]
Printers,
/// Region & Language settings page
#[cfg(feature = "page-region")]
RegionLanguage,

View file

@ -1,15 +1,20 @@
use std::collections::HashSet;
use std::fmt::Write;
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::{Element, Length, stream};
use cosmic::widget::{self, icon, settings, svg, text};
use cosmic::{Apply, surface};
use cosmic::{
Apply,
iced::core::text::Wrapping,
iced::{Element, Length, stream},
surface,
widget::{self, icon, settings, svg, text},
};
use cosmic_comp_config::{ZoomConfig, ZoomMovement};
use cosmic_config::{ConfigGet, ConfigSet};
use cosmic_settings_config::{Action, Binding, shortcuts};
use cosmic_settings_page::section::{self, Section};
use cosmic_settings_page::{self as page, Entity};
use cosmic_settings_page::{
self as page, Entity,
section::{self, Section},
};
use futures::SinkExt;
use slotmap::SlotMap;
use tracing::error;

View file

@ -1,17 +1,21 @@
use cosmic::cosmic_theme::{CosmicPalette, ThemeBuilder};
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::stream;
use cosmic::theme::CosmicTheme;
use cosmic::widget::{dropdown, settings, text};
use cosmic::{Apply, Element, Task, surface};
use cosmic_comp_config::CosmicCompConfig;
use cosmic::{
Apply, Element, Task,
cosmic_theme::{CosmicPalette, ThemeBuilder},
iced::core::text::Wrapping,
iced::stream,
surface,
theme::CosmicTheme,
widget::{dropdown, settings, text},
};
pub use cosmic_comp_config::ZoomMovement;
use cosmic_config::CosmicConfigEntry;
use cosmic_settings_a11y_manager_subscription as cosmic_a11y_manager;
use cosmic_settings_accessibility_subscription as a11y_bus;
use cosmic_settings_daemon_config::CosmicSettingsDaemonConfig;
use cosmic_settings_page::section::{self, Section};
use cosmic_settings_page::{self as page, Insert};
use cosmic_settings_page::{
self as page, Insert,
section::{self, Section},
};
use futures::SinkExt;
use num_traits::FromPrimitive;
use slotmap::SlotMap;
@ -37,21 +41,11 @@ pub struct Page {
daemon_helper: cosmic_config::Config,
dbus_sender: Option<UnboundedSender<a11y_bus::Request>>,
reader_enabled: bool,
comp_config: CosmicCompConfig,
comp_helper: cosmic_config::Config,
}
impl Default for Page {
fn default() -> Self {
let daemon_helper = CosmicSettingsDaemonConfig::config().unwrap();
let comp_helper = cosmic_config::Config::new("com.system76.CosmicComp", 1).unwrap();
let comp_config =
CosmicCompConfig::get_entry(&comp_helper).unwrap_or_else(|(errs, config)| {
for err in errs {
tracing::warn!(?err, "error while reading cosmic-comp config");
}
config
});
Page {
dbus_sender: None,
entity: page::Entity::default(),
@ -76,8 +70,6 @@ impl Default for Page {
.unwrap_or_default(),
daemon_helper,
reader_enabled: false,
comp_config,
comp_helper,
}
}
}
@ -90,7 +82,6 @@ pub enum Message {
ProtocolUnavailable,
Return,
ScreenReaderEnabled(bool),
SetCursorShakeToFind(bool),
SetScreenFilterActive(bool),
SetScreenFilterSelection(ColorFilter),
SetScreenInverted(bool),
@ -201,8 +192,6 @@ pub fn vision() -> section::Section<crate::pages::Message> {
invert_colors = fl!("accessibility", "invert-colors");
color_filters = fl!("accessibility", "color-filters");
color_filter_type = fl!("color-filter");
shake_cursor = fl!("accessibility", "shake-cursor");
shake_cursor_desc = fl!("accessibility", "shake-cursor-desc");
});
Section::default()
@ -292,13 +281,6 @@ pub fn vision() -> section::Section<crate::pages::Message> {
settings::item::builder(&descriptions[color_filter_type]).control(dropdown)
})
.add(
settings::item::builder(&descriptions[shake_cursor])
.description(&descriptions[shake_cursor_desc])
.toggler(page.comp_config.cursor_shake_to_find, |enabled| {
Message::SetCursorShakeToFind(enabled).into()
}),
)
.into()
})
}
@ -439,14 +421,6 @@ impl Page {
Message::Surface(a) => {
return cosmic::task::message(crate::app::Message::Surface(a));
}
Message::SetCursorShakeToFind(enabled) => {
if let Err(err) = self
.comp_config
.set_cursor_shake_to_find(&self.comp_helper, enabled)
{
tracing::error!(?err, "failed to set cursor_shake_to_find");
}
}
Message::SetSoundMono(active) => {
if let Err(err) = self
.daemon_config

View file

@ -2,23 +2,28 @@
// Copyright 2024 bbb651 <bar.ye651@gmail.com>
// SPDX-License-Identifier: GPL-3.0-only
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{self, dropdown, icon, settings};
use cosmic::{Apply, Element, Task, surface};
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::Arc,
};
use cosmic::{
Apply, Element, Task,
iced::Alignment,
surface,
widget::{self, dropdown, icon, settings},
};
use cosmic_config::{ConfigGet, ConfigSet};
use cosmic_settings_config::shortcuts::SystemActions;
use cosmic_settings_config::shortcuts::action::System;
use cosmic_settings_page::{self as page, Section, section};
use freedesktop_desktop_entry::{DesktopEntry, default_paths, get_languages_from_env};
use mime::Mime;
use freedesktop_desktop_entry::{
DesktopEntry, Iter as DesktopEntryIter, default_paths, get_languages_from_env,
};
use mime_apps::App;
use slotmap::SlotMap;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::io::SeekFrom;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use tokio::io::{AsyncSeekExt, AsyncWriteExt};
const DROPDOWN_WEB_BROWSER: usize = 0;
const DROPDOWN_FILE_MANAGER: usize = 1;
@ -47,7 +52,7 @@ pub enum Category {
#[derive(Clone, Debug)]
pub enum Message {
SetDefault(Category, usize),
Update(Arc<CachedMimeApps>),
Update(CachedMimeApps),
Surface(surface::Action),
}
@ -63,27 +68,28 @@ impl From<Message> for crate::pages::Message {
}
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct CachedMimeApps {
local_list: Option<(mime_apps::List, tokio::fs::File)>,
apps: Vec<AppMeta>,
known_mimes: BTreeSet<mime::Mime>,
pub list: mime_apps::List,
pub local_list: mime_apps::List,
pub apps: Vec<AppMeta>,
pub known_mimes: BTreeSet<mime::Mime>,
pub config_path: Box<Path>,
}
#[derive(Clone, Debug)]
pub struct AppMeta {
selected: Option<usize>,
app_ids: Vec<Box<str>>,
app_ids: Vec<String>,
apps: Vec<String>,
icons: Vec<icon::Handle>,
}
#[derive(Debug, Default)]
#[derive(Clone, Debug, Default)]
pub struct Page {
on_enter_handle: Option<cosmic::iced::task::Handle>,
mime_apps: Option<CachedMimeApps>,
shortcuts_config: Option<cosmic_config::Config>,
update_config: Option<tokio::task::JoinHandle<()>>,
}
impl page::AutoBind<crate::pages::Message> for Page {}
@ -107,45 +113,46 @@ impl page::Page<crate::pages::Message> for Page {
handle.abort();
}
let config_update_handle = self.update_config.take();
if self.shortcuts_config.is_none() {
self.shortcuts_config = cosmic_settings_config::shortcuts::context().ok();
}
let (task, on_enter_handle) = Task::future(async move {
// Wait for previous copy operation to complete.
if let Some(handle) = config_update_handle {
_ = handle.await;
}
let local_list = mime_apps::load_user_mimeapps().await.ok();
let mut list = mime_apps::List::default();
list.load_from_paths(&mime_apps::list_paths());
let assocs = mime_apps::associations::load_from_disk(&list);
let mut local_list = mime_apps::List::default();
if let Some(path) = mime_apps::local_list_path()
&& let Ok(buffer) = std::fs::read_to_string(&path)
{
local_list.load_from(&buffer);
}
let assocs = mime_apps::associations::by_app();
let apps = vec![
load_defaults(&list, &assocs, &["x-scheme-handler/http"]),
load_defaults(&list, &assocs, &["inode/directory"]),
load_defaults(&list, &assocs, &["x-scheme-handler/mailto"]),
load_defaults(
&list,
&assocs,
&["audio/mpeg", "application/ogg", "audio/x-flac", "video/mp4"],
),
load_defaults(&list, &assocs, &["video/mp4"]),
load_defaults(&list, &assocs, &["image/png"]),
load_defaults(&list, &assocs, &["text/calendar"]),
load_terminal_apps(&list, &assocs).await,
load_defaults(&list, &assocs, &["text/plain"]),
load_defaults(&assocs, &["x-scheme-handler/http"]).await,
load_defaults(&assocs, &["inode/directory"]).await,
load_defaults(&assocs, &["x-scheme-handler/mailto"]).await,
load_defaults(&assocs, &["audio/mp3", "application/ogg", "video/mp4"]).await,
load_defaults(&assocs, &["video/mp4"]).await,
load_defaults(&assocs, &["image/png"]).await,
load_defaults(&assocs, &["text/calendar"]).await,
load_terminal_apps(&assocs).await,
load_defaults(&assocs, &["text/plain"]).await,
];
Message::Update(Arc::new(CachedMimeApps {
Message::Update(CachedMimeApps {
apps,
list,
local_list,
known_mimes: mime_apps::mime_info::mime_types(),
}))
config_path: dirs::config_dir()
.expect("config dir not found")
.join("mimeapps.list")
.into(),
})
.into()
})
.abortable();
@ -186,7 +193,6 @@ impl Page {
"application/ogg",
"application/x-cue",
"application/x-ogg",
"audio/mpeg",
"audio/mp3",
"x-content/audio-cdda",
])
@ -231,16 +237,13 @@ impl Page {
"x-scheme-handler/https",
],
),
Category::TextEditor => (
DROPDOWN_TEXT_EDITOR,
&["application/x-zerosize", "text/plain"],
),
Category::TextEditor => (DROPDOWN_TEXT_EDITOR, &["text/plain"]),
Category::Mime(_mime_type) => return Task::none(),
};
let meta = &mut mime_apps.apps[category_id];
if meta.selected.is_none_or(|selected| selected != id) {
if meta.selected != Some(id) {
meta.selected = Some(id);
let appid = &meta.app_ids[id];
@ -251,40 +254,24 @@ impl Page {
assign_default_terminal(config, appid);
}
if let Some((local_list, local_file)) = mime_apps.local_list.as_mut() {
for mime in mime_types {
if let Ok(mime) = mime.parse() {
tracing::info!(target: "default-apps", ?mime, appid, "setting default for mime");
local_list.set_default_app(mime, [appid, ".desktop"].concat());
};
}
if let Some(config_update_handle) = self.update_config.take() {
config_update_handle.abort();
}
let mut buffer = local_list.to_string();
buffer.push('\n');
if let Ok(mut local_file) =
futures::executor::block_on(local_file.try_clone())
{
self.update_config = Some(tokio::spawn(async move {
tracing::debug!(target: "default-apps", buffer, "writing to mimeapps config");
_ = local_file.seek(SeekFrom::Start(0)).await;
_ = local_file.set_len(buffer.len() as u64).await;
_ = local_file.write_all(buffer.as_bytes()).await;
_ = local_file.flush().await;
_ = local_file.seek(SeekFrom::Start(0)).await;
_ = tokio::process::Command::new("update-desktop-database")
.status()
.await;
}));
}
for mime in mime_types {
if let Ok(mime) = mime.parse() {
mime_apps
.local_list
.set_default_app(mime, [appid, ".desktop"].concat());
};
}
let mut buffer = mime_apps.local_list.to_string();
buffer.push('\n');
_ = std::fs::write(&mime_apps.config_path, buffer);
_ = std::process::Command::new("update-desktop-database").status();
}
}
Message::Update(mime_apps) => self.mime_apps = Arc::into_inner(mime_apps),
Message::Update(mime_apps) => {
self.mime_apps = Some(mime_apps);
}
Message::Surface(a) => {
return cosmic::task::message(crate::app::Message::Surface(a));
}
@ -294,83 +281,269 @@ impl Page {
}
}
fn app_item(meta: &AppMeta, label: String, category: Category) -> widget::FlexRow<'_, Message> {
// Avoid creating popup_dropdown for empty app lists.
// Empty categories are rendered as non-interactive text to prevent Wayland crashes.
settings::flex_item(
label,
if meta.apps.is_empty() {
widget::text(fl!("default-apps", "not-installed")).apply(Element::from)
} else {
dropdown::popup_dropdown(
&meta.apps,
Some(meta.selected.unwrap_or(0)),
move |id| Message::SetDefault(category, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| crate::app::Message::PageMessage(crate::pages::Message::DefaultApps(a)),
)
.icons(Cow::Borrowed(&meta.icons))
.apply(Element::from)
},
)
.align_items(Alignment::Center)
.width(Length::Shrink)
}
fn apps() -> Section<crate::pages::Message> {
Section::default().view::<Page>(move |_binder, page, section| {
let Some(mime_apps) = page.mime_apps.as_ref() else {
return widget::space().into();
};
settings::section::with_capacity(9)
// Avoid creating popup_dropdown for empty app lists.
// Empty categories are rendered as non-interactive text to prevent Wayland crashes.
settings::section()
.title(&section.title)
.add(app_item(
&mime_apps.apps[DROPDOWN_WEB_BROWSER],
fl!("default-apps", "web-browser"),
Category::WebBrowser,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_FILE_MANAGER],
fl!("default-apps", "file-manager"),
Category::FileManager,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_MAIL],
fl!("default-apps", "mail-client"),
Category::Mail,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_MUSIC],
fl!("default-apps", "music"),
Category::Audio,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_VIDEO],
fl!("default-apps", "video"),
Category::Video,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_PHOTO],
fl!("default-apps", "photos"),
Category::Image,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_CALENDAR],
fl!("default-apps", "calendar"),
Category::Calendar,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_TERMINAL],
fl!("default-apps", "terminal"),
Category::Terminal,
))
.add(app_item(
&mime_apps.apps[DROPDOWN_TEXT_EDITOR],
fl!("default-apps", "text-editor"),
Category::TextEditor,
))
.add({
let meta = &mime_apps.apps[DROPDOWN_WEB_BROWSER];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "web-browser"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "web-browser"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::WebBrowser, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
.min_item_width(300.0)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_FILE_MANAGER];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "file-manager"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "file-manager"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::FileManager, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_MAIL];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "mail-client"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "mail-client"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::Mail, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_MUSIC];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "music"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "music"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::Audio, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_VIDEO];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "video"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "video"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::Video, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_PHOTO];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "photos"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "photos"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::Image, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_CALENDAR];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "calendar"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "calendar"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::Calendar, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_TERMINAL];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "terminal"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "terminal"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::Terminal, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.add({
let meta = &mime_apps.apps[DROPDOWN_TEXT_EDITOR];
if meta.apps.is_empty() {
settings::flex_item(
fl!("default-apps", "text-editor"),
widget::text(fl!("default-apps", "not-installed")),
)
.align_items(Alignment::Center)
} else {
settings::flex_item(
fl!("default-apps", "text-editor"),
dropdown::popup_dropdown(
&meta.apps,
meta.selected,
|id| Message::SetDefault(Category::TextEditor, id),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
|a| {
crate::app::Message::PageMessage(
crate::pages::Message::DefaultApps(a),
)
},
)
.icons(Cow::Borrowed(&meta.icons)),
)
.align_items(Alignment::Center)
}
})
.apply(Element::from)
.map(crate::pages::Message::DefaultApps)
})
@ -411,71 +584,57 @@ fn assign_default_terminal(config: &cosmic_config::Config, appid: &str) {
}
}
fn load_defaults(
list: &mime_apps::List,
assocs: &mime_apps::Associations,
for_mimes: &[&str],
) -> AppMeta {
async fn load_defaults(assocs: &BTreeMap<Arc<str>, Arc<App>>, for_mimes: &[&str]) -> AppMeta {
let mut unsorted = Vec::new();
let mut default_app = None;
let mut current_app = None;
for for_mime in for_mimes {
let Ok(mime) = Mime::from_str(for_mime) else {
continue;
let Ok(mime) = for_mime.parse() else {
return AppMeta {
selected: None,
app_ids: Vec::new(),
apps: Vec::new(),
icons: Vec::new(),
};
};
for default in list.default_app_for(&mime).into_iter().flatten() {
let appid = default.strip_suffix(".desktop").unwrap_or(default.as_ref());
let current_app_entry = xdg_mime_query_default(for_mime).await;
let current_appid = current_app_entry
.as_ref()
.and_then(|entry| entry.strip_suffix(".desktop"));
tracing::info!(target: "default-apps", ?mime, appid, "entry for mime");
if default_app.is_none() {
default_app = assocs.by_app_id.get(appid);
if default_app.is_some() {
break;
}
}
if unsorted.is_empty() {
current_app = current_appid.and_then(|appid| assocs.get(appid));
}
for (appid, app) in mime_apps::apps_for_mime(&mime, assocs) {
if app.icon.is_none() {
continue;
}
if unsorted.iter().any(|(id, _)| id == appid) {
continue;
}
unsorted.push((appid.clone(), app.clone()));
}
unsorted.extend(
mime_apps::apps_for_mime(&mime, assocs)
.map(|(app_id, app)| (app_id.clone(), app.clone())),
);
}
unsorted.sort_unstable_by_key(|(_, app)| app.name.clone());
unsorted.dedup_by_key(|(app_id, _)| app_id.clone());
let mut selected = None;
let mut app_ids = Vec::new();
let mut apps = Vec::new();
let mut icons = Vec::new();
let mut id = 0;
for (appid, app) in unsorted.iter() {
let Some(icon) = app.icon.as_deref() else {
continue;
};
if let Some(default_app) = default_app
&& app.name.as_ref() == default_app.name.as_ref()
for (id, (appid, app)) in unsorted.iter().enumerate() {
if let Some(current_app) = current_app
&& app.name.as_ref() == current_app.name.as_ref()
{
selected = Some(id);
}
app_ids.push(appid.as_ref().into());
apps.push(app.name.as_ref().into());
icons.push(if icon.starts_with('/') {
icon::from_path(PathBuf::from(icon))
icons.push(if app.icon.starts_with('/') {
icon::from_path(PathBuf::from(app.icon.as_ref()))
} else {
icon::from_name(icon).size(20).handle()
icon::from_name(app.icon.as_ref()).size(20).handle()
});
id += 1;
}
AppMeta {
@ -486,55 +645,86 @@ fn load_defaults(
}
}
async fn load_terminal_apps(list: &mime_apps::List, assocs: &mime_apps::Associations) -> AppMeta {
let mut selected = None;
let mut app_ids = Vec::new();
let mut apps = Vec::new();
let mut icons = Vec::new();
async fn xdg_mime_query_default(mime_type: &str) -> Option<String> {
let output = tokio::process::Command::new("xdg-mime")
.args(["query", "default", mime_type])
.output()
.await
.ok()?;
let mut terminals: Vec<_> = assocs
.apps
.iter()
.filter(|app| app.is_terminal && app.icon.is_some())
.collect();
if !output.status.success() {
return None;
}
terminals.sort_unstable_by_key(|app| app.name.clone());
String::from_utf8(output.stdout)
.ok()
.map(|string| string.trim().to_owned())
}
'outer: for for_mime in [
"x-scheme-handler/terminal",
"application/x-terminal-emulator",
] {
let Ok(mime) = Mime::from_str(for_mime) else {
continue;
};
async fn load_terminal_apps(assocs: &BTreeMap<Arc<str>, Arc<App>>) -> AppMeta {
let mut terminals = Vec::new();
let mut current_app = None;
for default in list.default_app_for(&mime).into_iter().flatten() {
let appid = default.strip_suffix(".desktop").unwrap_or(default.as_ref());
// Get the current default terminal if set
let current_entry = xdg_mime_query_default("x-scheme-handler/terminal").await;
let current_appid = current_entry
.as_ref()
.and_then(|entry| entry.strip_suffix(".desktop"));
for (id, app) in terminals.iter().enumerate() {
if app.appid.as_ref() == appid {
selected = Some(id);
break 'outer;
// Also check x-terminal-emulator
if current_app.is_none() {
let current_entry = xdg_mime_query_default("application/x-terminal-emulator").await;
let current_appid = current_entry
.as_ref()
.and_then(|entry| entry.strip_suffix(".desktop"));
if let Some(appid) = current_appid {
current_app = assocs.get(appid).cloned();
}
}
// Scan desktop entries for terminal applications
for path in DesktopEntryIter::new(default_paths()) {
if let Ok(bytes) = std::fs::read_to_string(&path)
&& let Ok(entry) = DesktopEntry::from_str(&path, &bytes, None::<&[&str]>)
{
// Check if it's a terminal application
if entry
.categories()
.map(|cats| cats.contains(&"TerminalEmulator"))
.unwrap_or(false)
{
let id = entry.id();
if let Some(app) = assocs.get(id) {
if current_appid.as_ref().map(|c| *c == id).unwrap_or(false) {
current_app = Some(app.clone());
}
terminals.push((Arc::from(id), app.clone()));
}
}
}
}
for (id, app) in terminals.into_iter().enumerate() {
let Some(icon) = app.icon.as_deref() else {
continue;
};
terminals.sort_unstable_by_key(|(_, app): &(Arc<str>, Arc<App>)| app.name.clone());
terminals.dedup_by(|a, b| a.0 == b.0);
if selected.is_none() && app.appid.as_ref() == "com.system76.CosmicTerm" {
let mut selected = None;
let mut app_ids = Vec::new();
let mut apps = Vec::new();
let mut icons = Vec::new();
for (id, (appid, app)) in terminals.iter().enumerate() {
if let Some(ref current_app) = current_app
&& app.name.as_ref() == current_app.name.as_ref()
{
selected = Some(id);
}
app_ids.push(app.appid.clone());
app_ids.push(appid.to_string());
apps.push(app.name.as_ref().into());
icons.push(if icon.starts_with('/') {
icon::from_path(PathBuf::from(icon))
icons.push(if app.icon.starts_with('/') {
icon::from_path(PathBuf::from(app.icon.as_ref()))
} else {
icon::from_name(icon).size(20).handle()
icon::from_name(app.icon.as_ref()).size(20).handle()
});
}

View file

@ -1,17 +1,25 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use std::process::ExitStatus;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{
process::ExitStatus,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use cosmic::cosmic_config::{self, ConfigGet, ConfigSet};
use cosmic::iced::stream;
use cosmic::widget::{self, dropdown, settings, text};
use cosmic::{Apply, Element, Task, surface};
use cosmic::{
Apply, Element, Task,
cosmic_config::{self, ConfigGet, ConfigSet},
iced::stream,
surface,
widget::{self, dropdown, settings, text},
};
use cosmic_comp_config::{EavesdroppingKeyboardMode, XwaylandDescaling, XwaylandEavesdropping};
use cosmic_randr_shell::List;
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use futures::SinkExt;
use slotmap::SlotMap;
use tokio::sync::oneshot;

View file

@ -1,8 +1,7 @@
use cosmic::app::ContextDrawer;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::text_input::focus;
use cosmic::widget::{button, icon, settings, text};
use cosmic::{Apply, Element, Task, task, widget};
use cosmic::{Apply, Element, Task, widget};
use cosmic_settings_page::section::Entity;
use cosmic_settings_page::{self as page, Content, Info, Section};
use freedesktop_desktop_entry::DesktopEntry;
@ -10,12 +9,8 @@ use itertools::Itertools;
use slotmap::{Key, SlotMap};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::LazyLock;
use tracing::error;
pub static ADD_APPLICATION_SEARCH: LazyLock<widget::Id> =
LazyLock::new(|| widget::Id::new("ADD_APPLICATION_SEARCH"));
#[derive(Clone, Debug)]
pub struct CachedApps {
apps: HashMap<DirectoryType, Vec<DesktopEntry>>,
@ -56,7 +51,6 @@ pub enum Message {
ShowApplicationSidebar(DirectoryType),
UpdateApplications(CachedApps),
UpdateStartupApplications(CachedApps),
FocusAddApplicationSearch,
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
@ -122,7 +116,6 @@ impl page::Page<crate::pages::Message> for Page {
let search = widget::search_input("", &self.application_search)
.on_input(|i| Message::ApplicationSearch(i).into())
.on_clear(Message::ApplicationSearch(String::new()).into())
.id(ADD_APPLICATION_SEARCH.clone())
.apply(Element::from);
Some(
@ -149,11 +142,8 @@ impl page::Page<crate::pages::Message> for Page {
let user_entries =
freedesktop_desktop_entry::Iter::new(user_dirs.into_iter()).entries(Some(&locales));
let mut user_entries_vec = user_entries.collect_vec();
sort_entries_by_name(&mut user_entries_vec, &locales);
let mut apps_hash = HashMap::with_capacity(1);
apps_hash.insert(DirectoryType::User, user_entries_vec);
apps_hash.insert(DirectoryType::User, user_entries.collect_vec());
Message::UpdateStartupApplications(CachedApps {
apps: apps_hash,
@ -227,8 +217,7 @@ impl Page {
}
Message::ShowApplicationSidebar(directory_type) => {
self.context = Some(Context::AddApplication(directory_type));
return cosmic::task::message(crate::app::Message::OpenContextDrawer(self.entity))
.chain(task::message(Message::FocusAddApplicationSearch));
return cosmic::task::message(crate::app::Message::OpenContextDrawer(self.entity));
}
Message::AddStartupApplication(directory_type, app) => {
let mut file_name = app.clone().appid;
@ -257,10 +246,6 @@ impl Page {
if let Some(target_apps) = target_apps {
let mut new_apps = target_apps.clone();
new_apps.push(app.clone());
sort_entries_by_name(
&mut new_apps,
&cached_startup_apps.locales,
);
cached_startup_apps
.apps
@ -327,26 +312,6 @@ impl Page {
self.target_directory_type = None;
self.context = None;
}
Message::FocusAddApplicationSearch => {
// retry until the widget is in the tree and focused or the dialog is removed.
if matches!(self.context, Some(Context::AddApplication(_))) {
return cosmic::iced::runtime::task::widget(
cosmic::iced::core::widget::operation::focusable::find_focused(),
)
.collect()
.then(|id| {
if id
.first()
.is_some_and(|id| *id == ADD_APPLICATION_SEARCH.clone())
{
Task::none()
} else {
focus(ADD_APPLICATION_SEARCH.clone())
.chain(task::message(Message::FocusAddApplicationSearch))
}
});
}
}
_ => {}
}
@ -468,14 +433,6 @@ fn apps() -> Section<crate::pages::Message> {
})
}
fn sort_entries_by_name(entries: &mut [DesktopEntry], locales: &[String]) {
entries.sort_by_cached_key(|e| {
e.name(locales)
.map(|n| n.to_lowercase())
.unwrap_or_else(|| e.appid.to_lowercase())
});
}
fn get_all_apps(locales: Vec<String>) -> Vec<DesktopEntry> {
let mut dedupe = HashSet::new();
@ -516,7 +473,5 @@ fn get_all_apps(locales: Vec<String>) -> Vec<DesktopEntry> {
dedupe.insert(app_id.to_owned());
}
sort_entries_by_name(&mut result, &locales);
result
}

View file

@ -3,8 +3,7 @@
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::{Alignment, Length, color};
use cosmic::widget::space::horizontal as horizontal_space;
use cosmic::widget::{self, settings, text};
use cosmic::widget::{self, settings, space::horizontal as horizontal_space, text};
use cosmic::{Apply, Element, Task, theme};
use cosmic_settings_bluetooth_subscription::*;
use cosmic_settings_page::{self as page, Section, section};
@ -12,35 +11,28 @@ use futures::channel::oneshot;
use futures::{SinkExt, StreamExt};
use slotmap::SlotMap;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock};
use std::sync::Arc;
use std::time::Duration;
use zbus::zvariant::OwnedObjectPath;
#[cfg(test)]
use crate::service_manager::MockServiceManager;
use crate::service_manager::ServiceManagerHandle;
static BLUETOOTH_PAGE_LABEL: LazyLock<String> = LazyLock::new(|| fl!("bluetooth"));
enum Dialog {
// RequestAuthorization {
// device: OwnedObjectPath,
// response: oneshot::Sender<bool>,
// },
RequestConfirmation {
device: String,
passkey: u32,
response: oneshot::Sender<bool>,
},
DisplayPasskey {
device: String,
passkey: u32,
entered: u16,
},
DisplayPinCode {
device: String,
pincode: String,
},
RenameDevice {
path: OwnedObjectPath,
name: String,
},
// RequestPasskey {
// device: OwnedObjectPath,
// response: oneshot::Sender<Option<u32>>,
// },
// RequestPinCode {
// device: OwnedObjectPath,
// response: oneshot::Sender<Option<String>>,
// },
}
#[derive(Default)]
@ -168,8 +160,6 @@ pub struct Page {
service_is_active: bool,
subscription: Option<tokio::sync::oneshot::Sender<()>>,
service_manager: ServiceManagerHandle,
}
impl page::Page<crate::pages::Message> for Page {
@ -179,19 +169,6 @@ impl page::Page<crate::pages::Message> for Page {
.description(fl!("xdg-entry-bluetooth-comment"))
}
fn header(&self) -> Option<Element<'_, crate::pages::Message>> {
if self.model.adapters.len() > 1 {
let (_, adapter) = self.model.get_selected_adapter()?;
return Some(crate::widget::sub_page_header(
&adapter.alias,
BLUETOOTH_PAGE_LABEL.as_str(),
Message::SelectAdapter(None).into(),
));
}
None
}
fn content(
&self,
sections: &mut SlotMap<section::Entity, Section<crate::pages::Message>>,
@ -278,108 +255,6 @@ impl page::Page<crate::pages::Message> for Page {
Some(dialog)
}
Dialog::DisplayPasskey {
device,
passkey,
entered,
} => {
let description = widget::text::body(fl!(
"bluetooth-display-passkey",
"description",
device = device
))
.wrapping(Wrapping::Word);
let passkey_str = format!("{passkey:06}");
let entered = *entered as usize;
let pin = widget::text::title1(passkey_str)
.width(Length::Fill)
.align_x(Alignment::Center)
.wrapping(Wrapping::None);
let mut control = widget::column::with_capacity(3).push(description).push(pin);
// Only show the key progress counter when the device actually
// reports keypress notifications. Most keyboards don't support
// this, so entered stays at 0 for the entire pairing process.
if entered > 0 {
let progress = widget::text::body(format!("{entered} / 6 keys entered"))
.width(Length::Fill)
.align_x(Alignment::Center)
.wrapping(Wrapping::None);
control = control.push(progress);
}
let control = control.spacing(theme::spacing().space_xxs);
let cancel_button =
widget::button::standard(fl!("cancel")).on_press(Message::PinCancel);
let dialog = widget::dialog()
.title(fl!("bluetooth-display-passkey"))
.control(control)
.secondary_action(cancel_button)
.apply(Element::from)
.map(Into::into);
Some(dialog)
}
Dialog::DisplayPinCode { device, pincode } => {
let description = widget::text::body(fl!(
"bluetooth-display-pin",
"description",
device = device
))
.wrapping(Wrapping::Word);
let pin = widget::text::title1(pincode.clone())
.width(Length::Fill)
.align_x(Alignment::Center)
.wrapping(Wrapping::None);
let control = widget::column::with_capacity(2)
.push(description)
.push(pin)
.spacing(theme::spacing().space_xxs);
let cancel_button =
widget::button::standard(fl!("cancel")).on_press(Message::PinCancel);
let dialog = widget::dialog()
.title(fl!("bluetooth-display-pin"))
.control(control)
.secondary_action(cancel_button)
.apply(Element::from)
.map(Into::into);
Some(dialog)
}
Dialog::RenameDevice { name, .. } => {
let is_valid = is_valid_bluetooth_alias(name);
let input = widget::text_input("", name)
.on_input(|value| Message::RenameDeviceInput(value))
.on_submit(|_| Message::RenameDeviceConfirm);
let rename_button = widget::button::suggested(fl!("rename"))
.on_press_maybe(is_valid.then_some(Message::RenameDeviceConfirm));
let cancel_button =
widget::button::standard(fl!("cancel")).on_press(Message::RenameDeviceCancel);
let dialog = widget::dialog()
.title(fl!("bluetooth-rename-device"))
.control(input)
.primary_action(rename_button)
.secondary_action(cancel_button)
.apply(Element::from)
.map(Into::into);
Some(dialog)
}
}
}
}
@ -396,10 +271,6 @@ pub enum Message {
PinConfirm,
PopupDevice(Option<OwnedObjectPath>),
PopupSetting(bool),
RenameDevice(OwnedObjectPath),
RenameDeviceInput(String),
RenameDeviceConfirm,
RenameDeviceCancel,
SelectAdapter(Option<OwnedObjectPath>),
ServiceActivate,
ServiceEnable,
@ -438,30 +309,6 @@ impl From<Event> for Message {
}
impl Page {
fn update_heading(&mut self) {
self.heading = if let Some((_, adapter)) = self.model.get_selected_adapter() {
fl!(
"bluetooth",
"status",
aliases = format!("“{}”", adapter.alias)
)
} else {
fl!(
"bluetooth",
"status",
aliases = self
.model
.adapters
.values()
.map(|adapter| format!("“{}”", adapter.alias))
.collect::<HashSet<String>>()
.into_iter()
.collect::<Vec<String>>()
.join(", ")
)
};
}
pub fn update(&mut self, message: Message) -> cosmic::Task<crate::Message> {
let span = tracing::span!(tracing::Level::INFO, "bluetooth::update");
let _span = span.enter();
@ -507,7 +354,28 @@ impl Page {
Event::SetAdapters(adapters) => {
let select_adapter = self.model.set_adapters(adapters);
self.update_heading();
if let Some((_, adapter)) = self.model.get_selected_adapter() {
self.heading = fl!(
"bluetooth",
"status",
aliases = format!("“{}”", adapter.alias)
);
} else {
self.heading = fl!(
"bluetooth",
"status",
aliases = self
.model
.adapters
.values()
.map(|adapter| format!("“{}”", adapter.alias))
.collect::<HashSet<String>>()
.into_iter()
.collect::<Vec<String>>()
.join(", ")
);
}
if let Some(adapter) = select_adapter {
return cosmic::task::message(Message::SelectAdapter(Some(adapter)));
@ -533,19 +401,6 @@ impl Page {
}
Event::UpdatedDevice(path, update) => {
// Dismiss passkey/pin display dialogs when pairing completes,
// since BlueZ may not always send Cancel after a successful pair.
if update
.iter()
.any(|u| matches!(u, DeviceUpdate::Paired(true)))
&& matches!(
self.dialog,
Some(Dialog::DisplayPasskey { .. } | Dialog::DisplayPinCode { .. })
)
{
self.dialog = None;
}
if let Some(existing) = self.model.devices.get_mut(&path) {
tracing::debug!("Device {} updated", existing.address);
existing.update(update);
@ -579,18 +434,7 @@ impl Page {
}
Event::DBusServiceUnknown => {
// D-Bus activation for org.bluez is absent. On systemd this usually
// means bluez isn't installed; on OpenRC it may be installed but lack
// the D-Bus service file. Check the service manager to disambiguate.
if self.service_manager.is_installed() {
// Service manager confirms the service exists — query its real state.
self.bluez_service_unknown = false;
self.service_is_active = self.service_manager.is_active();
self.service_is_enabled = self.service_manager.is_enabled();
} else {
// Genuinely not installed — let status() show the unknown message.
self.bluez_service_unknown = true;
}
self.bluez_service_unknown = true;
}
Event::Agent(message) => {
@ -620,32 +464,6 @@ impl Page {
});
}
bluez_zbus::agent1::Message::DisplayPasskey {
device,
passkey,
entered,
} => {
let device = self.model.devices.get(&device).map_or_else(
|| device.to_string(),
|device| device.alias_or_addr().to_owned(),
);
self.dialog = Some(Dialog::DisplayPasskey {
device,
passkey,
entered,
});
}
bluez_zbus::agent1::Message::DisplayPinCode { device, pincode } => {
let device = self.model.devices.get(&device).map_or_else(
|| device.to_string(),
|device| device.alias_or_addr().to_owned(),
);
self.dialog = Some(Dialog::DisplayPinCode { device, pincode });
}
bluez_zbus::agent1::Message::RequestPasskey { response, .. } => {
_ = response.send(None);
}
@ -661,10 +479,6 @@ impl Page {
_ => (),
}
}
Event::DeviceRenameFailed(path) => {
tracing::warn!("Failed to rename device {path}");
}
},
Message::PinCancel => {
@ -738,8 +552,8 @@ impl Page {
}
Message::DBusConnect(connection) => {
self.service_is_active = self.service_manager.is_active();
self.service_is_enabled = self.service_manager.is_enabled();
self.service_is_active = systemd::is_bluetooth_active();
self.service_is_enabled = systemd::is_bluetooth_enabled();
self.connection = Some(connection.clone());
let get_adapters_fut = get_adapters(connection.clone());
@ -794,7 +608,6 @@ impl Page {
Message::SelectAdapter(adapter_maybe) => {
tracing::debug!("Adapter selected: {adapter_maybe:?}");
self.model.selected_adapter = adapter_maybe;
self.update_heading();
self.model.update_status();
let Some(connection) = self.connection.as_ref() else {
tracing::error!("No DBus connection ready");
@ -871,46 +684,9 @@ impl Page {
}
}
Message::RenameDevice(path) => {
self.model.popup_device = None;
let name = self
.model
.devices
.get(&path)
.map_or_else(String::new, |d| d.alias_or_addr().to_owned());
self.dialog = Some(Dialog::RenameDevice { path, name });
}
Message::RenameDeviceInput(new_name) => {
if let Some(Dialog::RenameDevice { name, .. }) = &mut self.dialog {
*name = new_name;
}
}
Message::RenameDeviceCancel => {
if matches!(self.dialog, Some(Dialog::RenameDevice { .. })) {
self.dialog = None;
}
}
Message::RenameDeviceConfirm => {
if let Some(Dialog::RenameDevice { path, name }) = self.dialog.take() {
if let Some(connection) = self.connection.clone() {
return cosmic::task::future(rename_device(
connection,
path,
name.trim().into(),
));
} else {
tracing::warn!("No DBus connection ready");
}
}
}
Message::ServiceActivate => {
let activate_future = self.service_manager.activate();
return cosmic::task::future(async move {
activate_future.await;
return cosmic::task::future(async {
systemd::activate_bluetooth().await;
tokio::time::sleep(Duration::from_secs(3)).await;
match zbus::Connection::system().await {
@ -921,9 +697,8 @@ impl Page {
}
Message::ServiceEnable => {
let enable_future = self.service_manager.enable();
return cosmic::task::future(async move {
enable_future.await;
return cosmic::task::future(async {
systemd::enable_bluetooth().await;
tokio::time::sleep(Duration::from_secs(3)).await;
match zbus::Connection::system().await {
@ -982,7 +757,7 @@ fn status() -> Section<crate::pages::Message> {
return bluetooth_service_issue(
fl!("bluetooth", "inactive"),
fl!("activate"),
Message::ServiceActivate,
Message::ServiceEnable,
);
}
@ -1005,11 +780,6 @@ fn status() -> Section<crate::pages::Message> {
})
}
fn is_valid_bluetooth_alias(name: &str) -> bool {
let trimmed = name.trim();
!trimmed.is_empty() && trimmed.len() <= 248
}
fn popup_button(message: Option<Message>, text: &str) -> Element<'_, Message> {
let spacing = theme::spacing();
widget::text::body(text)
@ -1030,7 +800,6 @@ fn connected_devices() -> Section<crate::pages::Message> {
device_connect = fl!("bluetooth", "connect");
device_disconnect = fl!("bluetooth", "disconnect");
device_forget = fl!("bluetooth", "forget");
device_rename = fl!("rename");
});
Section::default()
@ -1068,17 +837,13 @@ fn connected_devices() -> Section<crate::pages::Message> {
.position(widget::popover::Position::Bottom)
.on_close(Message::PopupDevice(None))
.popup(
widget::column::with_capacity(3)
widget::column::with_capacity(2)
.push_maybe(device.is_connected().then(|| {
popup_button(
Some(Message::DisconnectDevice(path.clone())),
&descriptions[device_disconnect],
)
}))
.push(popup_button(
Some(Message::RenameDevice(path.clone())),
&descriptions[device_rename],
))
.push_maybe(device.paired.then(|| {
popup_button(
Some(Message::ForgetDevice(path.clone())),
@ -1245,110 +1010,36 @@ fn multiple_adapter() -> Section<crate::pages::Message> {
impl page::AutoBind<crate::pages::Message> for Page {}
impl Page {
#[cfg(test)]
fn with_service_manager(service_manager: ServiceManagerHandle) -> Self {
Self {
service_manager,
..Page::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use cosmic_settings_page::Page as _;
fn adapter(path: &str, alias: &str) -> (OwnedObjectPath, Adapter) {
(
OwnedObjectPath::try_from(path).unwrap(),
Adapter {
alias: alias.to_owned(),
..Adapter::default()
},
)
}
fn page_with_two_adapters() -> Page {
let mut page = Page::default();
let adapters = [
adapter("/org/bluez/hci0", "Adapter 0"),
adapter("/org/bluez/hci1", "Adapter 1"),
]
.into_iter()
.collect();
let _task = page.update(Message::BluetoothEvent(Event::SetAdapters(adapters)));
page
}
#[test]
fn bluetooth_header_is_absent_at_adapter_chooser() {
let page = page_with_two_adapters();
assert!(page.header().is_none());
}
#[test]
fn bluetooth_header_tracks_adapter_selection_and_clearing() {
let mut page = page_with_two_adapters();
let selected = OwnedObjectPath::try_from("/org/bluez/hci1").unwrap();
let _task = page.update(Message::SelectAdapter(Some(selected)));
assert!(page.header().is_some());
assert!(page.heading.contains("Adapter 1"));
let _task = page.update(Message::SelectAdapter(None));
assert!(page.header().is_none());
assert!(page.heading.contains("Adapter 0"));
assert!(page.heading.contains("Adapter 1"));
}
#[test]
fn test_dbus_service_unknown_with_installed_service_queries_manager() {
let bluetooth = MockServiceManager::new(true, false);
let mut page = Page::with_service_manager(ServiceManagerHandle::new(Box::new(bluetooth)));
let _task = page.update(Message::BluetoothEvent(Event::DBusServiceUnknown));
assert!(page.service_is_enabled);
assert!(!page.service_is_active);
assert!(!page.bluez_service_unknown);
}
#[test]
fn test_dbus_service_unknown_with_uninstalled_service_sets_bluez_unknown() {
let bluetooth = MockServiceManager::new(true, true).with_installed(false);
let mut page = Page::with_service_manager(ServiceManagerHandle::new(Box::new(bluetooth)));
let _task = page.update(Message::BluetoothEvent(Event::DBusServiceUnknown));
assert!(page.bluez_service_unknown);
assert!(!page.service_is_enabled);
assert!(!page.service_is_active);
}
#[test]
fn test_dbus_service_unknown_clears_previously_set_bluez_service_unknown() {
// Simulate a stale state and verify the handler re-checks via is_installed().
let bluetooth = MockServiceManager::new(true, true);
let mut page = Page::with_service_manager(ServiceManagerHandle::new(Box::new(bluetooth)));
page.bluez_service_unknown = true;
let _task = page.update(Message::BluetoothEvent(Event::DBusServiceUnknown));
assert!(!page.bluez_service_unknown);
}
#[tokio::test]
async fn test_service_activate_calls_through_to_service_manager() {
let bluetooth = MockServiceManager::new(false, false);
let mut page = Page::with_service_manager(ServiceManagerHandle::new(Box::new(bluetooth)));
let _task = page.update(Message::ServiceActivate);
}
#[tokio::test]
async fn test_service_enable_calls_through_to_service_manager() {
let bluetooth = MockServiceManager::new(false, false);
let mut page = Page::with_service_manager(ServiceManagerHandle::new(Box::new(bluetooth)));
let _task = page.update(Message::ServiceEnable);
mod systemd {
use futures::FutureExt;
pub fn activate_bluetooth() -> impl Future<Output = ()> + Send {
tokio::process::Command::new("pkexec")
.args(["systemctl", "start", "bluetooth"])
.status()
.map(|_| ())
}
pub fn enable_bluetooth() -> impl Future<Output = ()> + Send {
tokio::process::Command::new("pkexec")
.args(["systemctl", "enable", "--now", "bluetooth"])
.status()
.map(|_| ())
}
pub fn is_bluetooth_enabled() -> bool {
std::process::Command::new("systemctl")
.args(["is-enabled", "bluetooth"])
.status()
.map(|status| status.success())
.unwrap_or(true)
}
pub fn is_bluetooth_active() -> bool {
std::process::Command::new("systemctl")
.args(["is-active", "bluetooth"])
.status()
.map(|status| status.success())
.unwrap_or(true)
}
}

View file

@ -2,11 +2,12 @@ use cosmic::app::{ContextDrawer, context_drawer};
use cosmic::config::CosmicTk;
use cosmic::cosmic_config::{Config, ConfigSet};
use cosmic::cosmic_theme::Spacing;
use cosmic::iced::Alignment;
use cosmic::iced::core::{Color, Length};
use cosmic::widget::color_picker::ColorPickerUpdate;
use cosmic::widget::{ColorPickerModel, container, flex_row, row, settings, slider, text};
use cosmic::{Apply, Element, Task, task, widget};
use cosmic::widget::{
ColorPickerModel, color_picker::ColorPickerUpdate, container, flex_row, settings, text,
};
use cosmic::{Apply, Task};
use cosmic::{Element, widget};
use cosmic_config::ConfigGet;
use std::sync::Arc;
use tracing::error;
@ -14,8 +15,11 @@ use tracing::error;
use crate::app;
use crate::widget::color_picker_context_view;
use super::icon_themes::{IconHandles, IconThemes};
use super::{ContextView, Message, font_config, icon_themes, theme_manager};
use super::{
ContextView, Message, font_config, icon_themes,
icon_themes::{IconHandles, IconThemes},
theme_manager,
};
pub struct Content {
context_view: Option<ContextView>,
@ -36,12 +40,6 @@ pub struct Content {
icon_themes: IconThemes,
icon_handles: IconHandles,
tk_config: Option<Config>,
frosted: u8,
glass: f32,
frosted_system_interface: bool,
frosted_windows: bool,
frosted_panel: bool,
frosted_applets: bool,
comp_config: cosmic_config::Config,
#[cfg(feature = "cosmic-comp-config")]
@ -96,7 +94,7 @@ impl From<&theme_manager::Manager> for Content {
application_background: ColorPickerModel::new(
&*HEX,
&*RGB,
Some(theme.background(false).base.into()),
Some(theme.background.base.into()),
theme_manager.get_color(&ContextView::ApplicationBackground),
),
container_background: ColorPickerModel::new(
@ -108,7 +106,7 @@ impl From<&theme_manager::Manager> for Content {
interface_text: ColorPickerModel::new(
&*HEX,
&*RGB,
Some(theme.background(false).on.into()),
Some(theme.background.on.into()),
theme_manager.get_color(&ContextView::InterfaceText),
),
control_component: ColorPickerModel::new(
@ -124,12 +122,6 @@ impl From<&theme_manager::Manager> for Content {
theme_manager.get_color(&ContextView::AccentWindowHint),
),
font_config: font_config::Model::new(),
frosted: theme.frosted as u8,
glass: theme.alpha_map.guess_offset(),
frosted_system_interface: theme.frosted_system_interface,
frosted_windows: theme.frosted_windows,
frosted_panel: theme.frosted_panel,
frosted_applets: theme.frosted_applets,
icons_fetched: false,
icon_global: cosmic::config::apply_theme_global(),
icon_fetch_handle: None,
@ -153,16 +145,6 @@ impl Content {
}
}
pub fn preserve_from(&mut self, previous: &mut Content) {
self.font_config
.take_families_from(&mut previous.font_config);
self.icons_fetched = previous.icons_fetched;
self.icon_theme_active = previous.icon_theme_active;
self.icon_themes = std::mem::take(&mut previous.icon_themes);
self.icon_handles = std::mem::take(&mut previous.icon_handles);
}
pub fn update_font(
&mut self,
message: FontMessage,
@ -303,40 +285,6 @@ impl Content {
Task::none()
}
pub fn update_frosted_system_interface(&mut self, v: bool) -> Task<app::Message> {
self.frosted_system_interface = v;
Task::none()
}
pub fn update_frosted_windows(&mut self, v: bool) -> Task<app::Message> {
self.frosted_windows = v;
Task::none()
}
pub fn update_frosted_panel(&mut self, v: bool) -> Task<app::Message> {
self.frosted_panel = v;
Task::none()
}
pub fn update_frosted_applets(&mut self, v: bool) -> Task<app::Message> {
self.frosted_applets = v;
Task::none()
}
pub fn update_blur(&mut self, v: u8) -> Task<app::Message> {
self.frosted = v;
Task::none()
}
pub fn update_glass(&mut self, v: f32) -> Task<app::Message> {
self.glass = v;
Task::none()
}
pub fn on_open(&mut self, context_view: &ContextView) -> Task<app::Message> {
match *context_view {
ContextView::IconsAndToolkit => {
@ -352,7 +300,6 @@ impl Content {
}
ContextView::MonospaceFont | ContextView::SystemFont => {
self.font_config.reset();
return task::message(super::Message::FocusFontInput);
}
_ => {}
}
@ -384,7 +331,7 @@ impl Content {
self.application_background = ColorPickerModel::new(
&*HEX,
&*RGB,
Some(manager.theme().background(false).base.into()),
Some(manager.theme().background.base.into()),
manager.get_color(&ContextView::ApplicationBackground),
);
self.custom_accent = ColorPickerModel::new(
@ -402,7 +349,7 @@ impl Content {
self.interface_text = ColorPickerModel::new(
&*HEX,
&*RGB,
Some(manager.theme().background(false).on.into()),
Some(manager.theme().background.on.into()),
manager.get_color(&ContextView::InterfaceText),
);
self.control_component = ColorPickerModel::new(
@ -528,10 +475,6 @@ impl Content {
self.shadow_and_corners(),
crate::pages::Message::CloseContextDrawer,
),
ContextView::FrostedGlass => context_drawer(
self.frosted_glass(),
crate::pages::Message::CloseContextDrawer,
),
})
}
@ -615,66 +558,4 @@ impl Content {
.apply(Element::from)
.map(crate::pages::Message::Appearance)
}
pub fn frosted_glass(&self) -> Element<'_, crate::pages::Message> {
settings::section()
.add(
settings::item::builder(fl!("style", "frosted-panels"))
.description(fl!("style", "frosted-panels-desc"))
.toggler(self.frosted_panel, Message::FrostedPanel),
)
.add(
settings::item::builder(fl!("style", "frosted-applets"))
.description(fl!("style", "frosted-applets-desc"))
.toggler(self.frosted_applets, Message::FrostedApplets),
)
.add(
settings::item::builder(fl!("style", "frosted-system-interface"))
.description(fl!("style", "frosted-system-interface-desc"))
.toggler(
self.frosted_system_interface,
Message::FrostedSystemInterface,
),
)
.add(
settings::item::builder(fl!("style", "frosted-windows"))
.description(fl!("style", "frosted-windows-desc"))
.toggler(self.frosted_windows, Message::FrostedWindows),
)
.add(
settings::item::builder(fl!("style", "frosted-thickness")).flex_control({
row::with_children(vec![
text::body(fl!("style", "less")).into(),
slider(0..=13, self.frosted, Message::Blur)
.width(Length::Fill)
.apply(cosmic::widget::container)
.max_width(250)
.into(),
text::body(fl!("style", "more")).into(),
])
.align_y(Alignment::Center)
.spacing(8)
.width(Length::Fill)
}),
)
.add(
settings::item::builder(fl!("style", "glass-opacity")).flex_control({
row::with_children(vec![
text::body(fl!("style", "less")).into(),
slider(0.0..=1.0, self.glass, Message::Glass)
.step(0.05)
.width(Length::Fill)
.apply(cosmic::widget::container)
.max_width(250)
.into(),
text::body(fl!("style", "more")).into(),
])
.align_y(Alignment::Center)
.spacing(8)
.width(Length::Fill)
}),
)
.apply(Element::from)
.map(crate::pages::Message::Appearance)
}
}

View file

@ -1,10 +1,13 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use std::sync::{Arc, LazyLock};
use std::sync::Arc;
use cosmic::config::{CosmicTk, FontConfig};
use cosmic::{Apply, Element, Task, widget};
use cosmic::{
Apply, Element, Task,
config::{CosmicTk, FontConfig},
widget,
};
use cosmic_config::ConfigSet;
use crate::app;
@ -12,8 +15,6 @@ use crate::widget::selection_context_item;
use super::{ContextView, Message, drawer};
pub static FONT_SEARCH: LazyLock<widget::Id> = LazyLock::new(|| widget::Id::new("FONT_SEARCH"));
const INTERFACE_FONT: &str = "interface_font";
const MONOSPACE_FONT: &str = "monospace_font";
@ -93,11 +94,6 @@ impl Model {
self.font_filter.clear();
}
pub fn take_families_from(&mut self, other: &mut Model) {
self.interface_font_families = std::mem::take(&mut other.interface_font_families);
self.monospace_font_families = std::mem::take(&mut other.monospace_font_families);
}
pub fn font_loaded(
&mut self,
mono: Vec<Arc<str>>,
@ -171,7 +167,6 @@ impl Model {
.on_clear(Message::DrawerFont(drawer::FontMessage::Search(
String::new(),
)))
.id(FONT_SEARCH.clone())
.apply(Element::from)
.map(crate::pages::Message::Appearance)
}

View file

@ -1,13 +1,14 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::{collections::BTreeMap, path::PathBuf};
use super::Message;
use cosmic::Element;
use cosmic::iced::{Background, Length};
use cosmic::widget::{button, icon, text};
use cosmic::{
Element,
iced::{Background, Length},
widget::{button, icon, text},
};
use tokio::io::AsyncBufReadExt;
const ICON_PREV_N: usize = 6;

View file

@ -16,24 +16,23 @@ use cosmic::app::ContextDrawer;
use cosmic::config::CosmicTk;
use cosmic::cosmic_config::{Config, ConfigSet, CosmicConfigEntry};
use cosmic::cosmic_theme::palette::{FromColor, Hsv, Srgb};
use cosmic::cosmic_theme::{CornerRadii, Density, Roundness, ThemeBuilder, ThemeMode};
use cosmic::cosmic_theme::{CornerRadii, Density, ThemeBuilder, ThemeMode};
#[cfg(feature = "xdg-portal")]
use cosmic::dialog::file_chooser::{self, FileFilter};
use cosmic::iced::Subscription;
use cosmic::iced::core::{Alignment, Length};
use cosmic::widget::color_picker::ColorPickerUpdate;
use cosmic::widget::space::horizontal;
use cosmic::widget::text_input::focus;
use cosmic::widget::{button, container, row, settings, text};
use cosmic::{Apply, Element, Task, task, widget};
use cosmic::widget::{
button, color_picker::ColorPickerUpdate, container, row, settings, space::horizontal, text,
};
use cosmic::{Apply, Element, Task, widget};
#[cfg(feature = "wayland")]
use cosmic_panel_config::CosmicPanelConfig;
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use ron::ser::PrettyConfig;
use slotmap::{Key, SlotMap};
use crate::app;
use crate::pages::desktop::appearance::font_config::FONT_SEARCH;
#[derive(Clone, Copy, Debug)]
pub enum ContextView {
@ -41,7 +40,6 @@ pub enum ContextView {
ApplicationBackground,
ContainerBackground,
ControlComponent,
FrostedGlass,
#[cfg(feature = "cosmic-comp-config")]
ShadowAndCorners,
CustomAccent,
@ -141,7 +139,6 @@ pub enum Message {
#[cfg(feature = "xdg-portal")]
ExportSuccess,
FocusFontInput,
GapSize(u32),
#[cfg(feature = "xdg-portal")]
ImportError,
@ -160,12 +157,6 @@ pub enum Message {
UseDefaultWindowHint(bool),
WindowHintSize(u32),
Daytime(bool),
Blur(u8),
Glass(f32),
FrostedPanel(bool),
FrostedApplets(bool),
FrostedSystemInterface(bool),
FrostedWindows(bool),
}
impl From<Message> for crate::app::Message {
@ -180,6 +171,56 @@ impl From<Message> for crate::pages::Message {
}
}
#[derive(Debug, Clone, Copy)]
pub enum Roundness {
Round,
SlightlyRound,
Square,
}
impl From<Roundness> for CornerRadii {
fn from(value: Roundness) -> Self {
match value {
Roundness::Round => CornerRadii {
radius_0: [0.0; 4],
radius_xs: [4.0; 4],
radius_s: [8.0; 4],
radius_m: [16.0; 4],
radius_l: [32.0; 4],
radius_xl: [160.0; 4],
},
Roundness::SlightlyRound => CornerRadii {
radius_0: [0.0; 4],
radius_xs: [2.0; 4],
radius_s: [8.0; 4],
radius_m: [8.0; 4],
radius_l: [8.0; 4],
radius_xl: [8.0; 4],
},
Roundness::Square => CornerRadii {
radius_0: [0.0; 4],
radius_xs: [2.0; 4],
radius_s: [2.0; 4],
radius_m: [2.0; 4],
radius_l: [2.0; 4],
radius_xl: [2.0; 4],
},
}
}
}
impl From<CornerRadii> for Roundness {
fn from(value: CornerRadii) -> Self {
if (value.radius_m[0] - 16.0).abs() < 0.01 {
Self::Round
} else if (value.radius_m[0] - 8.0).abs() < 0.01 {
Self::SlightlyRound
} else {
Self::Square
}
}
}
impl Page {
#[allow(clippy::too_many_lines)]
pub fn update(&mut self, message: Message) -> Task<app::Message> {
@ -200,9 +241,6 @@ impl Page {
Message::DrawerOpen(context_view) => {
self.context_view = Some(context_view);
let mut previous =
std::mem::replace(&mut self.drawer, drawer::Content::from(&self.theme_manager));
self.drawer.preserve_from(&mut previous);
tasks.push(cosmic::task::message(
crate::app::Message::OpenContextDrawer(self.entity),
));
@ -251,8 +289,8 @@ impl Page {
#[cfg(feature = "wayland")]
tokio::task::spawn(async move {
Self::update_dock_padding(r);
Self::update_panel_radii(r);
Self::update_dock_padding(r);
});
}
@ -518,86 +556,6 @@ impl Page {
self.drawer.reset(&self.theme_manager);
}
}
Message::FocusFontInput => {
// retry until the widget is in the tree and focused or the dialog is removed.
if matches!(
self.context_view,
Some(ContextView::SystemFont | ContextView::MonospaceFont)
) {
return cosmic::iced::runtime::task::widget(
cosmic::iced::core::widget::operation::focusable::find_focused(),
)
.collect()
.then(|id| {
if id.first().is_some_and(|id| *id == FONT_SEARCH.clone()) {
Task::none()
} else {
focus(FONT_SEARCH.clone()).chain(task::message(Message::FocusFontInput))
}
});
}
}
Message::Blur(b) => {
let Ok(blur_strength) = b.try_into() else {
tracing::error!("Invalid blur strength: {b}");
return Task::none();
};
theme_staged = self.theme_manager.set_frosted(blur_strength).map(|_| {
self.drawer.reset(&self.theme_manager);
theme_manager::ThemeStaged::Current
});
tasks.push(self.drawer.update_blur(blur_strength as u8));
}
Message::Glass(glass) => {
let mut alpha_map = cosmic::cosmic_theme::AlphaMap::default();
let glass_offset_min = alpha_map.extremely_high_2;
let glass_offset_max = 1.0 - alpha_map.extremely_low;
let offset = (glass - 0.5) / 0.5
* if glass < 0.5 {
glass_offset_min
} else {
glass_offset_max
};
alpha_map = alpha_map.offset(offset);
// TODO optimize and apply to both light and dark themes
theme_staged = self.theme_manager.set_glass(alpha_map).map(|_| {
self.drawer.reset(&self.theme_manager);
theme_manager::ThemeStaged::Current
});
tasks.push(self.drawer.update_glass(glass));
}
Message::FrostedSystemInterface(v) => {
theme_staged = self.theme_manager.set_frosted_system_interface(v).map(|_| {
self.drawer.reset(&self.theme_manager);
theme_manager::ThemeStaged::Current
});
tasks.push(self.drawer.update_frosted_system_interface(v));
}
Message::FrostedWindows(v) => {
theme_staged = self.theme_manager.set_frosted_windows(v).map(|_| {
self.drawer.reset(&self.theme_manager);
theme_manager::ThemeStaged::Current
});
tasks.push(self.drawer.update_frosted_windows(v));
}
Message::FrostedPanel(v) => {
theme_staged = self.theme_manager.set_frosted_panel(v).map(|_| {
self.drawer.reset(&self.theme_manager);
theme_manager::ThemeStaged::Current
});
tasks.push(self.drawer.update_frosted_panel(v));
}
Message::FrostedApplets(v) => {
theme_staged = self.theme_manager.set_frosted_applets(v).map(|_| {
self.drawer.reset(&self.theme_manager);
theme_manager::ThemeStaged::Current
});
tasks.push(self.drawer.update_frosted_applets(v));
}
}
let mut tasks = cosmic::Task::batch(tasks);
@ -612,66 +570,113 @@ impl Page {
}
// TODO: cache panel and dock configs so that they needn't be re-read
#[cfg(feature = "wayland")]
fn load_panel_config(name: &str) -> Option<(Config, CosmicPanelConfig)> {
let helper = CosmicPanelConfig::cosmic_config(name).ok()?;
let config = CosmicPanelConfig::get_entry(&helper).ok()?;
(config.name == name).then_some((helper, config))
}
#[cfg(feature = "wayland")]
pub fn update_panel_radii(roundness: Roundness) {
let corner_radii: CornerRadii = roundness.into();
let radius = corner_radii.radius_xl[0] as u32;
let panel_config_helper = CosmicPanelConfig::cosmic_config("Panel").ok();
let dock_config_helper = CosmicPanelConfig::cosmic_config("Dock").ok();
for name in ["Panel", "Dock"] {
let Some((helper, mut config)) = Self::load_panel_config(name) else {
continue;
};
let mut panel_config = panel_config_helper.as_ref().and_then(|config_helper| {
let panel_config = CosmicPanelConfig::get_entry(config_helper).ok()?;
(panel_config.name == "Panel").then_some(panel_config)
});
let new_radius = if config.anchor_gap {
radius
} else if !config.expand_to_edges {
radius.min(12)
let mut dock_config = dock_config_helper.as_ref().and_then(|config_helper| {
let panel_config = CosmicPanelConfig::get_entry(config_helper).ok()?;
(panel_config.name == "Dock").then_some(panel_config)
});
if let Some(panel_config_helper) = panel_config_helper.as_ref()
&& let Some(panel_config) = panel_config.as_mut()
{
let radii = if panel_config.anchor_gap {
let cornder_radii: CornerRadii = roundness.into();
cornder_radii.radius_xl[0] as u32
} else if matches!(roundness, Roundness::Round) && !panel_config.expand_to_edges {
12
} else {
0
};
if let Err(why) = config.set_border_radius(&helper, new_radius) {
tracing::error!(?why, "Error updating {name} corner radii");
if let Err(why) = panel_config.set_border_radius(panel_config_helper, radii) {
tracing::error!(?why, "Error updating panel corner radii");
}
}
if let Some(dock_config_helper) = dock_config_helper.as_ref()
&& let Some(dock_config) = dock_config.as_mut()
{
let radii = if dock_config.anchor_gap {
let cornder_radii: CornerRadii = roundness.into();
cornder_radii.radius_xl[0] as u32
} else if matches!(roundness, Roundness::Round) && !dock_config.expand_to_edges {
12
} else {
0
};
if let Err(why) = dock_config.set_border_radius(dock_config_helper, radii) {
tracing::error!(?why, "Error updating dock corner radii");
}
}
}
#[cfg(feature = "wayland")]
pub fn update_dock_padding(roundness: Roundness) {
let Some((helper, mut config)) = Self::load_panel_config("Dock") else {
return;
};
let dock_config_helper = CosmicPanelConfig::cosmic_config("Dock").ok();
let padding = match roundness {
Roundness::Round | Roundness::SlightlyRound => 4,
Roundness::Square => 0,
};
let mut dock_config = dock_config_helper.as_ref().and_then(|config_helper| {
let panel_config = CosmicPanelConfig::get_entry(config_helper).ok()?;
(panel_config.name == "Dock").then_some(panel_config)
});
if let Err(why) = config.set_padding(&helper, padding) {
tracing::error!(?why, "Error updating dock padding");
if let Some(dock_config_helper) = dock_config_helper.as_ref()
&& let Some(dock_config) = dock_config.as_mut()
{
let padding = match roundness {
Roundness::Round => 4,
Roundness::SlightlyRound => 4,
Roundness::Square => 0,
};
if let Err(why) = dock_config.set_padding(dock_config_helper, padding) {
tracing::error!(?why, "Error updating dock padding");
}
}
}
// TODO: cache panel and dock configs so that they needn't be re-read
#[cfg(feature = "wayland")]
pub fn update_panel_spacing(density: Density) {
let spacing: cosmic::cosmic_theme::Spacing = density.into();
let space_none = spacing.space_none as u32;
let space_none = spacing.space_none;
let panel_config_helper = CosmicPanelConfig::cosmic_config("Panel").ok();
let dock_config_helper = CosmicPanelConfig::cosmic_config("Dock").ok();
let mut panel_config = panel_config_helper.as_ref().and_then(|config_helper| {
let panel_config = CosmicPanelConfig::get_entry(config_helper).ok()?;
(panel_config.name == "Panel").then_some(panel_config)
});
let mut dock_config = dock_config_helper.as_ref().and_then(|config_helper| {
let panel_config = CosmicPanelConfig::get_entry(config_helper).ok()?;
(panel_config.name == "Dock").then_some(panel_config)
});
for name in ["Panel", "Dock"] {
let Some((helper, mut config)) = Self::load_panel_config(name) else {
continue;
};
if let Err(err) = config.set_spacing(&helper, space_none) {
tracing::error!(?err, "Error updating {name} spacing");
if let Some(panel_config_helper) = panel_config_helper.as_ref()
&& let Some(panel_config) = panel_config.as_mut()
{
let update = panel_config.set_spacing(panel_config_helper, space_none as u32);
if let Err(err) = update {
tracing::error!(?err, "Error updating panel spacing");
}
}
};
if let Some(dock_config_helper) = dock_config_helper.as_ref()
&& let Some(dock_config) = dock_config.as_mut()
{
let update = dock_config.set_spacing(dock_config_helper, space_none as u32);
if let Err(err) = update {
tracing::error!(?err, "Error updating dock spacing");
}
};
}
fn can_reset(&self) -> bool {

View file

@ -1,12 +1,9 @@
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::core::{Alignment, Length};
use cosmic::iced::core::{Alignment, Length, text::Wrapping};
use cosmic::widget::icon::{from_name, icon};
use cosmic::widget::{button, container, settings, text};
use cosmic::{Apply, Element};
use cosmic_settings_page::Section;
use crate::pages::desktop::appearance::ContextView;
use super::{Message, Page, Roundness};
#[allow(clippy::too_many_lines)]
@ -15,7 +12,6 @@ pub fn section() -> Section<crate::pages::Message> {
round = fl!("style", "round");
slightly_round = fl!("style", "slightly-round");
square = fl!("style", "square");
frosted_glass = fl!("style", "frosted-glass");
});
let dark_round_style = from_name("illustration-appearance-dark-style-round").handle();
@ -140,10 +136,6 @@ pub fn section() -> Section<crate::pages::Message> {
)
.center_x(Length::Fill),
)
.add(crate::widget::go_next_item(
&descriptions[frosted_glass],
Message::DrawerOpen(ContextView::FrostedGlass),
))
.apply(Element::from)
.map(crate::pages::Message::Appearance)
})

View file

@ -1,8 +1,8 @@
use cosmic::cosmic_config::{Config, ConfigSet, CosmicConfigEntry};
use cosmic::cosmic_theme::palette::{Srgb, Srgba};
use cosmic::cosmic_theme::{
AlphaMap, BlurStrength, CornerRadii, DARK_THEME_BUILDER_ID, LIGHT_THEME_BUILDER_ID, Spacing,
Theme, ThemeBuilder, ThemeMode,
CornerRadii, DARK_THEME_BUILDER_ID, LIGHT_THEME_BUILDER_ID, Spacing, Theme, ThemeBuilder,
ThemeMode,
};
use cosmic::iced::core::Color;
@ -74,7 +74,7 @@ impl From<(Option<Config>, Option<Config>, Option<Vec<Srgba>>)> for ThemeCustomi
.success(theme.success.base.color)
.warning(theme.warning.base.color)
.neutral_tint(theme.palette.neutral_5.color)
.text_tint(theme.background(false).on.color);
.text_tint(theme.background.on.color);
theme_builder.gaps = theme.gaps;
@ -160,6 +160,20 @@ impl Default for Manager {
impl Manager {
pub fn build_theme(&mut self, stage: ThemeStaged) -> Task<app::Message> {
macro_rules! theme_transaction {
($config:ident, $current_theme:ident, $new_theme:ident, { $($name:ident;)+ }) => {
let tx = $config.transaction();
$(
if $current_theme.$name != $new_theme.$name {
_ = tx.set(stringify!($name), $new_theme.$name.clone());
}
)+
_ = tx.commit();
}
}
let map_data_fn = |customizer: &ThemeCustomizer| {
(customizer.builder.0.clone(), customizer.theme.1.clone())
};
@ -185,80 +199,32 @@ impl Manager {
cosmic::task::future(async move {
for (builder, config) in data.by_ref() {
if let Some(config) = config {
let cur = match Theme::get_entry(&config) {
let current_theme = match Theme::get_entry(&config) {
Ok(theme) => theme,
Err((_errs, theme)) => theme,
};
let new = builder.build();
// do this without the macro
let tx = config.transaction();
if cur.accent != new.accent {
_ = tx.set("accent", new.accent.clone());
}
if cur.accent_button != new.accent_button {
_ = tx.set("accent_button", new.accent_button.clone());
}
if cur.background(false) != new.background(false) {
_ = tx.set("background", new.background(false).clone());
}
if cur.background(true) != new.background(true) {
_ = tx.set("transparent_background", new.background(true).clone());
}
if cur.button != new.button {
_ = tx.set("button", new.button.clone());
}
if cur.destructive != new.destructive {
_ = tx.set("destructive", new.destructive.clone());
}
if cur.destructive_button != new.destructive_button {
_ = tx.set("destructive_button", new.destructive_button.clone());
}
if cur.link_button != new.link_button {
_ = tx.set("link_button", new.link_button.clone());
}
if cur.icon_button != new.icon_button {
_ = tx.set("icon_button", new.icon_button.clone());
}
if cur.palette != new.palette {
_ = tx.set("palette", new.palette.clone());
}
if cur.primary(false) != new.primary(false) {
_ = tx.set("primary", new.primary(false).clone());
}
if cur.secondary(false) != new.secondary(false) {
_ = tx.set("secondary", new.secondary(false).clone());
}
if cur.primary(true) != new.primary(true) {
_ = tx.set("transparent_primary", new.primary(true).clone());
}
if cur.secondary(true) != new.secondary(true) {
_ = tx.set("transparent_secondary", new.secondary(true).clone());
}
if cur.shade != new.shade {
_ = tx.set("shade", new.shade.clone());
}
if cur.success != new.success {
_ = tx.set("success", new.success.clone());
}
if cur.text_button != new.text_button {
_ = tx.set("text_button", new.text_button.clone());
}
if cur.warning != new.warning {
_ = tx.set("warning", new.warning.clone());
}
if cur.warning_button != new.warning_button {
_ = tx.set("warning_button", new.warning_button.clone());
}
if cur.window_hint != new.window_hint {
_ = tx.set("window_hint", new.window_hint.clone());
}
if cur.accent_text != new.accent_text {
_ = tx.set("accent_text", new.accent_text.clone());
}
_ = tx.commit();
let new_theme = builder.build();
theme_transaction!(config, current_theme, new_theme, {
accent;
accent_button;
background;
button;
destructive;
destructive_button;
link_button;
icon_button;
palette;
primary;
secondary;
shade;
success;
text_button;
warning;
warning_button;
window_hint;
accent_text;
});
}
}
@ -394,39 +360,6 @@ impl Manager {
Some(ThemeStaged::Both)
}
pub fn set_frosted(&mut self, frosted: BlurStrength) -> Option<ThemeStaged> {
self.dark.set_frosted(frosted)?;
self.light.set_frosted(frosted)?;
Some(ThemeStaged::Both)
}
pub fn set_glass(&mut self, alpha_map: AlphaMap) -> Option<ThemeStaged> {
self.dark.set_glass(alpha_map)?;
self.light.set_glass(alpha_map)?;
Some(ThemeStaged::Both)
}
pub fn set_frosted_panel(&mut self, enabled: bool) -> Option<ThemeStaged> {
self.dark.set_frosted_panel(enabled)?;
self.light.set_frosted_panel(enabled)?;
Some(ThemeStaged::Both)
}
pub fn set_frosted_applets(&mut self, enabled: bool) -> Option<ThemeStaged> {
self.dark.set_frosted_applets(enabled)?;
self.light.set_frosted_applets(enabled)?;
Some(ThemeStaged::Both)
}
pub fn set_frosted_system_interface(&mut self, enabled: bool) -> Option<ThemeStaged> {
self.dark.set_frosted_system_interface(enabled)?;
self.light.set_frosted_system_interface(enabled)?;
Some(ThemeStaged::Both)
}
pub fn set_frosted_windows(&mut self, enabled: bool) -> Option<ThemeStaged> {
self.dark.set_frosted_windows(enabled)?;
self.light.set_frosted_windows(enabled)?;
Some(ThemeStaged::Both)
}
pub fn get_color(&self, context: &ContextView) -> Option<Color> {
match *context {
ContextView::CustomAccent => self.custom_accent().map(Color::from),
@ -607,81 +540,6 @@ impl ThemeCustomizer {
Some(ThemeStaged::Current)
}
pub fn set_frosted(&mut self, frosted: BlurStrength) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;
self.builder.0.set_frosted(config, frosted).ok()?;
self.theme
.0
.set_frosted(self.theme.1.as_ref()?, frosted)
.ok()?;
Some(ThemeStaged::Current)
}
pub fn set_glass(&mut self, alpha_map: AlphaMap) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;
self.builder.0.set_alpha_map(config, alpha_map).ok()?;
self.theme
.0
.set_alpha_map(self.theme.1.as_ref()?, alpha_map)
.ok()?;
Some(ThemeStaged::Current)
}
pub fn set_frosted_windows(&mut self, enabled: bool) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;
self.builder.0.set_frosted_windows(config, enabled).ok()?;
self.theme
.0
.set_frosted_windows(self.theme.1.as_ref()?, enabled)
.ok()?;
Some(ThemeStaged::Current)
}
pub fn set_frosted_system_interface(&mut self, enabled: bool) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;
self.builder
.0
.set_frosted_system_interface(config, enabled)
.ok()?;
self.theme
.0
.set_frosted_system_interface(self.theme.1.as_ref()?, enabled)
.ok()?;
Some(ThemeStaged::Current)
}
pub fn set_frosted_applets(&mut self, enabled: bool) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;
self.builder.0.set_frosted_applets(config, enabled).ok()?;
self.theme
.0
.set_frosted_applets(self.theme.1.as_ref()?, enabled)
.ok()?;
Some(ThemeStaged::Current)
}
pub fn set_frosted_panel(&mut self, enabled: bool) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;
self.builder.0.set_frosted_panel(config, enabled).ok()?;
self.theme
.0
.set_frosted_panel(self.theme.1.as_ref()?, enabled)
.ok()?;
Some(ThemeStaged::Current)
}
// set active hints is set on all themes to be consistent between dark & light themes.
pub fn set_active_hint(&mut self, active_hint: u32) -> Option<ThemeStaged> {
let config = self.builder.1.as_ref()?;

View file

@ -1,16 +1,22 @@
use cosmic::app::ContextDrawer;
use cosmic::cosmic_config::CosmicConfigEntry;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{button, container, row};
use cosmic::{Apply, Element, Task};
use cosmic::{
Apply, Element, Task,
app::ContextDrawer,
cosmic_config::CosmicConfigEntry,
iced::{Alignment, Length},
widget::{button, container, row},
};
use cosmic_panel_config::CosmicPanelConfig;
use cosmic_settings_page::{self as page, Section, section};
use slotmap::{Key, SlotMap};
use std::borrow::Cow;
use crate::app;
use crate::pages::desktop::panel::applets_inner::{self, AppletsPage, ContextDrawerVariant, lists};
use crate::pages::{self};
use crate::{
app,
pages::{
self,
desktop::panel::applets_inner::{self, AppletsPage, ContextDrawerVariant, lists},
},
};
pub(crate) struct Page {
inner: applets_inner::Page,

View file

@ -1,8 +1,11 @@
use std::collections::HashMap;
use cosmic::cosmic_config::{ConfigSet, CosmicConfigEntry};
use cosmic::widget::{settings, text};
use cosmic::{Apply, Element, Task};
use cosmic::Apply;
use cosmic::{
Element, Task,
cosmic_config::{ConfigSet, CosmicConfigEntry},
widget::{settings, text},
};
use cosmic_panel_config::{CosmicPanelConfig, CosmicPanelContainerConfig};
use cosmic_settings_page::{self as page, Section, section};
use slotmap::SlotMap;

View file

@ -10,21 +10,23 @@ use cosmic::iced;
use cosmic::iced::core::clipboard::IconSurface;
use cosmic::widget::{Column, button, column, container, icon, list_column, row, text, text_input};
use cosmic::cosmic_config::{Config, CosmicConfigEntry};
use cosmic::iced::core::widget::{Operation, Tree, tree};
use cosmic::iced::core::{Clipboard, Shell, Widget, layout, renderer, window};
use cosmic::iced::runtime::Task;
use cosmic::iced::runtime::core::id::Id;
use cosmic::iced::{
Alignment, Border, Color, Length, Point, Rectangle, Size, Vector, event, mouse, overlay, touch,
use cosmic::{
Apply, Element,
cosmic_config::{Config, CosmicConfigEntry},
iced::core::{
Clipboard, Shell, Widget, layout, renderer,
widget::{Operation, Tree, tree},
},
iced::runtime::{Task, core::id::Id},
iced::{
Alignment, Border, Color, Length, Point, Rectangle, Size, Vector, core::window, event,
mouse, overlay, touch,
},
theme,
};
use cosmic::{Apply, Element, theme};
use std::borrow::Cow;
use std::fmt::Debug;
use std::mem;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::{borrow::Cow, fmt::Debug, mem, sync::LazyLock};
use crate::{app, pages};
use cosmic_panel_config::CosmicPanelConfig;

View file

@ -1,11 +1,12 @@
use cosmic::cctk::sctk::reexports::client::Proxy;
use cosmic::cctk::sctk::reexports::client::backend::ObjectId;
use cosmic::cctk::sctk::reexports::client::protocol::wl_output::WlOutput;
use cosmic::cosmic_config::{self, CosmicConfigEntry};
use cosmic::cosmic_theme::{Density, Roundness};
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{button, container, dropdown, row, settings, slider, space, text};
use cosmic::{Element, Task, surface};
use cosmic::{
Element, Task,
cctk::sctk::reexports::client::{Proxy, backend::ObjectId, protocol::wl_output::WlOutput},
cosmic_config::{self, CosmicConfigEntry},
cosmic_theme::Density,
iced::{Alignment, Length},
surface,
widget::{button, container, dropdown, row, settings, slider, space, text},
};
use cosmic::Apply;
use cosmic_config::ConfigSet;
@ -14,15 +15,16 @@ use cosmic_panel_config::{
CosmicPanelOuput, PanelAnchor, PanelSize,
};
use cosmic_settings_page::{self as page, Section};
use std::collections::HashMap;
use std::time::Duration;
use std::{collections::HashMap, time::Duration};
use crate::pages::desktop::appearance::Roundness;
pub struct PageInner {
pub(crate) config_helper: Option<cosmic_config::Config>,
pub(crate) panel_config: Option<CosmicPanelConfig>,
pub size: Option<PanelSize>,
pub opacity: f32,
pub opacity_changing: bool,
pub size: PanelSize,
pub outputs: Vec<String>,
pub anchors: Vec<String>,
pub backgrounds: Vec<String>,
@ -38,9 +40,9 @@ impl Default for PageInner {
Self {
config_helper: Option::default(),
panel_config: Option::default(),
size: Option::default(),
opacity: 0.0,
opacity_changing: false,
size: PanelSize::M,
outputs: vec![fl!("all-displays")],
anchors: vec![
Anchor(PanelAnchor::Left).to_string(),
@ -118,7 +120,7 @@ pub(crate) fn behavior_and_position<
.title(&section.title)
.add(
settings::item::builder(&descriptions[autohide_label])
.toggler(panel_config.autohide_enabled(), Message::AutoHidePanel),
.toggler(panel_config.autohide.is_some(), Message::AutoHidePanel),
)
.add(settings::item(
&descriptions[position],
@ -207,7 +209,9 @@ pub(crate) fn style<
text::body(fl!("small")).into(),
slider(
0..=4,
match inner.size {
match inner.size.as_ref().expect(
"PageInner.size is None even though PageInner.panel_config is Some",
) {
PanelSize::XS => 0,
PanelSize::S => 1,
PanelSize::M => 2,
@ -502,7 +506,7 @@ impl PageInner {
if let Err(err) = default.write_entry(config) {
tracing::error!(?err, "Error resetting panel config.");
}
self.size.clone_from(&default.size);
self.size = Some(default.size.clone());
self.system_default = Some(default.clone());
self.panel_config.clone_from(&self.system_default);
} else {
@ -542,10 +546,18 @@ impl PageInner {
Message::AutoHidePanel(enabled) => {
if enabled {
_ = panel_config.set_exclusive_zone(helper, false);
_ = panel_config.set_autohide(helper, AutoHide::OnOverlap);
_ = panel_config.set_autohide(
helper,
Some(AutoHide {
wait_time: 1000,
transition_time: 200,
handle_size: 4,
unhide_delay: 200,
}),
);
} else {
_ = panel_config.set_exclusive_zone(helper, true);
_ = panel_config.set_autohide(helper, AutoHide::Never);
_ = panel_config.set_autohide(helper, None);
}
}
Message::PanelAnchor(i) => {
@ -579,21 +591,30 @@ impl PageInner {
}
let theme = cosmic::theme::system_preference();
let theme = theme.cosmic();
let radius = theme.corner_radii.radius_xl[0] as u32;
let new_radius = if enabled {
radius
} else if !panel_config.expand_to_edges {
radius.min(12)
let radius = theme.corner_radii;
let roundness: Roundness = radius.into();
let new_radius;
if enabled {
let radii = theme.corner_radii.radius_xl[0] as u32;
new_radius = radii;
} else if matches!(roundness, Roundness::Round) && !panel_config.expand_to_edges {
new_radius = 12;
} else {
0
};
new_radius = 0;
}
_ = panel_config.set_border_radius(helper, new_radius).unwrap();
}
Message::PanelSize(size) => {
self.size = size;
self.size = Some(size);
}
Message::PanelSizeCommit => {
_ = panel_config.set_size(helper, self.size.clone());
_ = panel_config.set_size(
helper,
self.size
.as_ref()
.expect("PageInner.size is None even though it should be Some, since PageInner.panel_config is Some")
.clone()
);
// Reset any size overrides the user might have set
_ = panel_config.set_size_center(helper, None);
_ = panel_config.set_size_wings(helper, None);
@ -611,14 +632,17 @@ impl PageInner {
let theme = cosmic::theme::system_preference();
let theme = theme.cosmic();
let radius = theme.corner_radii.radius_xl[0] as u32;
let new_radius = if panel_config.anchor_gap {
radius
} else if !enabled {
radius.min(12)
let radius = theme.corner_radii;
let roundness: Roundness = radius.into();
let new_radius;
if panel_config.anchor_gap {
let radii = theme.corner_radii.radius_xl[0] as u32;
new_radius = radii;
} else if matches!(roundness, Roundness::Round) && !enabled {
new_radius = 12;
} else {
0
};
new_radius = 0;
}
_ = panel_config.set_border_radius(helper, new_radius).unwrap();
}
Message::OpacityRequest(opacity) => {
@ -653,7 +677,7 @@ impl PageInner {
}
}
Message::PanelConfig(c) => {
self.size = c.size.clone();
self.size = Some(c.size.clone());
self.panel_config = Some(*c);
return Task::none();
}

View file

@ -1,7 +1,6 @@
use std::collections::HashMap;
use cosmic::Task;
use cosmic::cosmic_config::CosmicConfigEntry;
use cosmic::{Task, cosmic_config::CosmicConfigEntry};
use cosmic_panel_config::{CosmicPanelConfig, CosmicPanelContainerConfig};
use cosmic_settings_page::{self as page, Section, section};
use slotmap::SlotMap;
@ -80,6 +79,7 @@ impl Default for Page {
// If the config is not present, it will be created with the default values and the name will not match
(panel_config.name == "Panel").then_some(panel_config)
});
let size = panel_config.as_ref().map(|c| c.size.clone());
let system_default = cosmic::cosmic_config::Config::system(
&format!("{}.Panel", cosmic_panel_config::NAME),
CosmicPanelConfig::VERSION,
@ -99,6 +99,7 @@ impl Default for Page {
inner: PageInner {
config_helper,
panel_config,
size,
container_config,
outputs_map: HashMap::new(),
system_default,

View file

@ -7,25 +7,37 @@ pub mod widgets;
pub use config::Config;
use url::Url;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::Arc,
};
use cosmic::app::ContextDrawer;
#[cfg(feature = "xdg-portal")]
use cosmic::dialog::file_chooser;
use cosmic::iced::core::text::{Ellipsize, EllipsizeHeightLimit};
use cosmic::iced::runtime::core::image::Handle as ImageHandle;
use cosmic::iced::{Alignment, Color, Length, Subscription, window};
use cosmic::widget::color_picker::ColorPickerUpdate;
use cosmic::widget::segmented_button::{self, SingleSelectModel};
use cosmic::widget::space::horizontal as horizontal_space;
use cosmic::widget::{
ColorPickerModel, button, dropdown, icon, list_column, row, settings, tab_bar, text,
use cosmic::{
Apply, Element, Task,
iced::core::text::{Ellipsize, EllipsizeHeightLimit},
widget::{ColorPickerModel, color_picker::ColorPickerUpdate, icon},
};
use cosmic::{app::ContextDrawer, iced::runtime::core::image::Handle as ImageHandle};
use cosmic::{
iced::Subscription,
widget::{
button, dropdown, list_column, row,
segmented_button::{self, SingleSelectModel},
settings,
space::horizontal as horizontal_space,
tab_bar, text,
},
};
use cosmic::{
iced::{Alignment, Color, Length, window},
surface,
};
use cosmic::{Apply, Element, Task, surface};
use cosmic_bg_config::Source;
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use cosmic_settings_wallpaper::{self as wallpaper, Entry, ScalingMode};
use image::imageops::FilterType::Lanczos3;
use image::{ImageBuffer, Rgba};
@ -65,7 +77,7 @@ pub enum Message {
AddFolder(Arc<Result<Url, file_chooser::Error>>),
/// Adds a new image file the system wallpaper folder.
#[cfg(feature = "xdg-portal")]
AddFiles(Arc<Result<Vec<Url>, file_chooser::Error>>),
AddFile(Arc<Result<Url, file_chooser::Error>>),
/// Cache currently displayed image.
CacheDisplayImage,
/// Selects an option in the category dropdown menu.
@ -787,11 +799,11 @@ impl Page {
.title(fl!("wallpaper", "image-dialog"))
.accept_label(fl!("dialog-add"))
.modal(false)
.open_files()
.open_file()
.await
.map(|response| response.urls().to_vec());
.map(|response| response.url().to_owned());
let message = Message::AddFiles(Arc::new(dialog_result));
let message = Message::AddFile(Arc::new(dialog_result));
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::Message::PageMessage(page_message)
});
@ -862,11 +874,6 @@ impl Page {
#[cfg(feature = "xdg-portal")]
Message::AddFolder(result) => {
let path = match dialog_response(result) {
DialogResponse::Paths(_) => {
// TODO find if there is a use of multi folder addition.
tracing::warn!("unexpected multi-path response for folder dialog");
return Task::none();
}
DialogResponse::Path(path) => path,
DialogResponse::Error(why) => {
tracing::error!(why, "dialog response error");
@ -892,30 +899,27 @@ impl Page {
}
#[cfg(feature = "xdg-portal")]
Message::AddFiles(result) => {
let paths = match dialog_response_multi(result) {
DialogResponse::Paths(paths) => paths,
DialogResponse::Path(path) => vec![path], // not really but for the sake of consistency..
Message::AddFile(result) => {
let path = match dialog_response(result) {
DialogResponse::Path(path) => path,
DialogResponse::Error(why) => {
tracing::error!(why, "dialog response error");
return Task::none();
}
};
let tasks = paths.into_iter().filter(|path| path.is_file()).map(|path| {
if path.is_file() {
tracing::info!(?path, "opening custom image");
// Loads a single custom image and its thumbnail for display in the backgrounds view.
cosmic::Task::future(async move {
return cosmic::Task::future(async move {
let result = wallpaper::load_image_with_thumbnail(path);
let message = Message::ImageAdd(result.map(Arc::new));
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::Message::PageMessage(page_message)
})
});
return Task::batch(tasks);
});
}
}
Message::Event(event) => match event {
@ -1425,33 +1429,27 @@ pub fn settings() -> Section<crate::pages::Message> {
enum DialogResponse {
Error(String),
Path(PathBuf),
Paths(Vec<PathBuf>),
}
#[cfg(feature = "xdg-portal")]
fn unwrap_dialog_response<T>(result: Arc<Result<T, file_chooser::Error>>) -> Result<T, String> {
let Some(result) = Arc::into_inner(result) else {
return Err(String::from("Arc::into_inner returned None"));
};
result.map_err(|why| {
let mut source: &dyn std::error::Error = &why;
let mut string = format!("open dialog subscription errored\n cause: {source}");
while let Some(new_source) = source.source() {
string.push_str(&format!("\n cause: {new_source}"));
source = new_source;
}
string
})
}
#[cfg(feature = "xdg-portal")]
fn dialog_response(result: Arc<Result<Url, file_chooser::Error>>) -> DialogResponse {
let selection = match unwrap_dialog_response(result) {
Ok(selection) => selection,
Err(why) => return DialogResponse::Error(why),
let Some(result) = Arc::into_inner(result) else {
return DialogResponse::Error(String::from("Arc::into_inner returned None"));
};
let selection = match result {
Ok(response) => response,
Err(why) => {
let mut source: &dyn std::error::Error = &why;
let mut string = format!("open dialog subscription errored\n cause: {source}");
while let Some(new_source) = source.source() {
string.push_str(&format!("\n cause: {new_source}"));
source = new_source;
}
return DialogResponse::Error(string);
}
};
let Ok(path) = selection.to_file_path() else {
@ -1460,22 +1458,3 @@ fn dialog_response(result: Arc<Result<Url, file_chooser::Error>>) -> DialogRespo
DialogResponse::Path(path)
}
#[cfg(feature = "xdg-portal")]
fn dialog_response_multi(result: Arc<Result<Vec<Url>, file_chooser::Error>>) -> DialogResponse {
let selections = match unwrap_dialog_response(result) {
Ok(selections) => selections,
Err(why) => return DialogResponse::Error(why),
};
let mut paths = Vec::with_capacity(selections.len());
for selection in selections {
let Ok(path) = selection.to_file_path() else {
tracing::warn!("not a valid file path: {}", selection.path());
continue;
};
paths.push(path);
}
DialogResponse::Paths(paths)
}

View file

@ -3,8 +3,8 @@
use super::Message;
use cosmic::iced::Radius;
use cosmic::iced::core::gradient::Linear;
use cosmic::iced::core::{Background, Border, Color, Degrees, Length};
use cosmic::iced::core::Border;
use cosmic::iced::core::{Background, Color, Degrees, Length, gradient::Linear};
use cosmic::iced::runtime::core::image::Handle as ImageHandle;
use cosmic::prelude::*;
use cosmic::widget::{Space, button, container};

View file

@ -1,14 +1,18 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use cosmic::iced::Length;
use cosmic::widget::{self, settings};
use cosmic::{Apply, Element, surface};
use cosmic::{
Apply, Element,
iced::Length,
surface,
widget::{self, settings},
};
use cosmic_comp_config::CosmicCompConfig;
use cosmic_config::{ConfigGet, ConfigSet};
use cosmic_settings_config::{Action, Binding, Shortcuts, shortcuts};
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use slotmap::SlotMap;
use tracing::error;
@ -92,7 +96,7 @@ impl Default for Page {
fl!("super-key", "launcher"),
fl!("super-key", "workspaces"),
fl!("super-key", "applications"),
fl!("super-key", "none"),
fl!("super-key", "disable"),
],
super_key_active: super_key_active_config(),
comp_config,
@ -243,7 +247,7 @@ pub fn window_management() -> Section<crate::pages::Message> {
_launcher = fl!("super-key", "launcher");
_workspaces = fl!("super-key", "workspaces");
_applications = fl!("super-key", "applications");
_none = fl!("super-key", "none");
_disable = fl!("super-key", "disable");
edge_gravity = fl!("edge-gravity");
});

View file

@ -3,11 +3,15 @@
// TODO make settings work
use cosmic::cosmic_config::{self, ConfigGet, ConfigSet};
use cosmic::widget::{self, settings};
use cosmic::{Apply, Element, surface};
use cosmic::{
Apply, Element,
cosmic_config::{self, ConfigGet, ConfigSet},
surface,
widget::{self, settings},
};
use cosmic_comp_config::workspace::{Action, WorkspaceConfig, WorkspaceLayout, WorkspaceMode};
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use slotmap::SlotMap;
use tracing::error;

View file

@ -5,9 +5,11 @@ use cosmic::Renderer;
use cosmic::iced::core::renderer::Quad;
use cosmic::iced::core::widget::{Tree, tree};
use cosmic::iced::core::{
self as core, Border, Clipboard, Element, Layout, Length, Point, Rectangle,
Renderer as IcedRenderer, Shell, Size, Widget, alignment, layout, mouse, renderer, text, touch,
self as core, Border, Clipboard, Element, Layout, Length, Rectangle, Renderer as IcedRenderer,
Shell, Size, Widget,
};
use cosmic::iced::core::{Point, layout, mouse, renderer, touch};
use cosmic::iced::core::{alignment, text};
use cosmic::widget::segmented_button::{self, SingleSelectModel};
use cosmic_randr_shell::{self as randr, OutputKey};
use randr::Transform;
@ -197,7 +199,6 @@ impl<Message: Clone> Widget<Message, cosmic::Theme, Renderer> for Arrangement<'_
);
shell.capture_event();
shell.request_redraw();
}
}
}
@ -245,13 +246,11 @@ impl<Message: Clone> Widget<Message, cosmic::Theme, Renderer> for Arrangement<'_
if let Some(ref on_placement) = self.on_placement {
shell.publish(on_placement(
output_key,
((region.x - state.max_dimensions.0 - bounds.x) * UNIT_PIXELS).round()
as i32,
((region.x - state.max_dimensions.0 - bounds.x) * UNIT_PIXELS) as i32,
((region.y
- (state.max_dimensions.1 / VERTICAL_DISPLAY_OVERHEAD)
- bounds.y)
* UNIT_PIXELS)
.round() as i32,
* UNIT_PIXELS) as i32,
));
}

View file

@ -20,10 +20,9 @@ use cosmic_settings_page::{self as page, Section, section};
use futures::SinkExt;
use indexmap::Equivalent;
use slotmap::{Key, SecondaryMap, SlotMap};
use std::collections::BTreeMap;
use std::process::ExitStatus;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock};
use std::{collections::BTreeMap, process::ExitStatus};
use tokio::sync::oneshot;
static DPI_SCALES: &[u32] = &[50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300];
@ -913,8 +912,8 @@ impl Page {
Some(orientation) => self.set_dialog(
Randr::Transform(match orientation {
1 => Transform::Rotate90,
2 => Transform::Rotate180,
3 => Transform::Rotate270,
2 => Transform::Flipped180,
3 => Transform::Flipped270,
_ => Transform::Normal,
}),
&request,
@ -1103,12 +1102,6 @@ impl Page {
.arg(itoa::Buffer::new().format(x))
.arg("--pos-y")
.arg(itoa::Buffer::new().format(y))
.arg("--refresh")
.arg(format!(
"{}.{:03}",
current.refresh_rate / 1000,
current.refresh_rate % 1000
))
.arg(name)
.arg(itoa::Buffer::new().format(current.size.0))
.arg(itoa::Buffer::new().format(current.size.1));

View file

@ -5,96 +5,50 @@ pub mod shortcuts;
use std::cmp;
use cosmic::app::{ContextDrawer, context_drawer};
use cosmic::cosmic_config::{self, ConfigSet};
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{self, ListColumn, button, container, icon, list, row, settings};
use cosmic::{Apply, Element, Task, theme};
use cosmic::{
Apply, Element, Task,
app::{ContextDrawer, context_drawer},
cosmic_config::{self, ConfigSet},
iced::{Alignment, Length},
theme,
widget::{self, ListColumn, button, container, icon, list, row, settings},
};
use cosmic_comp_config::{KeyboardConfig, NumlockState, XkbConfig};
use cosmic_settings_page::{self as page, Section, section};
use itertools::Itertools;
use slotmap::{DefaultKey, Key, SlotMap};
/// Contains all options for mapping a [SpecialKey].
/// The available options differ for each key being mapped.
enum SpecialKeyAlternative {
AltLeft,
AltRight,
Ctrl,
CtrlRight,
SwapWithCtrl,
Super,
SuperLeft,
SuperRight,
CapsLock,
ScrollLock,
MenuKey,
Backspace,
Escape,
SwapWithEscape,
PrintScreen,
None,
}
impl SpecialKeyAlternative {
fn display_text(&self) -> String {
match self {
Self::AltLeft => fl!("keyboard-special-char", "alt-left"),
Self::AltRight => fl!("keyboard-special-char", "alt-right"),
Self::Ctrl => fl!("keyboard-special-char", "ctrl"),
Self::CtrlRight => fl!("keyboard-special-char", "ctrl-right"),
Self::SwapWithCtrl => fl!("keyboard-special-char", "swap-with-ctrl"),
Self::Super => fl!("keyboard-special-char", "super"),
Self::SuperLeft => fl!("keyboard-special-char", "super-left"),
Self::SuperRight => fl!("keyboard-special-char", "super-right"),
Self::CapsLock => fl!("keyboard-special-char", "caps"),
Self::ScrollLock => fl!("keyboard-special-char", "scroll-lock"),
Self::MenuKey => fl!("keyboard-special-char", "menu"),
Self::Backspace => fl!("keyboard-special-char", "backspace"),
Self::Escape => fl!("keyboard-special-char", "escape"),
Self::SwapWithEscape => fl!("keyboard-special-char", "swap-with-escape"),
Self::PrintScreen => fl!("keyboard-special-char", "print-screen"),
Self::None => fl!("keyboard-special-char", "none"),
}
}
}
/// The second/right value is the key identifier, which is how it will be saved to the configuration.
/// These values are different for each [SpecialKey], even for the same [SpecialKeyAlternative].
/// The identifier starts with a prefix defined by [SpecialKey::prefixes].
type SpecialKeyOption = (SpecialKeyAlternative, &'static str);
/// Available options for [SpecialKey::Compose].
static COMPOSE_OPTIONS: &[SpecialKeyOption] = &[
static COMPOSE_OPTIONS: &[(&str, &str)] = &[
// ("Left Alt", "compose:lalt"), XXX?
(SpecialKeyAlternative::AltRight, "compose:ralt"),
(SpecialKeyAlternative::SuperLeft, "compose:lwin"),
(SpecialKeyAlternative::SuperRight, "compose:rwin"),
(SpecialKeyAlternative::MenuKey, "compose:menu"),
(SpecialKeyAlternative::CtrlRight, "compose:rctrl"),
(SpecialKeyAlternative::CapsLock, "compose:caps"),
(SpecialKeyAlternative::ScrollLock, "compose:sclk"),
(SpecialKeyAlternative::PrintScreen, "compose:prsc"),
("Right Alt", "compose:ralt"),
("Left Super", "compose:lwin"),
("Right Super", "compose:rwin"),
("Menu key", "compose:menu"),
("Right Ctrl", "compose:rctrl"),
("Caps Lock", "compose:caps"),
("Scroll Lock", "compose:sclk"),
("Print Screen", "compose:prsc"),
];
/// Available options for [SpecialKey::AlternateCharacters].
static ALTERNATE_CHARACTER_OPTIONS: &[SpecialKeyOption] = &[
(SpecialKeyAlternative::AltLeft, "lv3:lalt_switch"),
(SpecialKeyAlternative::AltRight, "lv3:ralt_switch"),
(SpecialKeyAlternative::SuperLeft, "lv3:lwin_switch"),
(SpecialKeyAlternative::SuperRight, "lv3:rwin_switch"),
(SpecialKeyAlternative::MenuKey, "lv3:menu_switch"),
static ALTERNATE_CHARACTER_OPTIONS: &[(&str, &str)] = &[
("Left Alt", "lv3:lalt_switch"),
("Right Alt", "lv3:ralt_switch"),
("Left Super", "lv3:lwin_switch"),
("Right Super", "lv3:rwin_switch"),
("Menu key", "lv3:menu_switch"),
// ("Right Ctrl", "lv3:"), XXX
(SpecialKeyAlternative::CapsLock, "lv3:caps_switch"),
("Caps Lock", "lv3:caps_switch"),
// ("Scroll Lock", "lv3:"), XXX
// ("Print Screen", "lv3"), XXX
];
/// Available options for [SpecialKey::CapsLock].
static CAPS_LOCK_OPTIONS: &[SpecialKeyOption] = &[
(SpecialKeyAlternative::Escape, "caps:escape"),
(SpecialKeyAlternative::SwapWithEscape, "caps:swapescape"),
(SpecialKeyAlternative::Backspace, "caps:backspace"),
(SpecialKeyAlternative::Super, "caps:super"),
(SpecialKeyAlternative::Ctrl, "caps:ctrl_modifier"),
(SpecialKeyAlternative::SwapWithCtrl, "ctrl:swapcaps"),
static CAPS_LOCK_OPTIONS: &[(&str, &str)] = &[
("Escape", "caps:escape"),
("Swap with Escape", "caps:swapescape"),
("Backspace", "caps:backspace"),
("Super", "caps:super"),
("Control", "caps:ctrl_modifier"),
("Swap with Control", "ctrl:swapcaps"),
];
#[derive(Clone, Debug)]
@ -118,8 +72,8 @@ pub enum SourceContext {
MoveDown(DefaultKey),
MoveUp(DefaultKey),
Remove(DefaultKey),
// Settings(DefaultKey),
// ViewLayout(DefaultKey),
Settings(DefaultKey),
ViewLayout(DefaultKey),
}
pub type Locale = String;
@ -192,9 +146,9 @@ pub enum SpecialKey {
impl SpecialKey {
pub fn title(self) -> String {
match self {
Self::Compose => fl!("keyboard-special-char", "compose"),
Self::AlternateCharacters => fl!("keyboard-special-char", "alternate"),
Self::CapsLock => fl!("keyboard-special-char", "caps"),
Self::Compose => "Compose".to_string(),
Self::AlternateCharacters => "Alternate Characters".to_string(),
Self::CapsLock => "Caps Lock".to_string(),
}
}
@ -211,7 +165,6 @@ fn popover_menu_row(
id: DefaultKey,
label: String,
message: impl Fn(DefaultKey) -> SourceContext + 'static,
disabled: bool,
) -> cosmic::Element<'static, Message> {
let spacing = theme::spacing();
widget::text::body(label)
@ -220,54 +173,37 @@ fn popover_menu_row(
.padding([spacing.space_xxxs, spacing.space_xs])
.width(Length::Fill)
.class(theme::Button::MenuItem)
.on_press_maybe(if disabled {
None
} else {
Some(Message::SourceContext(message(id)))
})
.on_press(Message::SourceContext(message(id)))
.apply(Element::from)
}
fn popover_menu(
id: DefaultKey,
is_first: bool,
is_last: bool,
) -> cosmic::Element<'static, Message> {
fn popover_menu(id: DefaultKey) -> cosmic::Element<'static, Message> {
widget::column::with_children([
popover_menu_row(
id,
fl!("keyboard-sources", "move-up"),
SourceContext::MoveUp,
is_first,
),
popover_menu_row(
id,
fl!("keyboard-sources", "move-down"),
SourceContext::MoveDown,
is_last,
),
widget::divider::horizontal::default()
.apply(widget::container)
.padding(8)
.into(),
// popover_menu_row(
// id,
// fl!("keyboard-sources", "settings"),
// SourceContext::Settings,
// false,
// ),
// popover_menu_row(
// id,
// fl!("keyboard-sources", "view-layout"),
// SourceContext::ViewLayout,
// false,
// ),
popover_menu_row(
id,
fl!("keyboard-sources", "remove"),
SourceContext::Remove,
false,
fl!("keyboard-sources", "settings"),
SourceContext::Settings,
),
popover_menu_row(
id,
fl!("keyboard-sources", "view-layout"),
SourceContext::ViewLayout,
),
popover_menu_row(id, fl!("keyboard-sources", "remove"), SourceContext::Remove),
])
.width(Length::Fixed(200.0))
.apply(widget::container)
@ -276,12 +212,7 @@ fn popover_menu(
.into()
}
fn popover_button(
id: DefaultKey,
expanded: bool,
is_first: bool,
is_last: bool,
) -> cosmic::Element<'static, Message> {
fn popover_button(id: DefaultKey, expanded: bool) -> cosmic::Element<'static, Message> {
let on_press = Message::ExpandInputSourcePopover(if expanded { None } else { Some(id) });
let button = button::icon(icon::from_name("view-more-symbolic"))
@ -291,7 +222,7 @@ fn popover_button(
if expanded {
widget::popover(button)
.position(widget::popover::Position::Bottom)
.popup(popover_menu(id, is_first, is_last))
.popup(popover_menu(id))
.on_close(Message::ExpandInputSourcePopover(None))
.into()
} else {
@ -303,16 +234,14 @@ fn input_source(
id: DefaultKey,
description: &str,
expanded_source_popover: Option<DefaultKey>,
is_first: bool,
is_last: bool,
) -> cosmic::Element<'_, Message> {
let expanded = expanded_source_popover.is_some_and(|expanded_id| expanded_id == id);
settings::item(description, popover_button(id, expanded, is_first, is_last)).into()
settings::item(description, popover_button(id, expanded)).into()
}
fn special_char_radio_row<'a>(
desc: String,
desc: &'a str,
value: Option<&'static str>,
current_value: Option<&'a str>,
) -> list::ListButton<'a, Message> {
@ -546,13 +475,15 @@ impl Page {
let _removed = self.active_layouts.remove(pos);
self.update_xkb_config();
}
} // SourceContext::Settings(_id) => {
// eprintln!("settings not implemented");
// }
}
// SourceContext::ViewLayout(_id) => {
// eprintln!("view layout not implemented");
// }
SourceContext::Settings(_id) => {
eprintln!("settings not implemented");
}
SourceContext::ViewLayout(_id) => {
eprintln!("view layout not implemented");
}
}
}
@ -690,22 +621,14 @@ impl Page {
let mut list = cosmic::widget::list_column();
if matches!(special_key, SpecialKey::CapsLock) {
list = list.add(special_char_radio_row(
SpecialKeyAlternative::CapsLock.display_text(),
None,
current,
));
list = list.add(special_char_radio_row("Caps Lock", None, current));
} else {
list = list.add(special_char_radio_row(
SpecialKeyAlternative::None.display_text(),
None,
current,
));
list = list.add(special_char_radio_row("None", None, current));
}
list = options
.iter()
.map(|(key, id)| special_char_radio_row(key.display_text(), Some(id), current))
.map(|(desc, id)| special_char_radio_row(desc, Some(id), current))
.fold(list, ListColumn::add);
widget::column::with_capacity(2)
@ -770,17 +693,12 @@ fn input_sources() -> Section<crate::pages::Message> {
// TODO Need something more custom, with drag and drop
let mut section = settings::section().title(&section.title);
for (position, id) in page.active_layouts.iter().enumerate() {
for id in &page.active_layouts {
if let Some((_locale, _variant, description, _source)) =
page.keyboard_layouts.get(*id)
{
section = section.add(input_source(
*id,
description,
page.expanded_source_popover,
position == 0,
position + 1 == page.active_layouts.len(),
));
section =
section.add(input_source(*id, description, page.expanded_source_popover));
}
}

View file

@ -8,7 +8,7 @@ use cosmic::iced::keyboard::{Key, Location, Modifiers};
use cosmic::iced::platform_specific::shell::wayland::commands::keyboard_shortcuts_inhibit;
use cosmic::iced::platform_specific::shell::wayland::keymap;
use cosmic::iced::{self, Alignment, Length};
use cosmic::widget::{self, button, icon, list, settings, text};
use cosmic::widget::{self, button, icon, settings, text};
use cosmic::{Apply, Element, Task, theme};
use cosmic_config::{ConfigGet, ConfigSet};
use cosmic_settings_config::shortcuts::{self, Action, Binding, Shortcuts};
@ -652,8 +652,7 @@ impl Model {
modifiers,
..
}) => {
use cosmic::iced::keyboard::Key;
use cosmic::iced::keyboard::key::Named;
use cosmic::iced::keyboard::{Key, key::Named};
if matches!(
key,
@ -670,8 +669,7 @@ impl Model {
location,
..
}) => {
use cosmic::iced::keyboard::Key;
use cosmic::iced::keyboard::key::Named;
use cosmic::iced::keyboard::{Key, key::Named};
if matches!(
key,
@ -867,11 +865,13 @@ fn context_drawer<'a>(
}
/// Display a shortcut as a list item
fn shortcut_item(
custom: bool,
id: usize,
data: &ShortcutModel,
) -> list::ListButton<'_, ShortcutMessage> {
fn shortcut_item(custom: bool, id: usize, data: &ShortcutModel) -> Element<'_, ShortcutMessage> {
#[derive(Copy, Clone, Debug)]
enum LocalMessage {
Remove,
Show,
}
let bindings = data
.bindings
.iter()
@ -880,7 +880,7 @@ fn shortcut_item(
.map(|(_, shortcut)| text::body(shortcut.binding.to_string()).into())
.collect::<Vec<_>>();
let shortcuts: Element<ShortcutMessage> = if bindings.is_empty() {
let shortcuts: Element<LocalMessage> = if bindings.is_empty() {
text::body(fl!("disabled")).into()
} else {
widget::column::with_children(bindings)
@ -900,7 +900,7 @@ fn shortcut_item(
.push(icon::from_name("go-next-symbolic").size(16))
.push_maybe(custom.then(|| {
widget::button::icon(icon::from_name("edit-delete-symbolic"))
.on_press(ShortcutMessage::DeleteShortcut(id))
.on_press(LocalMessage::Remove)
}))
.align_y(Alignment::Center)
.spacing(8);
@ -909,7 +909,14 @@ fn shortcut_item(
.flex_control(control)
.align_items(Alignment::Center)
.spacing(16)
.width(Length::Shrink)
.apply(list::button)
.on_press(ShortcutMessage::ShowShortcut(id, data.description.clone()))
.apply(widget::container)
.class(theme::Container::List)
.apply(widget::button::custom)
.class(theme::Button::Transparent)
.on_press(LocalMessage::Show)
.apply(Element::from)
.map(move |message| match message {
LocalMessage::Show => ShortcutMessage::ShowShortcut(id, data.description.clone()),
LocalMessage::Remove => ShortcutMessage::DeleteShortcut(id),
})
}

View file

@ -590,8 +590,7 @@ impl page::Page<crate::pages::Message> for Page {
&self,
core: &cosmic::Core,
) -> cosmic::iced::Subscription<crate::pages::Message> {
use cosmic::iced::event::listen_with;
use cosmic::iced::{self};
use cosmic::iced::{self, event::listen_with};
cosmic::iced::Subscription::batch(vec![
if self.add_shortcut.active
@ -606,8 +605,7 @@ impl page::Page<crate::pages::Message> for Page {
modifiers,
..
}) => {
use cosmic::iced::keyboard::Key;
use cosmic::iced::keyboard::key::Named;
use cosmic::iced::keyboard::{Key, key::Named};
if matches!(
key,
Key::Named(Named::Super | Named::Alt | Named::Control | Named::Shift)
@ -626,8 +624,7 @@ impl page::Page<crate::pages::Message> for Page {
location,
..
}) => {
use cosmic::iced::keyboard::Key;
use cosmic::iced::keyboard::key::Named;
use cosmic::iced::keyboard::{Key, key::Named};
if matches!(
key,
Key::Named(Named::Super | Named::Alt | Named::Control | Named::Shift)

View file

@ -2,9 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-only
use super::{ShortcutMessage, ShortcutModel};
use cosmic::app::ContextDrawer;
use cosmic::iced::platform_specific::shell::wayland::commands::keyboard_shortcuts_inhibit;
use cosmic::{Element, Task};
use cosmic::{Element, Task, app::ContextDrawer};
use cosmic_settings_config::shortcuts::Action;
use cosmic_settings_config::shortcuts::action::ResizeDirection;
use cosmic_settings_page::{self as page, Section, section};

View file

@ -15,16 +15,16 @@ pub mod tiling;
use cosmic::app::ContextDrawer;
use cosmic::iced::Length;
use cosmic::widget::list::ListButton;
use cosmic::widget::{self, settings, text};
use cosmic::{Apply, Element, Task};
use cosmic::widget::{self, icon, settings, text};
use cosmic::{Apply, Element, Task, theme};
use cosmic_config::ConfigGet;
use cosmic_settings_config::Binding;
use cosmic_settings_config::shortcuts::action::{
Direction, FocusDirection, Orientation, ResizeDirection,
};
use cosmic_settings_config::shortcuts::{self, Action, Shortcuts};
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use itertools::Itertools;
use shortcuts::action::System as SystemAction;
use slab::Slab;
@ -222,13 +222,11 @@ impl Page {
self.search.localized = SecondaryMap::new();
self.search.input = String::new();
self.search_model.on_clear();
self.modified.accessibility = 0;
self.modified.custom = 0;
self.modified.manage_windows = 0;
self.modified.move_windows = 0;
self.modified.nav = 0;
self.modified.system = 0;
self.modified.window_tiling = 0;
self.modified.custom = 0;
}
fn reload_search(&mut self) {
@ -410,13 +408,11 @@ impl Search {
.fold(
Slab::with_capacity(self.actions.len()),
|mut slab, (_, action)| {
if !slab.iter().any(|(_, model)| &model.action == action) {
slab.insert(ShortcutModel::new(
&self.defaults,
&self.shortcuts,
action.clone(),
));
}
slab.insert(ShortcutModel::new(
&self.defaults,
&self.shortcuts,
action.clone(),
));
slab
},
@ -501,18 +497,32 @@ fn shortcuts() -> Section<crate::pages::Message> {
}
/// Display a category as a list item
fn category_item(category: Category, name: &str, modified: u16) -> ListButton<'_, Message> {
crate::widget::go_next_with_item(
name,
(modified > 0).then(|| text::body(fl!("modified", count = modified)).apply(Element::from)),
Message::Category(category),
)
fn category_item(category: Category, name: &str, modified: u16) -> Element<'_, Message> {
let icon = icon::from_name("go-next-symbolic").size(16);
let control = if modified == 0 {
Element::from(icon)
} else {
widget::row::with_capacity(2)
.push(text::body(fl!("modified", count = modified)))
.push(icon)
.into()
};
settings::item::builder(name)
.control(control)
.spacing(16)
.apply(widget::container)
.class(theme::Container::List)
.apply(widget::button::custom)
.class(theme::Button::Transparent)
.width(Length::Fill)
.on_press(Message::Category(category))
.into()
}
fn action_category(action: &Action) -> Option<Category> {
Some(if accessibility::actions().contains(action) {
Category::Accessibility
} else if manage_windows::actions().contains(action) {
Some(if manage_windows::actions().contains(action) {
Category::ManageWindow
} else if move_window::actions().contains(action) {
Category::MoveWindow
@ -520,8 +530,6 @@ fn action_category(action: &Action) -> Option<Category> {
Category::Nav
} else if system::actions().contains(action) {
Category::System
} else if tiling::actions().contains(action) {
Category::WindowTiling
} else {
return None;
})

View file

@ -2,9 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-only
//
use super::{ShortcutMessage, ShortcutModel};
use cosmic::app::ContextDrawer;
use cosmic::iced::platform_specific::shell::wayland::commands::keyboard_shortcuts_inhibit;
use cosmic::{Element, Task};
use cosmic::{Element, Task, app::ContextDrawer};
use cosmic_settings_config::shortcuts::Action;
use cosmic_settings_config::shortcuts::action::Direction;
use cosmic_settings_page::{self as page, Section, section};

View file

@ -2,9 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-only
use super::{ShortcutMessage, ShortcutModel};
use cosmic::app::ContextDrawer;
use cosmic::iced::platform_specific::shell::wayland::commands::keyboard_shortcuts_inhibit;
use cosmic::{Element, Task};
use cosmic::{Element, Task, app::ContextDrawer};
use cosmic_settings_config::shortcuts::Action;
use cosmic_settings_config::shortcuts::action::System as SystemAction;
use cosmic_settings_page::{self as page, Section, section};

View file

@ -2,9 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-only
use super::{ShortcutMessage, ShortcutModel};
use cosmic::app::ContextDrawer;
use cosmic::iced::platform_specific::shell::wayland::commands::keyboard_shortcuts_inhibit;
use cosmic::{Element, Task};
use cosmic::{Element, Task, app::ContextDrawer};
use cosmic_settings_config::shortcuts::Action;
use cosmic_settings_config::shortcuts::action::Orientation;
use cosmic_settings_page::{self as page, Section, section};

View file

@ -1,551 +0,0 @@
// Copyright 2026 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
//
// Page « Logitech » — intégration OpenLogi dans les périphériques d'entrée.
// Pilotée par l'agent OpenLogi (openlogi-agent) via son IPC tarpc local.
// Les réglages permanents (remappage complet, profils) restent dans la GUI
// OpenLogi ; cette page couvre le quotidien : pile, DPI, SmartShift.
use cosmic::widget::{self, button, row, settings, text};
use cosmic::{Apply, Element, Task};
use cosmic_settings_page::{self as page, Section, section};
use openlogi_core::device::{BatteryInfo, DeviceKind};
use openlogi_core::hid::{
DeviceRoute, Dpi, DpiInfo, SmartShiftAutoDisengage, SmartShiftMode, SmartShiftStatus,
SmartShiftThreshold, WriteError,
};
use openlogi_ipc::{client, AgentClient, AgentSnapshot};
use slotmap::SlotMap;
use tarpc::context;
/// Clé d'identification stable d'un appareil dans les caches de la page.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct DeviceKey {
pub receiver: String,
pub slot: u8,
}
/// Ce que la page a réussi à lire pour un appareil donné.
/// `None` = non supporté (on n'affiche pas le réglage) ; `Some(Err)` = erreur.
#[derive(Clone, Debug, Default)]
pub struct DeviceReads {
pub dpi: Option<Result<DpiInfo, String>>,
pub smartshift: Option<Result<SmartShiftStatus, String>>,
}
/// Un appareil prêt à afficher : inventaire + lectures.
#[derive(Clone, Debug)]
pub struct DeviceEntry {
pub key: DeviceKey,
pub route: Option<DeviceRoute>,
pub slot: u8,
pub name: String,
pub online: bool,
pub battery: Option<BatteryInfo>,
pub pointer: bool,
pub reads: DeviceReads,
}
#[derive(Clone, Debug)]
pub struct SnapshotData {
pub agent_version: String,
pub hook_installed: bool,
pub devices: Vec<DeviceEntry>,
pub offline_count: usize,
}
#[derive(Clone, Debug)]
pub enum Message {
/// Résultat d'un rafraîchissement complet (None = agent injoignable).
Snapshot(Option<SnapshotData>),
/// Écriture DPI envoyée à l'agent ; maj optimiste du cache.
SetDpi(DeviceKey, DeviceRoute, Dpi),
/// Écriture SmartShift ; maj optimiste du cache.
SetSmartShift(DeviceKey, DeviceRoute, bool),
/// Confirmation (ou échec) d'une écriture, par relecture.
WriteConfirmed(DeviceKey, DeviceReads),
/// Lancer la GUI OpenLogi complète.
OpenApp,
/// Démarrer l'agent s'il ne tourne pas.
StartAgent,
/// Rafraîchir.
Refresh,
}
fn deliver(message: Message) -> crate::app::Message {
crate::app::Message::PageMessage(crate::pages::Message::Logitech(message))
}
#[derive(Default)]
pub struct Page {
entity: page::Entity,
on_enter_handle: Option<cosmic::iced::task::Handle>,
/// `None` : pas encore de réponse de l'agent. `Some(None)` : agent absent.
pub snapshot: Option<Option<SnapshotData>>,
}
impl page::Page<crate::pages::Message> for Page {
fn set_id(&mut self, entity: page::Entity) {
self.entity = entity;
}
fn on_enter(&mut self) -> Task<crate::pages::Message> {
self.start_refresh()
}
fn on_leave(&mut self) -> Task<crate::pages::Message> {
if let Some(handle) = self.on_enter_handle.take() {
handle.abort();
}
Task::none()
}
fn content(
&self,
sections: &mut SlotMap<section::Entity, Section<crate::pages::Message>>,
) -> Option<page::Content> {
Some(vec![sections.insert(devices()), sections.insert(more())])
}
fn info(&self) -> page::Info {
page::Info::new("logitech", "input-mouse-symbolic")
.title(fl!("logitech"))
.description(fl!("logitech-comment"))
}
}
impl page::AutoBind<crate::pages::Message> for Page {}
impl Page {
pub fn update(&mut self, message: Message) -> Task<crate::app::Message> {
match message {
Message::Snapshot(data) => {
self.snapshot = Some(data);
Task::none()
}
Message::SetDpi(key, route, dpi) => {
let write_route = route.clone();
Self::write(write_route, key, move |client| {
let dpi = dpi;
async move {
client
.set_dpi(context::current(), route.clone(), dpi)
.await
}
})
}
Message::SetSmartShift(key, route, enabled) => {
let previous = self
.snapshot
.as_ref()
.and_then(Option::as_ref)
.and_then(|s| s.devices.iter().find(|d| d.key == key))
.and_then(|d| d.reads.smartshift.clone())
.and_then(|r| r.ok());
// SmartShift activé : molette libre avec seuil de bascule.
// Désactivé : cliquet permanent (comme Options+).
let status = match (enabled, previous) {
(true, Some(previous)) => SmartShiftStatus {
mode: SmartShiftMode::Free,
..previous
},
(false, Some(previous)) => SmartShiftStatus {
mode: SmartShiftMode::Ratchet,
auto_disengage: SmartShiftAutoDisengage::Permanent,
..previous
},
(true, None) => SmartShiftStatus {
mode: SmartShiftMode::Free,
auto_disengage: SmartShiftAutoDisengage::Threshold(
SmartShiftThreshold::from_rounded(10.0),
),
tunable_torque: None,
},
(false, None) => SmartShiftStatus {
mode: SmartShiftMode::Ratchet,
auto_disengage: SmartShiftAutoDisengage::Permanent,
tunable_torque: None,
},
};
let write_route = route.clone();
Self::write(write_route, key, move |client| {
let status = status;
async move {
client
.set_smartshift(context::current(), route.clone(), status)
.await
}
})
}
Message::WriteConfirmed(..) => Task::none(),
Message::OpenApp => {
if let Err(err) = std::process::Command::new("openlogi-desktop").spawn() {
tracing::warn!("failed to launch openlogi-desktop: {err}");
}
Task::none()
}
Message::StartAgent => Task::future(async move {
_ = tokio::process::Command::new("systemctl")
.args(["--user", "start", "openlogi-agent.service"])
.status()
.await;
// Laisse le socket de l'agent s'ouvrir avant de réessayer.
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
deliver(Message::Refresh)
}),
Message::Refresh => {
self.start_refresh().map(crate::app::Message::PageMessage)
}
}
}
/// Rafraîchit l'inventaire : connexion à l'agent, snapshot, puis lectures
/// DPI/SmartShift de chaque appareil pointeur en ligne.
fn start_refresh(&mut self) -> Task<crate::pages::Message> {
if let Some(handle) = self.on_enter_handle.take() {
handle.abort();
}
let (task, handle) = Task::future(async move {
crate::pages::Message::Logitech(Message::Snapshot(fetch_snapshot().await))
})
.abortable();
self.on_enter_handle = Some(handle);
task
}
/// Envoie une écriture à l'agent, puis relit l'appareil pour confirmer.
fn write<F, Fut>(route: DeviceRoute, key: DeviceKey, f: F) -> Task<crate::app::Message>
where
F: FnOnce(AgentClient) -> Fut + Send + 'static,
Fut: std::future::Future<
Output = Result<Result<(), WriteError>, tarpc::client::RpcError>,
> + Send,
{
let read_route = route.clone();
Task::future(async move {
if let Ok(connection) = client::connect().await {
let result = f(connection.client).await;
if !matches!(result, Ok(Ok(()))) {
tracing::warn!("openlogi write failed: {result:?}");
}
}
// Relit l'appareil : la valeur affichée redevient la vérité.
let mut reads = DeviceReads::default();
if let Ok(connection) = client::connect().await {
reads.dpi = read_dpi(&connection.client, &read_route).await;
reads.smartshift = read_smartshift(&connection.client, &read_route).await;
}
deliver(Message::WriteConfirmed(key, reads))
})
}
}
/// Une erreur qui signale « l'appareil n'a pas cette fonctionnalité » :
/// le réglage correspondant ne doit simplement pas s'afficher.
fn is_unsupported(err: &WriteError) -> bool {
matches!(
err,
WriteError::FeatureUnsupported { .. } | WriteError::EmptyDpiList
)
}
async fn read_dpi(client: &AgentClient, route: &DeviceRoute) -> Option<Result<DpiInfo, String>> {
match client.read_dpi(context::current(), route.clone()).await {
Ok(Ok(info)) => Some(Ok(info)),
Ok(Err(err)) if is_unsupported(&err) => None,
Ok(Err(err)) => Some(Err(err.to_string())),
Err(err) => Some(Err(err.to_string())),
}
}
async fn read_smartshift(
client: &AgentClient,
route: &DeviceRoute,
) -> Option<Result<SmartShiftStatus, String>> {
match client
.read_smartshift(context::current(), route.clone())
.await
{
Ok(Ok(status)) => Some(Ok(status)),
Ok(Err(err)) if is_unsupported(&err) => None,
Ok(Err(err)) => Some(Err(err.to_string())),
Err(err) => Some(Err(err.to_string())),
}
}
/// Connexion + snapshot + lectures par appareil, en une passe.
async fn fetch_snapshot() -> Option<SnapshotData> {
let connection = client::connect().await.ok()?;
let AgentSnapshot {
status, inventory, ..
} = connection.client.snapshot(context::current()).await.ok()?;
let mut devices = Vec::new();
let mut offline_count = 0usize;
for inv in &inventory {
let receiver = inv
.receiver
.unique_id
.clone()
.unwrap_or_else(|| inv.receiver.name.clone());
for paired in &inv.paired {
if !paired.online {
offline_count += 1;
}
let route = DeviceRoute::device_route_for(inv, paired.slot);
let pointer = paired.kind == DeviceKind::Mouse;
// Ne parle qu'aux pointeurs en ligne, via leur route.
let reads = if paired.online && pointer {
match &route {
Some(route) => DeviceReads {
dpi: read_dpi(&connection.client, route).await,
smartshift: read_smartshift(&connection.client, route).await,
},
None => DeviceReads::default(),
}
} else {
DeviceReads::default()
};
devices.push(DeviceEntry {
key: DeviceKey {
receiver: receiver.clone(),
slot: paired.slot,
},
route,
slot: paired.slot,
name: paired.codename.clone().unwrap_or_else(|| {
fl!("logitech", "device-slot", slot = u32::from(paired.slot))
}),
online: paired.online,
battery: paired.battery.clone(),
pointer,
reads,
});
}
}
Some(SnapshotData {
agent_version: status.agent_version,
hook_installed: status.hook_installed,
devices,
offline_count,
})
}
/// La page ne se lie que si du matériel Logitech est présent (comme le
/// touchpad) : périphérique HID dont le vendor ID est 046d.
pub fn system_has_logitech() -> bool {
let Ok(mut enumerator) = udev::Enumerator::new() else {
return false;
};
let _res = enumerator.match_subsystem("hid");
let Ok(mut devices) = enumerator.scan_devices() else {
return false;
};
devices.any(|device| {
device
.property_value("HID_ID")
.and_then(|value| value.to_str())
.is_some_and(|id| {
// HID_ID = "bustype:vendor:product" en hexadécimal.
id.split(':')
.nth(1)
.is_some_and(|vendor| vendor.eq_ignore_ascii_case("0000046D"))
})
})
}
fn devices() -> Section<crate::pages::Message> {
crate::slab!(descriptions {
dpi = fl!("logitech", "dpi");
smartshift = fl!("logitech", "smartshift");
smartshift_desc = fl!("logitech", "smartshift-desc");
battery = fl!("logitech", "battery");
offline = fl!("logitech", "offline");
online = fl!("logitech", "online");
no_agent = fl!("logitech", "no-agent");
no_agent_desc = fl!("logitech", "no-agent-desc");
start_agent = fl!("logitech", "start-agent");
refresh = fl!("logitech", "refresh");
no_devices = fl!("logitech", "no-devices");
});
Section::default()
.title(fl!("logitech"))
.descriptions(descriptions)
.view::<Page>(move |binder, _page, section| {
let descriptions = &section.descriptions;
let logitech = binder.page::<Page>().expect("logitech page not found");
let mut list = settings::section().title(&section.title);
match &logitech.snapshot {
// Pas encore de réponse : proposition de rafraîchissement.
None => {
list = list.add(settings::item(
"",
button::text(&descriptions[refresh])
.on_press(crate::pages::Message::Logitech(Message::Refresh)),
));
}
// Agent injoignable : explication + remise en route.
Some(None) => {
let actions = row(vec![
button::text(&descriptions[start_agent])
.on_press(crate::pages::Message::Logitech(Message::StartAgent))
.into(),
button::text(fl!("logitech", "open-app"))
.on_press(crate::pages::Message::Logitech(Message::OpenApp))
.into(),
])
.spacing(8);
list = list
.add(settings::item(
&descriptions[no_agent],
text::body(&descriptions[no_agent_desc]),
))
.add(settings::item("", actions));
}
Some(Some(snapshot)) => {
if snapshot.devices.is_empty() {
list = list
.add(settings::item(&descriptions[no_devices], text::body("")));
}
for device in &snapshot.devices {
let mut details = Vec::new();
if let Some(batt) = &device.battery {
details
.push(format!("{} · {} %", descriptions[battery], batt.percentage));
}
details.push(if device.online {
descriptions[online].to_string()
} else {
descriptions[offline].to_string()
});
let details = details.join(" · ");
let Some(route) = device.route.clone() else {
list = list
.add(settings::item(&device.name, text::body(details)));
continue;
};
let item;
if let Some(Ok(dpi_info)) = &device.reads.dpi {
let dpi_info = dpi_info.clone();
let values: Vec<String> = dpi_info
.capabilities
.values()
.iter()
.map(|dpi| dpi.to_string())
.collect();
let selected = dpi_info
.capabilities
.values()
.iter()
.position(|dpi| *dpi == dpi_info.current);
let key = device.key.clone();
let dpi_route = route.clone();
let dpi_control = widget::dropdown(values, selected, move |index| {
let Some(dpi) =
dpi_info.capabilities.values().get(index).copied()
else {
return crate::pages::Message::Logitech(Message::Refresh);
};
crate::pages::Message::Logitech(Message::SetDpi(
key.clone(),
dpi_route.clone(),
dpi,
))
});
item = settings::item::builder(device.name.clone())
.description(details)
.control(dpi_control);
} else {
item = settings::item::builder(device.name.clone())
.description(details)
.control(text::body(""));
}
list = list.add(item);
if let Some(Ok(status)) = &device.reads.smartshift {
let status = *status;
let enabled = status.mode == SmartShiftMode::Free;
let key = device.key.clone();
list = list.add(
settings::item::builder(&descriptions[smartshift])
.description(&descriptions[smartshift_desc])
.toggler(
enabled,
move |value| {
crate::pages::Message::Logitech(
Message::SetSmartShift(
key.clone(),
route.clone(),
value,
),
)
},
),
);
}
}
}
}
list.apply(Element::from)
})
}
fn more() -> Section<crate::pages::Message> {
crate::slab!(descriptions {
open_app = fl!("logitech", "open-app");
open_app_desc = fl!("logitech", "open-app-desc");
});
Section::default()
.title(fl!("logitech", "more"))
.descriptions(descriptions)
.view::<Page>(move |_binder, _page, section| {
let descriptions = &section.descriptions;
settings::section()
.title(&section.title)
.add(
settings::item::builder(&descriptions[open_app])
.description(&descriptions[open_app_desc])
.control(button::text(&descriptions[open_app]).on_press(
crate::pages::Message::Logitech(Message::OpenApp),
)),
)
.apply(Element::from)
})
.into()
}

View file

@ -2,8 +2,10 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::app;
use cosmic::Task;
use cosmic::cosmic_config::{self, ConfigGet, ConfigSet};
use cosmic::{
Task,
cosmic_config::{self, ConfigGet, ConfigSet},
};
use cosmic_comp_config::input::{
AccelConfig, AccelProfile, ClickMethod, InputConfig, ScrollConfig, ScrollMethod, TapButtonMap,
TapConfig,
@ -12,7 +14,6 @@ use cosmic_settings_page as page;
use tracing::error;
pub mod keyboard;
pub mod logitech;
pub mod mouse;
pub mod touchpad;
@ -195,12 +196,6 @@ impl page::AutoBind<crate::pages::Message> for Page {
fn sub_pages(page: page::Insert<crate::pages::Message>) -> page::Insert<crate::pages::Message> {
let insert = page.sub_page::<keyboard::Page>().sub_page::<mouse::Page>();
let insert = if logitech::system_has_logitech() {
insert.sub_page::<logitech::Page>()
} else {
insert
};
if system_has_touchpad() {
insert.sub_page::<touchpad::Page>()
} else {

View file

@ -5,7 +5,8 @@ use cosmic::iced::{Alignment, Length};
use cosmic::widget::{self, row, settings, text};
use cosmic::{Apply, Element};
use cosmic_comp_config::input::AccelProfile;
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use slotmap::SlotMap;
use super::Message;

View file

@ -8,7 +8,8 @@ use cosmic::{Apply, Element};
use cosmic_comp_config::CosmicCompConfig;
use cosmic_comp_config::input::{AccelProfile, ClickMethod, ScrollMethod};
use cosmic_comp_config::workspace::{WorkspaceConfig, WorkspaceLayout};
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use slotmap::SlotMap;
use tracing::error;

View file

@ -17,8 +17,6 @@ pub mod input;
pub mod networking;
#[cfg(feature = "page-power")]
pub mod power;
#[cfg(feature = "page-printers")]
pub mod printers;
#[cfg(feature = "page-sound")]
pub mod sound;
pub mod system;
@ -66,8 +64,6 @@ pub enum Message {
#[cfg(feature = "page-input")]
Keyboard(input::keyboard::Message),
#[cfg(feature = "page-input")]
Logitech(input::logitech::Message),
#[cfg(feature = "page-input")]
KeyboardShortcuts(input::keyboard::shortcuts::Message),
#[cfg(feature = "page-legacy-applications")]
LegacyApplications(applications::legacy_applications::Message),
@ -86,15 +82,11 @@ pub enum Message {
PanelApplet(desktop::panel::applets_inner::Message),
#[cfg(feature = "page-power")]
Power(power::Message),
#[cfg(feature = "page-printers")]
Printers(printers::Message),
#[cfg(feature = "page-region")]
Region(time::region::Message),
#[cfg(feature = "page-sound")]
Sound(sound::Message),
#[cfg(feature = "page-sound")]
SoundApplications(sound::applications::Message),
#[cfg(feature = "page-sound")]
SoundDeviceProfiles(sound::device_profiles::Message),
StartupApps(applications::startup_apps::Message),
#[cfg(feature = "page-users")]

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,24 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
pub mod backend;
pub mod vpn;
pub mod wifi;
pub mod wired;
use std::process::Stdio;
use std::sync::Arc;
use std::{ffi::OsStr, process::Stdio, sync::Arc};
use anyhow::Context;
use cosmic::{Apply, Element, Task, widget};
use cosmic_dbus_networkmanager::{
interface::enums::{DeviceState, DeviceType},
nm::NetworkManager,
};
use cosmic_settings_network_manager_subscription as network_manager;
use cosmic_settings_page::{self as page, Section, section};
use futures::{SinkExt, StreamExt};
use secure_string::SecureString;
use slotmap::SlotMap;
use self::backend as network_manager;
use self::backend::devices::{DeviceState, DeviceType};
pub type SecretSender = Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<SecureString>>>>;
static NM_CONNECTION_EDITOR: &str = "nm-connection-editor";
@ -37,8 +37,8 @@ pub struct Page {
pub enum Message {
/// An error occurred.
Error(String),
/// Successfully connected to NetworkManager.
NetworkManagerConnect(nmrs::NetworkManager),
/// Successfully connected to the system dbus.
NetworkManagerConnect(zbus::Connection),
/// Open the wifi settings page with the selected device.
OpenPage {
page: page::Entity,
@ -143,7 +143,6 @@ impl page::Page<crate::pages::Message> for Page {
fl!("network-device-state", "unavailable")
}
DeviceState::Unknown => fl!("network-device-state", "unknown"),
DeviceState::Other(_) => fl!("network-device-state", "unknown"),
DeviceState::Unmanaged => fl!("network-device-state", "unmanaged"),
},
"preferences-wireless-symbolic",
@ -191,7 +190,6 @@ impl page::Page<crate::pages::Message> for Page {
fl!("network-device-state", "unplugged")
}
DeviceState::Unknown => fl!("network-device-state", "unknown"),
DeviceState::Other(_) => fl!("network-device-state", "unknown"),
DeviceState::Unmanaged => fl!("network-device-state", "unmanaged"),
},
"preferences-wired-symbolic",
@ -227,9 +225,9 @@ impl page::Page<crate::pages::Message> for Page {
fn on_enter(&mut self) -> cosmic::Task<crate::pages::Message> {
if self.nm_task.is_none() {
return cosmic::Task::future(async move {
nmrs::NetworkManager::new()
zbus::Connection::system()
.await
.context("failed to connect to NetworkManager")
.context("failed to create system dbus connection")
.map_or_else(
|why| Message::Error(why.to_string()),
Message::NetworkManagerConnect,
@ -312,47 +310,33 @@ impl Page {
Task::none()
}
fn connect(&mut self, nm: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn connect(&mut self, conn: zbus::Connection) -> Task<crate::app::Message> {
if self.nm_task.is_none() {
let (canceller, task) =
crate::utils::forward_event_loop(move |mut sender| async move {
match network_manager::devices::list(&nm, |_| true).await {
Ok(devices) => {
_ = sender
.send(crate::pages::Message::Networking(Message::UpdateDevices(
devices.into_iter().map(Arc::new).collect(),
)))
.await;
}
let network_manager = match NetworkManager::new(&conn).await {
Ok(n) => n,
Err(why) => {
_ = sender
.send(crate::pages::Message::Networking(Message::Error(
why.to_string(),
)))
.await;
}
}
tracing::error!(
why = why.to_string(),
"failed to connect to network_manager"
);
let Ok(events) = nm.network_events().await else {
return futures::future::pending().await;
return futures::future::pending().await;
}
};
let devices_changed = events.filter_map(|event| async {
match event {
Ok(nmrs::NetworkEvent::DeviceChanged { .. })
| Ok(nmrs::NetworkEvent::SettingsChanged(_))
| Ok(nmrs::NetworkEvent::NetworkManagerRestarted) => {
match network_manager::devices::list(&nm, |_| true).await {
Ok(devices) => Some(Message::UpdateDevices(
let mut devices_changed =
std::pin::pin!(network_manager.receive_devices_changed().await.then(
|_| async {
match network_manager::devices::list(&conn, |_| true).await {
Ok(devices) => Message::UpdateDevices(
devices.into_iter().map(Arc::new).collect(),
)),
Err(why) => Some(Message::Error(why.to_string())),
),
Err(why) => Message::Error(why.to_string()),
}
}
Ok(_) => None,
Err(why) => Some(Message::Error(why.to_string())),
}
});
futures::pin_mut!(devices_changed);
));
while let Some(message) = devices_changed.next().await {
_ = sender
@ -369,6 +353,16 @@ impl Page {
}
}
async fn nm_add_vpn_file<P: AsRef<OsStr>>(type_: &str, path: P) -> Result<(), String> {
tokio::process::Command::new("nmcli")
.args(["connection", "import", "type", type_, "file"])
.arg(path)
.stderr(Stdio::piped())
.output()
.await
.apply(crate::utils::map_stderr_output)
}
async fn nm_add_wired() -> Result<(), String> {
nm_connection_editor(&["--type=802-3-ethernet", "-c"]).await
}

View file

@ -1,27 +1,30 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
pub mod nmcli;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
use anyhow::Context;
use cosmic::dialog::file_chooser::FileFilter;
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::space::horizontal as horizontal_space;
use cosmic::widget::text_input::focus;
use cosmic::widget::{self, icon};
use cosmic::{Apply, Element, Task, task};
use cosmic::task;
use cosmic::{
Apply, Element, Task,
iced::core::text::Wrapping,
iced::{Alignment, Length},
widget::{self, icon, space::horizontal as horizontal_space, text_input::focus},
};
use cosmic_settings_network_manager_subscription::nm_secret_agent::{self, PasswordFlag};
use cosmic_settings_network_manager_subscription::{
self as network_manager, NetworkManagerState, UUID, current_networks::ActiveConnectionInfo,
};
use cosmic_settings_page::{self as page, Section, section};
use futures::{FutureExt, SinkExt, StreamExt};
use indexmap::IndexMap;
use secure_string::SecureString;
use tokio::sync::Mutex;
use super::backend as network_manager;
use super::backend::current_networks::ActiveConnectionInfo;
use super::backend::nm_secret_agent::{self, PasswordFlag};
use super::backend::{NetworkManagerState, UUID};
use crate::pages::networking::SecretSender;
pub static SECURE_INPUT_VPN: LazyLock<widget::Id> = LazyLock::new(widget::Id::unique);
@ -57,8 +60,8 @@ pub enum Message {
NetworkManager(network_manager::Event),
/// An update from the secret agent
SecretAgent(network_manager::nm_secret_agent::Event),
/// Successfully connected to NetworkManager.
NetworkManagerConnect(nmrs::NetworkManager),
/// Successfully connected to the system dbus.
NetworkManagerConnect(zbus::Connection),
/// Updates the password text input
PasswordUpdate(SecureString),
/// Refresh devices and their connection profiles
@ -92,7 +95,6 @@ pub enum ErrorKind {
ConnectionEditor,
ConnectionSettings,
DbusConnection,
OpenVpnConfigPath,
UpdatingState,
WireGuardConfigPath,
WireGuardDevice,
@ -107,7 +109,6 @@ impl ErrorKind {
ErrorKind::ConnectionEditor => fl!("vpn-error", "connection-editor"),
ErrorKind::ConnectionSettings => fl!("vpn-error", "connection-settings"),
ErrorKind::DbusConnection => fl!("dbus-connection-error"),
ErrorKind::OpenVpnConfigPath => fl!("vpn-error", "openvpn-config-path"),
ErrorKind::UpdatingState => fl!("vpn-error", "updating-state"),
ErrorKind::WireGuardConfigPath => fl!("vpn-error", "wireguard-config-path"),
ErrorKind::WireGuardDevice => fl!("vpn-error", "wireguard-device"),
@ -178,7 +179,7 @@ pub enum VpnDialog {
#[derive(Debug)]
pub struct NmState {
conn: nmrs::NetworkManager,
conn: zbus::Connection,
sender: futures::channel::mpsc::UnboundedSender<network_manager::Request>,
active_conns: Vec<ActiveConnectionInfo>,
devices: Vec<network_manager::devices::DeviceInfo>,
@ -368,22 +369,20 @@ impl page::Page<crate::pages::Message> for Page {
let (tx, rx) = tokio::sync::mpsc::channel(4);
self.secret_tx = Some(tx);
if self.nm_task.is_none() {
return cosmic::Task::batch([
cosmic::task::future(async move {
nmrs::NetworkManager::new()
.await
.context("failed to connect to NetworkManager")
.map_or_else(
|why| Message::Error(ErrorKind::DbusConnection, why.to_string()),
Message::NetworkManagerConnect,
)
}),
cosmic::Task::stream(nm_secret_agent::secret_agent_stream(
"com.system76.CosmicSettings.VPN.NetworkManager.SecretAgent",
rx,
))
.map(|m| crate::pages::Message::Vpn(Message::SecretAgent(m))),
]);
return cosmic::Task::batch([cosmic::task::future(async move {
zbus::Connection::system()
.await
.context("failed to create system dbus connection")
.map_or_else(
|why| Message::Error(ErrorKind::DbusConnection, why.to_string()),
Message::NetworkManagerConnect,
)
}),
cosmic::Task::stream(
cosmic_settings_network_manager_subscription::nm_secret_agent::secret_agent_stream("com.system76.CosmicSettings.VPN.NetworkManager.SecretAgent", rx),
)
.map(|m| crate::pages::Message::Vpn(Message::SecretAgent(m))),
]);
}
cosmic::Task::none()
@ -429,19 +428,7 @@ impl Page {
}
}
Message::KnownConnections(connections) => {
let mut connections: Vec<_> = connections.into_iter().collect();
connections.sort_by(|a, b| {
let name_a = match &a.1 {
ConnectionSettings::Vpn(s) => s.id.as_str(),
ConnectionSettings::Wireguard { id } => id.as_str(),
};
let name_b = match &b.1 {
ConnectionSettings::Vpn(s) => s.id.as_str(),
ConnectionSettings::Wireguard { id } => id.as_str(),
};
name_a.to_lowercase().cmp(&name_b.to_lowercase())
});
self.known_connections = connections.into_iter().collect();
self.known_connections = connections;
}
Message::UpdateDevices(devices) => {
self.update_devices(devices);
@ -494,8 +481,9 @@ impl Page {
Message::WireGuardConfig => {
if let Some(VpnDialog::WireGuardName(device, filename, path)) = self.dialog.take() {
return cosmic::task::future(async move {
let _ = filename;
match network_manager::import_wireguard(path, &device).await {
let new_path = path.replace(&filename, &device);
_ = std::fs::rename(&path, &new_path);
match super::nm_add_vpn_file("wireguard", new_path).await {
Ok(_) => Message::Refresh,
Err(why) => Message::Error(ErrorKind::Config, why.to_string()),
}
@ -508,12 +496,18 @@ impl Page {
if let Some(settings) = self.known_connections.get(&uuid) {
let settings = match settings {
ConnectionSettings::Vpn(settings) => settings,
ConnectionSettings::Wireguard { .. } => {
if let Some(NmState { ref sender, .. }) = self.nm_state {
_ = sender
.unbounded_send(network_manager::Request::ActivateVpn(uuid));
}
return Task::none();
ConnectionSettings::Wireguard { id } => {
let connection_name = id.clone();
return cosmic::task::future(async move {
if let Err(why) = nmcli::connect(&connection_name).await {
return Message::Error(
ErrorKind::Connect,
format!("failed to connect to WireGuard VPN: {why}"),
);
}
Message::Refresh
});
}
};
@ -533,10 +527,28 @@ impl Page {
return task::message(Message::FocusSecureInput);
}
_ => {
if let Some(NmState { ref sender, .. }) = self.nm_state {
_ = sender
.unbounded_send(network_manager::Request::ActivateVpn(uuid));
}
let connection_name = settings.id.clone();
let username = settings.username.clone();
return cosmic::task::future(async move {
if let Err(why) = nmcli::connect(&connection_name).await {
return Message::VpnDialogError(VpnDialog::Password {
error: Some((
ErrorKind::Connect,
format!("failed to connect to VPN: {why}"),
)),
id: connection_name.clone(),
uuid,
username: username.clone(),
description: None,
password: SecureString::from(""),
password_hidden: true,
// TODO grab from the current dialog
tx: Arc::new(Mutex::new(None)),
});
}
Message::Refresh
});
}
}
}
@ -603,65 +615,89 @@ impl Page {
};
if let VpnDialog::Password {
id: _,
id,
uuid,
username,
password,
tx,
..
} = dialog
&& let Some(NmState { ref sender, .. }) = self.nm_state
{
let username = username.clone().unwrap_or_default();
let username_unwrapped = username.clone().unwrap_or_default();
let task = self.activate_with_password(
id.clone(),
uuid.clone(),
username_unwrapped.clone(),
password.clone(),
);
let sec_tx = self.secret_tx.clone();
let nm_sender = sender.clone();
return Task::future(async move {
let mut guard = tx.lock().await;
if let Some(sender) = guard.take() {
let _ = sender.send(password);
} else {
if let Some(sec_tx) = sec_tx {
let (applied_tx, applied_rx) = tokio::sync::oneshot::channel();
if let Err(err) = sec_tx
.send(nm_secret_agent::Request::SetSecrets {
setting_name: "vpn".to_string(),
uuid: uuid.to_string(),
secrets: HashMap::from_iter([(
"password".to_string(),
return task
.then(move |_| {
let sec_tx = sec_tx.clone();
let uuid = uuid.clone();
let username = username.clone();
let password = password.clone();
let tx = tx.clone();
let id = id.clone();
Task::future(async move {
let mut guard = tx.lock().await;
if let Some(sender) = guard.take() {
let _ = sender.send(password);
} else {
// apply password and username then
if let Some(sec_tx) = sec_tx {
let (applied_tx, applied_rx) =
tokio::sync::oneshot::channel();
if let Err(err) = sec_tx
.send(nm_secret_agent::Request::SetSecrets {
setting_name: "vpn".to_string(),
uuid: uuid.to_string(),
secrets: HashMap::from_iter([
// username and password
(
"username".to_string(),
username.clone().unwrap_or_default().into(),
),
("password".to_string(), password.clone()),
]),
applied_tx,
})
.await
{
tracing::error!(%err, "failed to apply secret");
}
// wait max 1s for the applied signal
if let Err(err) = tokio::time::timeout(
std::time::Duration::from_secs(1),
applied_rx,
)
.await
{
tracing::error!(%err, "failed to apply secret");
}
}
// activate
if let Err(why) = nmcli::connect(&id).await {
return Message::VpnDialogError(VpnDialog::Password {
error: Some((
ErrorKind::Connect,
format!("failed to connect to VPN: {why}"),
)),
id: id.clone(),
uuid,
username: username.clone(),
description: None,
password,
)]),
applied_tx,
})
.await
{
tracing::error!(%err, "failed to apply secret");
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
});
}
}
if let Err(err) = tokio::time::timeout(
std::time::Duration::from_secs(1),
applied_rx,
)
.await
{
tracing::error!(%err, "failed to apply secret");
}
}
if !username.is_empty() {
_ = nm_sender.unbounded_send(
network_manager::Request::SetVpnUsername {
uuid: uuid.clone(),
username,
},
);
}
_ = nm_sender
.unbounded_send(network_manager::Request::ActivateVpn(uuid));
}
Message::Refresh
})
.map(crate::app::Message::from);
Message::Refresh
})
})
.map(crate::app::Message::from);
}
}
Message::RetryWithPassword => {
@ -670,49 +706,53 @@ impl Page {
};
if let VpnDialog::Password {
id: _,
id,
uuid,
username,
password,
..
} = dialog
&& let Some(NmState { ref sender, .. }) = self.nm_state
{
let username = username.unwrap_or_default();
let username_unwrapped = username.unwrap_or_default();
let sec_tx = self.secret_tx.clone();
let nm_sender = sender.clone();
return Task::future(async move {
if let Some(sec_tx) = sec_tx {
let (applied_tx, applied_rx) = tokio::sync::oneshot::channel();
let _ = sec_tx
.send(nm_secret_agent::Request::SetSecrets {
setting_name: "vpn".to_string(),
uuid: uuid.to_string(),
secrets: HashMap::from_iter([(
"password".to_string(),
password,
)]),
applied_tx,
})
.await;
let _ =
tokio::time::timeout(std::time::Duration::from_secs(1), applied_rx)
let task = self.activate_with_password(
id.clone(),
uuid.clone(),
username_unwrapped.clone(),
password.clone(),
);
return task
.then(move |_| {
let sec_tx = sec_tx.clone();
let uuid = uuid.clone();
let username = username_unwrapped.clone();
let password = password.clone();
Task::future(async move {
if let Some(sec_tx) = sec_tx {
let (applied_tx, applied_rx) = tokio::sync::oneshot::channel();
let _ = sec_tx
.send(nm_secret_agent::Request::SetSecrets {
setting_name: "vpn".to_string(),
uuid: uuid.to_string(),
secrets: HashMap::from_iter([
// username and password
("username".to_string(), username.clone().into()),
("password".to_string(), password.clone()),
]),
applied_tx,
})
.await;
// wait max 1s for the applied signal
let _ = tokio::time::timeout(
std::time::Duration::from_secs(1),
applied_rx,
)
.await;
}
if !username.is_empty() {
_ = nm_sender.unbounded_send(
network_manager::Request::SetVpnUsername {
uuid: uuid.clone(),
username,
},
);
}
_ = nm_sender.unbounded_send(network_manager::Request::ActivateVpn(uuid));
Message::Refresh
})
.map(crate::app::Message::from);
}
Message::Activate(uuid)
})
})
.map(crate::app::Message::from);
}
}
Message::UsernameUpdate(user) => {
@ -819,14 +859,56 @@ impl Page {
Task::none()
}
fn connect(&mut self, conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn activate_with_password(
&mut self,
connection_name: String,
uuid: Arc<str>,
username: String,
password: SecureString,
) -> Task<Message> {
cosmic::task::future(async move {
if let Err(why) = nmcli::set_username(&connection_name, &username).await {
return Message::VpnDialogError(VpnDialog::Password {
error: Some((ErrorKind::WithPassword("username"), why.to_string())),
id: connection_name.clone(),
uuid,
username: Some(username),
description: None,
password,
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
});
}
if let Err(why) = nmcli::add_fallback(&connection_name).await {
return Message::VpnDialogError(VpnDialog::Password {
error: Some((ErrorKind::Config, why.to_string())),
id: connection_name.clone(),
uuid,
username: Some(username),
password,
description: None,
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
});
}
Message::Refresh
})
}
fn connect(&mut self, conn: zbus::Connection) -> Task<crate::app::Message> {
if self.nm_task.is_none() {
let (canceller, task) =
crate::utils::forward_event_loop(move |mut sender| async move {
let (tx, mut rx) = futures::channel::mpsc::channel(1);
let watchers = std::pin::pin!(async move {
network_manager::watch(conn, tx).await;
futures::join!(
network_manager::watch(conn.clone(), tx.clone()),
network_manager::active_conns::watch(conn.clone(), tx.clone()),
network_manager::devices::watch(conn, true, tx)
)
});
let forwarder = std::pin::pin!(async move {
@ -923,20 +1005,7 @@ fn devices_view() -> Section<crate::pages::Message> {
widget::text::body(fl!("no-vpn")).into(),
])));
} else {
let mut known_connections: Vec<_> = page.known_connections.iter().collect();
known_connections.sort_by(|a, b| {
let name_a = match a.1 {
ConnectionSettings::Vpn(s) => s.id.as_str(),
ConnectionSettings::Wireguard { id } => id.as_str(),
};
let name_b = match b.1 {
ConnectionSettings::Vpn(s) => s.id.as_str(),
ConnectionSettings::Wireguard { id } => id.as_str(),
};
name_a.to_lowercase().cmp(&name_b.to_lowercase())
});
let known_networks = known_connections.into_iter().fold(
let known_networks = page.known_connections.iter().fold(
vpn_connections,
|networks, (uuid, connection)| {
let id = match connection {
@ -1045,7 +1114,7 @@ fn popup_button(message: Message, text: &str) -> Element<'_, Message> {
.into()
}
fn update_state(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn update_state(conn: zbus::Connection) -> Task<crate::app::Message> {
cosmic::task::future(async move {
match NetworkManagerState::new(&conn).await {
Ok(state) => Message::UpdateState(state),
@ -1054,7 +1123,7 @@ fn update_state(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
})
}
fn update_devices(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn update_devices(conn: zbus::Connection) -> Task<crate::app::Message> {
cosmic::task::future(async move {
let filter =
|device_type| matches!(device_type, network_manager::devices::DeviceType::WireGuard);
@ -1105,16 +1174,8 @@ fn add_network() -> Task<crate::app::Message> {
return Message::AddWireGuardDevice(device, filename.to_owned(), path);
} else {
let Ok(path) = response.url().to_file_path() else {
return Message::Error(
ErrorKind::OpenVpnConfigPath,
fl!("vpn-error", "openvpn-config-path-desc"),
);
};
network_manager::import_openvpn(path)
super::nm_add_vpn_file("openvpn", response.url().to_file_path().unwrap())
.await
.map_err(|why| why.to_string())
};
match result {
@ -1129,96 +1190,108 @@ fn add_network() -> Task<crate::app::Message> {
.apply(cosmic::task::future)
}
fn connection_settings(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
cosmic::task::future(async move {
let settings = async move {
let vpns = conn.list_vpn_connections().await?;
let mut settings = IndexMap::new();
fn connection_settings(conn: zbus::Connection) -> Task<crate::app::Message> {
let settings = async move {
let settings = network_manager::dbus::settings::NetworkManagerSettings::new(&conn).await?;
for vpn in vpns {
let uuid = Arc::from(vpn.uuid.as_str());
let data = match vpn.vpn_type {
nmrs::VpnType::WireGuard { .. } => ConnectionSettings::Wireguard { id: vpn.id },
nmrs::VpnType::OpenVpn {
_ = settings.load_connections(&[]).await;
let settings = settings
// Get a list of known connections.
.list_connections()
.await?
// Prepare for wrapping in a concurrent stream.
.into_iter()
.map(|conn| async move { conn })
// Create a concurrent stream for each connection.
.apply(futures::stream::FuturesOrdered::from_iter)
// Concurrently fetch settings for each connection, and filter for VPN.
.filter_map(|conn| async move {
let settings = conn.get_settings().await.ok()?;
let connection = settings.get("connection")?;
match connection
.get("type")?
.downcast_ref::<String>()
.ok()?
.as_str()
{
"vpn" => (),
"wireguard" => {
let id = connection.get("id")?.downcast_ref::<String>().ok()?;
let uuid = connection.get("uuid")?.downcast_ref::<String>().ok()?;
return Some((Arc::from(uuid), ConnectionSettings::Wireguard { id }));
}
_ => return None,
}
let vpn = settings.get("vpn")?;
let id = connection.get("id")?.downcast_ref::<String>().ok()?;
let uuid = connection.get("uuid")?.downcast_ref::<String>().ok()?;
let (connection_type, username, password_flag) = vpn
.get("data")
.and_then(|data| data.downcast_ref::<zbus::zvariant::Dict>().ok())
.map(|dict| {
let (mut connection_type, mut password_flag) = (None, None);
let mut username = vpn
.get("user-name")
.and_then(|u| u.downcast_ref::<String>().ok());
if dict
.get::<String, String>(&String::from("connection-type"))
.ok()
.flatten()
.as_deref()
// may be "password" or "password-tls"
.is_some_and(|p| p.starts_with("password"))
{
connection_type = Some(ConnectionType::Password);
username = Some(username.unwrap_or_default());
password_flag = dict
.get::<String, String>(&String::from("password-flags"))
.ok()
.flatten()
.and_then(|value| match value.as_str() {
"0" => Some(PasswordFlag::None),
"1" => Some(PasswordFlag::AgentOwned),
"2" => Some(PasswordFlag::NotSaved),
"4" => Some(PasswordFlag::NotRequired),
_ => None,
});
}
(connection_type, username, password_flag)
})
.unwrap_or_default();
Some((
Arc::from(uuid),
ConnectionSettings::Vpn(VpnConnectionSettings {
id,
connection_type,
user_name,
password_flags,
..
} => ConnectionSettings::Vpn(VpnConnectionSettings {
id: vpn.id,
username: user_name,
connection_type: connection_type
.filter(|ct| {
matches!(
ct,
nmrs::OpenVpnConnectionType::Password
| nmrs::OpenVpnConnectionType::PasswordTls
)
})
.map(|_| ConnectionType::Password),
password_flag: Some(password_flag(password_flags.0)),
password_flag,
username,
}),
nmrs::VpnType::OpenConnect {
user_name,
password_flags,
..
}
| nmrs::VpnType::StrongSwan {
user_name,
password_flags,
..
}
| nmrs::VpnType::Pptp {
user_name,
password_flags,
..
}
| nmrs::VpnType::L2tp {
user_name,
password_flags,
..
} => ConnectionSettings::Vpn(VpnConnectionSettings {
id: vpn.id,
username: user_name,
connection_type: Some(ConnectionType::Password),
password_flag: Some(password_flag(password_flags.0)),
}),
nmrs::VpnType::Generic {
user_name,
password_flags,
..
} => ConnectionSettings::Vpn(VpnConnectionSettings {
id: vpn.id,
username: user_name,
connection_type: Some(ConnectionType::Password),
password_flag: Some(password_flag(password_flags.0)),
}),
_ => ConnectionSettings::Vpn(VpnConnectionSettings {
id: vpn.id,
username: None,
connection_type: None,
password_flag: None,
}),
};
settings.insert(uuid, data);
}
))
})
// Reduce the settings list into
.fold(IndexMap::new(), |mut set, (uuid, data)| async move {
set.insert(uuid, data);
set
})
.await;
Ok::<_, nmrs::ConnectionError>(settings)
};
Ok::<_, zbus::Error>(settings)
};
cosmic::task::future(async move {
settings.await.map_or_else(
|why| Message::Error(ErrorKind::ConnectionSettings, why.to_string()),
Message::KnownConnections,
)
})
}
fn password_flag(value: u32) -> PasswordFlag {
match value {
0 => PasswordFlag::None,
1 => PasswordFlag::AgentOwned,
2 => PasswordFlag::NotSaved,
4 => PasswordFlag::NotRequired,
_ => PasswordFlag::AgentOwned,
}
}

View file

@ -0,0 +1,38 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use cosmic::Apply;
use std::process::Stdio;
pub async fn set_username(connection_name: &str, username: &str) -> Result<(), String> {
tokio::process::Command::new("nmcli")
.args(["con", "mod", connection_name, "vpn.user-name", username])
.stderr(Stdio::piped())
.output()
.await
.apply(crate::utils::map_stderr_output)
}
pub async fn add_fallback(connection_name: &str) -> Result<(), String> {
tokio::process::Command::new("nmcli")
.args([
"con",
"mod",
connection_name,
"+vpn.data",
"data-ciphers=AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305:AES-256-CBC:AES-128-CBC",
])
.stderr(Stdio::piped())
.output()
.await
.apply(crate::utils::map_stderr_output)
}
pub async fn connect(connection_name: &str) -> Result<(), String> {
tokio::process::Command::new("nmcli")
.args(["con", "up", connection_name])
.stderr(Stdio::piped())
.output()
.await
.apply(crate::utils::map_stderr_output)
}

View file

@ -1,27 +1,31 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, LazyLock};
use std::{
collections::{BTreeMap, BTreeSet},
sync::{Arc, LazyLock},
};
use anyhow::Context;
use cosmic::app::ContextDrawer;
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::widget::operation::focus_next;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::space::horizontal;
use cosmic::widget::text_input::focus;
use cosmic::widget::{self, column, icon};
use cosmic::{Apply, Element, Task, task};
use cosmic::{
Apply, Element, Task,
app::ContextDrawer,
iced::core::text::Wrapping,
iced::{Alignment, Length, widget::operation::focus_next},
task,
widget::{self, column, icon, space::horizontal, text_input::focus},
};
use cosmic_settings_network_manager_subscription::{
self as network_manager, NetworkManagerState,
available_wifi::{AccessPoint, NetworkType},
current_networks::ActiveConnectionInfo,
nm_secret_agent,
};
use cosmic_settings_page::{self as page, Section, section};
use futures::{SinkExt, StreamExt};
use secure_string::SecureString;
use tokio::sync::Mutex;
use super::backend as network_manager;
use super::backend::available_wifi::{AccessPoint, NetworkType};
use super::backend::current_networks::ActiveConnectionInfo;
use super::backend::{NetworkManagerState, nm_secret_agent};
use crate::pages::networking::SecretSender;
pub static SECURE_INPUT_WIFI: LazyLock<widget::Id> = LazyLock::new(widget::Id::unique);
@ -54,8 +58,8 @@ pub enum Message {
NetworkManager(network_manager::Event),
/// An update from the secret agent
SecretAgent(network_manager::nm_secret_agent::Event),
/// Successfully connected to NetworkManager.
NetworkManagerConnect(nmrs::NetworkManager),
/// Successfully connected to the system dbus.
NetworkManagerConnect(zbus::Connection),
/// Request an auth dialog
PasswordRequest(network_manager::SSID),
/// Update the password from the dialog
@ -101,7 +105,6 @@ enum WiFiDialog {
ssid: network_manager::SSID,
identity: Option<String>,
password: SecureString,
network_type: NetworkType,
password_hidden: bool,
tx: SecretSender,
},
@ -141,7 +144,7 @@ pub struct Page {
#[derive(Debug)]
pub struct NmState {
conn: nmrs::NetworkManager,
conn: zbus::Connection,
sender: futures::channel::mpsc::UnboundedSender<network_manager::Request>,
state: network_manager::NetworkManagerState,
devices: Vec<network_manager::devices::DeviceInfo>,
@ -294,23 +297,19 @@ impl page::Page<crate::pages::Message> for Page {
let (tx, rx) = tokio::sync::mpsc::channel(4);
self.secret_tx = Some(tx);
if self.nm_task.is_none() {
return Task::batch(vec![
cosmic::Task::future(async move {
nmrs::NetworkManager::new()
.await
.context("failed to connect to NetworkManager")
.map_or_else(
|why| Message::Error(why.to_string()),
Message::NetworkManagerConnect,
)
.apply(crate::pages::Message::WiFi)
}),
cosmic::Task::stream(nm_secret_agent::secret_agent_stream(
"com.system76.CosmicSettings.WiFi.NetworkManager.SecretAgent",
rx,
))
.map(|m| crate::pages::Message::WiFi(Message::SecretAgent(m))),
]);
return Task::batch(vec![cosmic::Task::future(async move {
zbus::Connection::system()
.await
.context("failed to create system dbus connection")
.map_or_else(
|why| Message::Error(why.to_string()),
Message::NetworkManagerConnect,
)
.apply(crate::pages::Message::WiFi)
}), cosmic::Task::stream(
cosmic_settings_network_manager_subscription::nm_secret_agent::secret_agent_stream("com.system76.CosmicSettings.WiFi.NetworkManager.SecretAgent", rx),
)
.map(|m| crate::pages::Message::WiFi(Message::SecretAgent(m)))]);
}
Task::none()
@ -356,22 +355,15 @@ impl Page {
}
match req {
network_manager::Request::Authenticate {
ssid,
identity,
network_type,
..
} => {
network_manager::Request::Authenticate { ssid, identity, .. } => {
if success {
self.connecting.remove(ssid.as_str());
} else {
self.connecting.remove(ssid.as_str());
// Request to retry
self.dialog = Some(WiFiDialog::Password {
ssid: ssid.into(),
identity,
password: SecureString::from(""),
network_type,
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
});
@ -388,13 +380,11 @@ impl Page {
if success || matches!(network_type, NetworkType::Open) {
self.connecting.remove(ssid.as_ref());
} else {
self.connecting.remove(ssid.as_ref());
self.dialog = Some(WiFiDialog::Password {
ssid,
identity: matches!(network_type, NetworkType::EAP)
.then(String::new),
password: SecureString::from(""),
network_type,
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
});
@ -462,7 +452,6 @@ impl Page {
let qr_string = if let Some(ref pass) = password {
let security = match security_type {
NetworkType::PskOrSae => "WPA",
NetworkType::Sae => "WPA",
NetworkType::EAP => "WPA",
NetworkType::Open => "",
};
@ -535,7 +524,6 @@ impl Page {
ssid,
identity: matches!(ap.network_type, NetworkType::EAP).then(String::new),
password: SecureString::from(""),
network_type: ap.network_type,
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
});
@ -559,7 +547,6 @@ impl Page {
ssid,
identity,
password,
network_type,
tx,
..
} = dialog
@ -578,7 +565,6 @@ impl Page {
ssid: ssid.to_string(),
identity,
password,
network_type,
secret_tx,
interface,
});
@ -631,7 +617,6 @@ impl Page {
}
Message::Disconnect(ssid) => {
self.close_popup_and_apply_updates();
self.connecting.remove(ssid.as_ref());
if let Some(nm) = self.nm_state.as_mut() {
_ = nm
.sender
@ -645,7 +630,6 @@ impl Page {
Message::Forget(ssid) => {
self.dialog = None;
self.close_popup_and_apply_updates();
self.connecting.remove(ssid.as_ref());
if let Some(nm) = self.nm_state.as_mut() {
_ = nm
.sender
@ -667,9 +651,6 @@ impl Page {
}
}
Message::WiFiEnable(enable) => {
if !enable {
self.connecting.clear();
}
if let Some(nm) = self.nm_state.as_mut() {
_ = nm
.sender
@ -678,9 +659,7 @@ impl Page {
}
}
Message::CancelDialog => {
if let Some(WiFiDialog::Password { ssid, .. }) = self.dialog.take() {
self.connecting.remove(ssid.as_ref());
}
self.dialog = None;
}
Message::Error(why) => {
tracing::error!(why);
@ -739,20 +718,15 @@ impl Page {
password: previous,
password_hidden: true,
identity: matches!(ap.network_type, NetworkType::EAP).then(String::new),
network_type: ap.network_type,
tx,
});
return task::message(Message::FocusSecureInput);
}
nm_secret_agent::Event::CancelGetSecrets { uuid: _, name: _ } => {
match self.dialog.take() {
Some(WiFiDialog::Password { ssid, .. }) => {
self.connecting.remove(ssid.as_ref());
}
other => {
self.dialog = other;
}
}
self.dialog = self
.dialog
.take()
.filter(|d| !matches!(d, &WiFiDialog::Password { .. }));
}
nm_secret_agent::Event::Failed(error) => {
tracing::error!(%error, "secret agent failure");
@ -760,18 +734,15 @@ impl Page {
ssid,
password,
identity,
network_type,
..
}) = self.dialog.take()
{
self.connecting.remove(ssid.as_ref());
self.dialog = Some(WiFiDialog::Password {
password,
password_hidden: true,
tx: Arc::new(Mutex::new(None)),
ssid,
identity,
network_type,
});
return task::message(Message::FocusSecureInput);
}
@ -802,14 +773,19 @@ impl Page {
Task::none()
}
fn connect(&mut self, conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn connect(&mut self, conn: zbus::Connection) -> Task<crate::app::Message> {
if self.nm_task.is_none() {
let (canceller, task) =
crate::utils::forward_event_loop(move |mut sender| async move {
let (tx, mut rx) = futures::channel::mpsc::channel(1);
let watchers = std::pin::pin!(async move {
network_manager::watch(conn, tx).await;
futures::join!(
network_manager::watch(conn.clone(), tx.clone()),
network_manager::active_conns::watch(conn.clone(), tx.clone()),
network_manager::wireless_enabled::watch(conn.clone(), tx.clone()),
network_manager::watch_connections_changed(conn, tx)
);
});
let forwarder = std::pin::pin!(async move {
@ -859,12 +835,6 @@ impl Page {
/// Withholds updates if the view more popup is displayed.
fn update_state(&mut self, state: NetworkManagerState) {
for active in &state.active_conns {
if let ActiveConnectionInfo::WiFi { name, .. } = active {
self.connecting.remove(name.as_str());
}
}
if let Some(ref mut nm_state) = self.nm_state {
if self.view_more_popup.is_some() {
self.withheld_state = Some(state);
@ -1206,9 +1176,10 @@ fn devices_view() -> Section<crate::pages::Message> {
// Search input (only shown when 15+ networks)
if show_search {
let search_input = widget::search_input("", &page.search_query)
.on_input(Message::SearchQuery)
.on_clear(Message::SearchQuery(String::new()));
let search_input =
widget::search_input(fl!("type-to-search"), &page.search_query)
.on_input(Message::SearchQuery)
.on_clear(Message::SearchQuery(String::new()));
visible_section = visible_section.push(search_input);
}
@ -1304,9 +1275,51 @@ fn popup_button(message: Message, text: &str) -> Element<'_, Message> {
.into()
}
fn connection_settings(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn connection_settings(conn: zbus::Connection) -> Task<crate::app::Message> {
let settings = async move {
let settings = network_manager::dbus::settings::NetworkManagerSettings::new(&conn).await?;
_ = settings.load_connections(&[]).await;
let settings = settings
// Get a list of known connections.
.list_connections()
.await?
// Prepare for wrapping in a concurrent stream.
.into_iter()
.map(|conn| async move { conn })
// Create a concurrent stream for each connection.
.apply(futures::stream::FuturesOrdered::from_iter)
// Concurrently fetch settings for each connection.
.filter_map(|conn| async move {
conn.get_settings()
.await
.map(network_manager::Settings::new)
.ok()
})
// Reduce the settings list into a SSID->UUID map.
.fold(BTreeMap::new(), |mut set, settings| async move {
if let Some(ref wifi) = settings.wifi
&& let Some(ssid) = wifi
.ssid
.clone()
.and_then(|ssid| String::from_utf8(ssid).ok())
&& let Some(ref connection) = settings.connection
&& let Some(uuid) = connection.uuid.clone()
{
set.insert(ssid.into(), uuid.into());
return set;
}
set
})
.await;
Ok::<_, zbus::Error>(settings)
};
cosmic::task::future(async move {
network_manager::wifi_connection_settings(conn)
settings
.await
.context("failed to get connection settings")
.map_or_else(
@ -1317,7 +1330,7 @@ fn connection_settings(conn: nmrs::NetworkManager) -> Task<crate::app::Message>
})
}
pub fn update_state(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
pub fn update_state(conn: zbus::Connection) -> Task<crate::app::Message> {
cosmic::task::future(async move {
match NetworkManagerState::new(&conn).await {
Ok(state) => Message::UpdateState(state),
@ -1326,7 +1339,7 @@ pub fn update_state(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
})
}
pub fn update_devices(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
pub fn update_devices(conn: zbus::Connection) -> Task<crate::app::Message> {
cosmic::task::future(async move {
let filter =
|device_type| matches!(device_type, network_manager::devices::DeviceType::Wifi);

View file

@ -1,23 +1,22 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::BTreeSet;
use std::sync::Arc;
use std::{collections::BTreeSet, sync::Arc};
use anyhow::Context;
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::space::horizontal as horizontal_space;
use cosmic::widget::{self, icon};
use cosmic::{Apply, Element, Task};
use cosmic::{
Apply, Element, Task,
iced::core::text::Wrapping,
iced::{Alignment, Length},
widget::{self, icon, space::horizontal as horizontal_space},
};
use cosmic_dbus_networkmanager::interface::enums::DeviceState;
use cosmic_settings_network_manager_subscription::{
self as network_manager, NetworkManagerState, current_networks::ActiveConnectionInfo,
};
use cosmic_settings_page::{self as page, Section, section};
use futures::{SinkExt, StreamExt};
use super::backend as network_manager;
use super::backend::NetworkManagerState;
use super::backend::current_networks::ActiveConnectionInfo;
use super::backend::devices::DeviceState;
pub type ConnectionId = Arc<str>;
#[derive(Clone, Debug)]
@ -34,8 +33,8 @@ pub enum Message {
Error(String),
/// An update from the network manager daemon
NetworkManager(network_manager::Event),
/// Successfully connected to NetworkManager.
NetworkManagerConnect(nmrs::NetworkManager),
/// Successfully connected to the system dbus.
NetworkManagerConnect(zbus::Connection),
/// Refresh devices and their connection profiles
Refresh,
/// Create a dialog to ask for confirmation of removal.
@ -93,7 +92,7 @@ pub struct Page {
#[derive(Debug)]
pub struct NmState {
conn: nmrs::NetworkManager,
conn: zbus::Connection,
sender: futures::channel::mpsc::UnboundedSender<network_manager::Request>,
active_conns: Vec<ActiveConnectionInfo>,
devices: Vec<Arc<network_manager::devices::DeviceInfo>>,
@ -156,9 +155,9 @@ impl page::Page<crate::pages::Message> for Page {
fn on_enter(&mut self) -> cosmic::Task<crate::pages::Message> {
if self.nm_task.is_none() {
return cosmic::task::future(async move {
nmrs::NetworkManager::new()
zbus::Connection::system()
.await
.context("failed to connect to NetworkManager")
.context("failed to create system dbus connection")
.map_or_else(
|why| Message::Error(why.to_string()),
Message::NetworkManagerConnect,
@ -358,14 +357,18 @@ impl Page {
Task::none()
}
fn connect(&mut self, conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn connect(&mut self, conn: zbus::Connection) -> Task<crate::app::Message> {
if self.nm_task.is_none() {
let (canceller, task) =
crate::utils::forward_event_loop(move |mut sender| async move {
let (tx, mut rx) = futures::channel::mpsc::channel(1);
let watchers = std::pin::pin!(async move {
network_manager::watch(conn, tx).await;
futures::join!(
network_manager::watch(conn.clone(), tx.clone()),
network_manager::active_conns::watch(conn.clone(), tx.clone()),
network_manager::devices::watch(conn, true, tx)
)
});
let forwarder = std::pin::pin!(async move {
@ -620,7 +623,7 @@ fn popup_button(message: Message, text: &str) -> Element<'_, Message> {
.into()
}
fn update_state(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn update_state(conn: zbus::Connection) -> Task<crate::app::Message> {
cosmic::task::future(async move {
match NetworkManagerState::new(&conn).await {
Ok(state) => Message::UpdateState(state),
@ -629,7 +632,7 @@ fn update_state(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
})
}
fn update_devices(conn: nmrs::NetworkManager) -> Task<crate::app::Message> {
fn update_devices(conn: zbus::Connection) -> Task<crate::app::Message> {
cosmic::task::future(async move {
let filter =
|device_type| matches!(device_type, network_manager::devices::DeviceType::Ethernet);

View file

@ -1,9 +1,7 @@
use futures::future::join_all;
use futures::{FutureExt, Stream, StreamExt};
use futures::{FutureExt, Stream, StreamExt, future::join_all};
use jiff::{Span, SpanRelativeTo, SpanRound, ToSpan, Unit};
use upower_dbus::{BatteryState, BatteryType, DeviceProxy};
use zbus::Connection;
use zbus::zvariant::ObjectPath;
use zbus::{Connection, zvariant::ObjectPath};
mod ppdaemon;
mod s76powerdaemon;

View file

@ -3,11 +3,12 @@ mod backend;
use self::backend::{GetCurrentPowerProfile, SetPowerProfile};
use backend::{Battery, ConnectedDevice, PowerProfile};
use cosmic::Task;
use cosmic::iced::core::text::{Ellipsize, EllipsizeHeightLimit};
use cosmic::iced::widget::{column, row};
use cosmic::iced::{self, Alignment, Length, stream};
use cosmic::widget::{self, settings, space, text};
use cosmic::{Apply, Task, surface};
use cosmic::{Apply, surface};
use cosmic_config::{Config, CosmicConfigEntry};
use cosmic_idle_config::CosmicIdleConfig;
use cosmic_settings_page::{self as page, Section, section};

View file

@ -1,536 +0,0 @@
// Copyright 2026 Lionel DARNIS <lionel@wopr.io>
// SPDX-License-Identifier: GPL-3.0-only
//! CUPS backend for the printers page.
//!
//! Read-only operations (destinations, jobs) use the `cups_rs` bindings to
//! libcups. Mutating operations (add, remove, default, pause) go through the
//! CUPS command line tools, which authenticate transparently against the
//! local scheduler for users in the CUPS system group.
use tokio::process::Command;
pub use cups_rs::{JobStatus, PrinterState};
const TEST_PAGE: &str = "/usr/share/cups/data/testprint";
/// `printer-type` bit marking destinations that CUPS merely discovered on the
/// network (dnssd browsing). Those are not real queues: they cannot be removed
/// or configured and vanish on their own, so the page must not list them.
const CUPS_PRINTER_DISCOVERED: u32 = 0x1000000;
/// libcups keeps process-wide global state; serialize every FFI call.
static CUPS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn cups_lock() -> std::sync::MutexGuard<'static, ()> {
CUPS_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// A printer queue known to the CUPS scheduler.
#[derive(Clone, Debug)]
pub struct Printer {
pub name: String,
pub info: String,
pub make_and_model: Option<String>,
pub location: Option<String>,
pub device_uri: Option<String>,
pub state: PrinterState,
pub state_reasons: Vec<String>,
pub accepting_jobs: bool,
pub is_default: bool,
}
/// An active print job.
#[derive(Clone, Debug)]
pub struct Job {
pub id: i32,
pub title: String,
pub dest: String,
pub status: JobStatus,
}
/// A device that a printer queue can be created for.
#[derive(Clone, Debug)]
pub struct Device {
pub uri: String,
pub info: String,
}
/// A printer driver (PPD or driverless profile).
#[derive(Clone, Debug)]
pub struct Driver {
pub id: String,
pub description: String,
}
/// Read operations (blocking FFI; call from a blocking task).
pub fn printers_sync() -> Result<Vec<Printer>, String> {
let _guard = cups_lock();
let destinations = cups_rs::get_all_destinations().map_err(|err| err.to_string())?;
Ok(destinations
.iter()
.filter(|dest| {
!dest
.get_option("printer-type")
.and_then(|value| value.parse::<u32>().ok())
.is_some_and(|printer_type| printer_type & CUPS_PRINTER_DISCOVERED != 0)
})
.map(|dest| Printer {
name: dest.name.clone(),
info: dest
.info()
.filter(|info| !info.is_empty())
.cloned()
.unwrap_or_else(|| dest.name.clone()),
make_and_model: dest.make_and_model().cloned(),
location: dest.location().cloned(),
device_uri: dest.device_uri().cloned(),
state: dest.state(),
state_reasons: dest
.state_reasons()
.into_iter()
.filter(|reason| reason != "none")
.collect(),
accepting_jobs: dest.is_accepting_jobs(),
is_default: dest.is_default,
})
.collect())
}
pub fn jobs_sync() -> Result<Vec<Job>, String> {
let _guard = cups_lock();
let jobs = cups_rs::get_active_jobs(None).map_err(|err| err.to_string())?;
Ok(jobs
.into_iter()
.map(|job| Job {
id: job.id,
title: job.title,
dest: job.dest,
status: job.status,
})
.collect())
}
pub fn cancel_job_sync(job_id: i32) -> Result<(), String> {
let _guard = cups_lock();
cups_rs::job::cancel_job(job_id).map_err(|err| err.to_string())
}
pub async fn print_test_page(printer: &str) -> Result<(), String> {
// Submit through `lp` so CUPS sniffs the format itself: the test page is
// a cups-filters PDF banner template (#PDF-BANNER), not PostScript, and
// cups_rs only allows a hardcoded list of document formats.
run_cli("lp", &["-d", printer, TEST_PAGE]).await
}
/// Discovery and administration (CUPS command line tools).
pub async fn devices() -> Result<Vec<Device>, String> {
let output = run_cli_capture("lpinfo", &["-v"]).await?;
let mut devices: Vec<Device> = Vec::new();
for line in output.lines() {
let Some((_, uri)) = line.split_once(char::is_whitespace) else {
continue;
};
let uri = uri.trim();
if !uri.contains("://") {
continue;
}
let info = device_info(uri);
// One entry per physical device: the same printer is advertised over
// several schemes (dnssd, ipp, ipps…). Prefer the dnssd URI, which
// keeps working across IP changes.
if let Some(existing) = devices.iter_mut().find(|device| device.info == info) {
if uri.starts_with("dnssd://") && !existing.uri.starts_with("dnssd://") {
existing.uri = uri.to_string();
}
continue;
}
devices.push(Device {
info,
uri: uri.to_string(),
});
}
Ok(devices)
}
pub async fn drivers() -> Result<Vec<Driver>, String> {
let output = run_cli_capture("lpinfo", &["-m"]).await?;
let mut drivers: Vec<Driver> = output
.lines()
.filter_map(|line| {
let (id, description) = line.split_once(char::is_whitespace)?;
Some(Driver {
id: id.trim().to_string(),
description: description.trim().to_string(),
})
})
.collect();
// Offer the driverless IPP Everywhere profile first.
drivers.sort_by_key(|driver| driver.id != "everywhere");
Ok(drivers)
}
pub async fn add_printer(name: &str, uri: &str, driver: &str) -> Result<(), String> {
run_cli("lpadmin", &["-p", name, "-E", "-v", uri, "-m", driver]).await
}
pub async fn remove_printer(name: &str) -> Result<(), String> {
match run_cli("lpadmin", &["-x", name]).await {
Ok(()) => Ok(()),
// A queue that vanished between listing and removal is already gone;
// treat it as a successful removal instead of an error.
Err(err)
if err.contains("n'existe pas") || err.to_lowercase().contains("not exist") =>
{
Ok(())
}
Err(err) => Err(err),
}
}
/// Default job options supported by a queue, with their current values.
///
/// Values are taken from the queue's PPD view (`lpoptions -l`): `PageSize`,
/// `MediaType`, `ColorModel`, `cupsPrintQuality` and `Duplex`, which
/// `lpadmin -o` can persist.
#[derive(Clone, Debug, Default)]
pub struct PrinterOptions {
pub media: Vec<String>,
pub media_default: Option<String>,
pub media_types: Vec<String>,
pub media_type_default: Option<String>,
pub color_models: Vec<String>,
pub color_model_default: Option<String>,
pub qualities: Vec<String>,
pub quality_default: Option<String>,
pub sides: Vec<String>,
pub sides_default: Option<String>,
}
pub async fn printer_options(name: &str) -> Result<PrinterOptions, String> {
let output = run_cli_capture("lpoptions", &["-p", name, "-l"]).await?;
let mut options = PrinterOptions::default();
for line in output.lines() {
let Some((key, values)) = line.split_once(':') else {
continue;
};
let key = key.split('/').next().unwrap_or(key).trim();
let parsed: Vec<(String, bool)> = values
.split_whitespace()
.map(|value| {
(
value.trim_start_matches('*').to_string(),
value.starts_with('*'),
)
})
.collect();
let (list, default) = match key {
"PageSize" => (&mut options.media, &mut options.media_default),
"MediaType" => (&mut options.media_types, &mut options.media_type_default),
"ColorModel" => (&mut options.color_models, &mut options.color_model_default),
"cupsPrintQuality" => (&mut options.qualities, &mut options.quality_default),
"Duplex" => (&mut options.sides, &mut options.sides_default),
_ => continue,
};
for (value, selected) in parsed {
// Custom.WIDTHxHEIGHT placeholders are not selectable values.
if value.starts_with("Custom.") {
continue;
}
if selected {
*default = Some(value.clone());
}
list.push(value);
}
}
Ok(options)
}
/// Set a queue-wide default job option (PageSize, cupsPrintQuality, Duplex…).
pub async fn set_default_option(printer: &str, option: &str, value: &str) -> Result<(), String> {
run_cli(
"lpadmin",
&["-p", printer, "-o", &format!("{option}={value}")],
)
.await
}
/// A consumable reported by the printer through the IPP marker attributes.
#[derive(Clone, Debug)]
pub struct Marker {
pub name: String,
/// 0-100; negative values mean unknown.
pub level: i32,
/// "#RRGGBB" when the printer advertises a color.
pub color: Option<String>,
}
/// Query ink levels directly from the printer.
///
/// The scheduler does not relay marker levels for driverless queues, so the
/// printer's IPP endpoint is resolved (dnssd -> ippfind) and queried with
/// ipptool. Returns an empty list when the printer does not report markers.
pub async fn markers(device_uri: &str) -> Vec<Marker> {
let Some(endpoint) = resolve_endpoint(device_uri).await else {
return Vec::new();
};
let names = query_marker_attribute(&endpoint, "marker-names").await;
let raw_levels = query_marker_attribute(&endpoint, "marker-levels").await;
let colors = query_marker_attribute(&endpoint, "marker-colors").await;
let levels: Vec<i32> = raw_levels
.iter()
.filter_map(|value| value.trim().parse::<i32>().ok())
.collect();
if levels.is_empty() {
return Vec::new();
}
(0..levels.len())
.map(|index| Marker {
name: names
.get(index)
.cloned()
.unwrap_or_else(|| format!("marker {}", index + 1)),
level: levels[index],
color: colors.get(index).cloned().filter(|value| value.starts_with('#')),
})
.collect()
}
/// Resolve a device URI into a queryable IPP endpoint.
async fn resolve_endpoint(device_uri: &str) -> Option<String> {
if device_uri.starts_with("ipp://") || device_uri.starts_with("ipps://") {
return Some(device_uri.to_string());
}
let rest = device_uri.strip_prefix("dnssd://")?;
let name = rest.split(['/', '?']).next()?;
let name = percent_decode(name.split("._").next()?);
let output = run_cli_capture(
"timeout",
&["8", "ippfind", "_ipp._tcp", "_ipps._tcp", "-N", &name, "-p"],
)
.await
.ok()?;
let mut fallback = None;
for line in output.lines() {
let line = line.trim();
if line.starts_with("ipps://") {
return Some(line.to_string());
}
if fallback.is_none() && line.starts_with("ipp://") {
fallback = Some(line.to_string());
}
}
fallback
}
/// Run one ipptool Get-Printer-Attributes query and return the displayed
/// values of a single marker attribute.
async fn query_marker_attribute(endpoint: &str, attribute: &str) -> Vec<String> {
let test_file = std::env::temp_dir().join(format!("cosmic-settings-printers-{attribute}.test"));
let content = format!(
"{{\n\
\x20 NAME \"{attribute}\"\n\
\x20 OPERATION Get-Printer-Attributes\n\
\x20 GROUP operation-attributes-tag\n\
\x20 ATTR charset attributes-charset utf-8\n\
\x20 ATTR naturalLanguage attributes-natural-language en\n\
\x20 ATTR uri printer-uri $uri\n\
\x20 ATTR keyword requested-attributes {attribute}\n\
\x20 STATUS successful-ok\n\
\x20 DISPLAY {attribute}\n\
}}\n"
);
if tokio::fs::write(&test_file, content).await.is_err() {
return Vec::new();
}
let Some(file_path) = test_file.to_str() else {
return Vec::new();
};
let Ok(output) =
run_cli_capture("timeout", &["8", "ipptool", endpoint, file_path]).await
else {
return Vec::new();
};
parse_display_values(&output).unwrap_or_default()
}
/// Extract the value cell of a single-DISPLAY ipptool table: the line
/// following the dashes separator, split on commas.
fn parse_display_values(output: &str) -> Option<Vec<String>> {
let mut lines = output.lines();
while let Some(line) = lines.next() {
if !line.trim().is_empty() && line.trim().chars().all(|c| c == '-') {
let values = lines.next()?.trim();
return Some(values.split(',').map(|value| value.trim().to_string()).collect());
}
}
None
}
pub async fn set_default(name: &str) -> Result<(), String> {
run_cli("lpadmin", &["-d", name]).await
}
pub async fn set_enabled(name: &str, enabled: bool) -> Result<(), String> {
if enabled {
run_cli("cupsenable", &[name]).await
} else {
run_cli("cupsdisable", &[name]).await
}
}
/// Sanitize a display name into a valid CUPS queue name.
///
/// No deduplication: `lpadmin` modifies the queue when the name already
/// exists, which also promotes the temporary queues CUPS auto-creates for
/// discovered devices into permanent ones.
pub fn queue_name(raw: &str) -> String {
let mut sanitized = String::with_capacity(raw.len());
for c in raw.chars() {
if c.is_alphanumeric() {
sanitized.push(c);
} else if matches!(c, '[' | ']' | '(' | ')') {
// Brackets usually wrap a model identifier; drop them so
// "series [32C998]" becomes "series_32C998", not "series__32C998_".
continue;
} else {
sanitized.push('_');
}
}
let base = sanitized
.split('_')
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join("_");
if base.is_empty() {
"Printer".to_string()
} else {
base
}
}
async fn run_cli(program: &str, args: &[&str]) -> Result<(), String> {
let output = run_cli_capture(program, args).await?;
drop(output);
Ok(())
}
async fn run_cli_capture(program: &str, args: &[&str]) -> Result<String, String> {
let output = Command::new(program)
.args(args)
.stdin(std::process::Stdio::null())
.output()
.await
.map_err(|err| format!("{program}: {err}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr);
if output.status.success() {
return Ok(stdout);
}
// Ignore deprecation notices lpadmin prints on stderr for PPD drivers.
let message = stderr
.lines()
.filter(|line| !line.contains("deprecated"))
.collect::<Vec<_>>()
.join(" ");
Err(if message.trim().is_empty() {
format!("{program} {}", args.join(" "))
} else {
message
})
}
fn device_info(uri: &str) -> String {
if let Some(rest) = uri.strip_prefix("dnssd://") {
let name = rest.split(['/', '?']).next().unwrap_or(rest);
let name = name.split("._").next().unwrap_or(name);
let decoded = percent_decode(name);
if !decoded.is_empty() {
return decoded;
}
}
if let Some(rest) = uri.strip_prefix("usb://") {
let path = rest.split('?').next().unwrap_or(rest);
let decoded = percent_decode(path).replace('/', " ");
if !decoded.trim().is_empty() {
return decoded;
}
}
if uri.starts_with("cups-pdf") {
return "PDF".to_string();
}
// ipp/ipps/socket/lpd/http(s) URIs: keep the host label and drop the
// dnssd-style service suffix ("Name._ipp._tcp.local" -> "Name").
if let Some((_, rest)) = uri.split_once("://")
&& let Some(host) = rest.split(['/', '?']).next()
{
let decoded = percent_decode(host);
let label = decoded.split("._").next().unwrap_or(&decoded);
let label = label.trim_end_matches(".local");
if !label.is_empty() && !label.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ':') {
return label.to_string();
}
}
percent_decode(uri)
}
fn percent_decode(input: &str) -> String {
let bytes = input.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' && index + 2 < bytes.len() {
let hex = &input[index + 1..index + 3];
if let Ok(value) = u8::from_str_radix(hex, 16) {
decoded.push(value);
index += 3;
continue;
}
}
decoded.push(bytes[index]);
index += 1;
}
String::from_utf8_lossy(&decoded).into_owned()
}

File diff suppressed because it is too large Load diff

View file

@ -1,464 +0,0 @@
// Copyright 2026 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use super::model;
use cosmic::desktop::{
DesktopEntryCache, DesktopLookupContext, DesktopResolveOptions, resolve_desktop_entry,
};
use cosmic::iced::{self, Alignment, Length, futures, window};
use cosmic::widget::space::horizontal as horizontal_space;
use cosmic::{Apply, Element, surface, widget};
use cosmic_config::{Config, ConfigGet};
use cosmic_settings_audio_client::{self as audio_client, CosmicAudioProxy};
use cosmic_settings_page::{self as page, Section, section};
use futures::executor::block_on;
use intmap::IntMap;
use slotmap::SlotMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
const AUDIO_CONFIG: &str = "com.system76.CosmicAudio";
const AMPLIFICATION_SINK: &str = "amplification_sink";
#[derive(Clone, Debug)]
pub enum Message {
Model(cosmic_settings_sound::Message),
SetBalance(u32, f32),
SetMute(u32, bool),
SetSink(u32, usize),
SetVolume(u32, u32),
Surface(surface::Action),
ToggleExpanded(u32),
}
impl From<Message> for crate::pages::Message {
fn from(message: Message) -> Self {
crate::pages::Message::SoundApplications(message)
}
}
impl From<Message> for crate::Message {
fn from(message: Message) -> Self {
crate::Message::PageMessage(message.into())
}
}
#[derive(Default)]
pub struct Page {
entity: page::Entity,
model: model::Model,
client: Option<Rc<RefCell<audio_client::Client>>>,
desktop_entries: DesktopEntryCache,
playback_icons: IntMap<u32, String>,
amplification_sink: bool,
expanded: Option<u32>,
}
impl page::AutoBind<crate::pages::Message> for Page {}
impl page::Page<crate::pages::Message> for Page {
fn on_enter(&mut self) -> cosmic::Task<crate::pages::Message> {
self.amplification_sink = Config::new(AUDIO_CONFIG, 1)
.ok()
.and_then(|config| config.get::<bool>(AMPLIFICATION_SINK).ok())
.unwrap_or(true);
cosmic::Task::none()
}
fn info(&self) -> page::Info {
page::Info::new("sound-applications", "preferences-sound-symbolic")
.title(fl!("sound-applications"))
}
fn content(
&self,
sections: &mut SlotMap<section::Entity, Section<crate::pages::Message>>,
) -> Option<page::Content> {
Some(vec![sections.insert(view())])
}
fn set_id(&mut self, entity: page::Entity) {
self.entity = entity;
}
fn on_leave(&mut self) -> cosmic::Task<crate::pages::Message> {
*self = Page {
entity: self.entity,
..Page::default()
};
cosmic::Task::none()
}
fn subscription(&self, _core: &cosmic::Core) -> iced::Subscription<crate::pages::Message> {
iced::Subscription::run(|| {
iced::stream::channel(
1,
move |emitter: futures::channel::mpsc::Sender<crate::pages::Message>| async move {
cosmic_settings_sound::subscribe(emitter, |m| Message::Model(m).into()).await
},
)
})
}
}
impl Page {
fn resolve_playback_icon(&mut self, node_id: u32, info: &audio_client::PlaybackInfo) {
let Some(candidate) = [
info.application_id.as_deref(),
info.icon_name.as_deref(),
info.application_name.as_deref(),
]
.into_iter()
.flatten()
.find(|value| !value.is_empty()) else {
return;
};
let mut context = DesktopLookupContext::new(candidate);
if let Some(icon_name) = info.icon_name.as_deref().filter(|value| !value.is_empty()) {
context = context.with_identifier(icon_name);
}
if let Some(application_name) = info
.application_name
.as_deref()
.filter(|value| !value.is_empty())
{
context = context.with_title(application_name);
}
let entry = resolve_desktop_entry(
&mut self.desktop_entries,
&context,
&DesktopResolveOptions::default(),
);
let entry_icon = entry.icon();
let icon_name = entry_icon
.filter(|value| !value.is_empty())
.or(info.icon_name.as_deref())
.or(info.application_id.as_deref())
.unwrap_or("application-default");
self.playback_icons.insert(node_id, icon_name.to_owned());
}
pub fn update(&mut self, message: Message) -> cosmic::Task<crate::app::Message> {
match message {
Message::Model(cosmic_settings_sound::Message::Subscription(message)) => {
match &message {
audio_client::Event::Playback(node_id, info) => {
self.resolve_playback_icon(*node_id, info);
}
audio_client::Event::RemoveNode(node_id) => {
self.playback_icons.remove(*node_id);
}
_ => {}
}
self.model.update(message);
}
Message::Model(cosmic_settings_sound::Message::Client(client)) => {
if let Some(client) = Arc::into_inner(client) {
self.client = Some(Rc::new(RefCell::new(client)));
self.model = model::Model::default();
self.playback_icons = IntMap::new();
}
}
Message::SetMute(node_id, mute) => {
self.model
.update(audio_client::Event::NodeMute(node_id, mute));
if let Some(client) = &self.client {
match block_on(client.borrow_mut().conn.set_node_mute(node_id, mute)) {
Ok(Ok(_)) => {}
Ok(Err(why)) => {
tracing::error!(?why, node_id, mute, "daemon rejected playback mute");
}
Err(why) => {
tracing::error!(?why, node_id, mute, "failed to set playback mute");
}
}
} else {
tracing::warn!(node_id, mute, "audio client is not connected");
}
}
Message::SetBalance(playback_id, balance) => {
if let Some(playback) = self
.model
.playback
.iter_mut()
.find(|playback| playback.id == playback_id)
{
playback.balance = Some(balance);
}
if let Some(client) = &self.client {
match block_on(
client
.borrow_mut()
.conn
.set_node_volume_balance(playback_id, Some(balance)),
) {
Ok(Ok(volume)) => {
self.model.update(audio_client::Event::NodeVolume(
playback_id,
volume.volume,
volume.balance,
));
}
Ok(Err(why)) => {
tracing::error!(
?why,
playback_id,
balance,
"daemon rejected playback balance"
);
}
Err(why) => {
tracing::error!(
?why,
playback_id,
balance,
"failed to set playback balance"
);
}
}
} else {
tracing::warn!(playback_id, balance, "audio client is not connected");
}
}
Message::SetSink(playback_id, sorted_pos) => {
let Some(&sink_pos) = self.model.sinks.sorted_index.get(sorted_pos) else {
return cosmic::Task::none();
};
let Some(&sink_id) = self.model.sinks.id.get(sink_pos as usize) else {
return cosmic::Task::none();
};
if let Some(client) = &self.client {
match block_on(
client
.borrow_mut()
.conn
.set_playback_sink(playback_id, sink_id),
) {
Ok(Ok(())) => {
if let Some(playback) = self
.model
.playback
.iter_mut()
.find(|playback| playback.id == playback_id)
{
playback.sink_id = Some(sink_id);
}
}
Ok(Err(why)) => {
tracing::error!(
?why,
playback_id,
sink_id,
"daemon rejected playback output"
);
}
Err(why) => {
tracing::error!(
?why,
playback_id,
sink_id,
"failed to set playback output"
);
}
}
} else {
tracing::warn!(playback_id, sink_id, "audio client is not connected");
}
}
Message::SetVolume(node_id, volume) => {
if let Some(playback) = self
.model
.playback
.iter_mut()
.find(|playback| playback.id == node_id)
{
playback.volume = volume;
}
if let Some(client) = &self.client {
match block_on(client.borrow_mut().conn.set_node_volume(node_id, volume)) {
Ok(Ok(_)) => {}
Ok(Err(why)) => {
tracing::error!(
?why,
node_id,
volume,
"daemon rejected playback volume"
);
}
Err(why) => {
tracing::error!(?why, node_id, volume, "failed to set playback volume");
}
}
} else {
tracing::warn!(node_id, volume, "audio client is not connected");
}
}
Message::Surface(action) => {
return cosmic::task::message(crate::app::Message::Surface(action));
}
Message::ToggleExpanded(node_id) => {
self.expanded = if self.expanded == Some(node_id) {
None
} else {
Some(node_id)
};
}
}
cosmic::Task::none()
}
}
pub fn view() -> Section<crate::pages::Message> {
Section::default().view::<Page>(move |_, page, _section| {
if page.model.playback.is_empty() {
return widget::settings::section()
.add(
widget::text::body(fl!("sound-applications", "none"))
.width(Length::Fill)
.align_x(Alignment::Center),
)
.into();
}
let mut applications = widget::settings::section();
for playback in page.model.playback.iter().cloned() {
let node_id = playback.id;
let mute = playback.mute;
let volume = playback.volume;
let expanded = page.expanded == Some(node_id);
let icon_name = page
.playback_icons
.get(node_id)
.map(String::as_str)
.unwrap_or("application-default");
let slider = if page.amplification_sink {
widget::slider(0..=150, volume, move |volume| {
Message::SetVolume(node_id, volume)
})
.breakpoints(&[100])
} else {
widget::slider(0..=100, volume, move |volume| {
Message::SetVolume(node_id, volume)
})
}
.width(Length::Fill)
.apply(widget::container)
.max_width(250.);
let volume_controls = widget::row::with_capacity(5)
.align_y(Alignment::Center)
.push(
widget::button::icon(widget::icon::from_name(if mute {
"audio-volume-muted-symbolic"
} else {
"audio-volume-high-symbolic"
}))
.on_press(Message::SetMute(node_id, !mute)),
)
.push(
widget::text::body(volume.to_string())
.width(Length::Fixed(22.))
.align_x(Alignment::Center),
)
.push(horizontal_space().width(8.))
.push(slider)
.push(
widget::button::icon(widget::icon::from_name(if expanded {
"go-up-symbolic"
} else {
"go-down-symbolic"
}))
.on_press(Message::ToggleExpanded(node_id)),
)
.apply(Element::from)
.map(crate::pages::Message::from);
applications = applications.add(
widget::settings::item::builder(playback.name().to_owned())
.icon(widget::icon::from_name(icon_name).size(16))
.flex_control(volume_controls)
.align_items(Alignment::Center),
);
if !expanded {
continue;
}
let selected_sink =
playback
.selected_sink(page.model.default_sink)
.and_then(|sink_id| {
let sink_pos = page.model.sinks.id.iter().position(|id| *id == sink_id)?;
page.model
.sinks
.sorted_index
.iter()
.position(|pos| usize::from(*pos) == sink_pos)
});
let output = widget::dropdown::popup_dropdown(
&page.model.sinks.sorted_display,
selected_sink,
move |pos| Message::SetSink(node_id, pos),
window::Id::RESERVED,
Message::Surface,
crate::Message::from,
)
.apply(Element::from)
.map(crate::pages::Message::from);
let balance = widget::row::with_capacity(5)
.align_y(Alignment::Center)
.push(
widget::column::with_capacity(2)
.align_x(Alignment::Center)
.push(widget::text::body(fl!("sound-output", "left")))
.push(horizontal_space().width(22.)),
)
.push(horizontal_space().width(8.))
.push(
widget::slider(0.0..=2.0, playback.balance.unwrap_or(1.0), move |balance| {
Message::SetBalance(node_id, balance)
})
.step(0.01)
.breakpoints(&[1.0]),
)
.push(horizontal_space().width(8.))
.push(
widget::column::with_capacity(2)
.align_x(Alignment::Center)
.push(widget::text::body(fl!("sound-output", "right")))
.push(horizontal_space().width(22.)),
)
.apply(Element::from)
.map(crate::pages::Message::from);
applications = applications
.add(widget::settings::item(
fl!("sound-output", "device"),
output,
))
.add(widget::settings::item(
fl!("sound-output", "balance"),
balance,
));
}
applications.into()
})
}

View file

@ -1,26 +1,13 @@
// Copyright 2025 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use super::model;
use cosmic::iced::futures;
use cosmic::{Apply, iced, widget};
use cosmic_settings_audio_client::{self as audio_client, CosmicAudioProxy};
use cosmic::{Apply, widget};
use cosmic_settings_page::{self as page, Section, section};
use futures::executor::block_on;
use cosmic_settings_sound_subscription::{self as subscription};
use slotmap::SlotMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Message {
/// Update for the model.
Model(cosmic_settings_sound::Message),
/// Set the profile of a sound device.
SetProfile(u32, u32),
/// Surface Action
Surface(cosmic::surface::Action),
}
pub enum Message {}
impl From<Message> for crate::pages::Message {
fn from(message: Message) -> Self {
@ -37,8 +24,6 @@ impl From<Message> for crate::Message {
#[derive(Default)]
pub struct Page {
entity: page::Entity,
model: model::Model,
client: Option<Rc<RefCell<audio_client::Client>>>,
}
impl page::AutoBind<crate::pages::Message> for Page {}
@ -56,83 +41,55 @@ impl page::Page<crate::pages::Message> for Page {
Some(vec![sections.insert(view())])
}
fn on_leave(&mut self) -> cosmic::Task<crate::pages::Message> {
cosmic::Task::done(crate::pages::Message::Sound(super::Message::Reload))
}
fn set_id(&mut self, entity: cosmic_settings_page::Entity) {
self.entity = entity;
}
fn on_leave(&mut self) -> cosmic::Task<crate::pages::Message> {
*self = Page {
entity: self.entity,
..Page::default()
};
cosmic::Task::none()
}
fn subscription(&self, _core: &cosmic::Core) -> iced::Subscription<crate::pages::Message> {
iced::Subscription::run(|| {
iced::stream::channel(
1,
move |emitter: futures::channel::mpsc::Sender<crate::pages::Message>| async move {
cosmic_settings_sound::subscribe(emitter, |m| Message::Model(m).into()).await
},
)
})
fn subscription(
&self,
_core: &cosmic::Core,
) -> cosmic::iced::Subscription<crate::pages::Message> {
cosmic::iced::Subscription::run(subscription::watch)
.map(|message| super::Message::Subscription(message).into())
}
}
impl Page {
pub fn update(&mut self, message: Message) -> cosmic::Task<crate::app::Message> {
match message {
Message::Model(cosmic_settings_sound::Message::Subscription(message)) => {
self.model.update(message);
}
Message::Model(cosmic_settings_sound::Message::Client(client)) => {
if let Some(client) = Arc::into_inner(client) {
self.client = Some(Rc::new(RefCell::new(client)));
self.model = model::Model {
text: model::Text {
hd_audio: fl!("sound-hd-audio"),
usb_audio: fl!("sound-usb-audio"),
},
..model::Model::default()
};
}
}
Message::Surface(a) => return cosmic::task::message(crate::app::Message::Surface(a)),
Message::SetProfile(id, index) => {
if let Some(client) = self.client.clone() {
block_on(async move {
_ = client.borrow_mut().conn.set_profile(id, index, true).await;
});
}
}
}
pub fn update(&mut self, _message: Message) -> cosmic::Task<crate::app::Message> {
cosmic::Task::none()
}
}
pub fn view() -> Section<crate::pages::Message> {
Section::default().view::<Page>(move |_, page, _section| {
let devices = page.model.device_profile_dropdowns.iter().cloned().map(
|(device_id, name, active_profile, indexes, descriptions)| {
Section::default().view::<Page>(move |binder, _page, _section| {
let sound_page_id = binder.find_page_by_id("sound").unwrap().0;
let sound_page = binder.page[sound_page_id]
.downcast_ref::<super::Page>()
.unwrap();
let devices = sound_page
.model
.device_profile_dropdowns
.iter()
.cloned()
.map(|(device_id, name, active_profile, indexes, descriptions)| {
let dropdown = widget::dropdown::popup_dropdown(
descriptions,
active_profile,
move |id| Message::SetProfile(device_id, indexes[id]),
move |id| super::Message::SetProfile(device_id, indexes[id]),
cosmic::iced::window::Id::RESERVED,
Message::Surface,
super::Message::Surface,
crate::Message::from,
)
.apply(cosmic::Element::from)
.map(crate::pages::Message::from);
widget::settings::item::builder(name).control(dropdown)
},
);
});
widget::settings::section().extend(devices).into()
})

View file

@ -1,22 +1,18 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
pub mod applications;
pub mod device_profiles;
use cosmic::iced::{self, Alignment, Length, window};
use cosmic::widget::space::horizontal as horizontal_space;
use cosmic::widget::{self, settings};
use cosmic::{Apply, Element, Task, surface};
use cosmic::{
Apply, Element, Task,
iced::{Alignment, Length, window},
surface,
widget::{self, settings, space::horizontal as horizontal_space},
};
use cosmic_config::{Config, ConfigGet, ConfigSet};
use cosmic_settings_audio_client::{self as audio_client, Client, CosmicAudioProxy};
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_sound::model;
use futures::executor::block_on;
use cosmic_settings_sound_subscription as subscription;
use slotmap::SlotMap;
use std::sync::atomic::AtomicU32;
use std::sync::{Arc, atomic};
use std::time::Duration;
const AUDIO_CONFIG: &str = "com.system76.CosmicAudio";
const AMPLIFICATION_SINK: &str = "amplification_sink";
@ -24,20 +20,22 @@ const AMPLIFICATION_SOURCE: &str = "amplification_source";
#[derive(Clone, Debug)]
pub enum Message {
/// Updates for the model.
Model(cosmic_settings_sound::Message),
/// Reattach the client
ReattachClient(Arc<Client>),
/// Reload the model
Reload,
/// Change the default output.
SetDefaultSink(usize),
/// Change the default input output.
SetDefaultSource(usize),
/// Set the profile of a sound device.
SetProfile(u32, u32),
/// Change the balance of the active sink.
SetSinkBalance(f32),
SetSinkBalance(u32),
/// Request to change the default output volume.
SetSinkVolume(u32),
/// Request to change the input volume.
SetSourceVolume(u32),
/// Messages handled by the sound module in cosmic-settings-subscriptions
Subscription(subscription::Message),
/// Surface Action
Surface(surface::Action),
/// Toggle the mute status of the output.
@ -62,38 +60,32 @@ impl From<Message> for crate::Message {
}
}
impl From<subscription::Message> for Message {
fn from(val: subscription::Message) -> Self {
Message::Subscription(val)
}
}
pub struct Page {
entity: page::Entity,
applications: page::Entity,
device_profiles: page::Entity,
client: Option<audio_client::Client>,
model: model::Model,
pub(self) model: subscription::Model,
sound_config: Option<Config>,
applied_sink_volume: Arc<AtomicU32>,
applied_sink_volume_balance: Arc<AtomicU32>,
applied_source_volume: Arc<AtomicU32>,
amplification_sink: bool,
amplification_source: bool,
}
impl Default for Page {
fn default() -> Self {
let mut model = subscription::Model::default();
model.unplugged_text = fl!("sound-device-port-unplugged");
model.hd_audio_text = fl!("sound-hd-audio");
model.usb_audio_text = fl!("sound-usb-audio");
Self {
entity: page::Entity::default(),
applications: page::Entity::default(),
device_profiles: page::Entity::default(),
client: None,
model: model::Model {
text: model::Text {
hd_audio: fl!("sound-hd-audio"),
usb_audio: fl!("sound-usb-audio"),
},
..model::Model::default()
},
model,
sound_config: None,
applied_sink_volume: Arc::new(AtomicU32::new(0)),
applied_sink_volume_balance: Arc::new(AtomicU32::new(0)),
applied_source_volume: Arc::new(AtomicU32::new(0)),
amplification_sink: false,
amplification_source: false,
}
@ -125,7 +117,6 @@ impl page::Page<crate::pages::Message> for Page {
Some(vec![
sections.insert(output()),
sections.insert(input()),
sections.insert(applications()),
sections.insert(device_profiles()),
])
}
@ -140,21 +131,17 @@ impl page::Page<crate::pages::Message> for Page {
self.entity = entity;
}
fn subscription(&self, _core: &cosmic::Core) -> iced::Subscription<crate::pages::Message> {
iced::Subscription::run(|| {
iced::stream::channel(
1,
move |emitter: futures::channel::mpsc::Sender<crate::pages::Message>| async move {
cosmic_settings_sound::subscribe(emitter, |m| Message::Model(m).into()).await
},
)
})
fn subscription(
&self,
_core: &cosmic::Core,
) -> cosmic::iced::Subscription<crate::pages::Message> {
cosmic::iced::Subscription::run(subscription::watch)
.map(|message| Message::Subscription(message).into())
}
fn on_leave(&mut self) -> Task<crate::pages::Message> {
*self = Page {
entity: self.entity,
applications: self.applications,
device_profiles: self.device_profiles,
..Page::default()
};
@ -168,136 +155,61 @@ impl page::AutoBind<crate::pages::Message> for Page {
mut page: page::Insert<crate::pages::Message>,
) -> page::Insert<crate::pages::Message> {
let id = page.sub_page_with_id::<device_profiles::Page>();
let applications_id = page.sub_page_with_id::<applications::Page>();
let model = page.model.page_mut::<Page>().unwrap();
model.device_profiles = id;
model.applications = applications_id;
page
}
}
impl Page {
pub fn update(&mut self, message: Message) -> Task<crate::app::Message> {
tracing::debug!(target: "sound", ?message, "update");
match message {
Message::Surface(a) => return cosmic::task::message(crate::app::Message::Surface(a)),
Message::Model(cosmic_settings_sound::Message::Subscription(message)) => {
self.model.update(message);
}
Message::Model(cosmic_settings_sound::Message::Client(client)) => {
if let Some(client) = Arc::into_inner(client) {
self.client = Some(client);
self.model = model::Model {
text: model::Text {
hd_audio: fl!("sound-hd-audio"),
usb_audio: fl!("sound-usb-audio"),
},
..model::Model::default()
};
}
}
Message::ReattachClient(client) => {
if let Some(client) = Arc::into_inner(client) {
self.client = Some(client);
}
}
Message::SetDefaultSink(pos) => {
if let Some(&pos) = self.model.sinks.sorted_index.get(pos)
&& let Some(&node_id) = self.model.sinks.id.get(pos as usize)
&& let Some(client) = self.client.as_mut()
{
block_on(async {
_ = client.conn.set_default(node_id, true).await;
});
}
}
Message::SetDefaultSource(pos) => {
if let Some(&pos) = self.model.sources.sorted_index.get(pos)
&& let Some(&node_id) = self.model.sources.id.get(pos as usize)
&& let Some(client) = self.client.as_mut()
{
block_on(async {
_ = client.conn.set_default(node_id, true).await;
});
}
}
Message::ToggleSinkMute => {
if let Some(ref mut client) = self.client {
block_on(async {
_ = client.conn.sink_mute_toggle().await;
});
}
}
Message::ToggleSourceMute => {
if let Some(ref mut client) = self.client {
block_on(async {
_ = client.conn.source_mute_toggle().await;
});
}
}
Message::SetSinkVolume(volume) => {
self.applied_sink_volume
.store(volume, atomic::Ordering::Relaxed);
self.model.active_sink.volume = volume;
self.model.active_sink.volume_text = volume.to_string();
if let Some(mut client) = self.client.take() {
let volume = Arc::clone(&self.applied_sink_volume);
return cosmic::Task::future(async move {
tokio::time::sleep(Duration::from_millis(128)).await;
_ = client
.conn
.set_sink_volume(volume.load(atomic::Ordering::Relaxed))
.await;
Message::ReattachClient(Arc::new(client)).into()
});
}
}
Message::SetSourceVolume(volume) => {
self.applied_source_volume
.store(volume, atomic::Ordering::Relaxed);
self.model.active_source.volume = volume;
self.model.active_source.volume_text = volume.to_string();
if let Some(mut client) = self.client.take() {
let volume = Arc::clone(&self.applied_source_volume);
return cosmic::Task::future(async move {
tokio::time::sleep(Duration::from_millis(128)).await;
_ = client
.conn
.set_source_volume(volume.load(atomic::Ordering::Relaxed))
.await;
Message::ReattachClient(Arc::new(client)).into()
});
}
Message::Subscription(message) => {
return self
.model
.update(message)
.map(|message| Message::Subscription(message).into());
}
Message::SetSinkBalance(balance) => {
self.applied_sink_volume_balance
.store((balance * 1000.0) as u32, atomic::Ordering::Relaxed);
self.model.active_sink.balance = Some(balance);
if let Some((mut client, sink_id)) = self.client.take().zip(self.model.default_sink)
{
let balance = Arc::clone(&self.applied_sink_volume_balance);
return cosmic::Task::future(async move {
tokio::time::sleep(Duration::from_millis(128)).await;
_ = client
.conn
.set_node_volume_balance(
sink_id,
Some(balance.load(atomic::Ordering::Relaxed) as f32 / 1000.0),
)
.await;
Message::ReattachClient(Arc::new(client)).into()
});
}
return self
.model
.set_sink_balance(balance)
.map(|message| Message::Subscription(message).into());
}
Message::SetDefaultSink(pos) => {
return self
.model
.set_default_sink(pos)
.map(|message| Message::Subscription(message).into());
}
Message::SetDefaultSource(pos) => {
return self
.model
.set_default_source(pos)
.map(|message| Message::Subscription(message).into());
}
Message::ToggleSinkMute => self.model.toggle_sink_mute(),
Message::ToggleSourceMute => self.model.toggle_source_mute(),
Message::SetSinkVolume(volume) => {
return self
.model
.set_sink_volume(volume)
.map(|message| Message::Subscription(message).into());
}
Message::SetSourceVolume(volume) => {
return self
.model
.set_source_volume(volume)
.map(|message| Message::Subscription(message).into());
}
Message::ToggleOverAmplificationSink(enabled) => {
@ -319,6 +231,18 @@ impl Page {
tracing::error!(?why, "Failed to save over amplification setting");
}
}
Message::SetProfile(object_id, index) => {
self.model.set_profile(object_id, index, true);
}
Message::Reload => {
let mut model = subscription::Model::default();
model.hd_audio_text = std::mem::take(&mut self.model.hd_audio_text);
model.unplugged_text = std::mem::take(&mut self.model.unplugged_text);
model.usb_audio_text = std::mem::take(&mut self.model.usb_audio_text);
self.model = model;
}
}
Task::none()
@ -338,17 +262,17 @@ fn input() -> Section<crate::pages::Message> {
.title(fl!("sound-input"))
.descriptions(descriptions)
.view::<Page>(move |_binder, page, section| {
if page.model.sources.id.is_empty() {
if page.model.sources().is_empty() {
return widget::space().into();
}
let slider = if page.amplification_source {
widget::slider(0..=150, page.model.active_source.volume, |change| {
widget::slider(0..=150, page.model.source_volume, |change| {
Message::SetSourceVolume(change).into()
})
.breakpoints(&[100])
} else {
widget::slider(0..=100, page.model.active_source.volume, |change| {
widget::slider(0..=100, page.model.source_volume, |change| {
Message::SetSourceVolume(change).into()
})
}
@ -359,25 +283,23 @@ fn input() -> Section<crate::pages::Message> {
let volume_control = widget::row::with_capacity(4)
.align_y(Alignment::Center)
.push(
widget::button::icon(widget::icon::from_name(
if page.model.active_source.mute {
"microphone-sensitivity-muted-symbolic"
} else {
"audio-input-microphone-symbolic"
},
))
widget::button::icon(widget::icon::from_name(if page.model.source_mute {
"microphone-sensitivity-muted-symbolic"
} else {
"audio-input-microphone-symbolic"
}))
.on_press(Message::ToggleSourceMute.into()),
)
.push(
widget::text::body(&page.model.active_source.volume_text)
widget::text::body(&page.model.source_volume_text)
.width(Length::Fixed(22.0))
.align_x(Alignment::Center),
)
.push(horizontal_space().width(8.))
.push(slider);
let devices = widget::dropdown::popup_dropdown(
&page.model.sources.sorted_display,
page.model.sources.active(),
page.model.sources(),
Some(page.model.active_source().unwrap_or(0)),
Message::SetDefaultSource,
window::Id::RESERVED,
Message::Surface,
@ -424,12 +346,12 @@ fn output() -> Section<crate::pages::Message> {
.descriptions(descriptions)
.view::<Page>(move |_binder, page, section| {
let slider = if page.amplification_sink {
widget::slider(0..=150, page.model.active_sink.volume, |change| {
widget::slider(0..=150, page.model.sink_volume, |change| {
Message::SetSinkVolume(change).into()
})
.breakpoints(&[100])
} else {
widget::slider(0..=100, page.model.active_sink.volume, |change| {
widget::slider(0..=100, page.model.sink_volume, |change| {
Message::SetSinkVolume(change).into()
})
}
@ -440,7 +362,7 @@ fn output() -> Section<crate::pages::Message> {
let volume_control = widget::row::with_capacity(4)
.align_y(Alignment::Center)
.push(
widget::button::icon(if page.model.active_sink.mute {
widget::button::icon(if page.model.sink_mute {
widget::icon::from_name("audio-volume-muted-symbolic")
} else {
widget::icon::from_name("audio-volume-high-symbolic")
@ -448,7 +370,7 @@ fn output() -> Section<crate::pages::Message> {
.on_press(Message::ToggleSinkMute.into()),
)
.push(
widget::text::body(&page.model.active_sink.volume_text)
widget::text::body(&page.model.sink_volume_text)
.width(Length::Fixed(22.0))
.align_x(Alignment::Center),
)
@ -456,8 +378,8 @@ fn output() -> Section<crate::pages::Message> {
.push(slider);
let devices = widget::dropdown::popup_dropdown(
&page.model.sinks.sorted_display,
page.model.sinks.active(),
page.model.sinks(),
Some(page.model.active_sink().unwrap_or(0)),
Message::SetDefaultSink,
window::Id::RESERVED,
Message::Surface,
@ -490,12 +412,12 @@ fn output() -> Section<crate::pages::Message> {
.push(horizontal_space().width(8.))
.push(
widget::slider(
0.0..=2.0,
page.model.active_sink.balance.unwrap_or(1.0),
0..=200,
(page.model.sink_balance.unwrap_or(1.0).max(0.) * 100.).round()
as u32,
|change| Message::SetSinkBalance(change).into(),
)
.step(0.01)
.breakpoints(&[1.0]),
.breakpoints(&[100]),
)
.push(horizontal_space().width(8.))
.push(
@ -531,31 +453,24 @@ fn device_profiles() -> Section<crate::pages::Message> {
.descriptions(descriptions)
.view::<Page>(move |_binder, page, section| {
let descriptions = &section.descriptions;
let button = widget::row::with_children(vec![
horizontal_space().into(),
widget::icon::from_name("go-next-symbolic").size(16).into(),
]);
settings::section()
.add(crate::widget::go_next_item(
&descriptions[button_txt],
crate::pages::Message::Page(page.device_profiles),
))
.into()
})
}
let device_profiles = settings::item::builder(&*descriptions[button_txt])
.control(button)
.spacing(16)
.apply(widget::container)
.width(Length::Fill)
.class(cosmic::theme::Container::List)
.apply(widget::button::custom)
.width(Length::Fill)
.class(cosmic::theme::Button::Transparent)
.on_press(crate::pages::Message::Page(page.device_profiles))
.width(Length::Fill);
/// A section for opening the application volume controls sub-page.
fn applications() -> Section<crate::pages::Message> {
crate::slab!(descriptions {
button_txt = fl!("sound-applications");
});
Section::default()
.descriptions(descriptions)
.view::<Page>(move |_binder, page, section| {
settings::section()
.add(crate::widget::go_next_item(
&section.descriptions[button_txt],
crate::pages::Message::Page(page.applications),
))
.into()
settings::section().add(device_profiles).into()
})
}
@ -574,3 +489,21 @@ fn applications() -> Section<crate::pages::Message> {
// .into()
// })
// }
// fn applications() -> Section<crate::pages::Message> {
// let mut descriptions = Slab::new();
// let applications = descriptions.insert(fl!("sound-applications", "desc"));
// Section::default()
// .title(fl!("sound-applications"))
// .descriptions(descriptions)
// .view::<Page>(move |_binder, _page, section| {
// settings::section().title(&section.title)
// .add(settings::item(
// &*section.descriptions[applications],
// text::body("TODO"),
// ))
// .into()
// })
// }

View file

@ -66,8 +66,7 @@ impl page::Page<crate::pages::Message> for Page {
fn on_enter(&mut self) -> Task<crate::pages::Message> {
let (task, handle) = Task::future(async move {
let info = Info::load().await;
crate::pages::Message::About(Message::Info(Box::new(info)))
crate::pages::Message::About(Message::Info(Box::new(Info::load())))
})
.abortable();

View file

@ -3,9 +3,7 @@
#[cfg(feature = "wgpu")]
use cosmic::iced::wgpu;
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::process::Command;
use std::{collections::HashMap, collections::HashSet, ffi::OsStr, process::Command};
#[must_use]
#[derive(Clone, Debug, Default)]
@ -31,7 +29,7 @@ impl Info {
}
#[cfg(feature = "wgpu")]
async fn wgpu_graphics() -> Vec<String> {
fn wgpu_graphics() -> Vec<String> {
let mut graphics = Vec::new();
// Use wgpu to enumerate GPUs. Works cross-platform and doesn't require external tools
@ -45,7 +43,7 @@ impl Info {
let mut seen_devices = HashSet::new();
let mut seen_names = HashSet::new();
for adapter in adapters.await {
for adapter in adapters {
let adapter_info = adapter.get_info();
if adapter_info.device_type == wgpu::DeviceType::Cpu {
@ -142,7 +140,7 @@ impl Info {
graphics
}
pub async fn load() -> Info {
pub fn load() -> Info {
let mut info = Info {
os_architecture: architecture(),
kernel_version: kernel_version(),
@ -194,7 +192,7 @@ impl Info {
#[cfg(feature = "wgpu")]
{
info.graphics = Self::wgpu_graphics().await;
info.graphics = Self::wgpu_graphics();
}
info

View file

@ -4,22 +4,25 @@
mod getent;
use crate::pages;
use cosmic::dialog::file_chooser;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::space::horizontal;
use cosmic::widget::{self, column, icon, list, row, settings, text};
use cosmic::{Apply, Element};
use cosmic::{
Apply, Element,
dialog::file_chooser,
iced::{Alignment, Length},
widget::{self, column, icon, list, row, settings, space::horizontal, text},
};
use cosmic_settings_page::{self as page, Section, section};
use image::GenericImageView;
use pwhash::{bcrypt, md5_crypt, sha256_crypt, sha512_crypt};
use regex::Regex;
use slotmap::SlotMap;
use std::collections::HashMap;
use std::fs::File;
use std::future::Future;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{
collections::HashMap,
fs::File,
future::Future,
io::{BufRead, BufReader},
path::{Path, PathBuf},
sync::Arc,
};
use url::Url;
use zbus_polkit::policykit1::CheckAuthorizationFlags;

View file

@ -2,19 +2,24 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::widget::selection_context_item;
use cosmic::app::ContextDrawer;
use cosmic::cosmic_config::{self, ConfigGet, ConfigSet};
use cosmic::iced::core::text::Wrapping;
use cosmic::widget::{self, dropdown, settings};
use cosmic::{Apply, Element, Task, surface};
use cosmic::{
Apply, Element, Task,
app::ContextDrawer,
cosmic_config::{self, ConfigGet, ConfigSet},
iced::core::text::Wrapping,
surface,
widget::{self, dropdown, list, settings},
};
use cosmic_settings_page::{self as page, Section, section};
use icu::calendar::types::Weekday;
use icu::calendar::{Gregorian, week};
use icu::datetime::input::{Date, DateTime, Time};
use icu::datetime::options::TimePrecision;
use icu::datetime::{DateTimeFormatter, DateTimeFormatterPreferences, fieldsets};
use icu::locale::Locale;
use icu::locale::preferences::extensions::unicode::keywords::HourCycle;
use icu::{
calendar::{Gregorian, types::Weekday, week},
datetime::{
DateTimeFormatter, DateTimeFormatterPreferences, fieldsets,
input::{Date, DateTime, Time},
options::TimePrecision,
},
locale::{Locale, preferences::extensions::unicode::keywords::HourCycle},
};
use slotmap::{Key, SlotMap};
pub use timedate_zbus::TimeDateProxy;
use tracing::error;

View file

@ -7,20 +7,22 @@ use std::sync::Arc;
use crate::widget::selection_context_item;
use cosmic::app::{ContextDrawer, context_drawer};
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{self, button};
use cosmic::widget::{self, button, list};
use cosmic::{Apply, Element};
use cosmic_config::{ConfigGet, ConfigSet};
use cosmic_settings_page::{self as page, Section, section};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use eyre::Context;
use icu::calendar::types::Weekday;
use icu::calendar::week;
use icu::datetime::input::{Date, DateTime, Time};
use icu::datetime::{DateTimeFormatter, DateTimeFormatterPreferences, fieldsets};
use icu::decimal::DecimalFormatter;
use icu::decimal::input::Decimal;
use icu::locale::Locale;
use icu::{
calendar::{types::Weekday, week},
datetime::{
DateTimeFormatter, DateTimeFormatterPreferences, fieldsets,
input::{Date, DateTime, Time},
},
decimal::{DecimalFormatter, input::Decimal},
locale::Locale,
};
use locales_rs as locale;
use regex::Regex;
use slotmap::{DefaultKey, SlotMap};
static GNOME_LANGUAGE_SELECTOR: &str = "gnome-language-selector";
@ -240,7 +242,9 @@ impl Page {
let region = region.lang_code.clone();
return cosmic::task::future(async move {
if set_locale(lang, region.clone()).await.is_ok() {
if let Ok(exit_status) = set_locale(lang, region.clone()).await
&& exit_status.success()
{
update_time_settings_after_region_change(region);
}
@ -494,8 +498,11 @@ mod preferred_languages {
use crate::pages::time::region::localized_iso_codes;
use super::Message;
use cosmic::iced::{Alignment, Length};
use cosmic::{Apply, widget};
use cosmic::{
Apply,
iced::{Alignment, Length},
widget,
};
use cosmic_settings_page::Section;
pub fn section() -> Section<crate::pages::Message> {
@ -703,26 +710,20 @@ pub async fn page_reload() -> eyre::Result<PageRefresh> {
let mut available_languages_set = BTreeSet::new();
// Use 'locale -a' instead of 'localectl list-locales' for OpenRC compatibility
let output_result = tokio::process::Command::new("locale")
.arg("-a")
let output = tokio::process::Command::new("localectl")
.arg("list-locales")
.output()
.await;
.await
.expect("Failed to run localectl");
let locale_list = match output_result {
Ok(output) => {
let output_str = String::from_utf8(output.stdout).unwrap_or_default();
parse_locale_output(&output_str)
let output = String::from_utf8(output.stdout).unwrap_or_default();
for line in output.lines() {
if line == "C.UTF-8" {
continue;
}
Err(why) => {
tracing::error!(?why, "failed to list available locales using 'locale -a'");
Vec::new()
}
};
for line in locale_list {
if let Some(locale) = registry.locale(&line) {
available_languages_set.insert(localized_locale(&locale, line));
if let Some(locale) = registry.locale(line) {
available_languages_set.insert(localized_locale(&locale, line.to_owned()));
}
}
@ -840,28 +841,27 @@ fn popover_menu_row(
.apply(Element::from)
}
/// Sets the system locale using D-Bus instead of localectl for OpenRC compatibility.
pub async fn set_locale(lang: String, region: String) -> eyre::Result<()> {
tracing::debug!("setting locale lang={lang}, region={region}");
let conn = zbus::Connection::system()
pub async fn set_locale(
lang: String,
region: String,
) -> Result<std::process::ExitStatus, std::io::Error> {
eprintln!("setting locale lang={lang}, region={region}");
tokio::process::Command::new("localectl")
.arg("set-locale")
.args(&[
["LANG=", &lang].concat(),
["LC_ADDRESS=", &region].concat(),
["LC_IDENTIFICATION=", &region].concat(),
["LC_MEASUREMENT=", &region].concat(),
["LC_MONETARY=", &region].concat(),
["LC_NAME=", &region].concat(),
["LC_NUMERIC=", &region].concat(),
["LC_PAPER=", &region].concat(),
["LC_TELEPHONE=", &region].concat(),
["LC_TIME=", &region].concat(),
])
.status()
.await
.wrap_err("failed to connect to system D-Bus")?;
let proxy = locale1::locale1Proxy::new(&conn)
.await
.wrap_err("failed to create locale1 D-Bus proxy")?;
let locale_settings = build_locale_settings(&lang, &region);
let locale_strs: Vec<&str> = locale_settings.iter().map(|s| s.as_str()).collect();
proxy
.set_locale(&locale_strs, true)
.await
.wrap_err("failed to set locale via D-Bus")?;
tracing::debug!("successfully set locale via D-Bus");
Ok(())
}
/// Sets the user's preferred language list via AccountsService D-Bus.
@ -883,7 +883,7 @@ pub async fn set_user_language(language_list: String) -> eyre::Result<()> {
.await
.wrap_err("failed to set language via AccountsService")?;
tracing::debug!("set user language via AccountsService: {language_list}");
eprintln!("set user language via AccountsService: {language_list}");
Ok(())
}
@ -1016,206 +1016,3 @@ fn strip_locale_suffix(locale: &str) -> String {
.unwrap_or(without_codeset)
.to_string()
}
/// Parses the output from `locale -a` command and returns a vector of locale strings.
/// Filters out pseudo-locales (C, POSIX) and accepts only allowed character encodings.
fn parse_locale_output(output: &str) -> Vec<String> {
// Regex to match pseudo-locales: C or POSIX, optionally followed by .anything
let pseudo_locale_re = Regex::new(r"^(C|POSIX)(\.|$)").unwrap();
// Regex to match UTF-8 encoded locales (case-insensitive)
// Supports optional modifiers after encoding (e.g., @euro, @valencia)
let utf8_encoding_re = Regex::new(r"(?i)\.(utf-?8)(@.*)?$").unwrap();
output
.lines()
.map(|line| line.trim())
.filter(|line| !pseudo_locale_re.is_match(line))
.filter(|line| utf8_encoding_re.is_match(line))
.map(|line| line.to_string())
.collect()
}
/// Builds the locale settings array for D-Bus SetLocale call.
/// Sets LANG to the language parameter and all LC_* variables to the region parameter.
fn build_locale_settings(lang: &str, region: &str) -> Vec<String> {
vec![
format!("LANG={}", lang),
format!("LC_ADDRESS={}", region),
format!("LC_IDENTIFICATION={}", region),
format!("LC_MEASUREMENT={}", region),
format!("LC_MONETARY={}", region),
format!("LC_NAME={}", region),
format!("LC_NUMERIC={}", region),
format!("LC_PAPER={}", region),
format!("LC_TELEPHONE={}", region),
format!("LC_TIME={}", region),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_locale_output_handles_empty_input() {
let output = "";
let result = parse_locale_output(output);
assert_eq!(result.len(), 0);
}
#[test]
fn test_parse_locale_output_preserves_locale_strings() {
let output = "en_US.utf8\nde_DE.utf8\nfr_FR.utf8\n";
let result = parse_locale_output(output);
assert_eq!(result.len(), 3);
assert!(result.contains(&"en_US.utf8".to_string()));
}
#[test]
fn test_build_locale_settings_includes_all_lc_variables() {
let lang = "en_US.UTF-8";
let region = "de_DE.UTF-8";
let settings = build_locale_settings(lang, region);
assert_eq!(settings.len(), 10);
assert!(settings.contains(&format!("LANG={}", lang)));
assert!(settings.contains(&format!("LC_ADDRESS={}", region)));
assert!(settings.contains(&format!("LC_IDENTIFICATION={}", region)));
assert!(settings.contains(&format!("LC_MEASUREMENT={}", region)));
assert!(settings.contains(&format!("LC_MONETARY={}", region)));
assert!(settings.contains(&format!("LC_NAME={}", region)));
assert!(settings.contains(&format!("LC_NUMERIC={}", region)));
assert!(settings.contains(&format!("LC_PAPER={}", region)));
assert!(settings.contains(&format!("LC_TELEPHONE={}", region)));
assert!(settings.contains(&format!("LC_TIME={}", region)));
}
#[test]
fn test_build_locale_settings_uses_correct_values() {
let lang = "fr_FR.UTF-8";
let region = "en_GB.UTF-8";
let settings = build_locale_settings(lang, region);
// LANG should use the lang parameter
assert!(settings.iter().any(|s| s == "LANG=fr_FR.UTF-8"));
// LC_* variables should use the region parameter
assert!(settings.iter().any(|s| s == "LC_TIME=en_GB.UTF-8"));
}
#[test]
fn test_parse_locale_output_filters_pseudo_locales() {
let output = "C\nC.utf8\nC.UTF-8\nPOSIX\nen_US.utf8\nde_DE.UTF-8\n";
let result = parse_locale_output(output);
// Should filter out all C and POSIX variants
assert!(!result.contains(&"C".to_string()));
assert!(!result.contains(&"C.utf8".to_string()));
assert!(!result.contains(&"C.UTF-8".to_string()));
assert!(!result.contains(&"POSIX".to_string()));
// Should keep actual locales
assert!(result.contains(&"en_US.utf8".to_string()));
assert!(result.contains(&"de_DE.UTF-8".to_string()));
assert_eq!(result.len(), 2);
}
#[test]
fn test_parse_locale_output_accepts_only_utf8_locales() {
let output =
"en_US\nen_US.utf8\nen_US.UTF-8\nar_IN\nar_IN.utf8\nde_DE.iso88591\nfr_FR.UTF-8\n";
let result = parse_locale_output(output);
// Should accept UTF-8 variants
assert!(result.contains(&"en_US.utf8".to_string()));
assert!(result.contains(&"en_US.UTF-8".to_string()));
assert!(result.contains(&"ar_IN.utf8".to_string()));
assert!(result.contains(&"fr_FR.UTF-8".to_string()));
// Should filter out non-UTF-8 encoded locales
assert!(!result.contains(&"en_US".to_string()));
assert!(!result.contains(&"ar_IN".to_string()));
assert!(!result.contains(&"de_DE.iso88591".to_string()));
assert_eq!(result.len(), 4);
}
#[test]
fn test_parse_locale_output_filters_any_c_posix_variant() {
let output = "C\nC.iso88591\nC.anything\nPOSIX\nPOSIX.utf8\nen_US.utf8\n";
let result = parse_locale_output(output);
// Should filter out any C or POSIX variant regardless of encoding
assert!(!result.contains(&"C".to_string()));
assert!(!result.contains(&"C.iso88591".to_string()));
assert!(!result.contains(&"C.anything".to_string()));
assert!(!result.contains(&"POSIX".to_string()));
assert!(!result.contains(&"POSIX.utf8".to_string()));
// Should keep actual locales
assert!(result.contains(&"en_US.utf8".to_string()));
assert_eq!(result.len(), 1);
}
#[test]
fn test_parse_locale_output_handles_whitespace() {
let output = " en_US.utf8 \n\t de_DE.UTF-8\t\n fr_FR.utf8 \n";
let result = parse_locale_output(output);
// Should handle leading/trailing whitespace
assert!(result.contains(&"en_US.utf8".to_string()));
assert!(result.contains(&"de_DE.UTF-8".to_string()));
assert!(result.contains(&"fr_FR.utf8".to_string()));
assert_eq!(result.len(), 3);
}
#[test]
fn test_parse_locale_output_handles_empty_lines() {
let output = "en_US.utf8\n\n\nde_DE.UTF-8\n\n";
let result = parse_locale_output(output);
// Should skip empty lines
assert!(result.contains(&"en_US.utf8".to_string()));
assert!(result.contains(&"de_DE.UTF-8".to_string()));
assert_eq!(result.len(), 2);
}
#[test]
fn test_parse_locale_output_catalan_not_filtered_as_pseudo() {
let output = "C\nca_ES.UTF-8\nca_ES.utf8\ncs_CZ.UTF-8\nen_US.utf8\n";
let result = parse_locale_output(output);
// Should filter out C but not Catalan (ca_*) or Czech (cs_*)
assert!(!result.contains(&"C".to_string()));
assert!(result.contains(&"ca_ES.UTF-8".to_string()));
assert!(result.contains(&"ca_ES.utf8".to_string()));
assert!(result.contains(&"cs_CZ.UTF-8".to_string()));
assert_eq!(result.len(), 4);
}
#[test]
fn test_parse_locale_output_handles_locale_modifiers() {
let output = "en_US.UTF-8@euro\nca_ES.UTF-8@valencia\nde_DE.utf8\n";
let result = parse_locale_output(output);
// Locales with modifiers should be accepted
assert!(result.contains(&"en_US.UTF-8@euro".to_string()));
assert!(result.contains(&"ca_ES.UTF-8@valencia".to_string()));
assert!(result.contains(&"de_DE.utf8".to_string()));
assert_eq!(result.len(), 3);
}
#[test]
fn test_parse_locale_output_case_variations() {
let output = "en_US.UTF-8\nen_US.utf-8\nen_US.utf8\nen_US.UTF8\nde_DE.Utf8\n";
let result = parse_locale_output(output);
// All case variations should be accepted (case-insensitive regex)
assert!(result.contains(&"en_US.UTF-8".to_string()));
assert!(result.contains(&"en_US.utf-8".to_string()));
assert!(result.contains(&"en_US.utf8".to_string()));
assert!(result.contains(&"en_US.UTF8".to_string()));
assert!(result.contains(&"de_DE.Utf8".to_string()));
assert_eq!(result.len(), 5);
}
}

View file

@ -1,631 +0,0 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
//! Service manager abstraction for managing system services.
//!
//! This module provides a trait-based interface for interacting with system
//! service managers (like systemd, OpenRC, etc.), allowing for testability
//! and flexibility across different init systems.
use std::future::Future;
use std::pin::Pin;
/// Trait for managing system services.
///
/// Implementations are bound to a specific service name and provide
/// methods to query service state and perform lifecycle operations.
pub trait ServiceManager {
/// Whether the service is configured to start on boot.
fn is_enabled(&self) -> bool;
/// Whether the service is currently running.
fn is_active(&self) -> bool;
/// Start the service.
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>>;
/// Enable the service to start on boot and start it now.
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>>;
/// Whether the service is installed on this system.
fn is_installed(&self) -> bool;
}
/// A newtype around `Box<dyn ServiceManager>` that enables `#[derive(Default)]`
/// on containing structs. Methods on `ServiceManager` are accessible via `Deref`.
///
/// The `Default` impl creates a manager for the `"bluetooth"` service, which is
/// currently the only consumer. If other services need this in the future the
/// default can be made configurable.
pub struct ServiceManagerHandle(Box<dyn ServiceManager>);
impl ServiceManagerHandle {
pub fn new(manager: Box<dyn ServiceManager>) -> Self {
Self(manager)
}
}
impl std::ops::Deref for ServiceManagerHandle {
type Target = dyn ServiceManager;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl Default for ServiceManagerHandle {
fn default() -> Self {
Self(create_default_service_manager("bluetooth"))
}
}
/// Log a warning or error after a privileged command completes.
fn log_command_result(
result: &Result<std::process::ExitStatus, std::io::Error>,
description: &str,
service: &str,
) {
match result {
Ok(status) if status.success() => {}
Ok(status) => tracing::warn!(
"{} for '{}' failed with exit code: {:?}",
description,
service,
status.code(),
),
Err(e) => tracing::error!("Failed to execute {} for '{}': {}", description, service, e,),
}
}
/// Run a privileged command via `pkexec`.
///
/// This is the common async entry point for service management actions
/// that require elevated privileges.
async fn run_pkexec_command(args: &[&str], description: &str, service: &str) {
let result = tokio::process::Command::new("pkexec")
.args(args)
.status()
.await;
log_command_result(&result, description, service);
}
/// Mock ServiceManager that returns configurable boolean values.
#[cfg(test)]
pub struct MockServiceManager {
enabled: bool,
active: bool,
installed: bool,
}
#[cfg(test)]
impl MockServiceManager {
pub fn new(enabled: bool, active: bool) -> Self {
Self {
enabled,
active,
installed: true,
}
}
pub fn with_installed(mut self, installed: bool) -> Self {
self.installed = installed;
self
}
}
#[cfg(test)]
impl ServiceManager for MockServiceManager {
fn is_enabled(&self) -> bool {
self.enabled
}
fn is_active(&self) -> bool {
self.active
}
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn is_installed(&self) -> bool {
self.installed
}
}
/// SystemD implementation of ServiceManager.
#[cfg(feature = "systemd")]
pub struct SystemDServiceManager {
service_name: String,
}
#[cfg(feature = "systemd")]
impl SystemDServiceManager {
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into(),
}
}
}
#[cfg(feature = "systemd")]
impl ServiceManager for SystemDServiceManager {
fn is_enabled(&self) -> bool {
std::process::Command::new("systemctl")
.args(["is-enabled", &self.service_name])
.status()
.map(|status| status.success())
.unwrap_or(true)
}
fn is_active(&self) -> bool {
std::process::Command::new("systemctl")
.args(["is-active", &self.service_name])
.status()
.map(|status| status.success())
.unwrap_or(true)
}
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
let service = self.service_name.clone();
Box::pin(async move {
run_pkexec_command(
&["systemctl", "start", &service],
"systemctl start",
&service,
)
.await;
})
}
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
let service = self.service_name.clone();
Box::pin(async move {
run_pkexec_command(
&["systemctl", "enable", "--now", &service],
"systemctl enable --now",
&service,
)
.await;
})
}
fn is_installed(&self) -> bool {
std::process::Command::new("systemctl")
.args(["cat", &self.service_name])
.status()
.map(|status| status.success())
.unwrap_or(false)
}
}
/// OpenRC implementation of ServiceManager.
#[cfg(feature = "openrc")]
pub struct OpenRcServiceManager {
service_name: String,
}
#[cfg(feature = "openrc")]
impl OpenRcServiceManager {
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into(),
}
}
}
/// Parses `rc-update show` output to check if a service is in any runlevel.
///
/// Uses exact service name matching to avoid false positives from prefix matches
/// (e.g., "bluetoothd" should not match a lookup for "bluetooth").
#[cfg(any(feature = "openrc", test))]
fn is_service_in_runlevel_output(output: &str, service_name: &str) -> bool {
output.lines().any(|line| {
line.split('|')
.next()
.map(|name| name.trim() == service_name)
.unwrap_or(false)
})
}
#[cfg(feature = "openrc")]
impl ServiceManager for OpenRcServiceManager {
fn is_enabled(&self) -> bool {
std::process::Command::new("rc-update")
.args(["show"])
.output()
.map(|output| {
is_service_in_runlevel_output(
&String::from_utf8_lossy(&output.stdout),
&self.service_name,
)
})
.unwrap_or(true)
}
fn is_active(&self) -> bool {
std::process::Command::new("rc-service")
.args([&self.service_name, "status"])
.status()
.map(|status| status.success())
.unwrap_or(true)
}
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
let service = self.service_name.clone();
Box::pin(async move {
run_pkexec_command(
&["rc-service", &service, "start"],
"rc-service start",
&service,
)
.await;
})
}
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
let service = self.service_name.clone();
Box::pin(async move {
run_pkexec_command(
&["rc-update", "add", &service, "default"],
"rc-update add",
&service,
)
.await;
run_pkexec_command(
&["rc-service", &service, "start"],
"rc-service start",
&service,
)
.await;
})
}
fn is_installed(&self) -> bool {
std::path::Path::new("/etc/init.d")
.join(&self.service_name)
.exists()
}
}
/// Detect the running service manager and create a manager for the named service.
///
/// Checks runtime directories (`/run/systemd/system`, `/run/openrc`) to determine
/// which service manager is actively running, rather than relying on which binaries
/// are installed. This avoids false detections when multiple service managers are
/// installed but only one is actively managing services.
pub fn detect_service_manager(
service_name: impl Into<String>,
) -> Result<Box<dyn ServiceManager>, String> {
let service_name = service_name.into();
#[cfg(feature = "systemd")]
{
if std::path::Path::new("/run/systemd/system").exists() {
tracing::debug!("Detected systemd service manager via /run/systemd/system");
return Ok(Box::new(SystemDServiceManager::new(service_name)));
}
}
#[cfg(feature = "openrc")]
{
if std::path::Path::new("/run/openrc").exists() {
tracing::debug!("Detected OpenRC service manager via /run/openrc");
return Ok(Box::new(OpenRcServiceManager::new(service_name)));
}
}
{
let mut checked = Vec::new();
#[cfg(feature = "systemd")]
checked.push("systemd (/run/systemd/system)");
#[cfg(feature = "openrc")]
checked.push("openrc (/run/openrc)");
Err(format!(
"Could not detect a running service manager. Checked for: {}. \
None of these service managers appear to be running on this system.",
checked.join(", ")
))
}
}
/// Factory: returns `MockServiceManager` in tests, detects the running service manager in production.
#[cfg(test)]
pub fn create_default_service_manager(_service_name: impl Into<String>) -> Box<dyn ServiceManager> {
Box::new(MockServiceManager::new(false, false))
}
#[cfg(not(test))]
pub fn create_default_service_manager(service_name: impl Into<String>) -> Box<dyn ServiceManager> {
let service_name = service_name.into();
detect_service_manager(&service_name).unwrap_or_else(|e| {
tracing::warn!(
"Failed to detect service manager: {}. Service management features will not be available.",
e
);
tracing::warn!(
"Using no-op service manager for '{}'. Service status will always report as enabled/active, but operations will not actually execute.",
service_name
);
// Graceful degradation — app continues but service management won't work
Box::new(NoOpServiceManager)
})
}
/// Fallback when no service manager is detected — reports everything as active but does nothing.
struct NoOpServiceManager;
impl ServiceManager for NoOpServiceManager {
fn is_enabled(&self) -> bool {
true
}
fn is_active(&self) -> bool {
true
}
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn is_installed(&self) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use tracing_subscriber::util::SubscriberInitExt;
#[test]
fn test_service_manager_trait_is_enabled() {
struct TestServiceManager {
enabled: bool,
installed: bool,
}
impl ServiceManager for TestServiceManager {
fn is_enabled(&self) -> bool {
self.enabled
}
fn is_active(&self) -> bool {
true
}
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn is_installed(&self) -> bool {
self.installed
}
}
let test_service = TestServiceManager {
enabled: true,
installed: true,
};
assert!(test_service.is_enabled());
let disabled_service = TestServiceManager {
enabled: false,
installed: true,
};
assert!(!disabled_service.is_enabled());
}
#[test]
fn test_service_manager_trait_is_active() {
struct TestServiceManager {
active: bool,
installed: bool,
}
impl ServiceManager for TestServiceManager {
fn is_enabled(&self) -> bool {
true
}
fn is_active(&self) -> bool {
self.active
}
fn activate(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn enable(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async {})
}
fn is_installed(&self) -> bool {
self.installed
}
}
let test_service = TestServiceManager {
active: true,
installed: true,
};
assert!(test_service.is_active());
let inactive_service = TestServiceManager {
active: false,
installed: true,
};
assert!(!inactive_service.is_active());
}
#[test]
fn test_mock_service_manager_returns_configured_values() {
let bluetooth = MockServiceManager::new(true, true);
assert!(bluetooth.is_enabled());
assert!(bluetooth.is_active());
let disabled_bluetooth = MockServiceManager::new(false, false);
assert!(!disabled_bluetooth.is_enabled());
assert!(!disabled_bluetooth.is_active());
}
#[test]
#[cfg(feature = "systemd")]
fn test_systemd_service_manager_implements_trait() {
let bluetooth = SystemDServiceManager::new("bluetooth");
// Can't test actual systemd calls in unit tests, but verify the struct exists
let _enabled: bool = bluetooth.is_enabled();
let _active: bool = bluetooth.is_active();
}
#[tokio::test]
async fn test_service_manager_trait_has_activate_method() {
let bluetooth = MockServiceManager::new(false, false);
bluetooth.activate().await;
}
#[tokio::test]
async fn test_service_manager_trait_has_enable_method() {
let bluetooth = MockServiceManager::new(false, false);
bluetooth.enable().await;
}
#[tokio::test]
async fn test_service_manager_activate_returns_future() {
let bluetooth = MockServiceManager::new(false, false);
let future = bluetooth.activate();
future.await;
}
#[tokio::test]
async fn test_service_manager_enable_returns_future() {
let bluetooth = MockServiceManager::new(false, false);
let future = bluetooth.enable();
future.await;
}
#[test]
fn test_default_service_manager_uses_mock_in_tests() {
let bluetooth = create_default_service_manager("bluetooth");
assert!(!bluetooth.is_enabled());
assert!(!bluetooth.is_active());
}
#[test]
#[cfg(feature = "openrc")]
fn test_openrc_service_manager_implements_trait() {
let bluetooth = OpenRcServiceManager::new("bluetooth");
// Can't test actual OpenRC calls in unit tests, but verify the struct exists
let _enabled: bool = bluetooth.is_enabled();
let _active: bool = bluetooth.is_active();
}
#[test]
fn test_detect_service_manager_returns_result() {
let result = detect_service_manager("test-service");
match result {
Ok(_) => {}
Err(e) => {
assert!(!e.is_empty());
assert!(
e.contains("service manager"),
"Error message should mention service manager: {}",
e
);
}
}
}
#[test]
fn test_mock_service_manager_accepts_service_name() {
let bluetooth = MockServiceManager::new(true, true);
assert!(bluetooth.is_enabled());
}
#[test]
fn test_mock_service_manager_is_installed_defaults_to_true() {
let bluetooth = MockServiceManager::new(true, true);
assert!(bluetooth.is_installed());
}
#[test]
fn test_mock_service_manager_with_installed_configures_state() {
let not_installed = MockServiceManager::new(true, true).with_installed(false);
assert!(!not_installed.is_installed());
let installed = MockServiceManager::new(true, true).with_installed(true);
assert!(installed.is_installed());
}
#[test]
fn test_no_op_service_manager_reports_not_installed() {
let no_op = NoOpServiceManager;
// When no service manager is detected at runtime, the fallback must report
// not-installed so DBusServiceUnknown falls through to the unknown-service path
// instead of showing a non-functional toggle.
assert!(!no_op.is_installed());
}
#[test]
fn test_parse_rc_update_output_exact_service_name() {
// Must use exact matching, not prefix matching — "bluetoothd" must not match "bluetooth".
let output = " bluetoothd | default\n";
let found = is_service_in_runlevel_output(output, "bluetooth");
assert!(!found);
}
#[test]
fn test_parse_rc_update_output_matches_exact_name() {
let output = " bluetooth | default\n";
let found = is_service_in_runlevel_output(output, "bluetooth");
assert!(found);
}
#[test]
fn test_parse_rc_update_output_not_found() {
let output = " dbus | default\n network | sysinit\n";
let found = is_service_in_runlevel_output(output, "bluetooth");
assert!(!found);
}
#[test]
fn test_log_command_result_logs_all_branches() {
let _guard = tracing_subscriber::fmt().with_test_writer().set_default();
let err_result: Result<std::process::ExitStatus, std::io::Error> = Err(
std::io::Error::new(std::io::ErrorKind::NotFound, "command not found"),
);
log_command_result(&err_result, "test command", "test-service");
let fail_result = std::process::Command::new("false").status();
log_command_result(&fail_result, "test false", "test-service");
let ok_result = std::process::Command::new("true").status();
log_command_result(&ok_result, "test true", "test-service");
}
#[test]
fn test_parse_rc_update_output_multi_line() {
let output = " dbus | default\n bluetooth | default\n network | sysinit\n";
let found = is_service_in_runlevel_output(output, "bluetooth");
assert!(found);
}
}

View file

@ -2,9 +2,11 @@ use std::any::TypeId;
use ashpd::desktop::location::{Location, LocationProxy};
use chrono::NaiveDate;
use cosmic::iced::futures::channel::mpsc::Sender;
use cosmic::iced::futures::{SinkExt, StreamExt, future};
use cosmic::iced::{Subscription, stream};
use cosmic::iced::{
Subscription,
futures::{SinkExt, StreamExt, channel::mpsc::Sender, future},
stream,
};
use sunrise::{Coordinates, SolarDay, SolarEvent};
use tokio::select;

View file

@ -1,5 +1,8 @@
use cosmic::iced::futures::{self, SinkExt};
use cosmic::iced::{Subscription, stream};
use cosmic::iced::{
Subscription,
futures::{self, SinkExt},
stream,
};
use notify::{Config, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::fmt::Debug;
use std::hash::Hash;

View file

@ -1,8 +1,10 @@
use std::path::PathBuf;
use cosmic::iced::futures::channel::mpsc::Sender;
use cosmic::iced::futures::{SinkExt, StreamExt, future};
use cosmic::iced::{Subscription, stream};
use cosmic::iced::{
Subscription,
futures::{SinkExt, StreamExt, channel::mpsc::Sender, future},
stream,
};
use image::{ImageBuffer, Rgba};
#[derive(Clone, Debug)]

View file

@ -1,8 +1,7 @@
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use cosmic::iced::Border;
use cosmic::theme;
use cosmic::{iced::Border, theme};
#[must_use]
pub fn display_container_frame() -> cosmic::theme::Container<'static> {

View file

@ -1,5 +1,4 @@
use std::future::Future;
use std::{io, process};
use std::{future::Future, io, process};
use futures::future::select;

View file

@ -8,9 +8,10 @@ use cosmic::cosmic_theme::Spacing;
use cosmic::iced::core::text::Wrapping;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::color_picker::ColorPickerUpdate;
use cosmic::widget::space::{horizontal, vertical};
use cosmic::widget::{
self, ColorPickerModel, button, column, container, divider, icon, list, row, settings, text,
self, ColorPickerModel, button, column, container, divider, icon, list, row, settings,
space::{horizontal, vertical},
text,
};
use cosmic::{Apply, Element, theme};
use cosmic_settings_page as page;
@ -205,10 +206,8 @@ pub fn go_next_with_item<'a, Msg: 'static>(
msg_opt: impl Into<Option<Msg>>,
) -> list::ListButton<'a, Msg> {
settings::item_row(vec![
text::body(description)
.width(Length::Fill)
.wrapping(Wrapping::Word)
.into(),
text::body(description).wrapping(Wrapping::Word).into(),
horizontal().into(),
row::with_capacity(2)
.push(item)
.push(icon::from_name("go-next-symbolic").size(16).icon())

View file

@ -0,0 +1,21 @@
[package]
name = "cosmic-pipewire"
version = "1.0.7"
edition = "2024"
repository = "https://github.com/pop-os/cosmic-settings"
rust-version.workspace = true
license = "MPL-2.0"
publish = true
[dependencies]
intmap = "3.1.3"
libspa = "0.9.2"
libspa-sys = "0.9.2"
pipewire = "0.9"
serde = { version = "1.0.228", features = ["derive"]}
serde_json = "1.0.149"
tracing = "0.1.44"
[features]
# Cache route port types
route-port-type = []

View file

@ -0,0 +1,358 @@
Mozilla Public License Version 2.0
==================================
## 1. Definitions
### 1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
### 1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
### 1.3. "Contribution"
means Covered Software of a particular Contributor.
### 1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
### 1.5. "Incompatible With Secondary Licenses"
means
+ (a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
+ (b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
### 1.6. "Executable Form"
means any form of the work other than Source Code Form.
### 1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
### 1.8. "License"
means this document.
### 1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
### 1.10. "Modifications"
means any of the following:
+ (a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
+ (b) any new file in Source Code Form that contains any Covered
Software.
### 1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
### 1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
### 1.13. "Source Code Form"
means the form of the work preferred for making modifications.
### 1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
## 2. License Grants and Conditions
### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
+ (a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
+ (a) for any code that a Contributor has removed from Covered Software;
or
+ (b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
+ (c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
## 3. Responsibilities
### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
+ (a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
+ (b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
## 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
## 5. Termination
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
## 6. Disclaimer of Warranty
**Covered Software is provided under this License on an "as is"
basis, without warranty of any kind, either expressed, implied, or
statutory, including, without limitation, warranties that the
Covered Software is free of defects, merchantable, fit for a
particular purpose or non-infringing. The entire risk as to the
quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You
(not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an
essential part of this License. No use of any Covered Software is
authorized under this License except under this disclaimer.**
#7. Limitation of Liability
**Under no circumstances and under no legal theory, whether tort
(including negligence), contract, or otherwise, shall any
Contributor, or anyone who distributes Covered Software as
permitted above, be liable to You for any direct, indirect,
special, incidental, or consequential damages of any character
including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any
and all other commercial damages or losses, even if such party
shall have been informed of the possibility of such damages. This
limitation of liability shall not apply to liability for death or
personal injury resulting from such party's negligence to the
extent applicable law prohibits such limitation. Some
jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and
limitation may not apply to You.**
## 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
## 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
## 10. Versions of the License
### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
### 10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View file

@ -0,0 +1,27 @@
// Copyright 2025 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use pipewire::device::DeviceInfoRef;
/// Device information
#[must_use]
#[derive(Clone, Debug)]
pub struct Device {
pub id: u32,
pub name: String,
}
impl Device {
/// Attains process info from a pipewire info node.
#[must_use]
pub fn from_device(info: &DeviceInfoRef) -> Option<Self> {
let props = info.props()?;
let device = Device {
id: props.get("object.id")?.parse::<u32>().ok()?,
name: props.get("device.description")?.to_owned(),
};
Some(device)
}
}

View file

@ -21,19 +21,20 @@ pub use route::{Route, RouteProps};
mod spa_utils;
pub use spa_utils::Channel;
use libspa::param::ParamType;
use libspa::param::format::FormatProperties;
use libspa::pod::serialize::PodSerializer;
use libspa::pod::{self, Pod};
use libspa::utils::SpaTypes;
use pipewire::device::{DeviceChangeMask, DeviceListener};
use pipewire::main_loop::MainLoopWeak;
use pipewire::metadata::MetadataListener;
use pipewire::node::NodeListener;
use pipewire::proxy::{ProxyListener, ProxyT};
use pipewire::types::ObjectType;
use std::cell::RefCell;
use std::rc::Rc;
use libspa::{
param::{ParamType, format::FormatProperties},
pod::{self, Pod, serialize::PodSerializer},
utils::SpaTypes,
};
use pipewire::{
device::{DeviceChangeMask, DeviceListener},
main_loop::MainLoopWeak,
metadata::MetadataListener,
node::NodeListener,
proxy::{ProxyListener, ProxyT},
types::ObjectType,
};
use std::{cell::RefCell, rc::Rc};
pub type NodeId = u32;
pub type RouteId = u32;

View file

@ -1,10 +1,8 @@
// Copyright 2025 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use crate::Channel;
use crate::spa_utils::array_from_pod;
use libspa::pod::Pod;
use libspa::utils::Id;
use crate::{Channel, spa_utils::array_from_pod};
use libspa::{pod::Pod, utils::Id};
use pipewire::node::{NodeInfoRef, NodeState};
use std::ffi::c_float;

View file

@ -0,0 +1,98 @@
// Copyright 2025 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
//! Currently unusued
use crate::pipewire::Direction;
use pipewire::port::PortInfoRef;
#[must_use]
#[derive(Clone, Debug)]
pub struct Port {
pub node_id: u32,
pub object_id: u32,
pub port_id: u32,
pub audio_channel: String,
pub format_dsp: String,
pub object_path: String,
pub port_direction: Direction,
pub port_group: String,
pub port_name: String,
pub port_alias: String,
pub port_physical: bool,
pub port_terminal: bool,
pub port_monitor: bool,
}
impl Port {
/// Attains process info from a pipewire info port.
#[must_use]
pub fn from_port(info: &PortInfoRef) -> Option<Self> {
let props = info.props()?;
let object_id = info.id();
let port_direction = match info.direction() {
libspa::utils::Direction::Input => Direction::Input,
libspa::utils::Direction::Output => Direction::Output,
_ => return None,
};
let mut node_id = 0;
let mut port_id = 0;
let mut port_monitor = false;
let mut port_physical = false;
let mut port_terminal = false;
let mut audio_channel = String::new();
let mut format_dsp = String::new();
let mut object_path = String::new();
let mut port_alias = String::new();
let mut port_group = String::new();
let mut port_name = String::new();
for (entry, value) in props.iter() {
match entry {
// 32 bit float mono audio
"format.dsp" => format_dsp = value.to_owned(),
// FR
"audio.channel" => audio_channel = value.to_owned(),
// playback
"port.group" => port_group = value.to_owned(),
// 1
"port.id" => port_id = value.parse::<u32>().ok()?,
// false
"port.monitor" => port_monitor = value == "true",
// true
"port.physical" => port_physical = value == "true",
// true
"port.terminal" => port_terminal = value == "true",
// alsa:acp:Device:3:playback:playback_1
"object.path" => object_path = value.to_owned(),
// playback_FR
"port.name" => port_name = value.to_owned(),
// MosArt USB Audio Device:playback_FR
"port.alias" => port_alias = value.to_owned(),
// 59
"node.id" => node_id = value.parse::<u32>().ok()?,
_ => (),
}
}
let port = Port {
format_dsp,
audio_channel,
port_id,
port_direction,
object_path,
port_name,
port_alias,
port_group,
port_monitor,
port_physical,
port_terminal,
node_id,
object_id,
};
Some(port)
}
}

View file

@ -1,8 +1,7 @@
// Copyright 2025 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use crate::Availability;
use crate::spa_utils::string_from_pod;
use crate::{Availability, spa_utils::string_from_pod};
use libspa::pod::Pod;
#[derive(Clone, Debug, Default)]

View file

@ -3,10 +3,11 @@
use std::ffi::{c_float, c_int};
use crate::spa_utils::{array_from_pod, string_from_pod};
use crate::{Availability, Channel, Direction};
use libspa::pod::Pod;
use libspa::utils::Id;
use crate::{
Availability, Channel, Direction,
spa_utils::{array_from_pod, string_from_pod},
};
use libspa::{pod::Pod, utils::Id};
#[derive(Clone, Debug, Default)]
pub struct Route {

View file

@ -0,0 +1,150 @@
// Copyright 2025 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use libspa::pod::Pod;
use std::ffi::CStr;
/// Read a `Pod`'s string if it contains a string.
pub fn string_from_pod(pod: &Pod) -> Option<String> {
if !pod.is_string() {
return None;
}
let mut cstr = std::ptr::null();
unsafe {
// SAFETY: Pod is checked to be a string beforehand
if libspa_sys::spa_pod_get_string(pod.as_raw_ptr(), &mut cstr) == 0 && !cstr.is_null() {
return Some(String::from_utf8_lossy(CStr::from_ptr(cstr).to_bytes()).into_owned());
}
}
None
}
/// SAFETY: Must be absolutely certain that the array is a compatible array.
pub unsafe fn array_from_pod<CType: Copy>(pod: &Pod) -> Option<Vec<CType>> {
if !pod.is_array() {
return None;
}
let mut len = 0;
unsafe {
let array: *mut CType = libspa_sys::spa_pod_get_array(pod.as_raw_ptr(), &mut len).cast();
if array.is_null() {
return None;
}
Some(std::slice::from_raw_parts(array, len as usize).to_vec())
}
}
#[repr(u32)]
#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
pub enum Channel {
#[default]
UNKNOWN = 0, // unspecified
NA, // N/A, silent
MONO, // mono stream
FL, // front left
FR, // front right
FC, // front center
LFE, // LFE
SL, // side left
SR, // side right
FLC, // front left center
FRC, // front right center
RC, // rear center
RL, // rear left
RR, // rear right
TC, // top center
TFL, // top front left
TFC, // top front center
TFR, // top front right
TRL, // top rear left
TRC, // top rear center
TRR, // top rear right
RLC, // rear left center
RRC, // rear right center
FLW, // front left wide
FRW, // front right wide
LFE2, // LFE 2
FLH, // front left high
FCH, // front center high
FRH, // front right high
TFLC, // top front left center
TFRC, // top front right center
TSL, // top side left
TSR, // top side right
LLFE, // left LFE
RLFE, // right LFE
BC, // bottom center
BLC, // bottom left center
BRC = 37, // bottom right center
AUX0 = 4096, // aux channels
AUX1,
AUX2,
AUX3,
AUX4,
AUX5,
AUX6,
AUX7,
AUX8,
AUX9,
AUX10,
AUX11,
AUX12,
AUX13,
AUX14,
AUX15,
AUX16,
AUX17,
AUX18,
AUX19,
AUX20,
AUX21,
AUX22,
AUX23,
AUX24,
AUX25,
AUX26,
AUX27,
AUX28,
AUX29,
AUX30,
AUX31,
AUX32,
AUX33,
AUX34,
AUX35,
AUX36,
AUX37,
AUX38,
AUX39,
AUX40,
AUX41,
AUX42,
AUX43,
AUX44,
AUX45,
AUX46,
AUX47,
AUX48,
AUX49,
AUX50,
AUX51,
AUX52,
AUX53,
AUX54,
AUX55,
AUX56,
AUX57,
AUX58,
AUX59,
AUX60,
AUX61,
AUX62,
AUX63 = 4159,
}

12
debian/changelog vendored
View file

@ -1,15 +1,3 @@
cosmic-settings (1.7.0) noble; urgency=medium
* Epoch 1.7.0 version update
-- Michael Murphy <michael@mmurphy.dev> Fri, 21 Aug 2026 20:44:57 +0200
cosmic-settings (1.0.12) noble; urgency=medium
* release: 1.0.12
-- Michael Murphy <mmstick@pop-os> Mon, 27 Apr 2026 15:24:27 +0200
cosmic-settings (1.0.7) noble; urgency=medium
* release: 1.0.7

4
debian/control vendored
View file

@ -8,14 +8,15 @@ Build-Depends:
fonts-open-sans,
just,
libclang-dev,
libdav1d-dev,
libexpat1-dev,
libfontconfig-dev,
libfreetype-dev,
libinput-dev,
libpipewire-0.3-dev,
libudev-dev,
libwayland-dev,
libxkbcommon-dev,
mold,
pkg-config,
rust-all,
Standards-Version: 4.6.2
@ -28,7 +29,6 @@ Depends:
${shlibs:Depends},
accountsservice,
cosmic-randr,
cosmic-settings-daemon,
gettext,
iso-codes,
network-manager-gnome,

7
debian/rules vendored
View file

@ -1,7 +1,6 @@
#!/usr/bin/make -f
export DESTDIR = debian/tmp
OS_VERSION = $(shell rg VERSION_ID /etc/os-release | awk -F\" '{print $2}')
%:
dh $@
@ -10,11 +9,7 @@ override_dh_auto_clean:
ischroot || just vendor
override_dh_auto_build:
ifeq ($(OS_VERSION),22.04)
test -e vendor.tar && just build-vendored || just build-release --no-default-features
else
test -e vendor.tar && just build-vendored || just build-release
endif
test -e vendor.tar && just build-vendored || just
override_dh_auto_install:
just rootdir=$(DESTDIR) install

View file

@ -1,6 +1,4 @@
tar-ignore=.github
tar-ignore=target/.rustc_info.json
tar-ignore=target/CACHEDIR.TAG
tar-ignore=target/debug
tar-ignore=target/release
tar-ignore=.vscode
tar-ignore=vendor
tar-ignore=target

6
flake.lock generated
View file

@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1785747939,
"narHash": "sha256-D740uKsMbgsfK2oaDenJLLPIZfq7W0/g4KN/Fls8eKs=",
"lastModified": 1760533177,
"narHash": "sha256-OwM1sFustLHx+xmTymhucZuNhtq98fHIbfO8Swm5L8A=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "104240a772428cc2e20d8fd86c9ddbb886bbaff2",
"rev": "35f590344ff791e6b1d6d6b8f3523467c9217caf",
"type": "github"
},
"original": {

View file

@ -41,7 +41,6 @@
libinput
libpulseaudio.dev
pipewire.dev
dav1d
];
RUST_SRC_PATH = rustPlatform.rustLibSrc;

View file

@ -16,7 +16,7 @@ xdg-entry-date-time-comment = المنطقة الزمنية وإعدادات ا
xdg-entry-default-apps = التطبيقات المبدئية
xdg-entry-default-apps-comment = متصفح الويب المبدئي، عميل البريد، متصفح الملفات، والتطبيقات الأخرى
xdg-entry-desktop = سطح المكتب
xdg-entry-desktop-comment = إعدادات خلفية الشاشة والمظهر واللوحة والإرساء وإدارة النوافذ ومساحة العمل
xdg-entry-desktop-comment = إعدادات خلفية الشاشة والمظهر واللوحة والمنصة وإدارة النوافذ ومساحة العمل
xdg-entry-displays = شاشات العرض
xdg-entry-displays-comment = أدِر إعدادات تضبيط العرض
xdg-entry-dock = الإرساء
@ -107,8 +107,6 @@ vpn-error = خطأ في VPN
.connect = فشل الاتصال بـ VPN
.connection-editor = فشل محرر الاتصال
.connection-settings = فشل الحصول على إعدادات الاتصالات النشطة
.openvpn-config-path = مسار ملف غير صالح لإعدادات OpenVPN
.openvpn-config-path-desc = يجب أن يكون الملف المختار موجودًا على نظام الملفات المحلي.
.updating-state = فشل تحديث حالة مدير الشبكة
.wireguard-config-path = مسار ملف غير صالح لتكوين WireGuard
.wireguard-config-path-desc = يجب أن يكون الملف المختار موجودًا على نظام ملفات محلي.
@ -275,26 +273,13 @@ frosted = تأثير الزجاج البلوري على واجهة النظام
enable-export = قم بتطبيق هذا المظهر على تطبيقات GNOME.
.desc = لا تدعم جميع مجموعات الأدوات التبديل التلقائي. قد تحتاج التطبيقات غير التابعة لـ COSMIC إلى إعادة التشغيل بعد تغيير المظهر.
icon-theme = نسق الأيقونات
.desc = يطبِّق مجموعة مختلفة من الأيقونات على التطبيقات
.desc = يطبق مجموعة مختلفة من الأيقونات على التطبيقات
text-tint = لون نص الواجهة
.desc = اللون المستخدم لاشتقاق ألوان نص الواجهة التي تتمتع بتباين كافٍ على الأسطح المختلفة
style = الأسلوب
style = المظهر
.round = دائري
.slightly-round = دائري قليلاً
.square = مربع
.frosted-glass = زجاج بلوري
.frosted-system-interface = واجهة النظام
.frosted-system-interface-desc = يُطبِّق مظهر الزجاج البلوري على المشغّل، ومكتبة التطبيقات، ونظرة عامة على مساحة العمل، وعناصر التحكم التي تظهر على الشاشة
.frosted-windows = النوافذ
.frosted-windows-desc = يطبِّق مظهر الزجاج البلوري على النوافذ ومربعات الحوار
.frosted-panels = اللوحات
.frosted-panels-desc = يطبِّق الزجاج البلوري على اللوحة وقاعدة الإرساء
.frosted-applets = البريمجات
.frosted-applets-desc = يطبِّق الزجاج البلوري على قوائم البريمجات الموجودة على اللوحة والإرساء
.frosted-thickness = السماكة البلورية
.less = أقل
.more = أكثر
.glass-opacity = عتامة الزجاج
interface-density = كثافة الواجهة
.comfortable = مريحة
.compact = صغير ة
@ -367,7 +352,7 @@ super-key = إجراءات مفتاح Super
.launcher = فتح مشغل التطبيقات
.workspaces = فتح مساحات العمل
.applications = فتح التطبيقات
.none = لا شيء
.disable = تعطيل
edge-gravity = تنجذب النوافذ العائمة إلى الحواف القريبة
window-controls = تحكمات النوافذ
.maximize = أظهر زر التكبير
@ -548,27 +533,11 @@ keyboard-sources = مصادر الإدخال
.view-layout = اعرض تخطيط لوحة المفاتيح
.remove = أزِل
.add = أضِف مصدر إدخال
keyboard-special-char = إدخال الأحرف الخاصة
keyboard-special-char = إدخال أحرف خاصة
.alternate = مفتاح الأحرف البديلة
.compose = مفتاح التكوين
.compose-desc = يتيح مفتاح التكوين إدخال مجموعة متنوعة من الأحرف. لاستخدامه، اضغط على مفتاح التكوين ثم سلسلة من الأحرف. على سبيل المثال، سيؤدي الضغط على مفتاح التكوين متبوعًا بالحرفين C و o إلى إدخال الرمز ©، بينما سيؤدي الضغط على مفتاح «التكوين» متبوعًا بالحرفين a و ‘ إلى إدخال الحرف á.
.caps = مفتاح قفل الحروف
.ctrl = مفتاح التحكم
.ctrl-right = مفتاح Ctrl الأيمن
.swap-with-ctrl = تبديل مع مفتاح التحكم
.alt = مفتاح Alt
.alt-left = مفتاح Alt الأيسر
.alt-right = Alt الأيمن
.super = Super
.super-left = Super الأيسر
.super-right = Super الأيمن
.menu = مفتاح القائمة
.backspace = مسافة للخلف
.escape = هروب (ESC)
.swap-with-escape = التبديل مع مفتاح الهروب
.print-screen = اطبع الشاشة
.scroll-lock = قفل التمرير
.none = لا شيء
.compose = مفتاح التركيب
.compose-desc = مفتاح التركيب يسمح بإدخال مجموعة واسعة من الأحرف. لاستخدامه، اضغط على مفتاح التركيب ثم اكتب تسلسلًا من الأحرف. على سبيل المثال، الضغط على مفتاح التركيب متبوعًا بـ C و o سيدخل الرمز ©، بينما الضغط على مفتاح التركيب متبوعًا بـ a و ‘ سيدخل الحرف á.
.caps = مفتاح Caps Lock
keyboard-typing-assist = الكتابة
.repeat-rate = معدل التكرار
.repeat-delay = تأخير التكرار
@ -942,9 +911,3 @@ xdg-entry-displays-keywords = COSMIC;عرض;
xdg-entry-workspaces = مساحات العمل
xdg-entry-wired-comment = الاتصالات السلكية وملفات تعريف الاتصال
no-search-results = لا توجد شبكات تطابق بحثك.
workspaces-navigation = التنقل
.wraparound = تنقل بين مساحة العمل الأولى والأخيرة باستخدام اختصارات لوحة المفاتيح والإيماءات
bluetooth-display-passkey = إقران البلوتوث
.description = يُرجى إدخال مفتاح المرور التالي على { $device }، ثم الضغط على مفتاح Enter
bluetooth-display-pin = إقتران البلوتوث
.description = يُرجى إدخال رمز PIN التالي على { $device }، ثم الضغط على Enter

View file

@ -1,11 +0,0 @@
cancel = Cancel·lar
confirm = Confirmar
password = Contrasenya
identity = Identitat
password-confirm = Confirmeu la contrasenya
connected = Connectat
settings = Configuració
save = Desa
forget-dialog = Oblidar aquesta xarxa Wi-Fi?
.description = Caldrà tornar a introduir la contrasenya per utilitzar aquesta xarxa en el futur.
close = Tancar

View file

@ -32,7 +32,7 @@ xdg-entry-network = Síť a Wi-Fi
xdg-entry-network-comment = Správa síťových připojení
xdg-entry-notifications = Oznámení
xdg-entry-notifications-comment = Režim Nerušit, oznámení na zamykací obrazovce a nastavení jednotlivých aplikací
xdg-entry-panel-comment = Hlavní systémová lišta pro nabídky a applety
xdg-entry-panel-comment = Hlavní systémová lišta pro menu a applety
xdg-entry-power = Napájení a baterie
xdg-entry-power-comment = Režimy napájení a možnosti úspory energie
xdg-entry-region-language = Region a jazyk
@ -86,10 +86,10 @@ dock = Dok
## Desktop: Panel
panel = Panel
panel-behavior-and-position = Chování a umístění
panel-behavior-and-position = Chování a pozice
.autohide = Automaticky skrýt panel
.dock-autohide = Automaticky skrýt dok
.position = Umístění na obrazovce
.position = Pozice na obrazovce
.display = Zobrazit na obrazovce
panel-top = Nahoře
panel-bottom = Dole
@ -116,9 +116,9 @@ panel-missing = Nastavení panelu chybí
.desc = Soubor nastavení panelu chybí kvůli poškození nebo použití vlastního nastavení.
.fix = Obnovit výchozí
applets = Applety
start-segment = Počáteční segment
start-segment = Začínající segment
center-segment = Prostřední segment
end-segment = Koncový segment
end-segment = Konečný segment
add = Přidat
add-applet = Přidat applet
search-applets = Vyhledat applety...
@ -215,8 +215,7 @@ sound-alerts = Upozornění
.volume = Hlasitost upozornění
.sound = Zvuk pro upozornění
sound-applications = Aplikace
.desc = Hlasitosti a nastavení aplikací
.none = Žádné aplikace nepoužívají zvuk
.desc = Hlasitosti aplikací a nastavení
## System
@ -281,24 +280,8 @@ keyboard-sources = Vstupní zdroje
keyboard-special-char = Zadávání speciálních znaků
.alternate = Klávesa pro náhradní znaky
.compose = Klávesa Compose
.compose-desc = Klávesa Compose umožňuje zadávat širokou škálu znaků. Pro její použití stiskněte Compose a poté zadejte sekvenci znaků. Například Compose, C, O vloží znak „©“, zatímco Compose, A, ‘ vloží znak „á“.
.compose-desc = Klávesa Compose umožňuje zadávat širokou škálu znaků. Pro její použití stiskněte Compose a poté zadejte sekvenci znaků. Například [Compose, C, O] vloží znak „©“, zatímco [Compose, A, ‘] znak „á“.
.caps = Klávesa Caps Lock
.ctrl = Control
.ctrl-right = Pravý Ctrl
.swap-with-ctrl = Zaměnit s klávesou Control
.alt = Alt
.alt-left = Levý Alt
.alt-right = Pravý Alt
.super = Super
.super-left = Levý Super
.super-right = Pravý Super
.menu = Klávesa Menu
.backspace = Backspace
.escape = Escape
.swap-with-escape = Zaměnit s klávesou Escape
.print-screen = Print Screen
.scroll-lock = Scroll Lock
.none = Žádná
## Input: Keyboard: Shortcuts
@ -370,10 +353,8 @@ accessibility = Přístupnost
.unavailable = Nedostupné
.screen-reader = Čtečka obrazovky
.high-contrast = Vysoký kontrast
.invert-colors = Inverze barev
.invert-colors = Převrátit barvy
.color-filters = Barevné filtry
.shake-cursor = Nalezení ukazatele zatřesením
.shake-cursor-desc = Rychlým zatřesením myší se ukazatel dočasně zvětší
hearing = Sluch
.mono = Přehrávat stereo zvuk jako mono
default = Výchozí
@ -437,8 +418,6 @@ vpn-error = Chyba VPN
.connect = Nepodařilo se připojit k VPN
.connection-editor = Editor připojení selhal
.connection-settings = Nepodařilo se získat nastavení aktivních připojení
.openvpn-config-path = Chybně zadaná cesta souboru nastavení OpenVPN
.openvpn-config-path-desc = Vybraný soubor musí být na lokálním souborovém systému
.updating-state = Nepodařilo se aktualizovat stav správce sítě
.wireguard-config-path = Chybně zadaná cesta souboru nastavení WireGuard
.wireguard-config-path-desc = Vybraný soubor musí být na lokálním souborovém systému
@ -464,14 +443,14 @@ container-background = Pozadí kontejneru
.desc = Používá se pro navigační postranní panel, výsuvný panel, dialogy a podobné prvky
control-tint = Odstín ovládacích prvků
.desc = Používá se pro pozadí standardních tlačítek, vyhledávacích polí, textových vstupů a podobných komponent
frosted = Efekt ledového skla na systémovém rozhraní
.desc = Použít rozmazané pozadí pro panel, dok, applety, spouštěč a knihovnu aplikací
frosted = Efekt zmrazeného okna na systémovém rozhraní
.desc = Použije rozmazané pozadí pro panel, dok, applety, spouštěč a knihovnu aplikací
enable-export = Použít aktuální motiv v aplikacích GNOME
.desc = Ne všechny toolkity podporují automatické přepínání. Aplikace, které nejsou postaveny na COSMIC toolkitu mohou vyžadovat restart po změně motivu.
password-mismatch = Heslo a jeho potvrzení se musí shodovat
invalid-username = Neplatné uživatelské jméno
icon-theme = Motiv ikon
.desc = Použít jinou sadu ikon pro aplikace
.desc = Použije jinou sadu ikon pro aplikace
monospace-font = Písmo s pevnou šířkou
window-management = Správa oken
window-tiling = Dlaždicový režim oken
@ -488,7 +467,7 @@ super-key = Akce klávesy Super
.launcher = Otevřít spouštěč
.workspaces = Otevřít pracovní plochy
.applications = Otevřít aplikace
.none = Žádná
.disable = Zakázat
edge-gravity = Plovoucí okna se přichytávají k blízkým okrajům
focus-navigation = Navigace zaměření
.focus-follows-cursor = Zaměření následuje kurzor
@ -524,7 +503,7 @@ magnifier = Lupa
.show_overlay = Zobrazit překrytí lupy
.increment = Krok přiblížení
.signin = Spustit lupu při přihlášení
.applet = Lupu lze přepnout (zap/vyp) v nabídce zobrazené po kliknutí na applet přímo v panelu
.applet = Lupu lze přepnout v appletu na panelu
.movement = Pohyb přiblíženého zobrazení
.continuous = Neustále s ukazatelem
.onedge = Když ukazatel dosáhne okraje
@ -532,9 +511,9 @@ magnifier = Lupa
color-filter = Typ barevného filtru
.unknown = Neznámý filtr aktivní
.greyscale = Stupně šedi
.deuteranopia = Zelená/červená (oslabené vnímání zelené, deuteranopie)
.protanopia = Červená/zelená (oslabené vnímání červené, protanopie)
.tritanopia = Modrá/žlutá (oslabené vnímání modré, tritanopie)
.deuteranopia = Zeleno/Červená (oslabení zelené, Deuteranopie)
.protanopia = Červeno/Zelená (oslabení červené, Protanopie)
.tritanopia = Modro/Žlutá (oslabení modré, Tritanopie)
text-tint = Odstín textu rozhraní
.desc = Používá se k odvození barev textu rozhraní, které mají dostatečný kontrast na různých površích
experimental-settings = Experimentální nastavení
@ -551,21 +530,8 @@ display = Obrazovky
.additional-scale-options = Další možnosti měřítka
style = Styl
.round = Kulatý
.slightly-round = Mírně zaoblený
.slightly-round = Lehce kulatý
.square = Hranatý
.frosted-glass = Efekt ledového skla
.frosted-system-interface = Rozhraní systému
.frosted-system-interface-desc = Použít efekt ledového skla pro spouštěč, knihovnu aplikací, přehled pracovních ploch a ovládací prvky na obrazovce
.frosted-windows = Okna
.frosted-windows-desc = Použít efekt ledového skla pro okna a dialogy
.frosted-panels = Panely
.frosted-panels-desc = Použít efekt ledového skla pro dok a panel
.frosted-applets = Applety
.frosted-applets-desc = Použít efekt ledového skla pro nabídky appletů na panelu a doku
.frosted-thickness = Tloušťka ledu
.less = menší
.more = větší
.glass-opacity = Krytí skla
interface-density = Hustota rozhraní
.comfortable = Pohodlné
.compact = Kompaktní
@ -661,13 +627,13 @@ power-saving = Možnosti úspory energie
disable-while-typing = Zakázat při psaní
input-devices = Vstupní zařízení
modified = { $count } změněných
slow = Pomalu
fast = Rychle
short = Krátká
long = Dlouhá
slow = Pomalá
fast = Rychlá
short = Krátké
long = Dlouhé
keyboard-typing-assist = Psaní
.repeat-rate = Rychlost opakování
.repeat-delay = Prodleva před opakováním
.repeat-rate = Frekvence opakování
.repeat-delay = Zpoždění opakování
keyboard-numlock-boot = Num Lock
.boot-state = Stav klávesy při spuštění systému
.last-boot = Poslední spuštění systému
@ -927,9 +893,3 @@ xdg-entry-displays-keywords = COSMIC;Obrazovka;Obrazovky;Displeje;Monitory;Zobra
xdg-entry-workspaces-keywords = COSMIC;Pracovní;Plocha;Plochy;Orientace;Přehled;Sledování;
xdg-entry-x11-applications-keywords = COSMIC;X11;Aplikace;Hra;Hry;Kompatibilita;
no-search-results = Žádné sítě neodpovídají vašemu vyhledávání.
workspaces-navigation = Navigace
.wraparound = Přecházet mezi první a poslední pracovní plochou pomocí klávesových zkratek a gest
bluetooth-display-passkey = Párování Bluetooth
.description = Zadejte prosím následující párovací kód na zařízení { $device } a poté stiskněte Enter
bluetooth-display-pin = Párování Bluetooth
.description = Zadejte prosím následující PIN na zařízení { $device } a poté stiskněte Enter

View file

@ -11,8 +11,8 @@ add-network = Tilføj Netværk
add-vpn = Tilføj VPN
airplane-on = Airplane mode is on. Flytilstand er slået til
cable-unplugged = Kabel frakoblet
connect = Opret forbindelse
connected = Forbundet
connect = Tilslut
connected = Tilsluttet
connecting = Tilslutter…
disconnect = Afbryd
forget = Glem
@ -21,14 +21,14 @@ network-and-wireless = Netværk & trådløst
no-networks = Der blev ikke fundet nogen netværk.
no-vpn = Ingen VPN-forbindelser tilgængelige.
password = Adgangskode
password-confirm = Bekræft adgangskode
password-confirm = Godkend Adgangskode
remove = Fjern
settings = Indstillinger
username = Brugernavn
visible-networks = Synlige Netværk
identity = Identitet
forget-dialog = Glem dette Wi-Fi-netværk?
.description = Du skal indtaste adgangskoden igen for at bruge dette Wi-Fi-netværk i fremtiden.
.description = Du skal indtaste en adgangskode igen for at bruge dette Wi-Fi-netværk i fremtiden.
network-device-state =
.activated = Tilsluttet
.config = Opretter forbindelse
@ -192,6 +192,7 @@ never = Aldrig
## Desktop: Udseende
appearance = Udseende
.desc = Accentfarver og tema.
accent-color = Accentfarve
app-background = Applikation eller vinduesbaggrund
auto = Auto
@ -199,11 +200,11 @@ close = Luk
color-picker = Farvevælger
copied-to-clipboard = Kopieret til udklipsholder
copy-to-clipboard = Kopiér til udklipsholder
dark = Mørkt
dark = Mørk
export = Eksporter
hex = Hex
import = Importer
light = Lyst
light = Lys
mode-and-colors = Tilstand og farver
recent-colors = Seneste farver
reset-to-default = Nulstil til standard
@ -514,7 +515,7 @@ show-extended-input-sources = Vis udvidede inputkilder
keyboard-shortcuts = Tastaturgenveje
.desc = Se og tilpas genveje
cancel = Afbryd
cancel = Annuller
command = Kommando
custom = Brugerdefineret
debug = Debug
@ -713,7 +714,7 @@ region = Region
## Applications
applications = Programmer
applications = Applikationer
## Applications: Default Applications
@ -807,38 +808,3 @@ full-name = Fulde navn
invalid-username = Ugyldigt brugernavn.
password-mismatch = Adgangskode og bekræftelse skal være ens.
save = Gem
xdg-entry-bluetooth-comment = Håndter Bluetoothenheder
xdg-entry-default-apps-comment = Standardwebbrowser, mailklient, filhåndtering og andre programmer
xdg-entry-appearance-keywords = COSMIC;Accent;Farve;Ikon;Skrifttype;Tema
xdg-entry-dock-keywords = COSMIC;Dock;Panel;Applet
xdg-entry-a11y = Tilgængelighed
xdg-entry-desktop-keywords = COSMIC;Skrivebord;
xdg-entry-displays-comment = Administrer skærmkonfigurationsindstillinger
xdg-entry-default-apps = Standardprogrammer
xdg-entry-applications-comment = Standardprogrammer, opstartsprogrammer og X11 program kompatibilitetsindstillinger
xdg-entry-about-keywords = COSMIC;Om
xdg-entry-a11y-keywords = COSMIC;Tilgængelighed;A11y;Skærm;Oplæser;Forstørrelse;Kontrast;Farve;
xdg-entry-desktop = Skrivebord
xdg-entry-date-time-keywords = COSMIC;Tid;Zone;
xdg-entry-keyboard = Tastatur
xdg-entry-a11y-comment = Skærmoplæsning, forstørrelse, høj kontrast og farvefiltre
xdg-entry-displays = Skærme
xdg-entry-date-time = Dato & tid
xdg-entry-input-comment = Tastatur- og museindstillinger
xdg-entry-bluetooth-keywords = COSMIC;Bluetooth;
xdg-entry-dock = Dock
xdg-entry-about-comment = Enhedsnavn, hardwareoplysninger og standardindstillinger for operativsystemet
xdg-entry-appearance-comment = Accentfarver og temaer
xdg-entry-input-keywords = COSMIC;Input;Tastatur;Mus;Mus;
xdg-entry-comment = Indstillingsprogram for COSMIC skrivebord
xdg-entry-applications = Applikationer
xdg-entry-default-apps-keywords = COSMIC;Standard;Program
xdg-entry-keywords = COSMIC;Indstillinger;
xdg-entry-about = Om
xdg-entry-input = Inputenheder
xdg-entry-applications-keywords = COSMIC;Standard;Program;Opstart;X11;Kompatibilitet
xdg-entry-appearance = Udseende
xdg-entry-displays-keywords = COSMIC;Skærm;
xdg-entry-date-time-comment = Tidszone, automatiske ur-indstillinger og tidsformat
xdg-entry-desktop-comment = Baggrund, udseende, panel, dock, vindueshåndtering og arbejdsområder
xdg-entry-dock-comment = En valgfri bjælke til apps og applets

View file

@ -9,7 +9,7 @@ number = { $number }
add-network = Netzwerk hinzufügen
.profile = Profil hinzufügen
add-vpn = VPN hinzufügen
airplane-on = Flugmodus ist eingeschaltet.
airplane-on = Flugzeugmodus ist eingeschaltet.
cable-unplugged = Kabel ausgesteckt
connect = Verbinden
connected = Verbunden
@ -60,8 +60,6 @@ vpn-error = VPN-Fehler
.connect = Verbinden mit dem VPN ist fehlgeschlagen
.connection-editor = Verbindungseditor ist fehlgeschlagen
.connection-settings = Abrufen der Einstellungen für aktive Verbindungen ist fehlgeschlagen
.openvpn-config-path = Ungültiger Dateipfad für OpenVPN-Konfiguration
.openvpn-config-path-desc = Die ausgewählte Datei muss sich im lokalen Dateisystem befinden.
.updating-state = Aktualisieren des Netzwerkmanager-Status ist fehlgeschlagen
.wireguard-config-path = Ungültiger Dateipfad für WireGuard-Konfiguration
.wireguard-config-path-desc = Die ausgewählte Datei muss sich im lokalen Dateisystem befinden.
@ -124,8 +122,6 @@ accessibility = Barrierefreiheit
.high-contrast = Modus für hohen Kontrast
.invert-colors = Farben invertieren
.color-filters = Farbfilter
.shake-cursor = Mauszeiger schütteln, um ihn zu finden
.shake-cursor-desc = Schüttle die Maus kurz, um den Mauszeiger vorübergehend zu vergrößern
hearing = Hören
.mono = Stereo-Audio als Mono abspielen
default = Standard
@ -238,19 +234,6 @@ style = Stil
.round = Rund
.slightly-round = Leicht rund
.square = Quadratisch
.frosted-glass = Milchglas
.frosted-system-interface = Systemschnittstelle
.frosted-system-interface-desc = Wendet einen Milchglaseffekt auf den Starter, die Anwendungsbibliothek, die Arbeitsflächenübersicht und die Bildschirmsteuerelemente an
.frosted-windows = Fenster
.frosted-windows-desc = Wendet einen Milchglaseffekt auf Fenster und Dialoge an
.frosted-panels = Panels
.frosted-panels-desc = Wendet einen Milchglaseffekt auf das Panel und das Dock an
.frosted-applets = Applets
.frosted-applets-desc = Wendet einen Milchglaseffekt auf die Applet-Menüs im Panel und im Dock an
.frosted-thickness = Dicke der Mattierung
.less = weniger
.more = mehr
.glass-opacity = Glastrübung
interface-density = Dichte der Benutzeroberfläche
.comfortable = Komfortabel
.compact = Kompakt
@ -280,12 +263,12 @@ applets = Applets
center-segment = Mittelsegment
end-segment = Endsegment
large = Groß
no-applets-found = Keine Applets gefunden ...
no-applets-found = Keine Applets gefunden...
panel-bottom = Unten
panel-left = Links
panel-right = Rechts
panel-top = Oben
search-applets = Applets suchen ...
search-applets = Applets suchen...
small = Klein
start-segment = Anfangssegment
panel-appearance = Aussehen
@ -323,7 +306,7 @@ super-key = Super-Tasten-Aktion
.launcher = Starter öffnen
.workspaces = Arbeitsflächen öffnen
.applications = Anwendungen öffnen
.none = Keine
.disable = Deaktivieren
edge-gravity = Schwebende Fenster werden von nahe gelegenen Kanten angezogen
window-controls = Fenstersteuerung
.minimize = Minimieren-Schaltfläche anzeigen
@ -433,7 +416,6 @@ sound-alerts = Alarmsignale
.sound = Alarmsignalklang
sound-applications = Anwendungen
.desc = Lautstärken und Einstellungen von Anwendungen
.none = Keine Anwendungen verwenden einen Klang
## Energie
@ -513,22 +495,6 @@ keyboard-special-char = Eingabe von Sonderzeichen
.compose = Compose-Taste
.compose-desc = Mit der Compose-Taste kannst du viele verschiedene Zeichen eingeben. Drück einfach die Compose-Taste und dann die Zeichen, die du brauchst. Wenn du zum Beispiel die Compose-Taste und dann C und o drückst, kommt ©, und wenn du die Compose-Taste und dann a und ' drückst, kommt á.
.caps = Feststelltaste
.ctrl = Steuerungstaste
.ctrl-right = Rechte Strg-Taste
.swap-with-ctrl = Mit der Steuerungstaste tauschen
.alt = Alt-Taste
.alt-left = Linke Alt-Taste
.alt-right = Rechte Alt-Taste
.super = Super-Taste
.super-left = Linke Super-Taste
.super-right = Rechte Super-Taste
.menu = Menü-Taste
.backspace = Rücktaste
.escape = Escape-Taste
.swap-with-escape = Mit der Escape-Taste tauschen
.print-screen = Druck-Taste
.scroll-lock = Rollen-Taste
.none = Keine
keyboard-typing-assist = Tippen
.repeat-rate = Wiederholungsrate
.repeat-delay = Wiederholungsverzögerung
@ -539,7 +505,7 @@ keyboard-numlock-boot = Numlock
.off = Deaktiviert
.set = Numlock-Boot-Status setzen
added = Hinzugefügt
type-to-search = Zum Suchen tippen ...
type-to-search = Zum Suchen tippen...
show-extended-input-sources = Erweiterte Eingabequellen anzeigen
## Input: Keyboard: Shortcuts
@ -946,9 +912,3 @@ xdg-entry-desktop-keywords = COSMIC;Desktop;
xdg-entry-desktop = Desktop
xdg-entry-a11y-keywords = COSMIC;Barrierefreiheit;A11y;Bildschirm;Leser;Vergrößerungsglas;Kontrast;Farbe;
xdg-entry-a11y-comment = Bildschirmleser, Vergrößerungsglas, hoher Kontrast und Farbfilter
workspaces-navigation = Navigation
.wraparound = Mit Tastenkombinationen und Gesten zwischen der ersten und letzten Arbeitsfläche wechseln
bluetooth-display-passkey = Bluetooth-Kopplung
.description = Bitte gib den folgenden Passkey auf { $device } ein und drücke dann die Eingabetaste
bluetooth-display-pin = Bluetooth-Kopplung
.description = Bitte gib die folgende PIN auf { $device } ein und drücke dann die Eingabetaste

View file

@ -1,860 +1 @@
share = Κοινοποίηση δικτύου
connect = Σύνδεση
close = Κλείσιμο
save = Αποθήκευση
password = Κωδικός πρόσβασης
remove = Αφαίρεση
import = Εισαγωγή
username = Όνομα χρήστη
light = Ανοιχτόχρωμο
ok = OK
applets = Μικροεφαρμογές
dbus-connection-error = Αποτυχία σύνδεσης στο DBus
dark = Σκουρόχρωμο
cancel = Ακύρωση
settings = Ρυθμίσεις
replace = Αντικατάσταση
add = Προσθήκη
appearance = Εμφάνιση
panel-left = Αριστερά
panel-top = Πάνω
region = Περιοχή
forget-dialog = Διαγραφή αυτού του δικτύου Wi-Fi;
.description = Θα χρειαστεί να εισαγάγετε ξανά τον κωδικό πρόσβασης για να χρησιμοποιήσετε αυτό το δίκτυο Wi-Fi στο μέλλον.
default = Προεπιλογή
unknown = Άγνωστο
connecting = Σύνδεση…
export = Εξαγωγή
panel-right = Δεξιά
rgb = RGB
desktop = Επιφάνεια εργασίας
identity = Ταυτότητα
disconnect = Αποσύνδεση
app = Ρυθμίσεις COSMIC
debug = Εντοπισμός σφαλμάτων
number = { $number }
small = Μικρό
terminate = Τερματισμός
password-confirm = Επιβεβαίωση κωδικού πρόσβασης
applications = Εφαρμογές
connected = Συνδέθηκε
large = Μεγάλο
confirm = Επιβεβαίωση
enable = Ενεργοποίηση
never = Ποτέ
activate = Ενεργοποίηση
dialog-add = Προσθήκη
command = Εντολή
panel-bottom = Κάτω
navigate = Πλοήγηση
colors = Χρώματα
xdg-entry-touchpad = Επιφάνεια αφής
xdg-entry-bluetooth-comment = Διαχείριση συσκευών Bluetooth
xdg-entry-appearance-keywords = Έμφαση;Χρώμα;Εικονίδιο;Γραμματοσειρά;Θέμα;COSMIC;Accent;Color;Icon;Font;Theme
xdg-entry-mouse = Ποντίκι
firmware = Υλικολογισμικό
xdg-entry-a11y = Προσβασιμότητα
xdg-entry-desktop-keywords = Επιφάνεια;Εργασίας;COSMIC;Desktop;
xdg-entry-users = Χρήστες
xdg-entry-default-apps = Προεπιλεγμένες εφαρμογές
xdg-entry-applications-comment = Προεπιλεγμένες εφαρμογές, εφαρμογές εκκίνησης και ρυθμίσεις συμβατότητας εφαρμογών με το X11
xdg-entry-about-keywords = Πληροφορίες;Σχετικά;Περί;COSMIC;About
xdg-entry-notifications = Ειδοποιήσεις
xdg-entry-a11y-keywords = Προσβασιμότητα;Προσιτότητα;Οθόνη;Ανάγνωση;Αναγνώστης;Μεγεθυντικός;Φακός;Αντίθεση;Χρώμα;COSMIC;Accessibility;A11y;Screen;Reader;Magnifier;Contrast;Color;
xdg-entry-desktop = Επιφάνεια εργασίας
xdg-entry-date-time-keywords = Ζώνη;Ώρα;COSMIC;Time;Zone;
xdg-entry-wallpaper = Ταπετσαρία
xdg-entry-keyboard = Πληκτρολόγιο
xdg-entry-a11y-comment = Ανάγνωση οθόνης, μεγεθυντικός φακός, υψηλή αντίθεση και χρωματικά φίλτρα
xdg-entry-displays = Οθόνες
sound = Ήχος
xdg-entry-date-time = Ημερομηνία και ώρα
notifications = Ειδοποιήσεις
xdg-entry-bluetooth-keywords = Σύνδεση;COSMIC;Bluetooth;
about = Πληροφορίες
workspaces = Χώροι εργασίας
xdg-entry-wireless = Wi-Fi
xdg-entry-about-comment = Όνομα συσκευής, πληροφορίες υλικού, προεπιλογές λειτουργικού συστήματος
xdg-entry-appearance-comment = Χρώματα έμφασης και θέματα
xdg-entry-comment = Εφαρμογή ρυθμίσεων για το περιβάλλον επιφάνειας εργασίας COSMIC
xdg-entry-applications = Εφαρμογές
xdg-entry-default-apps-keywords = Προεπιλογή;Προεπιλεγμένη;Εφαρμογή;COSMIC;Default;Application
xdg-entry-keywords = Προτιμήσεις;Ρυθμίσεις;COSMIC;Settings;
xdg-entry-about = Πληροφορίες
xdg-entry-input = Συσκευές εισόδου
keyboard = Πληκτρολόγιο
xdg-entry-appearance = Εμφάνιση
xdg-entry-sound = Ήχος
xdg-entry-displays-keywords = Οθόνη;COSMIC;Display;
xdg-entry-workspaces = Χώροι εργασίας
xdg-entry-date-time-comment = Ζώνη ώρας, αυτόματη ρύθμιση ρολογιού και μορφοποίηση ώρας
system-shortcut = Σύστημα
.app-library = Άνοιγμα βιβλιοθήκης εφαρμογών
.brightness-down = Μείωση φωτεινότητας οθόνης
.brightness-up = Αύξηση φωτεινότητας οθόνης
.display-toggle = Εναλλαγή εσωτερικής οθόνης
.home-folder = Άνοιγμα προσωπικού φακέλου
.keyboard-brightness-down = Μείωση φωτεινότητας πληκτρολογίου
.keyboard-brightness-up = Αύξηση φωτεινότητας πληκτρολογίου
.launcher = Άνοιγμα γραμμής εκκίνησης
.log-out = Αποσύνδεση
.lock-screen = Κλείδωμα οθόνης
.mute = Σίγαση εξόδου ήχου
.mute-mic = Σίγαση εισόδου μικροφώνου
.play-pause = Αναπαραγωγή/παύση
.play-next = Επόμενο κομμάτι
.play-prev = Προηγούμενο κομμάτι
.poweroff = Τερματισμός λειτουργίας
.screenshot = Λήψη στιγμιότυπου οθόνης
.suspend = Αναστολή λειτουργίας
.terminal = Άνοιγμα τερματικού
.touchpad-toggle = Εναλλαγή λειτουργίας επιφάνειας αφής
.volume-lower = Μείωση έντασης εξόδου ήχου
.volume-raise = Αύξηση έντασης εξόδου ήχου
.web-browser = Άνοιγμα προγράμματος περιήγησης ιστού
.window-switcher = Εναλλαγή μεταξύ των ανοικτών παραθύρων
.window-switcher-previous = Εναλλαγή μεταξύ των ανοικτών παραθύρων (αντίστροφα)
.workspace-overview = Άνοιγμα επισκόπησης χώρων εργασίας
super-key = Ενέργεια πλήκτρου Super
.launcher = Άνοιγμα γραμμής εκκίνησης
.workspaces = Άνοιγμα χώρων εργασίας
.applications = Άνοιγμα εφαρμογών
.none = Καμία
x-minutes =
{ $number } { $number ->
[one] λεπτό
*[other] λεπτά
}
vrr = Μεταβλητός ρυθμός ανανέωσης
.enabled = Ενεργός
.force = Πάντα
.auto = Αυτόματα
.disabled = Ανενεργός
window-hint-accent = Χρώμα ένδειξης ενεργού παραθύρου
fit-to-screen = Προσαρμογή στην οθόνη
control-tint = Απόχρωση στοιχείων ελέγχου
.desc = Χρησιμοποιείται για το φόντο των τυπικών κουμπιών, εισόδων αναζήτησης, εισόδων κειμένου και παρόμοιων στοιχείων
vpn-error = Σφάλμα VPN
.config = Αποτυχία προσθήκης διαμόρφωσης VPN
.connect = Αποτυχία σύνδεσης στο VPN
.connection-editor = Αποτυχία επεξεργαστή συνδέσεων
.connection-settings = Αποτυχία λήψης ρυθμίσεων για ενεργές συνδέσεις
.openvpn-config-path = Μη έγκυρη διαδρομή αρχείου για τη διαμόρφωση του OpenVPN
.openvpn-config-path-desc = Το επιλεγμένο αρχείο πρέπει να βρίσκεται σε τοπικό σύστημα αρχείων.
.updating-state = Αποτυχία ενημέρωσης κατάστασης διαχειριστή δικτύου
.wireguard-config-path = Μη έγκυρη διαδρομή αρχείων για τη διαμόρφωση του WireGuard
.wireguard-config-path-desc = Το επιλεγμένο αρχείο πρέπει να βρίσκεται στο τοπικό σύστημα αρχείων.
.wireguard-device = Αποτυχία δημιουργίας συσκευής WireGuard
.with-password =
Αποτυχία ορισμού { $field ->
*[username] ονόματος χρήστη
[password] κωδικού πρόσβασης
[password-flags] σημαιών κωδικού πρόσβασης
} VPN με το nmcli
toggle-stacking = Εναλλαγή στοίβαξης παραθύρων
no-applets-found = Δεν βρέθηκαν μικροεφαρμογές...
zoom-in = Μεγέθυνση
place-here = Τοποθετήστε τις μικροεφαρμογές εδώ
-requires-restart = Απαιτεί επανεκκίνηση
workspaces-orientation = Προσανατολισμός χώρων εργασίας
.vertical = Κάθετος
.horizontal = Οριζόντιος
acceleration-desc = Προσαρμόζει αυτόματα την ευαισθησία ιχνηλάτησης με βάση την ταχύτητα
all-displays = Όλες οι οθόνες
scheduling = Προγραμματισμός
.manual = Χειροκίνητο πρόγραμμα
frosted = Εφέ ημιδιαφανούς γυαλιού στο περιβάλλον συστήματος
.desc = Εφαρμόζει θόλωση του φόντου της γραμμής συστήματος, της μπάρας εφαρμογών, της γραμμής εκκίνησης και της βιβλιοθήκης εφαρμογών
about-hardware = Υλικό
.model = Μοντέλο υλικού
.memory = Μνήμη
.processor = Επεξεργαστής
.graphics = Γραφικά
.disk-capacity = Χωρητικότητα δίσκου
short = Σύντομη
vpn = VPN
.connections = Συνδέσεις VPN
.error = Αποτυχία προσθήκης διαμόρφωσης VPN
.remove = Αφαίρεση προφίλ σύνδεσης
.select-file = Επιλογή αρχείου διαμόρφωσης VPN
power-mode = Λειτουργία ενέργειας
.battery = Εκτεταμένη διάρκεια μπαταρίας
.battery-desc = Μειωμένη χρήση ενέργειας και χαμηλές επιδόσεις
.balanced = Ισορροπημένη
.balanced-desc = Μέτριες επιδόσεις και ήπια χρήση ενέργειας
.performance = Υψηλές επιδόσεις
.performance-desc = Κορυφαίες επιδόσεις και υψηλή χρήση ενέργειας
.no-backend = Δεν βρέθηκε υπηρεσία παρασκηνίου. Εγκαταστήστε το system76-power ή το power-profiles-daemon.
wired = Ενσύρματη δικτύωση
.adapter = Προσαρμογέας ενσύρματου δικτύου { $id }
.connections = Ενσύρματες συνδέσεις
.devices = Ενσύρματες συσκευές
.remove = Αφαίρεση προφίλ σύνδεσης
bluetooth-available = Κοντινές συσκευές
cable-unplugged = Αποσυνδεδεμένο καλώδιο
color-picker = Εργαλείο επιλογής χρωμάτων
interface-font = Γραμματοσειρά συστήματος
zoom-out = Σμίκρυνση
hot-corner = Γωνία συντόμευσης
.top-left-corner = Ενεργοποίηση της πάνω αριστερής γωνίας συντόμευσης για τους χώρους εργασίας
keyboard-typing-assist = Πληκτρολόγηση
.repeat-rate = Ρυθμός επανάληψης
.repeat-delay = Καθυστέρηση επανάληψης
edge-gravity = Έλξη αιωρούμενων παραθύρων στις κοντινές άκρες
amplification = Ενίσχυση ήχου
.desc = Επιτρέπει την αύξηση της έντασης στο 150%
recent-colors = Πρόσφατα χρώματα
about-os = Λειτουργικό σύστημα
.os = Λειτουργικό σύστημα
.os-architecture = Αρχιτεκτονική λειτουργικού συστήματος
.kernel = Έκδοση πυρήνα
.desktop-environment = Περιβάλλον επιφάνειας εργασίας
.windowing-system = Σύστημα διαχείρισης παραθύρων
panel-behavior-and-position = Συμπεριφορά και θέσεις
.autohide = Αυτόματη απόκρυψη γραμμής συστήματος
.dock-autohide = Αυτόματη απόκρυψη μπάρας εφαρμογών
.position = Θέση στην οθόνη
.display = Εμφάνιση στην οθόνη
add-language = Προσθήκη γλώσσας
.context = Προσθήκη γλώσσας
password-mismatch = Ο κωδικός πρόσβασης και το πεδίο επιβεβαίωσης θα πρέπει να είναι ίδια
accessibility = Προσβασιμότητα
.vision = Όραση
.on = Ενεργό
.off = Ανενεργό
.unavailable = Μη διαθέσιμο
.screen-reader = Ανάγνωση οθόνης
.high-contrast = Λειτουργία υψηλής αντίθεσης
.invert-colors = Αναστροφή χρωμάτων
.color-filters = Φίλτρα χρωμάτων
.shake-cursor = Ανακίνηση για εντοπισμό του κέρσορα
.shake-cursor-desc = Ανακινήστε γρήγορα το ποντίκι για να μεγεθυνθεί προσωρινά ο κέρσορας
container-background = Φόντο πλαισίων
.desc-detail = Το χρώμα φόντου πλαισίων χρησιμοποιείται για την πλαϊνή στήλη πλοήγησης, το πλευρικό συρτάρι, τα παράθυρα διαλόγων και παρόμοια γραφικά στοιχεία. Από προεπιλογή, το χρώμα φόντου πλαισίων προκύπτει αυτόματα από το φόντο των παραθύρων.
.reset = Επαναφορά στο αυτόματο
.desc = Χρησιμοποιείται για την πλαϊνή στήλη πλοήγησης, το πλευρικό συρτάρι, τα παράθυρα διαλόγων και παρόμοια γραφικά στοιχεία
primary-button = Κύριο κουμπί
.desc = Ορίζει τη σειρά των φυσικών κουμπιών
.left = Αριστερό
.right = Δεξί
sound-alerts = Ειδοποιήσεις
.volume = Ένταση ήχου ειδοποιήσεων
.sound = Ήχος ειδοποιήσεων
icon-theme = Θέμα εικονιδίων
.desc = Εφαρμόζει ένα διαφορετικό σύνολο εικονιδίων για εφαρμογές
keyboard-shortcuts = Συντομεύσεις πληκτρολογίου
.desc = Προβολή και προσαρμογή συντομεύσεων
switch-between-windows = Εναλλαγή μεταξύ των παραθύρων
text-tint = Απόχρωση κειμένου περιβάλλοντος χρήστη
.desc = Χρησιμοποιείται για τον προσδιορισμό των χρωμάτων του κειμένου του περιβάλλοντος χρήστη ώστε να έχουν επαρκή αντίθεση σε διάφορες επιφάνειες
online-accounts = Διαδικτυακοί λογαριασμοί
.desc = Προσθήκη λογαριασμών, IMAP και SMTP, εταιρικών συνδέσεων
open-workspaces-view = Άνοιγμα επισκόπησης χώρων εργασίας
all = Όλα
remove-user = Αφαίρεση χρήστη
sound-input = Είσοδος ήχου
.volume = Ένταση εισόδου
.device = Συσκευή εισόδου
.level = Επίπεδο εισόδου
add-another-keybinding = Προσθήκη άλλου συνδυασμού πλήκτρων
copy-to-clipboard = Αντιγραφή στο πρόχειρο
monospace-font = Γραμματοσειρά σταθερού πλάτους
experimental-settings = Πειραματικές ρυθμίσεις
recent-folders = Πρόσφατοι φάκελοι
color-filter = Τύπος φίλτρου χρωμάτων
.unknown = Άγνωστο φίλτρο ενεργό
.greyscale = Κλίμακα του γκρι
.deuteranopia = Πράσινο/κόκκινο (αδυναμία στο πράσινο, Δευτερανοπία)
.protanopia = Κόκκινο/πράσινο (αδυναμία στο κόκκινο, Πρωτανοπία)
.tritanopia = Μπλε/κίτρινο (αδυναμία στο μπλε, Τριτανοπία)
migrate-workspace =
Μεταφορά χώρου εργασίας { $direction ->
*[down] στην κάτω έξοδο
[left] στην αριστερή έξοδο
[right] στη δεξιά έξοδο
[up] στην πάνω έξοδο
}
battery = Μπαταρία
.minute =
{ $value } { $value ->
[one] λεπτό
*[other] λεπτά
}
.hour =
{ $value } { $value ->
[one] ώρα
*[other] ώρες
}
.day =
{ $value } { $value ->
[one] ημέρα
*[other] ημέρες
}
.less-than-minute = Λιγότερο από ένα λεπτό
.and = και
.remaining-time =
{ $time } μέχρι την { $action ->
[full] πλήρη φόρτιση
*[other] αποφόρτιση
}
search-applets = Αναζήτηση μικροεφαρμογών...
pinch-to-zoom = Τσίμπημα για ζουμ
.desc = Χρησιμοποιήστε δύο δάχτυλα για να κάνετε ζουμ στο περιεχόμενο, σε εφαρμογές που το υποστηρίζουν
wifi = Wi-Fi
.adapter = Προσαρμογέας Wi-Fi { $id }
.forget = Διαγραφή αυτού του δικτύου
x-hours =
{ $number } { $number ->
[one] ώρα
*[other] ώρες
}
added = Προστέθηκε
input-source-switch = Εναλλαγή πηγών εισόδου γλώσσας πληκτρολογίου
focus-navigation = Πλοήγηση εστίασης
.focus-follows-cursor = Η εστίαση ακολουθεί τον κέρσορα
.focus-follows-cursor-delay = Η εστίαση ακολουθεί την καθυστέρηση του κέρσορα σε ms
.cursor-follows-focus = Ο κέρσορας ακολουθεί την εστίαση
full-name = Ονοματεπώνυμο
app-background = Φόντο παραθύρων
keyboard-sources = Πηγές εισόδου
.desc = Μπορείτε να αλλάξετε τις πηγές εισόδου με τον συνδυασμό πλήκτρων Super+Space, τον οποίο μπορείτε να προσαρμόσετε στις ρυθμίσεις συντομεύσεων πληκτρολογίου.
.move-up = Μετακίνηση πάνω
.move-down = Μετακίνηση κάτω
.settings = Ρυθμίσεις
.view-layout = Προβολή διάταξης πληκτρολογίου
.remove = Αφαίρεση
.add = Προσθήκη πηγής εισόδου
nav-shortcuts = Πλοήγηση
.prev-output = Εστίαση στην προηγούμενη έξοδο
.next-output = Εστίαση στην επόμενη έξοδο
.last-workspace = Εστίαση στον τελευταίο χώρο εργασίας
.prev-workspace = Εστίαση στον προηγούμενο χώρο εργασίας
.next-workspace = Εστίαση στον επόμενο χώρο εργασίας
.focus =
Εστίαση κατά ένα παράθυρο { $direction ->
*[down] προς τα κάτω
[in] προς τα μέσα
[left] προς τα αριστερά
[out] προς τα έξω
[right] προς τα δεξιά
[up] προς τα πάνω
}
.output =
Εναλλαγή { $direction ->
*[down] στην κάτω έξοδο
[left] στην αριστερή έξοδο
[right] στη δεξιά έξοδο
[up] στην πάνω έξοδο
}
.workspace = Μετάβαση στον χώρο εργασίας { $num }
hearing = Ακοή
.mono = Αναπαραγωγή στερεοφωνικού ήχου ως μονοφωνικού
preferred-languages = Προτιμώμενες γλώσσες
.desc = Η σειρά των γλωσσών καθορίζει ποια γλώσσα θα χρησιμοποιείται για το περιβάλλον χρήστη. Οι αλλαγές θα εφαρμοστούν στην επόμενη σύνδεση.
panel-style = Στυλ
.anchor-gap = Κενό ανάμεσα στη γραμμή συστήματος και στις άκρες της οθόνης
.dock-anchor-gap = Κενό ανάμεσα στην μπάρα εφαρμογών και στις άκρες της οθόνης
.extend = Επέκταση της γραμμής συστήματος στις άκρες της οθόνης
.dock-extend = Επέκταση της μπάρας εφαρμογών στις άκρες της οθόνης
.appearance = Εμφάνιση
.size = Μέγεθος
.background-opacity = Αδιαφάνεια φόντου
panel-appearance = Εμφάνιση
.match = Συμφωνία με την επιφάνεια εργασίας
.light = Ανοιχτόχρωμη
.dark = Σκουρόχρωμη
workspaces-multi-behavior = Συμπεριφορά πολλαπλών οθονών
.span = Κοινοί χώροι εργασίας σε όλες τις οθόνες
.separate = Ξεχωριστοί χώροι εργασίας ανά οθόνη
replace-shortcut-dialog = Αντικατάσταση συντόμευσης;
.desc = Η συντόμευση { $shortcut } χρησιμοποιείται από το { $name }. Εάν την αντικαταστήσετε, το { $name } θα απενεργοποιηθεί.
about-device = Όνομα συσκευής
.desc = Αυτό το όνομα εμφανίζεται σε άλλα δίκτυα ή συσκευές Bluetooth
no-vpn = Δεν διατίθενται συνδέσεις VPN.
start-segment = Αρχικό τμήμα
reset-to-default = Επαναφορά προεπιλογών
enable-export = Εφαρμογή τρέχοντος θέματος σε εφαρμογές GNOME
.desc = Δεν υποστηρίζουν όλα τα σύνολα εργαλείων την αυτόματη εναλλαγή. Ενδέχεται να χρειαστεί επανεκκίνηση των μη-COSMIC εφαρμογών μετά από αλλαγή του θέματος.
shortcut-name = Όνομα συντόμευσης
style = Στυλ
.round = Στρογγυλό
.slightly-round = Ελαφρώς στρογγυλό
.square = Τετράγωνο
.frosted-glass = Ημιδιαφανές γυαλί
.frosted-system-interface = Περιβάλλον συστήματος
.frosted-system-interface-desc = Εφαρμόζει το εφέ ημιδιαφανούς γυαλιού στη γραμμή εκκίνησης, τη βιβλιοθήκη εφαρμογών, την επισκόπηση χώρων εργασίας και τα στοιχεία ελέγχου στην οθόνη
.frosted-windows = Παράθυρα
.frosted-windows-desc = Εφαρμόζει το εφέ ημιδιαφανούς γυαλιού στα παράθυρα και τους διαλόγους
.frosted-panels = Γραμμές συστήματος
.frosted-panels-desc = Εφαρμόζει το εφέ ημιδιαφανούς γυαλιού στη γραμμή συστήματος και την μπάρα εφαρμογών
.frosted-applets = Μικροεφαρμογές
.frosted-applets-desc = Εφαρμόζει το εφέ ημιδιαφανούς γυαλιού στα μενού των μικροεφαρμογών στη γραμμή συστήματος και την μπάρα εφαρμογών
.frosted-thickness = Βαθμός θολότητας
.less = λίγο
.more = πολύ
.glass-opacity = Αδιαφάνεια γυαλιού
panel-applets = Διαμόρφωση
.dock-desc = Διαμόρφωση των μικροεφαρμογών της μπάρας εφαρμογών
.desc = Διαμόρφωση των μικροεφαρμογών της γραμμής συστήματος
qr-code-unavailable = Δεν διατίθεται κωδικός QR
window-tiling = Παράθεση παραθύρων
.horizontal = Ορισμός οριζόντιου προσανατολισμού
.vertical = Ορισμός κάθετου προσανατολισμού
.swap-window = Εναλλαγή παραθύρου
.toggle-tiling = Εναλλαγή παράθεσης παραθύρων
.toggle-stacking = Εναλλαγή στοίβαξης παραθύρων
.toggle-floating = Εναλλαγή αιώρησης παραθύρων
.toggle-orientation = Εναλλαγή προσανατολισμού
change-password = Αλλαγή κωδικού πρόσβασης
disable-while-typing = Απενεργοποίηση κατά την πληκτρολόγηση
long = Μεγάλη
copied-to-clipboard = Αντιγράφηκε στο πρόχειρο
bluetooth-confirm-pin = Επιβεβαίωση PIN για σύνδεση Bluetooth
.description = Επιβεβαιώστε ότι το ακόλουθο PIN είναι ίδιο με αυτό που εμφανίζεται στο { $device }
legacy-app-scaling = Κλιμάκωση εφαρμογών στο σύστημα παραθύρων X11
.scaled-gaming = Βελτιστοποίηση για παιχνίδια και εφαρμογές πλήρους οθόνης
.gaming-description = Οι εφαρμογές σε X11 ενδέχεται να εμφανίζονται ελαφρώς μεγαλύτερες/μικρότερες σε σύγκριση με τις εφαρμογές σε Wayland
.scaled-applications = Βελτιστοποίηση για εφαρμογές
.applications-description = Τα παιχνίδια και οι εφαρμογές πλήρους οθόνης σε X11 ενδέχεται να μην αντιστοιχούν στην ανάλυση της οθόνης σας
.scaled-compatibility = Λειτουργία μέγιστης συμβατότητας
.compatibility-description = Οι εφαρμογές σε X11 ενδέχεται να εμφανίζονται θολές σε οθόνες HiDPI
.preferred-display = Προτιμώμενη οθόνη για παιχνίδια και εφαρμογές πλήρους οθόνης σε X11
.no-display = Καμία
night-light = Νυχτερινός φωτισμός
.auto = Αυτόματα (από τη δύση έως την ανατολή)
.desc = Μείωση του μπλε φωτός με θερμότερα χρώματα
custom-shortcuts = Προσαρμοσμένες συντομεύσεις
.add = Προσθήκη συντόμευσης
.context = Προσθήκη προσαρμοσμένης συντόμευσης
.none = Δεν υπάρχουν προσαρμοσμένες συντομεύσεις
visible-networks = Ορατά δίκτυα
window-hint-accent-toggle = Χρήση του χρώματος έμφασης για την ένδειξη ενεργού παραθύρου
type-to-search = Πληκτρολογήστε για αναζήτηση...
workspaces-behavior = Συμπεριφορά χώρων εργασίας
.dynamic = Δυναμικοί χώροι εργασίας
.dynamic-desc = Αυτόματη κατάργηση των κενών χώρων εργασίας.
.fixed = Σταθερός αριθμός χώρων εργασίας
.fixed-desc = Προσθήκη ή κατάργηση χώρων εργασίας στην επισκόπηση.
wireguard-dialog = Προσθήκη συσκευής WireGuard
.description = Επιλέξτε ένα όνομα συσκευής για τη διαμόρφωση του WireGuard.
remove-connection-dialog = Αφαίρεση προφίλ σύνδεσης;
.vpn-description = Θα χρειαστεί να εισαγάγετε ξανά τον κωδικό πρόσβασης για να χρησιμοποιήσετε αυτό το δίκτυο στο μέλλον.
.wired-description = Θα χρειαστεί να δημιουργήσετε εκ νέου αυτό το προφίλ για να το χρησιμοποιήσετε στο μέλλον.
click-behavior = Συμπεριφορά κλικ
.click-finger = Δευτερεύον κλικ με δύο δάχτυλα και μεσαίο κλικ με τρία δάχτυλα
.button-areas = Δευτερεύον κλικ στην κάτω δεξιά γωνία και μεσαίο κλικ στο κάτω κεντρικό μέρος
move-windows = Μετακίνηση παραθύρων
.direction =
Μετακίνηση παραθύρου { $direction ->
*[down] προς τα κάτω
[left] προς τα αριστερά
[right] προς τα δεξιά
[up] προς τα πάνω
}
.display =
Μετακίνηση παραθύρου κατά μία οθόνη { $direction ->
*[down] προς τα κάτω
[left] προς τα αριστερά
[right] προς τα δεξιά
[up] προς τα πάνω
}
.workspace =
Μετακίνηση παραθύρου κατά έναν χώρο εργασίας { $direction ->
*[below] προς τα κάτω
[left] προς τα αριστερά
[right] προς τα δεξιά
[above] προς τα πάνω
}
.workspace-num = Μετακίνηση παραθύρου στον χώρο εργασίας { $num }
.prev-workspace = Μετακίνηση παραθύρου στον προηγούμενο χώρο εργασίας
.next-workspace = Μετακίνηση παραθύρου στον επόμενο χώρο εργασίας
.last-workspace = Μετακίνηση παραθύρου στον τελευταίο χώρο εργασίας
.next-display = Μετακίνηση παραθύρου στην επόμενη οθόνη
.prev-display = Μετακίνηση παραθύρου στην προηγούμενη οθόνη
.send-to-prev-workspace = Μετακίνηση παραθύρου στον προηγούμενο χώρο εργασίας
.send-to-next-workspace = Μετακίνηση παραθύρου στον επόμενο χώρο εργασίας
switch-workspaces = Εναλλαγή χώρων εργασίας
.horizontal = Ολίσθηση με τέσσερα δάχτυλα προς τα αριστερά/δεξιά
.vertical = Ολίσθηση με τέσσερα δάχτυλα προς τα πάνω/κάτω
system-controls = Έλεγχος συστήματος
auto-switch = Αυτόματη εναλλαγή μεταξύ ανοιχτόχρωμης και σκουρόχρωμης λειτουργίας
.sunrise = Εναλλαγή στην ανοιχτόχρωμη λειτουργία την ανατολή
.sunset = Εναλλαγή στη σκουρόχρωμη λειτουργία τη δύση
.next-sunrise = Εναλλαγή στην ανοιχτόχρωμη λειτουργία στην επόμενη ανατολή
.next-sunset = Εναλλαγή στην ανοιχτόχρωμη λειτουργία στην επόμενη δύση
add-vpn = Προσθήκη VPN
keyboard-numlock-boot = Πλήκτρο Numlock
.boot-state = Κατάσταση κατά την εκκίνηση
.last-boot = Τελευταία εκκίνηση
.on = Ενεργό
.off = Ανενεργό
.set = Ορισμός κατάστασης Numlock κατά την εκκίνηση
about-related = Σχετικές ρυθμίσεις
.support = Λήψη υποστήριξης
tap-to-click = Πάτημα για κλικ
.desc = Ενεργοποιεί το πάτημα με ένα δάχτυλο για κύριο κλικ, με δύο δάχτυλα για δευτερεύον κλικ και με τρία δάχτυλα για μεσαίο κλικ
interface-density = Πυκνότητα περιβάλλοντος χρήστη
.comfortable = Άνετο
.compact = Πυκνό
.spacious = Ευρύχωρο
open-application-library = Άνοιγμα βιβλιοθήκης εφαρμογών
slow = Αργός
network-name = Όνομα δικτύου
scrolling = Κύλιση
.two-finger = Κύλιση με δύο δάχτυλα
.edge = Κύλιση κατά μήκος της άκρης με ένα δάχτυλο
.speed = Ταχύτητα κύλισης
.natural = Φυσική κατεύθυνση κύλισης
.natural-desc = Κύλιση του περιεχομένου, αντί της προβολής
auth-dialog = Απαιτείται πιστοποίηση
.vpn-description = Εισαγάγετε το όνομα χρήστη και τον κωδικό πρόσβασης που απαιτούνται από την υπηρεσία VPN.
.wifi-description = Εισαγάγετε τον κωδικό πρόσβασης ή το κλειδί κρυπτογράφησης. Μπορείτε επίσης να συνδεθείτε πατώντας το κουμπί «WPS» του δρομολογητή.
add-user = Προσθήκη χρήστη
add-image = Προσθήκη εικόνας
migrate-workspace-next = Μεταφορά χώρου εργασίας στην επόμενη έξοδο
airplane-on = Η λειτουργία πτήσης είναι ενεργή.
formatting = Μορφοποίηση
.dates = Ημερομηνίες
.time = Ώρα
.date-and-time = Ημερομηνία και ώρα
.numbers = Αριθμοί
.measurement = Μονάδα μέτρησης
.paper = Χαρτί
disabled = Ανενεργό
add-applet = Προσθήκη μικροεφαρμογής
show-extended-input-sources = Εμφάνιση εκτεταμένων πηγών εισόδου
mode-and-colors = Λειτουργία και χρώματα
forget = Διαγραφή
center-segment = Κεντρικό τμήμα
panel-missing = Απουσία διαμόρφωσης γραμμής συστήματος
.desc = Το αρχείο διαμόρφωσης της γραμμής συστήματος απουσιάζει λόγω της χρήσης μιας προσαρμοσμένης διαμόρφωσης ή είναι κατεστραμμένο.
.fix = Επαναφορά προεπιλογής
invalid-username = Μη έγκυρο όνομα χρήστη
mirroring = Κατοπτρισμός
.id = Κατοπτρισμός { $id }
.dont = Να μην γίνει κατοπτρισμός
.mirror = Κατοπτρισμός { $display }
.project =
Προβολή σε { $display ->
[all] όλες τις οθόνες
*[other] { $display }
}
.project-count =
Προβολή σε { $count } { $count ->
[1] άλλη οθόνη
*[other] άλλες οθόνες
}
orientation = Προσανατολισμός
.standard = Τυπικός
.rotate-90 = Περιστροφή 90°
.rotate-180 = Περιστροφή 180°
.rotate-270 = Περιστροφή 270°
auto = Αυτόματο
end-segment = Τελικό τμήμα
bluetooth-adapters = Προσαρμογείς Bluetooth
time-format = Μορφή ημερομηνίας και ώρας
.twenty-four = 24ωρη μορφή
.show-seconds = Εμφάνιση δευτερολέπτων
.first = Πρώτη ημέρα εβδομάδας
.show-date = Εμφάνιση ημερομηνίας στη μικροεφαρμογή ώρας
.friday = Παρασκευή
.saturday = Σάββατο
.sunday = Κυριακή
.monday = Δευτέρα
accent-color = Χρώμα έμφασης
type-key-combination = Εισαγάγετε τον συνδυασμό πλήκτρων
manage-windows = Διαχείριση παραθύρων
.close = Κλείσιμο παραθύρου
.maximize = Μεγιστοποίηση παραθύρου
.fullscreen = Παράθυρο σε πλήρη οθόνη
.minimize = Ελαχιστοποίηση παραθύρου
.resize-inwards = Αλλαγή μεγέθους παραθύρου προς τα μέσα
.resize-outwards = Αλλαγή μεγέθους παραθύρου προς τα έξω
.toggle-sticky = Εναλλαγή καρφιτσωμένου παραθύρου
install-additional-languages = Εγκατάσταση πρόσθετων γλωσσών
sound-output = Έξοδος ήχου
.volume = Ένταση εξόδου
.device = Συσκευή εξόδου
.level = Επίπεδο εξόδου
.config = Διαμόρφωση
.balance = Ισορροπία
.left = Αριστερό
.right = Δεξί
window-controls = Στοιχεία ελέγχου παραθύρων
.maximize = Εμφάνιση κουμπιού μεγιστοποίησης
.minimize = Εμφάνιση κουμπιού ελαχιστοποίησης
.active-window-hint = Εμφάνιση ένδειξης ενεργού παραθύρου
window-management-appearance = Διαχείριση παραθύρων
.active-hint = Μέγεθος ένδειξης ενεργού παραθύρου
.gaps = Κενά γύρω από τα παράθυρα σε παράθεση
migrate-workspace-prev = Μεταφορά χώρου εργασίας στην προηγούμενη έξοδο
legacy-app-global-shortcuts = Καθολικές συντομεύσεις σε εφαρμογές X11
.desc = Οι καθολικές συντομεύσεις επιτρέπουν σε πατήματα πλήκτρων και συμβάντα κουμπιών ποντικιού που εκτελούνται στις εφαρμογές να αναγνωρίζονται από άλλες εφαρμογές για λειτουργίες, όπως πάτημα για ομιλία ή πάτημα για σίγαση. Από προεπιλογή, οι καθολικές συντομεύσεις είναι απενεργοποιημένες στις εφαρμογές X11 για να διασφαλιστεί ότι οι άλλες εφαρμογές δεν μπορούν να παρακολουθούν τα συμβάντα πληκτρολογίου και ποντικιού που περιέχουν ευαίσθητες πληροφορίες.
.none = Κανένα πλήκτρο
.modifiers = Πλήκτρα τροποποίησης (Super, Shift, Control, Alt)
.combination = Όλα τα πλήκτρα, ενώ είναι πατημένα τα Super, Control ή Alt
.all = Όλα τα πλήκτρα
.mouse = Συμβάντα κουμπιών ποντικιού σε εφαρμογές X11
power-saving = Επιλογές εξοικονόμησης ενέργειας
.turn-off-screen-after = Απενεργοποίηση οθόνης μετά από
.auto-suspend = Αυτόματη αναστολή
.auto-suspend-ac = Αυτόματη αναστολή με τροφοδοσία ρεύματος
.auto-suspend-battery = Αυτόματη αναστολή με τροφοδοσία μπαταρίας
connected-devices = Συνδεδεμένες συσκευές
.unknown = Άγνωστη συσκευή
icons-and-toolkit = Εικονίδια και θέματα συνόλου εργαλείων
sound-applications = Εφαρμογές
.desc = Ένταση και ρυθμίσεις ήχου εφαρμογών
.none = Καμία εφαρμογή δεν χρησιμοποιεί ήχο
time-zone = Ζώνη ώρας
.auto = Αυτόματη ζώνη ώρας
.auto-info = Απαιτεί τη χρήση υπηρεσιών τοποθεσίας και πρόσβαση στο διαδίκτυο
fast = Γρήγορος
add-color = Προσθήκη χρώματος
add-network = Προσθήκη δικτύου
.profile = Προσθήκη προφίλ
network-device-state =
.activated = Συνδεδεμένο
.config = Σύνδεση
.deactivating = Αποσύνδεση
.disconnected = Αποσυνδεδεμένο
.failed = Αποτυχία σύνδεσης
.ip-check = Έλεγχος σύνδεσης
.ip-config = Αίτημα για διεύθυνση IP και πληροφορίες δρομολόγησης
.need-auth = Απαιτεί πιστοποίηση
.prepare = Προετοιμασία για σύνδεση
.secondaries = Αναμονή για δευτερεύουσα σύνδεση
.unavailable = Μη διαθέσιμο
.unknown = Άγνωστη κατάσταση
.unmanaged = Χωρίς διαχείριση
.unplugged = Αποσυνδεδεμένο καλώδιο
gestures = Χειρονομίες
.four-finger-down = Ολίσθηση με τέσσερα δάχτυλα προς τα κάτω
.four-finger-left = Ολίσθηση με τέσσερα δάχτυλα προς τα αριστερά
.four-finger-right = Ολίσθηση με τέσσερα δάχτυλα προς τα δεξιά
.four-finger-up = Ολίσθηση με τέσσερα δάχτυλα προς τα πάνω
.three-finger-any = Ολίσθηση με τρία δάχτυλα προς κάθε κατεύθυνση
system = Σύστημα και λογαριασμοί
no-networks = Δεν βρέθηκαν δίκτυα.
open-new-folder = Άνοιγμα νέου φακέλου
fill = Συμπλήρωση
custom = Προσαρμοσμένες
bluetooth-paired = Παλαιότερες συνδεδεμένες συσκευές
.connect = Σύνδεση
.battery = { $percentage }% μπαταρία
dialog = Παράθυρο διαλόγου
.title = Διατήρηση αυτών των ρυθμίσεων οθόνης;
.keep-changes = Διατήρηση αλλαγών
.change-prompt = Οι αλλαγές των ρυθμίσεων θα αναιρεθούν αυτόματα σε { $time } δευτερόλεπτα.
.revert-settings = Επαναφορά ρυθμίσεων
workspaces-overview-thumbnails = Μικρογραφίες επισκόπησης χώρων εργασίας
.show-number = Εμφάνιση αριθμού χώρων εργασίας
.show-name = Εμφάνιση ονόματος χώρων εργασίας
color = Χρώμα
.depth = Βάθος χρωμάτων
.profile = Προφίλ χρωμάτων
.sidebar = Προφίλ χρωμάτων
.temperature = Θερμοκρασία χρωμάτων
hex = 16αδικό
magnifier = Μεγεθυντικός φακός
.controls =
Ή χρησιμοποιήστε αυτές τις συντομεύσεις: { $zoom_in ->
[zero] { "" }
*[other]
{ "" }
{ $zoom_in } για μεγέθυνση,
}{ $zoom_out ->
[zero] { "" }
*[other]
{ "" }
{ $zoom_out } για σμίκρυνση,
}
Super + κύλιση με το ποντίκι
.scroll_controls = Ενεργοποίηση ζουμ ποντικιού ή επιφάνειας αφής με Super + κύλιση
.show_overlay = Εμφάνιση της επικάλυψης μεγεθυντικού φακού
.increment = Αύξηση ζουμ
.signin = Έναρξη μεγεθυντικού φακού κατά τη σύνδεση
.applet = Εναλλαγή μεγεθυντικού φακού στη γραμμή συστήματος
.movement = Η ζουμαρισμένη προβολή μετακινείται
.continuous = Συνέχεια με τον κέρσορα
.onedge = Όταν ο κέρσορας φτάνει στην άκρη
.centered = Για να διατηρεί τον κέρσορα στο κέντρο
administrator = Διαχειριστής
.desc = Οι διαχειριστές μπορούν να αλλάζουν ρυθμίσεις για όλους τους χρήστες, να προσθέτουν και να καταργούν άλλους χρήστες
scan-to-connect-description = Σαρώστε τον κωδικό QR για να συνδεθείτε σε αυτό το δίκτυο.
modified = { $count } τροποποιήσεις
sound-usb-audio = Ήχος USB
sound-device-profiles = Προφίλ συσκευών
sound-hd-audio = Ήχος HD
shadow-and-corners = Σκίαση και γωνίες παραθύρων
shadows-tiling = Παράθεση παραθύρων
.clip = Συμφωνία με τις γωνίες συστήματος
.shadow = Εφαρμογή σκιών
shadows-floating = Αιωρούμενα παράθυρα
.clip = Συμφωνία με τις γωνίες συστήματος και εφαρμογή σκιών
sound-device-port-unplugged = Αποσυνδεδεμένο
workspaces-overview = Επισκόπηση χώρων εργασίας
.action-on-typing = Ενέργεια κατά την πληκτρολόγηση
.none = Καμία
.launcher = Άνοιγμα γραμμής εκκίνησης
.applications = Άνοιγμα εφαρμογών
time-region = Περιοχή και γλώσσα
power = Ενέργεια και μπαταρία
xdg-entry-wired = Ενσύρματη δικτύωση
xdg-entry-startup-apps-comment = Διαμόρφωση των εφαρμογών που εκτελούνται κατά τη σύνδεση
xdg-entry-region-language = Περιοχή και γλώσσα
time-date = Ημερομηνία και ώρα
.auto = Αυτόματη ρύθμιση
.auto-ntp = Η ημερομηνία και η ώρα θα ενημερώνονται αυτόματα όταν οριστεί ζώνη ώρας
xdg-entry-mouse-keywords = Ποντίκι;Επιτάχυνση;Κύλιση;COSMIC;Mouse;Acceleration;Scrolling;
xdg-entry-notifications-keywords = Ειδοποίηση;Κλείδωμα;COSMIC;Notification;Lock;
xdg-entry-startup-apps-keywords = Εφαρμογή;Εκκίνηση;COSMIC;Startup;Application;
xdg-entry-default-apps-comment = Προεπιλεγμένο πρόγραμμα περιήγησης ιστού, πρόγραμμα ηλεκτρονικού ταχυδρομείου, εφαρμογή περιήγησης αρχείων και άλλες εφαρμογές
xdg-entry-keyboard-comment = Πηγές εισόδου, εναλλαγή, εισαγωγή ειδικών χαρακτήρων, συντομεύσεις
xdg-entry-wired-keywords = Σύνδεση;Δίκτυο;Ενσύρματο;COSMIC;Wired;LAN;Network;Connection;
xdg-entry-power = Ενέργεια και μπαταρία
xdg-entry-dock-keywords = Μικροεφαρμογή;Μπάρα;Εφαρμογών;Γραμμή;Συστήματος;COSMIC;Dock;Panel;Applet
bluetooth = Bluetooth
.status = Αυτό το σύστημα είναι ορατό ως { $aliases } όσο είναι ανοικτές οι ρυθμίσεις του Bluetooth.
.connected = Συνδεδεμένο
.connecting = Σύνδεση
.disconnecting = Αποσύνδεση
.connect = Σύνδεση
.disconnect = Αποσύνδεση
.forget = Διαγραφή
.dbus-error = Προέκυψε σφάλμα κατά την αλληλεπίδραση με το DBus: { $why }
.disabled = Η υπηρεσία Bluetooth είναι απενεργοποιημένη
.inactive = Η υπηρεσία Bluetooth δεν είναι ενεργή
.unknown = Δεν ήταν δυνατή η ενεργοποίηση της υπηρεσίας Bluetooth. Είναι εγκατεστημένο το BlueZ;
xdg-entry-mouse-comment = Ταχύτητα ποντικιού, επιτάχυνση και φυσική κατεύθυνση κύλισης
xdg-entry-system = Σύστημα και λογαριασμοί
xdg-entry-panel-keywords = Μικροεφαρμογή;Γραμμή;Συστήματος;COSMIC;Panel;Applet
xdg-entry-window-management = Διαχείριση παραθύρων
xdg-entry-time-language-comment = Διαχείριση ημερομηνίας, ώρας, περιοχής και γλώσσας συστήματος
default-apps = Προεπιλεγμένες εφαρμογές
.web-browser = Περιήγηση ιστού
.file-manager = Διαχείριση αρχείων
.mail-client = Ηλεκτρονικό ταχυδρομείο
.music = Μουσική
.video = Βίντεο
.photos = Φωτογραφίες
.calendar = Ημερολόγιο
.terminal = Τερματικό
.other-associations = Άλλες συσχετίσεις
.text-editor = Επεξεργασία κειμένου
.not-installed = Δεν έχει εγκατασταθεί
xdg-entry-x11-applications-keywords = Εφαρμογή;Παιχνίδι;Συμβατότητα;COSMIC;X11;Application;Game;Compatibility;
xdg-entry-displays-comment = Διαχείριση ρυθμίσεων διαμόρφωσης οθονών
xdg-entry-touchpad-keywords = Επιφάνεια;Αφή;Χειρονομία;COSMIC;Touchpad;Gesture;
xdg-entry-time-language = Ώρα και γλώσσα
window-management = Διαχείριση παραθύρων
xdg-entry-system-keywords = Σύστημα;Πληροφορίες;Λογαριασμοί;Υλικολογισμικό;COSMIC;System;Info;Accounts;Firmware;
xdg-entry-wireless-keywords = Σύνδεση;Δίκτυο;COSMIC;WiFi;Wi-Fi;Network;Connection;
mouse = Ποντίκι
.speed = Ταχύτητα ποντικιού
.acceleration = Ενεργοποίηση επιτάχυνσης ποντικιού
dock = Μπάρα εφαρμογών
xdg-entry-panel = Γραμμή συστήματος
display = Οθόνες
.arrangement = Διάταξη οθονών
.arrangement-desc = Σύρετε τις οθόνες για να τις αναδιατάξετε
.enable = Ενεργοποίηση οθόνης
.external = Εξωτερική οθόνη { $size } { $output }
.laptop = Οθόνη φορητού υπολογιστή { $size }
.options = Επιλογές οθόνης
.refresh-rate = Ρυθμός ανανέωσης
.resolution = Ανάλυση
.scale = Κλίμακα
.additional-scale-options = Πρόσθετες επιλογές κλίμακας
xdg-entry-wireless-comment = Συνδέσεις Wi-Fi και προφίλ σύνδεσης
xdg-entry-desktop-comment = Ρυθμίσεις ταπετσαρίας, εμφάνισης, γραμμής συστήματος, μπάρας εφαρμογών, διαχείρισης παραθύρων και χώρων εργασίας
xdg-entry-network = Δίκτυα και ασύρματη σύνδεση
xdg-entry-users-comment = Πιστοποίηση και λογαριασμοί χρηστών
startup-apps = Εφαρμογές εκκίνησης
.add = Προσθήκη εφαρμογής
.user = Εφαρμογές που εκκινούνται όταν κάνετε σύνδεση
.none = Δεν έχουν προστεθεί εφαρμογές εκκίνησης
.remove-dialog-title = Αφαίρεση του «{ $name }»;
.remove-dialog-description = Αφαίρεση αυτής της εφαρμογής εκκίνησης;
.add-startup-app = Προσθήκη εφαρμογής εκκίνησης
xdg-entry-input-comment = Ρυθμίσεις πληκτρολογίου και ποντικιού
input-devices = Συσκευές εισόδου
xdg-entry-dock-comment = Μια προαιρετική μπάρα για εφαρμογές και μικροεφαρμογές
xdg-entry-network-keywords = Δίκτυο;Δικτύωση;Ασύρματο;COSMIC;Network;Wireless;WiFi;VPN;
xdg-entry-wallpaper-comment = Εικόνες ταπετσαρίας, χρώματα και επιλογές παρουσίασης διαφανειών
xdg-entry-dock = Μπάρα εφαρμογών
xdg-entry-startup-apps = Εφαρμογές εκκίνησης
xdg-entry-workspaces-keywords = Χώρος;Εργασίας;Προσανατολισμός;Επισκόπηση;Οθόνη;COSMIC;Workspace;Orientation;Overview;Monitor;
xdg-entry-system-comment = Πληροφορίες συστήματος, λογαριασμοί και ενημερώσεις υλικολογισμικού
xdg-entry-x11-applications-comment = Κλιμάκωση εφαρμογών συστήματος παραθύρων X11, κύρια οθόνη και καθολικές συντομεύσεις
xdg-entry-region-language-comment = Μορφοποίηση ημερομηνιών, ώρας και αριθμών με βάση την περιοχή σας
panel = Γραμμή συστήματος
xdg-entry-wallpaper-keywords = Ταπετσαρία;Φόντο;Παρουσίαση;Διαφανειών;COSMIC;Wallpaper;Background;Slideshow;
xdg-entry-users-keywords = Λογαριασμός;Χρήστης;COSMIC;User;Account;
xdg-entry-vpn-keywords = Δίκτυο;Σύνδεση;COSMIC;VPN;Network;Connection;OpenVPN;OpenConnect;
users = Χρήστες
.admin = Διαχειριστής
.standard = Τυπικός
.profile-add = Επιλογή εικόνας προφίλ
xdg-entry-time-language-keywords = Σύστημα;Ώρα;Ημερομηνία;Περιοχή;Γλώσσα;COSMIC;System;Time;Date;Region;Language;
xdg-entry-input-keywords = Εισαγωγή;Είσοδος;Πληκτρολόγιο;Ποντίκι;Ποντίκια;COSMIC;Input;Keyboard;Mouse;Mice;
xdg-entry-notifications-comment = Λειτουργία «Μην ενοχλείτε», ειδοποιήσεις οθόνης κλειδώματος και ρυθμίσεις ανά εφαρμογή
xdg-entry-sound-keywords = Ήχος;Ειδοποίηση;COSMIC;Sound;Audio;Alert;Pipewire;
xdg-entry-power-keywords = Μπαταρία;Ισχύς;Ενέργεια;COSMIC;Power;Battery
legacy-applications = Συμβατότητα εφαρμογών X11
xdg-entry-region-language-keywords = Περιοχή;Γλώσσα;Ημερομηνία;Μορφή;Ώρα;Τοπικές;Τοπικοποίηση;COSMIC;Region;Language;Date;Format;Time;Locale;Localization;
xdg-entry-applications-keywords = Προεπιλογή;Προεπιλεγμένες;Εφαρμογές;Εφαρμογή;Εκκίνηση;Συμβατότητα;COSMIC;Default;Application;Startup;X11;Compatibility
xdg-entry-sound-comment = Ρυθμίσεις ήχου για συσκευές, ειδοποιήσεις και εφαρμογές
wallpaper = Ταπετσαρία
.change = Αλλαγή εικόνας κάθε
.fit = Προσαρμογή ταπετσαρίας
.folder-dialog = Επιλογή φακέλου ταπετσαριών
.image-dialog = Επιλογή εικόνας ταπετσαρίας
.plural = Ταπετσαρίες
.same = Κοινή ταπετσαρία για όλες τις οθόνες
.slide = Παρουσίαση διαφανειών
xdg-entry-touchpad-comment = Ταχύτητα επιφάνειας αφής, επιλογές κλικ και χειρονομίες
xdg-entry-keyboard-keywords = Πληκτρολόγιο;Είσοδος;Πηγή;Συντομεύσεις;COSMIC;Keyboard;Input;Source;Shortcuts;
xdg-entry-vpn-comment = Συνδέσεις VPN και προφίλ σύνδεσης
xdg-entry-window-management-keywords = Παράθυρο;Διαχείριση;Παράθεση;Πλήκτρο;COSMIC;Window;Management;Tiling;Super;Key;
xdg-entry-workspaces-comment = Προσανατολισμός χώρων εργασίας, επισκόπηση και συμπεριφορά πολλαπλών οθονών
xdg-entry-network-comment = Διαχείριση συνδέσεων δικτύου
xdg-entry-panel-comment = Η κύρια γραμμή του συστήματος για μενού και μικροεφαρμογές
touchpad = Επιφάνεια αφής
.acceleration = Ενεργοποίηση επιτάχυνσης επιφάνειας αφής
.speed = Ταχύτητα επιφάνειας αφής
xdg-entry-power-comment = Λειτουργίες ενέργειας και επιλογές εξοικονόμησης ενέργειας
time = Ώρα και γλώσσα
xdg-entry-x11-applications = Συμβατότητα εφαρμογών X11
xdg-entry-window-management-comment = Ενέργεια πλήκτρου Super, επιλογές ελέγχου παραθύρων και πρόσθετες επιλογές παράθεσης παραθύρων
xdg-entry-wired-comment = Ενσύρματες συνδέσεις και προφίλ σύνδεσης
known-networks = Γνωστά δίκτυα
network-and-wireless = Δίκτυα και ασύρματη δικτύωση
keyboard-special-char = Εισαγωγή ειδικών χαρακτήρων
.alternate = Πλήκτρο εναλλακτικών χαρακτήρων
.compose = Πλήκτρο σύνθεσης
.compose-desc = Το πλήκτρο σύνθεσης επιτρέπει την εισαγωγή μιας ευρείας ποικιλίας χαρακτήρων. Για να το χρησιμοποιήσετε, πατήστε το πλήκτρο σύνθεσης και έπειτα, μια ακολουθία χαρακτήρων. Για παράδειγμα, μπορείτε να εισαγάγετε τον χαρακτήρα «©» πατώντας το πλήκτρο σύνθεσης, ακολουθούμενο από τα «C» και «o», ή τον χαρακτήρα «á» πατώντας το πλήκτρο σύνθεσης, ακολουθούμενο από τα «a» και «‘» .
.caps = Πλήκτρο Caps Lock
.ctrl = Control
.ctrl-right = Δεξί Ctrl
.swap-with-ctrl = Εναλλαγή με Control
.alt = Alt
.alt-left = Αριστερό Alt
.alt-right = Δεξί Alt
.super = Super
.super-left = Αριστερό Super
.super-right = Δεξί Super
.menu = Πλήκτρο μενού
.backspace = Backspace
.escape = Escape
.swap-with-escape = Εναλλαγή με Escape
.print-screen = Print Screen
.scroll-lock = Scroll Lock
.none = Κανένα
no-search-results = Δεν αντιστοιχεί κανένα δίκτυο στην αναζήτησή σας.
workspaces-navigation = Πλοήγηση
.wraparound = Μετακίνηση μεταξύ του πρώτου και του τελευταίου χώρου εργασίας με συντομεύσεις πληκτρολογίου και χειρονομίες
bluetooth-display-passkey = Σύζευξη Bluetooth
.description = Πληκτρολογήστε το ακόλουθο κλειδί πρόσβασης στο { $device } και πατήστε Enter
bluetooth-display-pin = Σύζευξη Bluetooth
.description = Πληκτρολογήστε το ακόλουθο PIN στο { $device } και πατήστε Enter

View file

@ -1,9 +0,0 @@
save = Save
cancel = Cancel
connected = Connected
confirm = Confirm
replace = Replace
settings = Settings
appearance = Appearance
dark = Dark
light = Light

View file

@ -198,8 +198,6 @@ vpn-error = VPN Error
.connect = Failed to connect to VPN
.connection-editor = Connection editor failed
.connection-settings = Failed to get settings for active connections
.openvpn-config-path = Invalid file path for OpenVPN config
.openvpn-config-path-desc = Chosen file must be on a local file system.
.updating-state = Failed to update network manager state
.wireguard-config-path = Invalid file path for WireGuard config
.wireguard-config-path-desc = Chosen file must be on a local file system.
@ -233,7 +231,6 @@ online-accounts = Online accounts
activate = Activate
confirm = Confirm
enable = Enable
rename = Rename
bluetooth = Bluetooth
.status = This system is visible as { $aliases } while Bluetooth settings are open.
@ -255,14 +252,6 @@ bluetooth-paired = Previously connected devices
bluetooth-confirm-pin = Confirm Bluetooth PIN
.description = Please confirm that the following PIN matches the one displayed on { $device }
bluetooth-display-passkey = Bluetooth Pairing
.description = Please type the following passkey on { $device }, then press Enter
bluetooth-display-pin = Bluetooth Pairing
.description = Please type the following PIN on { $device }, then press Enter
bluetooth-rename-device = Rename Device
bluetooth-available = Nearby devices
bluetooth-adapters = Bluetooth adapters
@ -278,8 +267,6 @@ accessibility = Accessibility
.high-contrast = High contrast mode
.invert-colors = Invert colors
.color-filters = Color filters
.shake-cursor = Shake pointer to find it
.shake-cursor-desc = Quickly shake the mouse to temporarily enlarge the pointer
hearing = Hearing
.mono = Play stereo audio as mono
@ -406,20 +393,7 @@ style = Style
.round = Round
.slightly-round = Slightly round
.square = Square
.frosted-glass = Frosted glass
.frosted-system-interface = System interface
.frosted-system-interface-desc = Applies frosted glass to Launcher, application library, workspace overview, on-screen controls
.frosted-windows = Windows
.frosted-windows-desc = Applies frosted glass to windows and dialogs
.frosted-panels = Panels
.frosted-panels-desc = Applies frosted glass to panel and dock
.frosted-applets = Applets
.frosted-applets-desc = Applies frosted glass to applet menus on panel and dock
.frosted-thickness = Frost thickness
.less = less
.more = more
.glass-opacity = Glass opacity
interface-density = Interface density
.comfortable = Comfortable
.compact = Compact
@ -502,7 +476,7 @@ super-key = Super key action
.launcher = Open Launcher
.workspaces = Open Workspaces
.applications = Open Applications
.none = None
.disable = Disable
edge-gravity = Floating windows gravitate to nearby edges
@ -638,7 +612,6 @@ sound-alerts = Alerts
sound-applications = Applications
.desc = Application volumes and settings
.none = No applications are using sound
# No speaker, headphones, or microphone plugged into sound card port
sound-device-port-unplugged = Unplugged
@ -648,92 +621,6 @@ sound-usb-audio = USB Audio
# Profiles for sound card devices
sound-device-profiles = Device profiles
# Printers settings page
printers = Printers
xdg-entry-printers-comment = Manage printers and print jobs
printers-add = Add printer
printers-add-in-progress = Adding printer…
printers-added = Printer “{ $name }” added
printers-cancel-job = Cancel job
printers-color-black = Black
printers-color-cmy = CMY
printers-color-cmyk = CMYK
printers-color-gray = Grayscale
printers-color-rgb = Color
printers-color-rgb-16 = Color (16-bit)
printers-color-rgb-24 = Color (24-bit)
printers-color-rgb-48 = Color (48-bit)
printers-default = Default
printers-details = Printer details
printers-device = Device
printers-device-uri = Device URI
printers-driver = Driver
printers-error = Operation failed: { $error }
printers-ink-black = Black
printers-ink-cyan = Cyan
printers-ink-levels = Ink levels
printers-ink-magenta = Magenta
printers-ink-yellow = Yellow
printers-job-aborted = Aborted
printers-job-canceled = Canceled
printers-job-completed = Completed
printers-job-held = Held
printers-job-pending = Pending
printers-job-processing = Printing
printers-job-stopped = Stopped
printers-job-unknown = Unknown
printers-jobs = Print jobs
printers-loading = Searching for devices…
printers-location = Location
printers-make-default = Set as default
printers-media-type-cardstock = Cardstock
printers-media-type-envelope = Envelope
printers-media-type-labels = Labels
printers-media-type-photographic = Photo paper
printers-media-type-photographic-glossy = Glossy photo paper
printers-media-type-photographic-matte = Matte photo paper
printers-media-type-photographic-satin = Satin photo paper
printers-media-type-stationery = Plain paper
printers-media-type-stationery-coated = Coated paper
printers-media-type-stationery-fine = Fine paper
printers-media-type-stationery-inkjet = Inkjet paper
printers-media-type-stationery-letterhead = Letterhead paper
printers-media-type-stationery-preprint = Preprinted paper
printers-media-type-stationery-recycled = Recycled paper
printers-media-type-transparency = Transparency
printers-name = Name
printers-no-devices = No devices found
printers-no-matching-drivers = No matching drivers
printers-no-printers = No printers configured
printers-no-printers-desc = Printers connected to this computer or discovered on the network will appear here.
printers-not-accepting = Not accepting jobs
printers-option-color = Color mode
printers-option-media = Paper format
printers-option-media-type = Paper type
printers-option-quality = Print quality
printers-option-sides = Two-sided printing
printers-options = Print options
printers-pause = Pause
printers-quality-draft = Draft
printers-quality-high = High
printers-quality-normal = Normal
printers-remove = Remove printer
printers-remove-confirm = Remove this printer?
printers-remove-confirm-button = Remove
printers-remove-confirm-description = “{ $name }” will be removed from this system. Print jobs queued on it will be discarded.
printers-resume = Resume
printers-sides-long-edge = Long edge
printers-sides-one-sided = One-sided
printers-sides-short-edge = Short edge
printers-state = State
printers-state-idle = Idle
printers-state-processing = Printing
printers-state-reasons = State reasons
printers-state-stopped = Paused
printers-state-unknown = Unknown
printers-submit = Add
printers-test-page = Print test page
# Power & Battery settings page
power = Power & battery
@ -818,22 +705,6 @@ keyboard-special-char = Special Character Entry
.compose = Compose key
.compose-desc = The compose key allows a wide variety of characters to be entered. To use it, press compose and then a sequence of characters. For example, compose key followed by C and o will enter ©, while compose key followed by a and ‘ will enter á.
.caps = Caps Lock key
.ctrl = Control
.ctrl-right = Right Ctrl
.swap-with-ctrl = Swap with Control
.alt = Alt
.alt-left = Left Alt
.alt-right = Right Alt
.super = Super
.super-left = Left Super
.super-right = Right Super
.menu = Menu key
.backspace = Backspace
.escape = Escape
.swap-with-escape = Swap with Escape
.print-screen = Print Screen
.scroll-lock = Scroll Lock
.none = None
keyboard-typing-assist = Typing
.repeat-rate = Repeat rate
@ -994,26 +865,6 @@ mouse = Mouse
.speed = Mouse speed
.acceleration = Enable mouse acceleration
## Input: Logitech (OpenLogi)
logitech = Logitech
.device-slot = Logitech device {$slot}
.battery = Battery
.online = Online
.offline = Offline
.dpi = Sensitivity (DPI)
.smartshift = SmartShift wheel
.smartshift-desc = Let the wheel switch freely to fast scrolling when spun
.no-agent = The OpenLogi agent is not running
.no-agent-desc = Start the agent to configure paired Logitech devices from here
.start-agent = Start the agent
.open-app = Open OpenLogi
.open-app-desc = Button remapping, profiles and advanced settings live in the OpenLogi app
.refresh = Refresh
.no-devices = No paired Logitech device was found
.more = More settings
logitech-comment = Logitech mice and keyboards, through OpenLogi
## Input: Touchpad
click-behavior = Click Behavior

View file

@ -167,5 +167,3 @@ firmware = فریمور
users = کاربران
.desc = احراز هویت و ورود، قفل صفحه.
save = ذخیره
cancel = لغو

View file

@ -516,19 +516,6 @@ style = Tyyli
.round = Pyöristetty
.slightly-round = Hieman pyöristetty
.square = Nelikulmainen
.frosted-glass = Huurteinen lasi
.frosted-system-interface = Järjestelmän käyttöliittymä
.frosted-system-interface-desc = Toteuttaa huurteisen lasin käynnistimeen, sovelluskirjastoon, työtilan yleiskuvaan ja näytöllä näkyviin säätimiin
.frosted-windows = Ikkunat
.frosted-windows-desc = Toteuttaa huurteisen lasin ikkunoihin ja vahvistusikkunoihin
.frosted-panels = Paneelit
.frosted-panels-desc = Toteuttaa huurteisen lasin paneeliin ja telakkaan
.frosted-applets = Sovelmat
.frosted-applets-desc = Toteuttaa huurteisen lasin sovelmavalikkoihin paneelissa ja telakassa
.frosted-thickness = Huurteen tiheys
.less = vähemmän
.more = enemmän
.glass-opacity = Lasin peittävyys
panel-applets = Asetukset
.dock-desc = Telakkasovelmien asetukset
.desc = Paneelisovelmien asetukset
@ -791,8 +778,6 @@ accessibility = Esteettömyys
.high-contrast = Suurikontrastinen tila
.invert-colors = Käänteiset värit
.color-filters = Värisuodattimet
.shake-cursor = Ravista osoitinta paikantaaksesi sen
.shake-cursor-desc = Ravista nopeasti hiirtä suurentaaksesi osoittimen väliaikaisesti
debug = Vianjäljitys
system-shortcut = Järjestelmä
.app-library = Avaa sovelluskirjasto
@ -833,9 +818,3 @@ shadows-tiling = Asetellut ikkunat
.clip = Sovita järjestelmän kulmiin
.shadow = Käytä varjoja
no-search-results = Hakuasi vastaavia verkkoja ei löytynyt.
workspaces-navigation = Liikkuminen
.wraparound = Siirry ensimmäisen ja viimeisen työtilan välillä käyttäen pikanäppäimiä ja eleitä
bluetooth-display-passkey = Bluetooth-parinmuodostus
.description = Syötä seuraava turva-avain laitteelle { $device }, ja paina sitten Enter
bluetooth-display-pin = Bluetooth-parinmuodostus
.description = Syötä seuraava PIN-koodi laitteelle { $device }, ja paina sitten Enter

View file

View file

@ -70,7 +70,7 @@ add-network = Ajouter un réseau
add-vpn = Ajouter un VPN
airplane-on = Mode avion activé.
cable-unplugged = Câble débranché
connect = Se connecter
connect = Connecter
connected = Connecté
connecting = Connexion…
disconnect = Se déconnecter
@ -117,8 +117,6 @@ vpn-error = Erreur VPN
.connect = Échec de la connexion au VPN
.connection-editor = Échec de l'éditeur de connexion
.connection-settings = Échec de l'obtention des paramètres des connexions actives
.openvpn-config-path = Chemin du fichier de configuration OpenVPN invalide
.openvpn-config-path-desc = Le fichier sélectionné doit se trouver sur un système de fichiers local.
.updating-state = Échec de la mise à jour de l'état du gestionnaire de réseau
.wireguard-config-path = Chemin de fichier invalide pour la configuration WireGuard
.wireguard-config-path-desc = Le fichier choisi doit se trouver sur un système de fichiers local.
@ -235,7 +233,7 @@ container-background = Arrière-plan
.desc = La couleur principale de l'arrière-plan est utilisée pour la barre latérale de navigation, le panneau latéral, les boîtes de dialogue et les widgets similaires
control-tint = Teinte des composants de contrôle
.desc = Utilisé pour les arrière-plans des boutons standards, les entrées de recherche, les entrées de texte et les composants similaires
frosted = Effet de verre dépoli dans l'interface système
frosted = Effet de verre sur l'interface système
.desc = Applique un effet de flou d'arrière-plan au panneau, au dock, aux applets, au lanceur et à la bibliothèque d'applications
enable-export = Appliquer ce thème aux applications GNOME
.desc = Certaines boîtes à outils ne supportent pas le changement automatique de thème. Les applications non-COSMIC peuvent nécessiter un redémarrage après un changement de thème.
@ -244,22 +242,9 @@ icon-theme = Thème d'icônes
text-tint = Teinte du texte de l'interface
.desc = Utilisée pour obtenir des couleurs de texte d'interface offrant un contraste suffisant sur différentes surfaces
style = Style
.round = Arrondi
.slightly-round = Légèrement arrondi
.round = Rond
.slightly-round = Légèrement rond
.square = Carré
.frosted-glass = Verre dépoli
.frosted-system-interface = Interface système
.frosted-system-interface-desc = Applique un effet de verre dépoli au lanceur, à la bibliothèque d’applications, à la vue d’ensemble de l’espace de travail et aux contrôles à l’écran
.frosted-windows = Fenêtres
.frosted-windows-desc = Applique un effet de verre dépoli aux fenêtres et aux boîtes de dialogue
.frosted-panels = Panneaux
.frosted-panels-desc = Applique un effet de verre dépoli au panneau et au dock
.frosted-applets = Applets
.frosted-applets-desc = Applique un effet de verre dépoli aux menus des applets du panneau et du dock
.frosted-thickness = Épaisseur du verre dépoli
.less = moins
.more = plus
.glass-opacity = Opacité du verre
interface-density = Densité de l'interface
.comfortable = Confortable
.compact = Compact
@ -332,7 +317,7 @@ super-key = Action de la touche Super
.launcher = Ouvrir le Lanceur
.workspaces = Ouvrir les Espaces de travail
.applications = Ouvrir les Applications
.none = Aucun
.disable = Désactiver
window-controls = Contrôles des fenêtres
.maximize = Afficher le bouton maximiser
.minimize = Afficher le bouton minimiser
@ -441,94 +426,6 @@ sound-alerts = Alertes
.sound = Alertes sonores
sound-applications = Applications
.desc = Volumes et paramètres d'application
.none = Aucune application n'utilise le son
## Printers
printers = Imprimantes
xdg-entry-printers-comment = Gérer les imprimantes et les travaux d'impression
printers-add = Ajouter une imprimante
printers-add-in-progress = Ajout de l'imprimante…
printers-added = Imprimante « { $name } » ajoutée
printers-cancel-job = Annuler le travail
printers-color-black = Noir
printers-color-cmy = CMJ
printers-color-cmyk = CMJN
printers-color-gray = Niveaux de gris
printers-color-rgb = Couleur
printers-color-rgb-16 = Couleur (16 bits)
printers-color-rgb-24 = Couleur (24 bits)
printers-color-rgb-48 = Couleur (48 bits)
printers-default = Par défaut
printers-details = Détails de l'imprimante
printers-device = Périphérique
printers-device-uri = URI du périphérique
printers-driver = Pilote
printers-error = Échec de l'opération : { $error }
printers-ink-black = Noir
printers-ink-cyan = Cyan
printers-ink-levels = Niveaux d'encre
printers-ink-magenta = Magenta
printers-ink-yellow = Jaune
printers-job-aborted = Interrompu
printers-job-canceled = Annulé
printers-job-completed = Terminé
printers-job-held = Retenu
printers-job-pending = En attente
printers-job-processing = Impression en cours
printers-job-stopped = Arrêté
printers-job-unknown = Inconnu
printers-jobs = Travaux d'impression
printers-loading = Recherche des périphériques…
printers-location = Emplacement
printers-make-default = Définir par défaut
printers-media-type-cardstock = Papier cartonné
printers-media-type-envelope = Enveloppe
printers-media-type-labels = Étiquettes
printers-media-type-photographic = Papier photo
printers-media-type-photographic-glossy = Papier photo brillant
printers-media-type-photographic-matte = Papier photo mat
printers-media-type-photographic-satin = Papier photo satiné
printers-media-type-stationery = Papier ordinaire
printers-media-type-stationery-coated = Papier couché
printers-media-type-stationery-fine = Papier fin
printers-media-type-stationery-inkjet = Papier jet d'encre
printers-media-type-stationery-letterhead = Papier à en-tête
printers-media-type-stationery-preprint = Papier pré-imprimé
printers-media-type-stationery-recycled = Papier recyclé
printers-media-type-transparency = Transparent
printers-name = Nom
printers-no-devices = Aucun périphérique trouvé
printers-no-matching-drivers = Aucun pilote ne correspond
printers-no-printers = Aucune imprimante configurée
printers-no-printers-desc = Les imprimantes connectées à cet ordinateur ou découvertes sur le réseau apparaîtront ici.
printers-not-accepting = N'accepte pas les travaux
printers-option-color = Mode de couleur
printers-option-media = Format du papier
printers-option-media-type = Type de papier
printers-option-quality = Qualité d'impression
printers-option-sides = Impression recto-verso
printers-options = Options d'impression
printers-pause = Suspendre
printers-quality-draft = Brouillon
printers-quality-high = Haute
printers-quality-normal = Normale
printers-remove = Supprimer l'imprimante
printers-remove-confirm = Supprimer cette imprimante ?
printers-remove-confirm-button = Supprimer
printers-remove-confirm-description = « { $name } » sera supprimée du système. Les travaux en attente sur cette imprimante seront abandonnés.
printers-resume = Reprendre
printers-sides-long-edge = Bords longs
printers-sides-one-sided = Recto seul
printers-sides-short-edge = Bords courts
printers-state = État
printers-state-idle = Disponible
printers-state-processing = Impression en cours
printers-state-reasons = Causes de l'état
printers-state-stopped = En pause
printers-state-unknown = Inconnu
printers-submit = Ajouter
printers-test-page = Imprimer une page de test
## Power
@ -607,23 +504,7 @@ keyboard-special-char = Saisie de caractères spéciaux
.alternate = Touche de caractères alternatifs
.compose = Touche de composition
.compose-desc = La touche de composition permet d'entrer une grande variété de caractères. Pour l'utiliser, appuyez sur composition puis une séquence de caractères. Par exemple, la touche composition suivie de C et o entrera ©, tandis que la touche composition suivie de a et ‘ entrera á.
.caps = Touche de verrouillage des majuscules
.ctrl = Ctrl
.ctrl-right = Ctrl Droite
.swap-with-ctrl = Echanger avec Ctrl
.alt = Alt
.alt-left = Alt Gauche
.alt-right = Alt Droite
.super = Super
.super-left = Super Gauche
.super-right = Super Droite
.menu = Touche de menu
.backspace = Retour arrière
.escape = Echap
.swap-with-escape = Echanger avec Echap
.print-screen = Impression Ecran
.scroll-lock = Arrêt Défilement
.none = Aucune
.caps = Touche Verr Màj
keyboard-typing-assist = Saisie
.repeat-rate = Taux de répétition
.repeat-delay = Délai de répétition
@ -766,26 +647,6 @@ mouse = Souris
.speed = Vitesse de la souris
.acceleration = Activer l'accélération de la souris
## Input: Logitech (OpenLogi)
logitech = Logitech
.device-slot = Appareil Logitech {$slot}
.battery = Pile
.online = En ligne
.offline = Hors ligne
.dpi = Sensibilité (DPI)
.smartshift = Molette SmartShift
.smartshift-desc = La molette passe en défilement libre quand elle est lancée vite
.no-agent = L'agent OpenLogi n'est pas lancé
.no-agent-desc = Démarrez l'agent pour configurer les appareils Logitech appairés depuis ici
.start-agent = Démarrer l'agent
.open-app = Ouvrir OpenLogi
.open-app-desc = Remappage des boutons, profils et réglages avancés dans l'application OpenLogi
.refresh = Rafraîchir
.no-devices = Aucun appareil Logitech appairé trouvé
.more = Plus de réglages
logitech-comment = Souris et claviers Logitech, via OpenLogi
## Input: Touchpad
click-behavior = Comportement de clic
@ -916,8 +777,6 @@ accessibility = Accessibilité
.high-contrast = Mode contraste élevé
.invert-colors = Inverser les couleurs
.color-filters = Filtres de couleurs
.shake-cursor = Secouer le curseur pour le localiser
.shake-cursor-desc = Secouez rapidement la souris pour agrandir temporairement le curseur
color-filter = Type de filtre de couleurs
.unknown = Filtre inconnu actif
.greyscale = Niveaux de gris
@ -1044,9 +903,3 @@ xdg-entry-keyboard-keywords = COSMIC;Clavier;Saisie;Source;Raccourcis;
xdg-entry-window-management-keywords = COSMIC;Fenêtre;Gestion;Agencement;Super;Touche;
xdg-entry-displays-keywords = COSMIC;Écran;
no-search-results = Aucun réseau ne correspond à votre recherche.
workspaces-navigation = Navigation
.wraparound = Passez du premier au dernier espace de travail à l'aide des raccourcis clavier et des gestes
bluetooth-display-passkey = Appairage Bluetooth
.description = Veuillez saisir le code d’association sur { $device }, puis appuyer sur Entrée
bluetooth-display-pin = Appairage Bluetooth
.description = Veuillez saisir le code PIN suivant sur { $device }, puis appuyer sur Entrée

Some files were not shown because too many files have changed in this diff Show more