Skip to content

Commit

Permalink
rfct: Split up session loading for readability
Browse files Browse the repository at this point in the history
Now there are distinct steps to session loading. Regex was replaced
with a desktop file parsing library. This makes the code easier
to comprehend and allows for better flexibility in the future
(rharish101#67).
  • Loading branch information
max-ishere committed Sep 5, 2024
1 parent 2d63a55 commit 250f3b4
Show file tree
Hide file tree
Showing 8 changed files with 305 additions and 357 deletions.
206 changes: 63 additions & 143 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 2 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,15 @@ license = "GPL-3.0-or-later"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
chrono = { version = "0.4.22", default-features = false }
async-recursion = "1.1.1"
clap = { version = "4.1.4", features = ["derive"] }
const_format = "0.2.26"
derivative = "2.2.0"
file-rotate = "0.7.2"
glob = "0.3.0"
freedesktop_entry_parser = "1.3.0"
greetd_ipc = { version = "0.9.0", features = ["tokio-codec"] }
gtk4 = "0.5"
lru = "0.9.0"
pwd = "1.4.0"
regex = "1.7.1"
relm4 = "0.5.0"
serde = { version = "1.0.142", features = ["derive"] }
serde-tuple-vec-map = "1.0.1"
Expand All @@ -35,7 +33,6 @@ toml = "0.6.0"
tracing = "0.1.37"
tracing-appender = "0.2.2"
tracing-subscriber = { version = "0.3.16", features = ["local-time"] }
tracker = "0.2.0"

[features]
gtk4_8 = ["gtk4/v4_8"]
Expand Down
6 changes: 0 additions & 6 deletions src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,3 @@ pub const POWEROFF_CMD: &str = env_or!("POWEROFF_CMD", "poweroff");

/// Default greeting message
pub const GREETING_MSG: &str = "Welcome back!";

/// Directories separated by `:`, containing desktop files for X11/Wayland sessions
pub const SESSION_DIRS: &str = env_or!(
"SESSION_DIRS",
"/usr/share/xsessions:/usr/share/wayland-sessions"
);
13 changes: 8 additions & 5 deletions src/gui/component/auth_ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use tracing::error;
use crate::greetd::Greetd;
use crate::gui::component::greetd_controls::GreetdControlsInit;
use crate::gui::component::{GreetdControlsOutput, SelectorInit, SelectorMsg, SelectorOutput};
use crate::sysutil::SessionInfo;

use super::greetd_controls::{GreetdControls, GreetdState};
use super::{EntryOrDropDown, GreetdControlsMsg, Selector, SelectorOption};
Expand All @@ -23,7 +24,7 @@ where
{
pub initial_user: String,
pub users: HashMap<String, String>,
pub sessions: HashMap<String, Vec<String>>,
pub sessions: HashMap<String, SessionInfo>,

pub last_user_session_cache: HashMap<String, EntryOrDropDown>,

Expand Down Expand Up @@ -157,9 +158,9 @@ where
.launch(SelectorInit {
entry_placeholder: "Session command".to_string(),
options: sessions
.keys()
.map(|name| SelectorOption {
id: name.clone(),
.iter()
.map(|(xdg_id, SessionInfo { name, .. })| SelectorOption {
id: xdg_id.clone(),
text: name.clone(),
})
.collect(),
Expand All @@ -172,7 +173,9 @@ where
let SelectorOutput::CurrentSelection(entry) = output;
let cmdline = match entry {
EntryOrDropDown::Entry(cmdline) => shlex::split(&cmdline),
EntryOrDropDown::DropDown(id) => sessions.get(&id).cloned(),
EntryOrDropDown::DropDown(id) => sessions
.get(&id)
.map(|SessionInfo { command, .. }| command.clone()),
};

Self::Input::SessionChanged(cmdline)
Expand Down
1 change: 0 additions & 1 deletion src/gui/component/greetd_controls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,6 @@ where
GreetdState::NotCreated(_) => gtk::Box {
set_halign: gtk::Align::End,
#[template] LoginButton {
#[watch]
grab_focus: (),

connect_clicked => GreetdControlsMsg::AdvanceAuthentication,
Expand Down
4 changes: 2 additions & 2 deletions src/gui/component/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use relm4::prelude::*;

#[cfg(feature = "gtk4_8")]
use crate::config::BgFit;
use crate::greetd::Greetd;
use crate::{greetd::Greetd, sysutil::SessionInfo};

mod selector;
pub use selector::*;
Expand All @@ -30,7 +30,7 @@ where
Client: Greetd,
{
pub users: HashMap<String, String>,
pub sessions: HashMap<String, Vec<String>>,
pub sessions: HashMap<String, SessionInfo>,

pub initial_user: String,
pub last_user_session_cache: HashMap<String, EntryOrDropDown>,
Expand Down
43 changes: 30 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@ mod gui;
mod sysutil;
pub mod tomlutils;

use std::collections::HashMap;
use std::fs::{create_dir_all, OpenOptions};
use std::io::{Result as IoResult, Write};
use std::path::{Path, PathBuf};

use cache::Cache;
use cache::{Cache, SessionIdOrCmdline};
use clap::{Parser, ValueEnum};
use constants::CACHE_PATH;
use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate};
use greetd::MockGreetd;
use gui::component::{App, AppInit, EntryOrDropDown, GreetdState};
use sysutil::{SystemUsersAndSessions, User};
use sysutil::SystemUsersAndSessions;
use tracing::subscriber::set_global_default;
use tracing::warn;
use tracing_appender::{non_blocking, non_blocking::WorkerGuard};
Expand All @@ -31,6 +32,9 @@ use tracing_subscriber::{

use crate::constants::{APP_ID, CONFIG_PATH, CSS_PATH, LOG_PATH};

#[macro_use]
extern crate async_recursion;

#[cfg(test)]
#[macro_use]
extern crate test_case;
Expand Down Expand Up @@ -77,20 +81,29 @@ struct Args {
}

fn main() {
let args = Args::parse();
let Args {
logs,
log_level,
verbose,
config,
style,
demo,
} = Args::parse();
// Keep the guard alive till the end of the function, since logging depends on this.
let _guard = init_logging(&args.logs, &args.log_level, args.verbose);
let _guard = init_logging(&logs, &log_level, verbose);

// TODO: Is there a better way? we have to not start tokio until OffsetTime is initialized.
// TODO: What on earth is this let binding?
let (cache, (SystemUsersAndSessions { users, sessions }, non_fatal_errors)) =
let (cache, SystemUsersAndSessions { users, sessions }) =
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
let (cache, users) =
tokio::join!(Cache::load(CACHE_PATH), SystemUsersAndSessions::load());
let (cache, users) = tokio::join!(
Cache::load(CACHE_PATH),
SystemUsersAndSessions::load(Vec::new())
);

(
cache.unwrap_or_else(|err| {
Expand All @@ -106,25 +119,29 @@ fn main() {
.and_then(|user| users.contains_key(user).then_some(user.to_string()))
.unwrap_or_else(|| users.keys().next().cloned().unwrap_or_default()); // TODO: Make Init accept an option

let last_user_session_cache = cache
let mut last_user_session_cache: HashMap<_, _> = cache
.user_to_last_sess
.into_iter()
.filter_map(|(username, session)| match session {
cache::SessionIdOrCmdline::ID(id) => sessions
SessionIdOrCmdline::ID(id) => sessions
.contains_key(&id)
.then_some((username, EntryOrDropDown::DropDown(id))),

cache::SessionIdOrCmdline::Command(cmd) => {
Some((username, EntryOrDropDown::Entry(cmd)))
}
SessionIdOrCmdline::Command(cmd) => Some((username, EntryOrDropDown::Entry(cmd))),
})
.collect();

let app = relm4::RelmApp::new(APP_ID);

let users = users
.into_iter()
.map(|(sys, User { full_name, .. })| (sys, full_name))
.map(|(sys, user)| {
if sessions.is_empty() {
last_user_session_cache
.insert(sys.clone(), EntryOrDropDown::Entry(user.shell().to_owned()));
}
(sys, user.full_name)
})
.collect();

app.run::<App<MockGreetd>>(AppInit {
Expand Down
Loading

0 comments on commit 250f3b4

Please sign in to comment.