Improve design

This commit is contained in:
Jeremy Soller 2023-10-02 16:00:34 -06:00
parent 4077ff0949
commit ce0f2984c6
No known key found for this signature in database
GPG key ID: DCFCA852D3906975
3 changed files with 821 additions and 387 deletions

1026
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,7 +6,7 @@ edition = "2021"
[dependencies] [dependencies]
env_logger = "0.10" env_logger = "0.10"
log = "0.4" log = "0.4"
uzers = "0.11" pwd = "1"
[dependencies.greetd_ipc] [dependencies.greetd_ipc]
version = "0.9" version = "0.9"
@ -15,7 +15,7 @@ features = ["sync-codec"]
[dependencies.libcosmic] [dependencies.libcosmic]
git = "https://github.com/pop-os/libcosmic" git = "https://github.com/pop-os/libcosmic"
default-features = false default-features = false
features = ["tokio", "wayland"] features = ["tokio", "winit"]
[dependencies.tokio] [dependencies.tokio]
version = "1" version = "1"

View file

@ -6,23 +6,22 @@
use cosmic::app::{message, Command, Core, Settings}; use cosmic::app::{message, Command, Core, Settings};
use cosmic::{executor, iced, widget, Element}; use cosmic::{executor, iced, widget, Element};
use greetd_ipc::{codec::SyncCodec, AuthMessageType, Request, Response}; use greetd_ipc::{codec::SyncCodec, AuthMessageType, Request, Response};
use std::{env, io, sync::Arc}; use std::{env, fs, io, path::Path, sync::Arc};
use tokio::net::UnixStream; use tokio::net::UnixStream;
use uzers::os::unix::UserExt;
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init(); env_logger::init();
// This method is unsafe 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).
let users: Vec<uzers::User> = unsafe { let users: Vec<_> = /* unsafe */ {
uzers::all_users() pwd::Passwd::iter()
.filter(|user| { .filter(|user| {
if user.uid() < 1000 { if user.uid < 1000 {
// Skip system accounts // Skip system accounts
return false; return false;
} }
match user.shell().file_name().and_then(|x| x.to_str()) { match Path::new(&user.shell).file_name().and_then(|x| x.to_str()) {
// Skip shell ending in false // Skip shell ending in false
Some("false") => false, Some("false") => false,
// Skip shell ending in nologin // Skip shell ending in nologin
@ -30,6 +29,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
_ => true, _ => true,
} }
}) })
.map(|user| {
let icon_path = Path::new("/var/lib/AccountsService/icons").join(&user.name);
let icon_opt = if icon_path.is_file() {
match fs::read(&icon_path) {
Ok(icon_data) => Some(widget::image::Handle::from_memory(icon_data)),
Err(err) => {
log::error!("failed to read {:?}: {:?}", icon_path, err);
None
}
}
} else {
None
};
(user, icon_opt)
})
.collect() .collect()
}; };
@ -62,7 +76,7 @@ pub enum SocketState {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum InputState { pub enum InputState {
None, None,
Username(String), Username,
Auth(bool, String, String), Auth(bool, String, String),
} }
@ -72,7 +86,8 @@ pub enum Message {
None, None,
Socket(SocketState), Socket(SocketState),
Input(InputState), Input(InputState),
Submit, Username(String),
Auth(String),
Login, Login,
} }
@ -144,7 +159,7 @@ async fn request(socket: Arc<UnixStream>, request: Request) -> Message {
/// The [`App`] stores application-specific state. /// The [`App`] stores application-specific state.
pub struct App { pub struct App {
core: Core, core: Core,
users: Vec<uzers::User>, users: Vec<(pwd::Passwd, Option<widget::image::Handle>)>,
socket_state: SocketState, socket_state: SocketState,
input_state: InputState, input_state: InputState,
} }
@ -155,7 +170,7 @@ impl cosmic::Application for App {
type Executor = executor::Default; type Executor = executor::Default;
/// Argument received [`cosmic::Application::new`]. /// Argument received [`cosmic::Application::new`].
type Flags = Vec<uzers::User>; type Flags = Vec<(pwd::Passwd, Option<widget::image::Handle>)>;
/// Message type specific to our [`App`]. /// Message type specific to our [`App`].
type Message = Message; type Message = Message;
@ -186,7 +201,7 @@ impl cosmic::Application for App {
users, users,
socket_state: SocketState::Pending, socket_state: SocketState::Pending,
//TODO: set to pending until socket is open? //TODO: set to pending until socket is open?
input_state: InputState::Username(String::new()), input_state: InputState::Username,
}, },
Command::perform( Command::perform(
async { async {
@ -213,41 +228,39 @@ impl cosmic::Application for App {
Message::Input(input_state) => { Message::Input(input_state) => {
self.input_state = input_state; self.input_state = input_state;
} }
Message::Submit => match &self.socket_state { Message::Username(username) => match &self.socket_state {
SocketState::Open(socket) => match &self.input_state { SocketState::Open(socket) => {
InputState::None => {} let socket = socket.clone();
InputState::Username(username) => { let username = username.clone();
let socket = socket.clone(); return Command::perform(
let username = username.clone(); async move {
return Command::perform( message::app(request(socket, Request::CreateSession { username }).await)
async move { },
message::app( |x| x,
request(socket, Request::CreateSession { username }).await, );
}
_ => todo!("socket not open but username provided"),
},
Message::Auth(value) => match &self.socket_state {
SocketState::Open(socket) => {
let socket = socket.clone();
let value = value.clone();
return Command::perform(
async move {
message::app(
request(
socket,
Request::PostAuthMessageResponse {
response: Some(value),
},
) )
}, .await,
|x| x, )
); },
} |x| x,
InputState::Auth(_secret, _prompt, value) => { );
let socket = socket.clone(); }
let value = value.clone(); _ => todo!("socket not open but authentication provided"),
return Command::perform(
async move {
message::app(
request(
socket,
Request::PostAuthMessageResponse {
response: Some(value),
},
)
.await,
)
},
|x| x,
);
}
},
_ => todo!("socket not open but input provided"),
}, },
Message::Login => match &self.socket_state { Message::Login => match &self.socket_state {
SocketState::Open(socket) => { SocketState::Open(socket) => {
@ -277,59 +290,70 @@ impl cosmic::Application for App {
/// Creates a view after each update. /// Creates a view after each update.
fn view(&self) -> Element<Self::Message> { fn view(&self) -> Element<Self::Message> {
let mut column = widget::column::with_capacity(2); let content: Element<_> = match &self.socket_state {
SocketState::Pending => widget::text("Opening GREETD_SOCK").into(),
match &self.socket_state {
SocketState::Pending => {
column = column.push(widget::text("Opening GREETD_SOCK"));
}
SocketState::Open(_) => match &self.input_state { SocketState::Open(_) => match &self.input_state {
InputState::None => {} InputState::None => {
InputState::Username(username) => { //TODO
column = column.push(widget::text("Username:")); widget::text("").into()
column = column.push( }
widget::text_input("Username", &username) InputState::Username => {
.on_input(|username| Message::Input(InputState::Username(username))) let mut row = widget::row::with_capacity(self.users.len()).spacing(12.0);
.on_submit(Message::Submit), for (user, icon_opt) in &self.users {
); let mut column = widget::column::with_capacity(2).spacing(12.0);
match icon_opt {
for user in &self.users { Some(icon) => {
match user.name().to_str() { column = column.push(
Some(user_name) => { widget::Image::new(icon.clone())
column = column.push(widget::button(user_name).on_press( .width(iced::Length::Fixed(256.0))
Message::Input(InputState::Username(user_name.to_string())), .height(iced::Length::Fixed(256.0)),
)); )
} }
None => {} None => {}
} }
match &user.gecos {
Some(gecos) => {
column = column.push(widget::text(gecos));
}
None => {}
}
row = row.push(
widget::MouseArea::new(
widget::cosmic_container::container(column)
.layer(cosmic::cosmic_theme::Layer::Primary)
.padding(16)
.style(cosmic::theme::Container::Primary),
)
.on_press(Message::Username(user.name.clone())),
);
} }
row.into()
} }
InputState::Auth(secret, prompt, value) => { InputState::Auth(secret, prompt, value) => {
let mut column = widget::column::with_capacity(2)
.spacing(12.0)
.width(iced::Length::Fixed(400.0));
column = column.push(widget::text(prompt)); column = column.push(widget::text(prompt));
let text_input = widget::text_input("", &value) let text_input = widget::text_input("", &value)
.on_input(|value| { .on_input(|value| {
Message::Input(InputState::Auth(*secret, prompt.clone(), value)) Message::Input(InputState::Auth(*secret, prompt.clone(), value))
}) })
.on_submit(Message::Submit); .on_submit(Message::Auth(value.clone()));
if *secret { if *secret {
column = column.push(text_input.password()); column = column.push(text_input.password());
} else { } else {
column = column.push(text_input); column = column.push(text_input);
} }
column.into()
} }
}, },
SocketState::NotSet => { SocketState::NotSet => widget::text("GREETD_SOCK variable not set").into(),
column = column.push(widget::text("GREETD_SOCK variable not set"));
}
SocketState::Error(err) => { SocketState::Error(err) => {
column = column.push(widget::text(format!( widget::text(format!("Failed to open GREETD_SOCK: {:?}", err)).into()
"Failed to open GREETD_SOCK: {:?}",
err
)))
} }
} };
let centered = widget::container(column.spacing(12.0).width(iced::Length::Fixed(400.0))) let centered = widget::container(content)
.width(iced::Length::Fill) .width(iced::Length::Fill)
.height(iced::Length::Fill) .height(iced::Length::Fill)
.align_x(iced::alignment::Horizontal::Center) .align_x(iced::alignment::Horizontal::Center)