Compare commits

..

No commits in common. "local/yoda-main" and "post-1.6-merge-20260819" have entirely different histories.

32 changed files with 1119 additions and 1627 deletions

View file

@ -1,10 +1,8 @@
Replace this text with a description of your changes, and why these changes are important. Read and acknowledge the list below. PRs without a completed checkbox will be closed. - [ ] I have disclosed use of any AI generated code in my commit messages.
- If you are using an LLM, and do not fully understand the changes it is making to the code base, do not create a PR.
- In our experience, AI generated code often results in overly complex code that lacks enough context for a proper fix or feature inclusion. This results in considerably longer code reviews. Due to this, AI authored or partially authored PRs may be closed without comment.
- [ ] I understand these changes in full and will be able to respond to review comments.
- [ ] My change is accurately described in the commit message.
- [ ] My contribution is tested and working as described.
- [ ] I have read the [Developer Certificate of Origin](https://developercertificate.org/) and certify my contribution under its conditions.
---
- I have not included any LLM (also known as AI) generated content in this PR, including code, comments, and descriptions.
- I understand these changes in full and will be able to respond to review comments.
- My change is accurately described in the commit message.
- My contribution is tested and working as described.
- I have read the [Developer Certificate of Origin](https://developercertificate.org/) and certify my contribution under its conditions.
- [ ] I have read and followed all of the above requirements. For more information, see our [contributor guide](https://github.com/pop-os/pop/blob/master/CONTRIBUTING.md).

View file

@ -1,14 +0,0 @@
# From https://github.com/mheap/require-checklist-action, license MIT
name: Require Checklist
on:
pull_request:
types: [opened, edited, synchronize]
jobs:
job1:
runs-on: ubuntu-latest
steps:
- uses: mheap/require-checklist-action@v2
with:
requireChecklist: true

15
.zed/settings.json Normal file
View file

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

1809
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
[package] [package]
name = "cosmic-greeter" name = "cosmic-greeter"
version = "1.10.0" version = "0.1.0"
edition = "2024" edition = "2024"
[build-dependencies] [build-dependencies]
@ -18,7 +18,6 @@ cosmic-comp-config.workspace = true
cosmic-config = { workspace = true, features = ["calloop", "macro"] } cosmic-config = { workspace = true, features = ["calloop", "macro"] }
cosmic-greeter-config.workspace = true cosmic-greeter-config.workspace = true
cosmic-greeter-daemon = { path = "daemon" } cosmic-greeter-daemon = { path = "daemon" }
cosmic-osk-config = { git = "https://github.com/pop-os/cosmic-osk" }
dirs = "6" dirs = "6"
cosmic = { package = "libcosmic-yoda", path = "../libcosmic", default-features = false, features = [ cosmic = { package = "libcosmic-yoda", path = "../libcosmic", default-features = false, features = [
"advanced-shaping", "advanced-shaping",
@ -90,7 +89,6 @@ image = { version = "0.25", default-features = false, features = [
] } ] }
# JPEG-XL support # JPEG-XL support
jxl-oxide = { version = "0.12.6", features = ["image"] } jxl-oxide = { version = "0.12.6", features = ["image"] }
enumflags2 = "0.7.12"
[dependencies.greetd_ipc] [dependencies.greetd_ipc]
version = "0.10.3" version = "0.10.3"
@ -173,8 +171,8 @@ iced_widget = { path = "../libcosmic/iced/widget" }
iced_winit = { path = "../libcosmic/iced/winit" } iced_winit = { path = "../libcosmic/iced/winit" }
[patch."https://github.com/pop-os/cosmic-protocols"] [patch."https://github.com/pop-os/cosmic-protocols"]
cosmic-client-toolkit = { path = "../cosmic-protocols/client-toolkit" }
cosmic-protocols = { path = "../cosmic-protocols" } cosmic-protocols = { path = "../cosmic-protocols" }
cosmic-client-toolkit = { path = "../cosmic-protocols/client-toolkit" }
[patch."https://github.com/pop-os/cosmic-settings-daemon"] [patch."https://github.com/pop-os/cosmic-settings-daemon"]
cosmic-settings-config = { path = "../cosmic-settings-daemon/config" } cosmic-settings-config = { path = "../cosmic-settings-daemon/config" }
@ -189,7 +187,3 @@ dnd = { path = "../window_clipboard/dnd" }
mime = { path = "../window_clipboard/mime" } mime = { path = "../window_clipboard/mime" }
clipboard_wayland = { path = "../window_clipboard/wayland" } clipboard_wayland = { path = "../window_clipboard/wayland" }
clipboard_macos = { path = "../window_clipboard/macos" } clipboard_macos = { path = "../window_clipboard/macos" }
# Yoda: cosmic-osk-config depuis le checkout local (meme source que le paquet cosmic-osk).
[patch."https://github.com/pop-os/cosmic-osk"]
cosmic-osk-config = { path = "../cosmic-osk/config" }

View file

@ -1,70 +0,0 @@
cargo-target-dir := env('CARGO_TARGET_DIR', 'target')
# Compile with debug profile
[no-cd]
build-debug *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
# Runs a check with JSON message format for IDE integration
[no-cd]
check-json: (check '--message-format=json')
# Remove Cargo build artifacts
[no-cd]
clean:
cargo clean
# Also remove .cargo and vendored dependencies
[no-cd]
clean-dist: clean
rm -rf .cargo vendor vendor.tar target
# Run the application for testing purposes
[no-cd]
run *args:
cargo run {{args}}
# Run `cargo test`
[no-cd]
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
# Extracts vendored dependencies
[no-cd]
vendor-extract:
rm -rf vendor
tar pxf vendor.tar

View file

@ -1,6 +1,6 @@
[package] [package]
name = "cosmic-greeter-config" name = "cosmic-greeter-config"
version = "1.10.0" version = "0.1.0"
edition = "2024" edition = "2024"
description = "Configuration for COSMIC Greeter" description = "Configuration for COSMIC Greeter"
repository = "https://github.com/pop-os/cosmic-greeter" repository = "https://github.com/pop-os/cosmic-greeter"

View file

@ -1,6 +1,6 @@
[package] [package]
name = "cosmic-greeter-daemon" name = "cosmic-greeter-daemon"
version = "1.10.0" version = "0.1.0"
edition = "2024" edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -28,8 +28,7 @@ whitespace-conf = "1"
#TODO: reduce features #TODO: reduce features
tokio = { workspace = true, features = ["full"] } tokio = { workspace = true, features = ["full"] }
xdg = "3.0" xdg = "3.0"
zbus_systemd = { version = "0.26000.0", features = ["home1"], optional = true }
[features] [features]
default = ["systemd"] default = ["systemd"]
systemd = ["tracing-journald", "zbus_systemd"] systemd = ["tracing-journald"]

View file

@ -1,12 +1,11 @@
use cosmic_comp_config::output::randr; use cosmic_comp_config::output::randr;
use cosmic_config::CosmicConfigEntry; use cosmic_config::CosmicConfigEntry;
use kdl::KdlDocument; use kdl::KdlDocument;
use std::collections::{BTreeMap, BTreeSet}; use std::collections::BTreeMap;
use std::fs; use std::fs;
use std::io::Read; use std::io::Read;
use std::os::unix::fs::OpenOptionsExt; use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use zbus::Connection;
pub use cosmic_applets_config::time::TimeAppletConfig; pub use cosmic_applets_config::time::TimeAppletConfig;
pub use cosmic_bg_config::state::State as BgState; pub use cosmic_bg_config::state::State as BgState;
@ -17,41 +16,12 @@ pub use cosmic_theme::{Theme, ThemeBuilder};
pub struct UserFilter { pub struct UserFilter {
uid_min: u32, uid_min: u32,
uid_max: u32, uid_max: u32,
homed_uids: BTreeSet<u32>,
} }
impl UserFilter { impl Default for UserFilter {
#[cfg(feature = "systemd")] fn default() -> Self {
async fn get_homed_uids() -> Result<BTreeSet<u32>, zbus::Error> {
use zbus_systemd::home1;
let connection = Connection::system().await?;
let homed = home1::ManagerProxy::new(&connection).await?;
let homed_uids = homed
.list_homes()
.await?
.iter()
.map(|(_, uid, ..)| *uid)
.collect();
Ok(homed_uids)
}
pub async fn new() -> Self {
let login_defs_data = fs::read_to_string("/etc/login.defs").unwrap_or_default(); let login_defs_data = fs::read_to_string("/etc/login.defs").unwrap_or_default();
let login_defs = whitespace_conf::parse(&login_defs_data); let login_defs = whitespace_conf::parse(&login_defs_data);
#[cfg(feature = "systemd")]
let homed_uids = Self::get_homed_uids()
.await
.inspect_err(|e| {
tracing::warn!("failed to list dynamic UIDs from systemd-homed: {e:?}")
})
.unwrap_or_default();
#[cfg(not(feature = "systemd"))]
let homed_uids = BTreeSet::new();
Self { Self {
uid_min: login_defs uid_min: login_defs
.get("UID_MIN") .get("UID_MIN")
@ -61,14 +31,17 @@ impl UserFilter {
.get("UID_MAX") .get("UID_MAX")
.and_then(|x| x.parse::<u32>().ok()) .and_then(|x| x.parse::<u32>().ok())
.unwrap_or(65000), .unwrap_or(65000),
homed_uids,
} }
} }
}
impl UserFilter {
pub fn new() -> Self {
Self::default()
}
pub fn filter(&self, user: &pwd::Passwd) -> bool { pub fn filter(&self, user: &pwd::Passwd) -> bool {
if (user.uid < self.uid_min || user.uid > self.uid_max) if user.uid < self.uid_min || user.uid > self.uid_max {
&& !self.homed_uids.contains(&user.uid)
{
// Skip system accounts // Skip system accounts
return false; return false;
} }
@ -128,48 +101,6 @@ impl UserData {
} }
} }
fn load_icon_as_user(&mut self) {
//TODO: use accountsservice?
let icon_paths = [
//IMPORTANT: This file is owned by root and safe to read (it won't be a link to /etc/shadow for example)
// It may not exist if the user uses one of the system icons. In that case, we should read the
// information in /var/lib/AccountsService/users, and then read the icon path as the user
Path::new("/var/lib/AccountsService/icons").join(&self.name),
// systemd-homed cache
Path::new("/var/cache/systemd/home")
.join(&self.name)
.join("avatar"),
];
for icon_path in icon_paths {
match fs::OpenOptions::new()
.read(true)
// Do not follow symlinks
.custom_flags(libc::O_NOFOLLOW)
.open(&icon_path)
{
Ok(mut icon_file) => {
let mut icon_data = Vec::new();
match icon_file.read_to_end(&mut icon_data) {
Ok(count) => {
icon_data.truncate(count);
self.icon_opt = Some(icon_data);
return;
}
Err(err) => {
tracing::error!("failed to read icon data {:?}: {:?}", icon_path, err);
}
}
}
Err(err) => {
tracing::warn!("failed to open icon {:?}: {:?}", icon_path, err);
}
}
}
tracing::error!("failed to load icon for user {:?}", self.name)
}
pub fn load_config_as_user(&mut self) { pub fn load_config_as_user(&mut self) {
self.icon_opt = None; self.icon_opt = None;
self.theme_opt = None; self.theme_opt = None;
@ -178,7 +109,33 @@ impl UserData {
self.xkb_config_opt = None; self.xkb_config_opt = None;
self.time_applet_config = Default::default(); self.time_applet_config = Default::default();
self.load_icon_as_user(); //TODO: use accountsservice?
//IMPORTANT: This file is owned by root and safe to read (it won't be a link to /etc/shadow for example)
// It may not exist if the user uses one of the system icons. In that case, we should read the
// information in /var/lib/AccountsService/users, and then read the icon path as the user
let icon_path = Path::new("/var/lib/AccountsService/icons").join(&self.name);
match fs::OpenOptions::new()
.read(true)
// Do not follow symlinks
.custom_flags(libc::O_NOFOLLOW)
.open(&icon_path)
{
Ok(mut icon_file) => {
let mut icon_data = Vec::new();
match icon_file.read_to_end(&mut icon_data) {
Ok(count) => {
icon_data.truncate(count);
self.icon_opt = Some(icon_data);
}
Err(err) => {
tracing::error!("failed to read icon data {:?}: {:?}", icon_path, err);
}
}
}
Err(err) => {
tracing::error!("failed to open icon {:?}: {:?}", icon_path, err);
}
}
let mut is_dark = true; let mut is_dark = true;
match cosmic_theme::ThemeMode::config() { match cosmic_theme::ThemeMode::config() {
@ -252,16 +209,6 @@ impl UserData {
tracing::error!("failed to create cosmic-bg state helper: {:?}", err); tracing::error!("failed to create cosmic-bg state helper: {:?}", err);
} }
} }
if self.bg_state.wallpapers.is_empty() {
self.bg_state.wallpapers.push((
String::new(),
BgSource::Path(
Path::new("/var/cache/systemd/home")
.join(&self.name)
.join("login-background"),
),
));
}
self.load_wallpapers_as_user(); self.load_wallpapers_as_user();
match cosmic_config::Config::new("com.system76.CosmicComp", CosmicCompConfig::VERSION) { match cosmic_config::Config::new("com.system76.CosmicComp", CosmicCompConfig::VERSION) {

View file

@ -70,8 +70,8 @@ struct GreeterProxy;
#[zbus::interface(name = "com.system76.CosmicGreeter")] #[zbus::interface(name = "com.system76.CosmicGreeter")]
impl GreeterProxy { impl GreeterProxy {
async fn get_user_data(&mut self) -> Result<String, GreeterError> { fn get_user_data(&mut self) -> Result<String, GreeterError> {
let user_filter = UserFilter::new().await; let user_filter = UserFilter::new();
// The pwd::Passwd method is unsafe (but not labelled as such) due to using global state (libc pwent functions). // The pwd::Passwd method is unsafe (but not labelled as such) due to using global state (libc pwent functions).
// To prevent issues, this should only be called once in the entire process space at a time // To prevent issues, this should only be called once in the entire process space at a time

6
debian/changelog vendored
View file

@ -1,9 +1,3 @@
cosmic-greeter (1.10.0) noble; urgency=medium
* Epoch 1.10.0 version update
-- Michael Murphy <michael@mmurphy.dev> Mon, 05 Oct 2026 21:20:24 +0200
cosmic-greeter (0.1.0) jammy; urgency=medium cosmic-greeter (0.1.0) jammy; urgency=medium
* Initial release. * Initial release.

View file

@ -1,8 +1,8 @@
[Unit] [Unit]
Description=COSMIC Greeter Description=COSMIC Greeter
After=systemd-user-sessions.service plymouth-quit-wait.service cosmic-greeter-daemon.service After=systemd-user-sessions.service plymouth-quit-wait.service cosmic-greeter-daemon.service
After=getty@tty1.service ksmcon@tty1.service After=getty@tty1.service
Conflicts=getty@tty1.service kmscon@tty1.service Conflicts=getty@tty1.service
Wants=cosmic-greeter-daemon.service Wants=cosmic-greeter-daemon.service
[Service] [Service]

View file

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

View file

@ -1,37 +0,0 @@
{
rust-overlay ? import (import ./nix/flake-parse.nix "rust-overlay"),
pkgs ? import (import ./nix/flake-parse.nix "nixpkgs") {
system = builtins.currentSystem;
overlays = [ rust-overlay ];
},
}:
let
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
extensions = [
"rust-analyzer"
"rust-src"
"llvm-tools"
];
};
in
{
shell = import ./nix/shell.nix {
inherit pkgs rustToolchain;
};
formatter = import ./nix/formatter.nix { inherit pkgs rustToolchain; };
packages =
let
rustPlatform = pkgs.makeRustPlatform {
cargo = rustToolchain;
rustc = rustToolchain;
};
in
rec {
default = pkgs.callPackage ./nix/package.nix {
inherit rustPlatform;
};
sessiond-seat = default;
};
}

45
flake.lock generated
View file

@ -1,45 +0,0 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1788881743,
"narHash": "sha256-151taSq/21cxagiIu7hyMVl68+FbHfwBP4lh6TB6KOM=",
"rev": "d6524aaca2ff07876657ae2b323f24be4874944b",
"type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1069856.d6524aaca2ff/nixexprs.tar.xz"
},
"original": {
"type": "tarball",
"url": "https://channels.nixos.org/nixos-unstable/nixexprs.tar.xz"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1788851328,
"narHash": "sha256-YOwlUD0Lt/3SulKhZ7z0Jmgbq/DWh8SjnGwUlFSw+YM=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "6ae57a71bcb0bebc7a66cc2bd76942c4cf649167",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

View file

@ -1,84 +0,0 @@
{
inputs = {
nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.xz";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs =
{
self,
nixpkgs,
rust-overlay,
...
}:
let
systems = [
"x86_64-linux"
"aarch64-linux"
];
pkgsFor =
system:
import nixpkgs {
inherit system;
overlays = [ rust-overlay.overlays.default ];
};
forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f (pkgsFor system));
in
{
devShells = forAllSystems (pkgs: {
default =
let
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
extensions = [
"rust-analyzer"
"rust-src"
"llvm-tools"
];
};
in
import ./nix/shell.nix { inherit pkgs rustToolchain; };
});
packages = forAllSystems (
pkgs:
let
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
extensions = [
"rust-analyzer"
"rust-src"
"llvm-tools"
];
};
rustPlatform = pkgs.makeRustPlatform {
cargo = rustToolchain;
rustc = rustToolchain;
};
in
{
cosmic-greeter = pkgs.callPackage ./nix/package.nix {
inherit rustPlatform;
};
default = self.packages.${pkgs.stdenv.hostPlatform.system}.cosmic-greeter;
}
);
formatter = forAllSystems (
pkgs:
let
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
extensions = [
"rust-analyzer"
"rust-src"
"llvm-tools"
];
};
in
import ./nix/formatter.nix { inherit pkgs rustToolchain; }
);
};
}

View file

@ -2,7 +2,7 @@ accessibility = Přístupnost
.screen-reader = Čtečka obrazovky .screen-reader = Čtečka obrazovky
.magnifier = Lupa .magnifier = Lupa
.high-contrast = Vysoký kontrast .high-contrast = Vysoký kontrast
.invert-colors = Inverze barev .invert-colors = Převrátit barvy
cancel = Zrušit cancel = Zrušit
caps-lock = Caps Lock je aktivní. caps-lock = Caps Lock je aktivní.
enter-user = Zadat jméno ručně... enter-user = Zadat jméno ručně...

View file

@ -1,4 +1,4 @@
cancel = Afbryd cancel = Annuller
restart = Genstart restart = Genstart
caps-lock = Skiftelås er aktiv. caps-lock = Skiftelås er aktiv.
enter-user = Indtast navn manuelt... enter-user = Indtast navn manuelt...

View file

@ -9,7 +9,6 @@ caps-lock = Caps Lock is active.
enter-user = Enter name manually... enter-user = Enter name manually...
type-username = Username: type-username = Username:
keyboard-layout = Keyboard layout keyboard-layout = Keyboard layout
on-screen-keyboard = On-screen keyboard
restart = Restart restart = Restart
restart-now = Restart now? restart-now = Restart now?
restart-timeout = The system will restart automatically restart-timeout = The system will restart automatically

View file

@ -1,4 +1,4 @@
cancel = Semmet cancel = Sefsex
restart-timeout = restart-timeout =
Anagraw ad yales tanekra s wudem awurman Anagraw ad yales tanekra s wudem awurman
{ $seconds -> { $seconds ->

View file

@ -13,5 +13,3 @@ shutdown-timeout =
[1] d’aquí 1 segondas. [1] d’aquí 1 segondas.
*[other] d’aquí { $seconds } segondas. *[other] d’aquí { $seconds } segondas.
} }
cancel = Anullar
user = Utilizaire

View file

@ -2,10 +2,10 @@ cancel = ยกเลิก
keyboard-layout = ผังคีย์บอร์ด keyboard-layout = ผังคีย์บอร์ด
restart = รีสตาร์ท restart = รีสตาร์ท
restart-now = รีสตาร์ทตอนนี้เลยหรือไม่ restart-now = รีสตาร์ทตอนนี้เลยหรือไม่
restart-timeout = ระบบจะรีสตาร์ทโดยอัตโนมัติภายใน { $seconds } วินาที restart-timeout = ระบบจะรีสตาร์ทโดยอัตโนมัติภายใน {$seconds} วินาที
session = เซสชั่น session = เซสชั่น
shutdown = ปิดระบบ shutdown = ปิดระบบ
shutdown-now = ปิดระบบตอนนี้เลยหรือไม่ shutdown-now = ปิดระบบตอนนี้เลยหรือไม่
shutdown-timeout = ระบบจะปิดลงโดยอัตโนมัติภายใน { $seconds } วินาที shutdown-timeout = ระบบจะปิดลงโดยอัตโนมัติภายใน {$seconds} วินาที
suspend = ระงับ suspend = ระงับ
user = ผู้ใช้ user = ผู้ใช้

View file

@ -1,12 +0,0 @@
inputName:
let
lock = builtins.fromJSON (builtins.readFile ../flake.lock);
namedNode = lock.nodes.${lock.nodes.root.inputs.${inputName}}.locked;
githubTarball = fetchTarball {
url =
namedNode.url
or "https://github.com/${namedNode.owner}/${namedNode.repo}/archive/${namedNode.rev}.tar.gz";
sha256 = namedNode.narHash;
};
in
githubTarball

View file

@ -1,17 +0,0 @@
{ pkgs, rustToolchain }:
pkgs.writeShellApplication {
name = "nix3-fmt-wrapper";
runtimeInputs = builtins.attrValues {
inherit (pkgs)
nixfmt
taplo
fd
;
inherit rustToolchain;
};
text = ''
fd "$@" -t f -e nix -x nixfmt -q '{}'
fd "$@" -t f -e toml -x taplo format '{}'
cargo fmt
'';
}

View file

@ -1,108 +0,0 @@
{
lib,
stdenv,
fetchFromGitHub,
rustPlatform,
libcosmicAppHook,
cmake,
just,
cosmic-randr,
dav1d,
libinput,
linux-pam,
udev,
coreutils,
xkeyboard_config,
nixosTests,
orca,
withLogind ? true,
withUpower ? true,
withNetworkManager ? true,
}:
rustPlatform.buildRustPackage (finalAttrs: {
pname = "cosmic-greeter";
version = "1.6.0";
src = fetchFromGitHub {
owner = "pop-os";
repo = "cosmic-greeter";
tag = "epoch-${finalAttrs.version}";
hash = "sha256-hDVdl2+7NVLA+YxO2HToni57IEr0i4OGTsYDc3YGTuw=";
};
postPatch = ''
substituteInPlace src/greeter.rs --replace-fail '/usr/bin/env' '${lib.getExe' coreutils "env"}'
substituteInPlace src/greeter.rs --replace-fail '/usr/bin/orca' '${lib.getExe orca}'
'';
cargoHash = "sha256-vHR9go8/iVUT7oBV8h+mmBvhi2oSKNBKtV0uoDOr6go=";
buildNoDefaultFeatures = true;
buildFeatures =
lib.optionals withLogind [ "logind" ]
++ lib.optionals withUpower [ "upower" ]
++ lib.optionals withNetworkManager [ "networkmanager" ];
separateDebugInfo = true;
__structuredAttrs = true;
env.VERGEN_GIT_SHA = finalAttrs.src.tag;
nativeBuildInputs = [
rustPlatform.bindgenHook
cmake
just
libcosmicAppHook
];
buildInputs = [
cosmic-randr
dav1d
libinput
linux-pam
udev
orca
];
dontUseJustBuild = true;
dontUseJustCheck = true;
justFlags = [
"--set"
"prefix"
(placeholder "out")
"--set"
"cargo-target-dir"
"target/${stdenv.hostPlatform.rust.cargoShortTarget}"
];
preFixup = ''
libcosmicAppWrapperArgs+=(
--prefix PATH : ${lib.makeBinPath [ cosmic-randr ]}
--set-default X11_BASE_RULES_XML ${xkeyboard_config}/share/X11/xkb/rules/base.xml
--set-default X11_BASE_EXTRA_RULES_XML ${xkeyboard_config}/share/X11/xkb/rules/extra.xml
)
'';
passthru = {
tests = {
inherit (nixosTests)
cosmic
cosmic-autologin
cosmic-noxwayland
cosmic-autologin-noxwayland
;
};
};
meta = {
homepage = "https://github.com/pop-os/cosmic-greeter";
description = "Greeter for the COSMIC Desktop Environment";
mainProgram = "cosmic-greeter";
license = lib.licenses.gpl3Only;
teams = [ lib.teams.cosmic ];
platforms = lib.platforms.linux;
};
})

View file

@ -1,31 +0,0 @@
{ pkgs, rustToolchain }:
pkgs.mkShell {
name = "cosmic-greeter-devshell";
packages = builtins.attrValues {
inherit
rustToolchain
;
inherit (pkgs)
rust-analyzer-unwrapped
nixd
libxkbcommon
dav1d
libinput
linux-pam
gcc
glibc
cmake
;
inherit (pkgs.llvmPackages)
libclang
llvm
;
};
nativeBuildInputs = [ pkgs.pkg-config ];
RUST_SRC_PATH = "${rustToolchain}/lib/rustlib/src/rust/library";
LLVM_CONFIG_PATH = "${pkgs.llvmPackages.llvm}/bin/llvm-config";
LIBCLANG_PATH = "${pkgs.llvmPackages.libclang.lib}/lib";
BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.linux-pam}/include -I${pkgs.glibc.dev}/include";
}

1
rustfmt.toml Normal file
View file

@ -0,0 +1 @@
imports_granularity = "Module"

View file

@ -10,7 +10,6 @@ use cosmic::iced::{self, Rectangle, Size, Subscription};
use cosmic::surface::corner_radius::rounded_rect_strips; use cosmic::surface::corner_radius::rounded_rect_strips;
use cosmic::widget::rectangle_tracker::{RectangleUpdate, rectangle_tracker_subscription}; use cosmic::widget::rectangle_tracker::{RectangleUpdate, rectangle_tracker_subscription};
use cosmic::widget::{self, RectangleTracker}; use cosmic::widget::{self, RectangleTracker};
use cosmic_config::CosmicConfigEntry;
use cosmic_greeter_daemon::{BgSource, UserData}; use cosmic_greeter_daemon::{BgSource, UserData};
use cosmic_protocols::keyboard_layout::v1::client::zcosmic_keyboard_layout_v1::ZcosmicKeyboardLayoutV1; use cosmic_protocols::keyboard_layout::v1::client::zcosmic_keyboard_layout_v1::ZcosmicKeyboardLayoutV1;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
@ -20,7 +19,6 @@ use wayland_client::{Connection, Proxy};
use crate::keyboard_layout_wayland; use crate::keyboard_layout_wayland;
pub const MAX_WIDTH: f32 = 866.;
pub const DEFAULT_MENU_ITEM_HEIGHT: f32 = 36.; pub const DEFAULT_MENU_ITEM_HEIGHT: f32 = 36.;
#[derive(Debug, Clone, Eq, PartialEq)] #[derive(Debug, Clone, Eq, PartialEq)]
@ -30,18 +28,6 @@ pub struct ActiveLayout {
pub variant: String, pub variant: String,
} }
impl ActiveLayout {
pub fn name(&self) -> String {
let mut name = self.layout.clone();
if !self.variant.is_empty() {
name.push_str(" (");
name.push_str(&self.variant);
name.push_str(")");
}
name
}
}
pub struct Common<M> { pub struct Common<M> {
pub wayland_connection: Option<Connection>, pub wayland_connection: Option<Connection>,
pub keyboard_layout: Option<ZcosmicKeyboardLayoutV1>, pub keyboard_layout: Option<ZcosmicKeyboardLayoutV1>,
@ -81,7 +67,6 @@ pub enum Message {
Focus(SurfaceId), Focus(SurfaceId),
Key(Modifiers, Key, Option<SmolStr>), Key(Modifiers, Key, Option<SmolStr>),
NetworkIcon(Option<&'static str>), NetworkIcon(Option<&'static str>),
OnScreenKeyboard,
SubsurfaceOpened(SurfaceId), SubsurfaceOpened(SurfaceId),
OutputEvent(OutputEvent, WlOutput), OutputEvent(OutputEvent, WlOutput),
PowerInfo(Option<(f64, bool, bool)>), PowerInfo(Option<(f64, bool, bool)>),
@ -291,26 +276,6 @@ impl<M: From<Message> + Send + 'static> Common<M> {
self.network_icon_opt = self.network_icon_opt =
network_icon_opt.map(|name| widget::icon::from_name(name).into()); network_icon_opt.map(|name| widget::icon::from_name(name).into());
} }
Message::OnScreenKeyboard => {
use cosmic_osk_config::Config;
match Config::handler() {
Ok(handler) => {
let mut config = match Config::get_entry(&handler) {
Ok(config) => config,
Err((errs, config)) => {
tracing::warn!("failed to parse OSK config: {:?}", errs);
config
}
};
if let Err(err) = config.set_always_shown(&handler, !config.always_shown) {
tracing::error!("failed to set OSK always_shown config: {}", err);
}
}
Err(err) => {
tracing::error!("failed to create OSK config handler: {}", err);
}
}
}
Message::OutputEvent(output_event, output) => { Message::OutputEvent(output_event, output) => {
if self.wayland_connection.is_none() { if self.wayland_connection.is_none() {
if let Some(backend) = output.backend().upgrade() { if let Some(backend) = output.backend().upgrade() {

View file

@ -11,7 +11,6 @@ use cosmic::cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity
use cosmic::cosmic_config::{self, ConfigSet}; use cosmic::cosmic_config::{self, ConfigSet};
use cosmic::cosmic_theme::{self, CosmicPalette}; use cosmic::cosmic_theme::{self, CosmicPalette};
use cosmic::desktop::fde::{DesktopEntry, get_languages_from_env}; use cosmic::desktop::fde::{DesktopEntry, get_languages_from_env};
use cosmic::iced::core::text::{Ellipsize, EllipsizeHeightLimit};
use cosmic::iced::event::listen_with; use cosmic::iced::event::listen_with;
use cosmic::iced::event::wayland::OutputEvent; use cosmic::iced::event::wayland::OutputEvent;
use cosmic::iced::futures::SinkExt; use cosmic::iced::futures::SinkExt;
@ -19,15 +18,15 @@ use cosmic::iced::platform_specific::runtime::wayland::layer_surface::{
IcedMargin, IcedOutput, SctkLayerSurfaceSettings, IcedMargin, IcedOutput, SctkLayerSurfaceSettings,
}; };
use cosmic::iced::platform_specific::shell::wayland::commands::layer_surface::{ use cosmic::iced::platform_specific::shell::wayland::commands::layer_surface::{
Anchor, KeyboardInteractivity, Layer, destroy_layer_surface, Anchor, KeyboardInteractivity, Layer, destroy_layer_surface, get_layer_surface,
}; };
use cosmic::iced::platform_specific::shell::wayland::commands::subsurface::reposition_subsurface; use cosmic::iced::platform_specific::shell::wayland::commands::subsurface::reposition_subsurface;
use cosmic::iced::runtime::core::window::Id as SurfaceId; use cosmic::iced::runtime::core::window::Id as SurfaceId;
use cosmic::iced::runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings; use cosmic::iced::runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings;
use cosmic::iced::{ use cosmic::iced::{
self, Alignment, Background, Border, Length, Point, Rectangle, Size, Subscription, window, self, Alignment, Background, Border, Color, Length, Point, Rectangle, Size, Subscription,
window,
}; };
use cosmic::surface::action::{LiveSettings, app_layer_shell};
use cosmic::widget::{id_container, text}; use cosmic::widget::{id_container, text};
use cosmic::{Element, executor, surface, theme, widget}; use cosmic::{Element, executor, surface, theme, widget};
use cosmic_greeter_config::Config as CosmicGreeterConfig; use cosmic_greeter_config::Config as CosmicGreeterConfig;
@ -42,7 +41,7 @@ use std::num::NonZeroU32;
use std::process::Stdio; use std::process::Stdio;
use std::sync::{Arc, LazyLock}; use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use std::{fs, io, process, thread}; use std::{fs, io, process};
use tokio::process::Child; use tokio::process::Child;
use tokio::time; use tokio::time;
use tracing::metadata::LevelFilter; use tracing::metadata::LevelFilter;
@ -53,7 +52,7 @@ use wayland_client::Proxy;
use wayland_client::protocol::wl_output::WlOutput; use wayland_client::protocol::wl_output::WlOutput;
use zbus::{Connection, proxy}; use zbus::{Connection, proxy};
use crate::common::{self, Common, DEFAULT_MENU_ITEM_HEIGHT, MAX_WIDTH}; use crate::common::{self, Common, DEFAULT_MENU_ITEM_HEIGHT};
use crate::fl; use crate::fl;
static USERNAME_ID: LazyLock<iced::id::Id> = LazyLock::new(|| iced::id::Id::new("username-id")); static USERNAME_ID: LazyLock<iced::id::Id> = LazyLock::new(|| iced::id::Id::new("username-id"));
@ -78,8 +77,8 @@ async fn user_data_dbus() -> Result<Vec<UserData>, Box<dyn Error>> {
Ok(user_datas) Ok(user_datas)
} }
async fn user_data_fallback() -> Vec<UserData> { fn user_data_fallback() -> Vec<UserData> {
let user_filter = UserFilter::new().await; let user_filter = UserFilter::new();
// The pwd::Passwd method is unsafe (but not labelled as such) due to using global state (libc pwent functions). // The pwd::Passwd method is unsafe (but not labelled as such) due to using global state (libc pwent functions).
/* unsafe */ /* unsafe */
@ -131,7 +130,7 @@ pub fn main() -> Result<(), Box<dyn Error>> {
Ok(ok) => ok, Ok(ok) => ok,
Err(err) => { Err(err) => {
tracing::error!("failed to load user data from daemon: {}", err); tracing::error!("failed to load user data from daemon: {}", err);
runtime.block_on(user_data_fallback()) user_data_fallback()
} }
}; };
@ -281,21 +280,7 @@ pub fn main() -> Result<(), Box<dyn Error>> {
sessions sessions
}; };
match process::Command::new("cosmic-osk") let logind_available = cfg!(feature = "logind") && crate::logind::is_available();
.arg("overlay")
.env("RUST_LOG", "cosmic_osk=info")
.spawn()
{
Ok(mut child) => {
thread::spawn(move || match child.wait() {
Ok(status) => tracing::warn!("cosmic-osk exited: {}", status),
Err(err) => tracing::error!("failed to wait on cosmic-osk: {}", err),
});
}
Err(err) => {
tracing::error!("failed to spawn cosmic-osk: {}", err);
}
}
let flags = Flags { let flags = Flags {
user_icons: user_datas user_icons: user_datas
@ -306,10 +291,7 @@ pub fn main() -> Result<(), Box<dyn Error>> {
sessions, sessions,
greeter_config, greeter_config,
greeter_config_handler, greeter_config_handler,
#[cfg(feature = "logind")] logind_available,
logind_available: crate::logind::is_available(),
#[cfg(not(feature = "logind"))]
logind_available: false,
}; };
let settings = Settings::default().no_main_window(true); let settings = Settings::default().no_main_window(true);
@ -381,9 +363,6 @@ pub enum Message {
Common(common::Message), Common(common::Message),
OutputEvent(OutputEvent, WlOutput), OutputEvent(OutputEvent, WlOutput),
Auth(Option<String>), Auth(Option<String>),
/// Non-fatal error message from PAM (`PAM_ERROR_MSG`), reported by greetd as an auth
/// message of type `Error`. Unlike [`Message::Error`] the conversation stays alive.
AuthError(String),
ConfigUpdateUser, ConfigUpdateUser,
DialogCancel, DialogCancel,
DialogConfirm, DialogConfirm,
@ -407,7 +386,7 @@ pub enum Message {
Session(String), Session(String),
Shutdown, Shutdown,
Socket(SocketState), Socket(SocketState),
Surface(surface::Action<Message>), Surface(surface::Action),
Suspend, Suspend,
Username(String), Username(String),
EnterUser(bool, String), EnterUser(bool, String),
@ -499,9 +478,9 @@ impl App {
.window_size .window_size
.get(&id) .get(&id)
.map(|s| s.width) .map(|s| s.width)
.unwrap_or(MAX_WIDTH); .unwrap_or(800.);
let menu_width = if window_width > MAX_WIDTH { let menu_width = if window_width > 800. {
MAX_WIDTH 800.
} else { } else {
window_width window_width
}; };
@ -601,23 +580,9 @@ impl App {
}; };
let mut input_button = widget::popover( let mut input_button = widget::popover(
widget::container( widget::button::custom(widget::icon::from_name("input-keyboard-symbolic"))
widget::button::custom(
widget::text(
self.common
.active_layouts
.get(self.common.current_keyboard_layout)
.map(|x| x.name())
.unwrap_or_default(),
)
.ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(1)))
.height(16)
.center(),
)
.padding(12.0) .padding(12.0)
.on_press(Message::DropdownToggle(Dropdown::Keyboard)), .on_press(Message::DropdownToggle(Dropdown::Keyboard)),
)
.max_width(80),
) )
.position(widget::popover::Position::Bottom); .position(widget::popover::Position::Bottom);
if matches!(self.dropdown_opt, Some(Dropdown::Keyboard)) { if matches!(self.dropdown_opt, Some(Dropdown::Keyboard)) {
@ -733,13 +698,6 @@ impl App {
text(fl!("accessibility")), text(fl!("accessibility")),
widget::tooltip::Position::Top widget::tooltip::Position::Top
), ),
widget::tooltip(
widget::button::custom(widget::icon::from_name("input-keyboard-symbolic"))
.padding(12.0)
.on_press(Message::Common(common::Message::OnScreenKeyboard)),
text(fl!("on-screen-keyboard")),
widget::tooltip::Position::Top,
),
widget::tooltip( widget::tooltip(
input_button, input_button,
text(fl!("keyboard-layout")), text(fl!("keyboard-layout")),
@ -1003,7 +961,7 @@ impl App {
appearance appearance
}, },
))) )))
.width(Length::Fixed(MAX_WIDTH)); .width(Length::Fixed(800.0));
let menu = if let Some(t) = self.common.rectangle_tracker.as_ref() { let menu = if let Some(t) = self.common.rectangle_tracker.as_ref() {
Element::from(t.container((id, false), menu)) Element::from(t.container((id, false), menu))
} else { } else {
@ -1220,12 +1178,6 @@ impl cosmic::Application for App {
fn update(&mut self, message: Self::Message) -> Task<Message> { fn update(&mut self, message: Self::Message) -> Task<Message> {
match message { match message {
Message::Common(common_message) => { Message::Common(common_message) => {
if matches!(&common_message, common::Message::Prompt(_, _, Some(_)))
&& self.authenticating
{
self.authenticating = false;
self.common.prompt_opt = None;
}
// In greetd's IPC protocol, the greeter must acknowledge auth messages by // In greetd's IPC protocol, the greeter must acknowledge auth messages by
// sending PostAuthMessageResponse. For non-interactive "info" messages // sending PostAuthMessageResponse. For non-interactive "info" messages
// (fingerprint prompts typically come through here), the correct response // (fingerprint prompts typically come through here), the correct response
@ -1291,10 +1243,10 @@ impl cosmic::Application for App {
let unwrapped_size = size let unwrapped_size = size
.map(|s| (s.0.unwrap_or(1920), s.1.unwrap_or(1080))) .map(|s| (s.0.unwrap_or(1920), s.1.unwrap_or(1080)))
.unwrap_or((1920, 1080)); .unwrap_or((1920, 1080));
let (loc, sub_size) = if unwrapped_size.0 as f32 > MAX_WIDTH { let (loc, sub_size) = if unwrapped_size.0 > 800 {
( (
Point::new((unwrapped_size.0 as f32 - MAX_WIDTH) / 2., 32.), Point::new(unwrapped_size.0 as f32 / 2. - 400., 32.),
Size::new(MAX_WIDTH, unwrapped_size.1 as f32 - 32.), Size::new(800., unwrapped_size.1 as f32 - 32.),
) )
} else { } else {
( (
@ -1330,41 +1282,27 @@ impl cosmic::Application for App {
); );
return Task::batch([ return Task::batch([
self.update_user_data(), self.update_user_data(),
cosmic::surface::surface_task(app_layer_shell( get_layer_surface(SctkLayerSurfaceSettings {
|_: &App| LiveSettings { id: surface_id,
padding: None, layer: Layer::Overlay,
corners: None, keyboard_interactivity: KeyboardInteractivity::Exclusive,
blur: Some(false), input_zone: None,
anchor: Anchor::TOP | Anchor::LEFT | Anchor::BOTTOM | Anchor::RIGHT,
output: IcedOutput::Output(output),
namespace: "cosmic-locker".into(),
size: Some((None, None)),
margin: IcedMargin {
top: 0,
bottom: 0,
left: 0,
right: 0,
}, },
move |_: &mut App| { exclusive_zone: -1,
let output = output.clone(); size_limits: iced::Limits::NONE.min_width(1.0).min_height(1.0),
SctkLayerSurfaceSettings { }),
id: surface_id, cosmic::task::message(cosmic::Action::Cosmic(
layer: Layer::Top, cosmic::app::Action::Surface(msg),
keyboard_interactivity: KeyboardInteractivity::Exclusive,
input_zone: None,
anchor: Anchor::TOP
| Anchor::LEFT
| Anchor::BOTTOM
| Anchor::RIGHT,
output: IcedOutput::Output(output),
namespace: "cosmic-greeter".into(),
size: Some((None, None)),
margin: IcedMargin {
top: 0,
bottom: 0,
left: 0,
right: 0,
},
exclusive_zone: -1,
size_limits: iced::Limits::NONE
.min_width(1.0)
.min_height(1.0),
}
},
None,
)), )),
cosmic::task::message(cosmic::Action::Surface(msg)),
]); ]);
} }
OutputEvent::Removed => { OutputEvent::Removed => {
@ -1555,18 +1493,6 @@ impl cosmic::Application for App {
self.authenticating = true; self.authenticating = true;
self.send_request(Request::PostAuthMessageResponse { response }); self.send_request(Request::PostAuthMessageResponse { response });
} }
Message::AuthError(error) => {
self.common.error_opt = Some(error);
if self.authenticating {
// Cancel failed password session so pam_faillock records the attempt.
self.authenticating = false;
self.send_request(Request::CancelSession);
} else {
// The conversation continues, so acknowledge like any other
// non-interactive auth message rather than cancelling the session.
self.send_request(Request::PostAuthMessageResponse { response: None });
}
}
Message::Login => { Message::Login => {
self.common.prompt_opt = None; self.common.prompt_opt = None;
self.common.error_opt = None; self.common.error_opt = None;
@ -1717,7 +1643,9 @@ impl cosmic::Application for App {
self.greetd_sender = Some(sender); self.greetd_sender = Some(sender);
} }
Message::Surface(a) => { Message::Surface(a) => {
return cosmic::task::message(cosmic::Action::Surface(a)); return cosmic::task::message(cosmic::Action::Cosmic(
cosmic::app::Action::Surface(a),
));
} }
Message::ScreenReader(enabled) => { Message::ScreenReader(enabled) => {
if enabled if enabled
@ -1915,8 +1843,8 @@ impl cosmic::Application for App {
tracing::error!("Failed to find subsurface menu id"); tracing::error!("Failed to find subsurface menu id");
return Task::none(); return Task::none();
}; };
let loc = if size.width > MAX_WIDTH { let loc = if size.width > 800. {
Point::new((size.width - MAX_WIDTH) / 2., 32.) Point::new(size.width / 2. - 400., 32.)
} else { } else {
Point::new(0., 32.) Point::new(0., 32.)
}; };

View file

@ -115,8 +115,7 @@ pub fn subscription() -> Subscription<Message> {
.await; .await;
} }
greetd_ipc::AuthMessageType::Error => { greetd_ipc::AuthMessageType::Error => {
// PAM_ERROR_MSG: a failed attempt, not a dead session. _ = sender.send(Message::Error(auth_message)).await;
_ = sender.send(Message::AuthError(auth_message)).await;
} }
}, },
greetd_ipc::Response::Error { greetd_ipc::Response::Error {

View file

@ -4,18 +4,16 @@
use color_eyre::eyre::WrapErr; use color_eyre::eyre::WrapErr;
use cosmic::app::{Core, Settings, Task}; use cosmic::app::{Core, Settings, Task};
use cosmic::cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity; use cosmic::cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity;
use cosmic::iced::core::text::{Ellipsize, EllipsizeHeightLimit};
use cosmic::iced::event::wayland::{OutputEvent, SessionLockEvent}; use cosmic::iced::event::wayland::{OutputEvent, SessionLockEvent};
use cosmic::iced::futures::{self, SinkExt}; use cosmic::iced::futures::{self, SinkExt};
use cosmic::iced::platform_specific::shell::wayland::commands::session_lock::{ use cosmic::iced::platform_specific::shell::wayland::commands::session_lock::{
destroy_lock_surface, lock, unlock, destroy_lock_surface, get_lock_surface, lock, unlock,
}; };
use cosmic::iced::runtime::core::window::Id as SurfaceId; use cosmic::iced::runtime::core::window::Id as SurfaceId;
use cosmic::iced::runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings; use cosmic::iced::runtime::platform_specific::wayland::subsurface::SctkSubsurfaceSettings;
use cosmic::iced::{ use cosmic::iced::{
self, Alignment, Background, Border, Length, Point, Rectangle, Size, Subscription, self, Alignment, Background, Border, Length, Point, Rectangle, Size, Subscription,
}; };
use cosmic::surface::action::LiveSettings;
use cosmic::{Element, executor, surface, theme, widget}; use cosmic::{Element, executor, surface, theme, widget};
use cosmic_config::CosmicConfigEntry; use cosmic_config::CosmicConfigEntry;
use cosmic_greeter_daemon::{TimeAppletConfig, UserData}; use cosmic_greeter_daemon::{TimeAppletConfig, UserData};
@ -35,7 +33,7 @@ use tracing_subscriber::{EnvFilter, fmt};
use wayland_client::Proxy; use wayland_client::Proxy;
use wayland_client::protocol::wl_output::WlOutput; use wayland_client::protocol::wl_output::WlOutput;
use crate::common::{self, Common, DEFAULT_MENU_ITEM_HEIGHT, MAX_WIDTH}; use crate::common::{self, Common, DEFAULT_MENU_ITEM_HEIGHT};
use crate::fl; use crate::fl;
fn lockfile_opt() -> Option<PathBuf> { fn lockfile_opt() -> Option<PathBuf> {
@ -81,6 +79,8 @@ pub fn main(user: pwd::Passwd) -> Result<(), Box<dyn std::error::Error>> {
// We are already the user at this point // We are already the user at this point
user_data.load_config_as_user(); user_data.load_config_as_user();
let logind_available = cfg!(feature = "logind") && crate::logind::is_available();
let flags = Flags { let flags = Flags {
user_icon: user_data user_icon: user_data
.icon_opt .icon_opt
@ -88,10 +88,7 @@ pub fn main(user: pwd::Passwd) -> Result<(), Box<dyn std::error::Error>> {
.map(widget::image::Handle::from_bytes), .map(widget::image::Handle::from_bytes),
user_data, user_data,
lockfile_opt: lockfile_opt(), lockfile_opt: lockfile_opt(),
#[cfg(feature = "logind")] logind_available,
logind_available: crate::logind::is_available(),
#[cfg(not(feature = "logind"))]
logind_available: false,
}; };
let settings = Settings::default().no_main_window(true); let settings = Settings::default().no_main_window(true);
@ -275,7 +272,7 @@ pub enum Message {
KeyboardLayout(usize), KeyboardLayout(usize),
Inhibit(Arc<OwnedFd>), Inhibit(Arc<OwnedFd>),
Submit(String), Submit(String),
Surface(surface::Action<Message>), Surface(surface::Action),
Suspend, Suspend,
TimeAppletConfig(TimeAppletConfig), TimeAppletConfig(TimeAppletConfig),
Error(String), Error(String),
@ -327,9 +324,9 @@ impl App {
.window_size .window_size
.get(&surface_id) .get(&surface_id)
.map(|s| s.width) .map(|s| s.width)
.unwrap_or(MAX_WIDTH); .unwrap_or(800.);
let menu_width = if window_width > MAX_WIDTH { let menu_width = if window_width > 800. {
MAX_WIDTH 800.
} else { } else {
window_width window_width
}; };
@ -418,23 +415,9 @@ impl App {
}; };
let mut input_button = widget::popover( let mut input_button = widget::popover(
widget::container( widget::button::custom(widget::icon::from_name("input-keyboard-symbolic"))
widget::button::custom(
widget::text(
self.common
.active_layouts
.get(self.common.current_keyboard_layout)
.map(|x| x.name())
.unwrap_or_default(),
)
.ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(1)))
.height(16)
.center(),
)
.padding(12.0) .padding(12.0)
.on_press(Message::DropdownToggle(Dropdown::Keyboard)), .on_press(Message::DropdownToggle(Dropdown::Keyboard)),
)
.max_width(80),
) )
.position(widget::popover::Position::Bottom); .position(widget::popover::Position::Bottom);
if matches!(self.dropdown_opt, Some(Dropdown::Keyboard)) { if matches!(self.dropdown_opt, Some(Dropdown::Keyboard)) {
@ -458,13 +441,6 @@ impl App {
.padding(12.0) .padding(12.0)
.on_press(Message::None), .on_press(Message::None),
*/ */
widget::tooltip(
widget::button::custom(widget::icon::from_name("input-keyboard-symbolic"))
.padding(12.0)
.on_press(Message::Common(common::Message::OnScreenKeyboard)),
widget::text(fl!("on-screen-keyboard")),
widget::tooltip::Position::Top,
),
widget::tooltip( widget::tooltip(
input_button, input_button,
widget::text(fl!("keyboard-layout")), widget::text(fl!("keyboard-layout")),
@ -686,7 +662,6 @@ impl cosmic::Application for App {
/// Creates the application, and optionally emits command on initialize. /// Creates the application, and optionally emits command on initialize.
fn init(mut core: Core, flags: Self::Flags) -> (Self, Task<Self::Message>) { fn init(mut core: Core, flags: Self::Flags) -> (Self, Task<Self::Message>) {
core.set_app_type(cosmic::core::AppType::System); core.set_app_type(cosmic::core::AppType::System);
let (mut common, common_task) = Common::init(core); let (mut common, common_task) = Common::init(core);
common.on_output_event = Some(Box::new(|output_event, output| { common.on_output_event = Some(Box::new(|output_event, output| {
Message::OutputEvent(output_event, output) Message::OutputEvent(output_event, output)
@ -734,12 +709,6 @@ impl cosmic::Application for App {
match message { match message {
Message::None => {} Message::None => {}
Message::Common(common_message) => { Message::Common(common_message) => {
if matches!(&common_message, common::Message::Prompt(_, _, Some(_)))
&& self.authenticating
{
self.authenticating = false;
self.common.prompt_opt = None;
}
return self.common.update(common_message); return self.common.update(common_message);
} }
Message::OutputEvent(output_event, output) => { Message::OutputEvent(output_event, output) => {
@ -805,10 +774,10 @@ impl cosmic::Application for App {
let unwrapped_size = size let unwrapped_size = size
.map(|s| (s.0.unwrap_or(1920), s.1.unwrap_or(1080))) .map(|s| (s.0.unwrap_or(1920), s.1.unwrap_or(1080)))
.unwrap_or((1920, 1080)); .unwrap_or((1920, 1080));
let (loc, sub_size) = if unwrapped_size.0 as f32 > MAX_WIDTH { let (loc, sub_size) = if unwrapped_size.0 > 800 {
( (
Point::new(unwrapped_size.0 as f32 / 2. - 400., 32.), Point::new(unwrapped_size.0 as f32 / 2. - 400., 32.),
Size::new(MAX_WIDTH, unwrapped_size.1 as f32 - 32.), Size::new(800., unwrapped_size.1 as f32 - 32.),
) )
} else { } else {
( (
@ -843,19 +812,11 @@ impl cosmic::Application for App {
); );
if matches!(self.state, State::Locked { .. }) { if matches!(self.state, State::Locked { .. }) {
return cosmic::task::message(cosmic::Action::Surface( return get_lock_surface(surface_id, output).chain({
cosmic::surface::action::lock( cosmic::task::message(cosmic::Action::Cosmic(
|| LiveSettings { cosmic::app::Action::Surface(msg),
padding: None, ))
corners: None, });
blur: Some(false),
},
surface_id,
output,
None::<fn() -> cosmic::Element<'static, cosmic::Action<Message>>>,
),
))
.chain(cosmic::task::message(cosmic::Action::Surface(msg)));
} }
} }
OutputEvent::Removed => { OutputEvent::Removed => {
@ -886,10 +847,10 @@ impl cosmic::Application for App {
let unwrapped_size = size let unwrapped_size = size
.map(|s| (s.0.unwrap_or(1920), s.1.unwrap_or(1080))) .map(|s| (s.0.unwrap_or(1920), s.1.unwrap_or(1080)))
.unwrap_or((1920, 1080)); .unwrap_or((1920, 1080));
let (loc, sub_size) = if unwrapped_size.0 as f32 > MAX_WIDTH { let (loc, sub_size) = if unwrapped_size.0 > 800 {
( (
Point::new(unwrapped_size.0 as f32 / 2. - 400., 32.), Point::new(unwrapped_size.0 as f32 / 2. - 400., 32.),
Size::new(MAX_WIDTH, unwrapped_size.1 as f32 - 32.), Size::new(800., unwrapped_size.1 as f32 - 32.),
) )
} else { } else {
(Point::ORIGIN, Size::new(1920., 1080.)) (Point::ORIGIN, Size::new(1920., 1080.))
@ -995,18 +956,7 @@ impl cosmic::Application for App {
// Create lock surfaces // Create lock surfaces
for (output, surface_id) in self.common.surface_ids.iter() { for (output, surface_id) in self.common.surface_ids.iter() {
commands.push(cosmic::task::message(cosmic::Action::Surface( commands.push(get_lock_surface(*surface_id, output.clone()));
cosmic::surface::action::lock(
|| LiveSettings {
padding: None,
corners: None,
blur: Some(false),
},
*surface_id,
output.clone(),
None::<fn() -> cosmic::Element<'static, cosmic::Action<Message>>>,
),
)));
if let Some((rect, name)) = self if let Some((rect, name)) = self
.common .common
@ -1041,7 +991,9 @@ impl cosmic::Application for App {
app.menu(subsurface_id).map(cosmic::Action::App) app.menu(subsurface_id).map(cosmic::Action::App)
})), })),
); );
commands.push(cosmic::task::message(cosmic::Action::Surface(msg))); commands.push(cosmic::task::message(cosmic::Action::Cosmic(
cosmic::app::Action::Surface(msg),
)));
} else { } else {
tracing::error!("no rectangle for subsurface creation..."); tracing::error!("no rectangle for subsurface creation...");
} }
@ -1206,7 +1158,9 @@ impl cosmic::Application for App {
} }
} }
Message::Surface(a) => { Message::Surface(a) => {
return cosmic::task::message(cosmic::Action::Surface(a)); return cosmic::task::message(cosmic::Action::Cosmic(
cosmic::app::Action::Surface(a),
));
} }
} }
Task::none() Task::none()
@ -1218,8 +1172,17 @@ impl cosmic::Application for App {
} }
/// Creates a view after each update. /// Creates a view after each update.
fn view_window(&self, _surface_id: SurfaceId) -> Element<'_, Self::Message> { fn view_window(&self, surface_id: SurfaceId) -> Element<'_, Self::Message> {
widget::space::horizontal().into() let img = self
.common
.surface_images
.get(&surface_id)
.unwrap_or(&self.common.fallback_background);
widget::image(img)
.content_fit(iced::ContentFit::Cover)
.width(Length::Fill)
.height(Length::Fill)
.into()
} }
fn subscription(&self) -> Subscription<Self::Message> { fn subscription(&self) -> Subscription<Self::Message> {
@ -1257,8 +1220,7 @@ impl cosmic::Application for App {
}), }),
); );
#[cfg(feature = "logind")] if cfg!(feature = "logind") && self.flags.logind_available {
if self.flags.logind_available {
subscriptions.push(crate::logind::subscription()); subscriptions.push(crate::logind::subscription());
} }