Compare commits

...

35 Commits

Author SHA1 Message Date
Luke D. Jones c2aa81bfe3 asusd: fixing a blocking op 2022-12-25 22:22:52 +13:00
Luke D. Jones 8dcb209026 ROGCC: Don't notify user if changing to same mux mode 2022-12-10 21:42:52 +13:00
Luke D. Jones bdb6c5b2ff Prep 4.5.6 release 2022-12-10 21:08:52 +13:00
Luke D. Jones a318fbceec asusd: check if nvidia-powerd enabled before toggling 2022-12-10 21:05:27 +13:00
Luke D. Jones 8feacf863a asusd: Very basic support for running a command on AC/Battery switching 2022-12-10 20:51:00 +13:00
Luke D. Jones 0c62582515 ROGCC: Very basic support for running a command on AC/Battery switching 2022-12-10 20:17:45 +13:00
Luke D. Jones 3c575e4d2a ROGCC: Minor correction to tray menu 2022-12-10 19:37:20 +13:00
Luke D. Jones dbfd73da5e ROGCC: Better handle the use of GPU MUX without supergfxd 2022-12-10 19:30:30 +13:00
Luke D. Jones b1ee449b97 Adjust profile task to help TUF laptops notify 2022-12-09 10:03:45 +13:00
Luke D. Jones 245c035dc9 Fix tasks not always running correctly on boot/sleep/wake/shutdown 2022-12-08 20:12:55 +13:00
Luke D. Jones 07daa0df61 Fix: ROGCC: show option for LED notifications 2022-12-08 16:27:00 +13:00
Luke D. Jones c7893b16f9 Fix: ROGCC: Remove unwrap causing panic on main thread
Closes #293
2022-12-08 11:14:01 +13:00
Luke Jones 8e8681c190 Merge branch 'main' into 'main'
add led modes for FX506HC

See merge request asus-linux/asusctl!144
2022-12-07 20:29:23 +00:00
HerrWinfried b26c6a55f0 add led modes for FX506HC 2022-12-07 11:41:49 +00:00
Luke D. Jones 93d472fe74 Use correct defaults for GfxMode and GfxPower 2022-12-07 12:31:52 +13:00
Luke D. Jones 5469c73f11 Adjust gitlab pipeline to ignore checks for tags 2022-12-07 11:55:09 +13:00
Luke D. Jones ad95765954 Add missing files 2022-12-07 11:50:17 +13:00
Luke D. Jones e42a5bc3e9 ROGCC: don't require supergfxd to be running
Prep fixes for new tag and release
2022-12-07 11:47:27 +13:00
Luke D. Jones 28347e87eb Prep new minor release 2022-12-06 20:10:03 +13:00
Luke D. Jones b34cb672c3 Fix: ROGCC: log and show more errors on startup 2022-12-06 14:28:35 +13:00
Luke D. Jones 559ddc9a22 Fix: ROGCC: remove unused arg in fan curve widget 2022-12-06 10:08:11 +13:00
Luke D. Jones a8c014881f Version bump for RC 2022-12-06 09:48:24 +13:00
Luke D. Jones f417032ed9 Fix: ROGCC: apply changes to correct fan curve profile
The fan curve profile changes were applying to the currently *active*
profile and not the GUI selected profile being changed. Fixed.

Also clarify the buttons for fan curve apply.
2022-12-06 09:47:48 +13:00
Luke D. Jones 616fb3aea6 chore: cranky cleanups 2022-12-05 20:31:39 +13:00
Luke D. Jones 6e6e057995 Update changelog 2022-12-05 19:44:50 +13:00
Luke D. Jones 085e63ebab Merge commit 'fdadffcdde82' because of borked HEAD after pull 2022-12-05 19:44:08 +13:00
Luke D. Jones fdadffcdde Fix: ROGCC: Correctly deny badly formed fan graphs
Closes #286
2022-12-05 19:40:00 +13:00
Luke Jones 5f51527dd7 Merge branch 'piivanov-main-patch-89025' into 'main'
Add led modes for G713RM

See merge request asus-linux/asusctl!143
2022-12-04 20:53:46 +00:00
Peter Ivanov 39525980a0 Add led modes for G713RM 2022-12-04 17:39:32 +00:00
Luke D. Jones 83a0b570e0 Cause great pain to self with cargo-deny + cargo-cranky 2022-12-04 22:10:08 +13:00
Luke D. Jones 2bfbce36b0 Bump dependencies 2022-12-04 22:09:28 +13:00
Luke D. Jones 2705b08dca Cause great pain to self with cargo-deny + cargo-cranky 2022-12-04 21:49:47 +13:00
Luke D. Jones 2fca7a09c4 bump dependencies 2022-12-04 20:16:33 +13:00
Luke Jones ef0da62c55 Merge branch 'maxbachmann-main-patch-99498' into 'main'
add led modes for G513RM

See merge request asus-linux/asusctl!141
2022-12-04 01:48:10 +00:00
maxbachmann 9dab120bcf add led modes for G513RM 2022-12-03 22:03:35 +00:00
83 changed files with 1975 additions and 897 deletions
+1
View File
@@ -2,6 +2,7 @@
vendor.tar.xz vendor.tar.xz
cargo-config cargo-config
.idea .idea
vendor
vendor-* vendor-*
vendor_* vendor_*
.vscode-ctags .vscode-ctags
+42 -7
View File
@@ -1,27 +1,62 @@
image: rust:latest image: rust:latest
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
paths:
# Don't include `incremental` to save space
# Debug
- target/debug/build/
- target/debug/deps/
- target/debug/.fingerprint/
- target/debug/.cargo-lock
- target/debug/df_storyteller
# Release
- target/release/build/
- target/release/deps/
- target/release/.fingerprint/
- target/release/.cargo-lock
before_script: before_script:
- apt-get update -qq && apt-get install -y -qq libudev-dev libgtk-3-dev - apt-get update -qq && apt-get install -y -qq libudev-dev libgtk-3-dev grep
stages: stages:
- format
- check
- test - test
- build - release
test: format:
except:
- tags
script:
- echo "nightly" > rust-toolchain
- rustup component add rustfmt
- cargo fmt --check
check:
except:
- tags
script: script:
- rustup component add clippy - rustup component add clippy
- cargo check - cargo check
- cargo clippy # deny currently catches too much
#- cargo install cargo-deny && cargo deny
- cargo install cargo-cranky && cargo cranky
test:
except:
- tags
script:
- cargo test - cargo test
build: release:
only: only:
- main - tags
script: script:
- make && make vendor - make && make vendor
artifacts: artifacts:
paths: paths:
- vendor_asus-nb-ctrl_*.tar.xz - vendor_asusctl_*.tar.xz
- cargo-config - cargo-config
variables: variables:
+40
View File
@@ -5,6 +5,46 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] ## [Unreleased]
## [v4.5.7]
### Changed
- ROGCC: Don't notify user if changing to same mux mode
- asusd: don't block on systemd-unit change: removes all shoddy external command calls in favour of async dbus calls
## [v4.5.6]
### Changed
- Fix tasks not always running correctly on boot/sleep/wake/shutdown by finishing the move to async
- Change how the profile/fan change task monitors changes due to TUF laptops behaving slightly different
- ROGCC: Better handle the use of GPU MUX without supergfxd
- ROGCC: Track if reboot required when not using supergfxd
- Add env var for logging levels to daemon and gui (`RUST_LOG=<error|warn|info|debug|trace>`)
- ROGCC: Very basic support for running a command on AC/Battery switching, this is in config at `~/.config/rog/rog-control-center.cfg`, and for now must be edited by hand and ROGCC restarted (run ROGCC in BG to use effectively)
+ Run ROGCC from terminal to see errors of the AC/Battery command
+ Support for editing via ROGCC GUI will come in future
+ This is ideal for userspace tasks
- asusd: Very basic support for running a command on AC/Battery switching, this is in config at `/etc/asusd/asusd.conf`. A restart of asusd is not required if edited.
+ This is ideal for tasks that require root access (BE SAFE!)
- The above AC/Battery commands are probably best set to run a script for more complex tasks
- asusd: check if nvidia-powerd enabled before toggling
## [v4.5.5]
### Changed
- remove an unwrap() causing panic on main ROGCC thread
## [v4.5.4]
### Changed
- ROGCC:: Allow ROGCC to run without supergfxd
- ROGCC: Tray/notifs now reads dGPU status directly via supergfx crate (supergfxd not required)
- Add rust-toolchain to force minimum rust version
## [v4.5.3]
### Changed
- Adjust how fan graph in ROGCC works, deny incorrect graphs
- Fix to apply the fan curve change in ROGCC to the correct profile
- Support for G713RS LED modes (Author: Peter Ivanov)
- Support for G713RM LED modes (Author: maxbachmann)
- Fix VivoBook detection
- Update dependencies to get latest winit crate (fixes various small issues)
## [v4.5.2] ## [v4.5.2]
### Changed ### Changed
- Update dependencies and bump version - Update dependencies and bump version
Generated
+595 -181
View File
File diff suppressed because it is too large Load Diff
+8 -8
View File
@@ -2,14 +2,14 @@
members = ["asusctl", "daemon", "daemon-user", "rog-platform", "rog-dbus", "rog-anime", "rog-aura", "rog-profiles", "rog-control-center"] members = ["asusctl", "daemon", "daemon-user", "rog-platform", "rog-dbus", "rog-anime", "rog-aura", "rog-profiles", "rog-control-center"]
[workspace.package] [workspace.package]
version = "4.5.2" version = "4.5.7"
[workspace.dependencies] [workspace.dependencies]
async-trait = "^0.1" async-trait = "^0.1"
tokio = { version = "^1.21.2", features = ["macros", "rt-multi-thread", "time", "sync"]} tokio = { version = "^1.22.0", features = ["macros", "rt-multi-thread", "time", "sync"]}
concat-idents = "^1.1" concat-idents = "^1.1"
dirs = "^4.0" dirs = "^4.0"
smol = "^1.2" smol = "^1.3"
zbus = "^3.5" zbus = "^3.5"
logind-zbus = { version = "^3.0.3" } #, default-features = false, features = ["non_blocking"] } logind-zbus = { version = "^3.0.3" } #, default-features = false, features = ["non_blocking"] }
@@ -20,19 +20,19 @@ serde_json = "^1.0"
toml = "^0.5.9" toml = "^0.5.9"
log = "^0.4" log = "^0.4"
env_logger = "^0.9.3" env_logger = "^0.10.0"
glam = { version = "^0.22", features = ["serde"] } glam = { version = "^0.22", features = ["serde"] }
gumdrop = "^0.8" gumdrop = "^0.8"
udev = "^0.6" udev = "^0.7"
rusb = "^0.9" rusb = "^0.9"
sysfs-class = "^0.1.2" sysfs-class = "^0.1.3"
inotify = "^0.10.0" inotify = "^0.10.0"
png_pong = "^0.8" png_pong = "^0.8"
pix = "^0.13" pix = "^0.13"
tinybmp = "^0.3" tinybmp = "^0.4.0"
gif = "^0.11" gif = "^0.12.0"
notify-rust = { git = "https://github.com/flukejones/notify-rust.git", default-features = false, features = ["z"] } notify-rust = { git = "https://github.com/flukejones/notify-rust.git", default-features = false, features = ["z"] }
+121
View File
@@ -0,0 +1,121 @@
# https://github.com/ericseppanen/cargo-cranky
# cargo install cargo-cranky && cargo cranky
warn = [
"clippy::all",
"clippy::await_holding_lock",
"clippy::bool_to_int_with_if",
"clippy::char_lit_as_u8",
"clippy::checked_conversions",
"clippy::dbg_macro",
"clippy::debug_assert_with_mut_call",
"clippy::disallowed_methods",
"clippy::disallowed_script_idents",
"clippy::doc_link_with_quotes",
"clippy::doc_markdown",
"clippy::empty_enum",
"clippy::enum_glob_use",
"clippy::equatable_if_let",
"clippy::exit",
"clippy::expl_impl_clone_on_copy",
"clippy::explicit_deref_methods",
"clippy::explicit_into_iter_loop",
"clippy::explicit_iter_loop",
"clippy::fallible_impl_from",
"clippy::filter_map_next",
"clippy::flat_map_option",
"clippy::float_cmp_const",
"clippy::fn_params_excessive_bools",
"clippy::fn_to_numeric_cast_any",
"clippy::from_iter_instead_of_collect",
"clippy::if_let_mutex",
"clippy::implicit_clone",
"clippy::imprecise_flops",
"clippy::index_refutable_slice",
"clippy::inefficient_to_string",
"clippy::invalid_upcast_comparisons",
"clippy::iter_not_returning_iterator",
"clippy::iter_on_empty_collections",
"clippy::iter_on_single_items",
"clippy::large_digit_groups",
"clippy::large_stack_arrays",
"clippy::large_types_passed_by_value",
"clippy::let_unit_value",
"clippy::linkedlist",
"clippy::lossy_float_literal",
"clippy::macro_use_imports",
"clippy::manual_assert",
"clippy::manual_instant_elapsed",
"clippy::manual_ok_or",
"clippy::manual_string_new",
"clippy::map_err_ignore",
"clippy::map_flatten",
"clippy::map_unwrap_or",
"clippy::match_on_vec_items",
"clippy::match_same_arms",
"clippy::match_wild_err_arm",
"clippy::match_wildcard_for_single_variants",
"clippy::mem_forget",
"clippy::mismatched_target_os",
"clippy::mismatching_type_param_order",
"clippy::missing_enforced_import_renames",
# "clippy::missing_errors_doc",
"clippy::missing_safety_doc",
"clippy::mut_mut",
"clippy::mutex_integer",
"clippy::needless_borrow",
"clippy::needless_continue",
"clippy::needless_for_each",
"clippy::needless_pass_by_value",
"clippy::negative_feature_names",
"clippy::nonstandard_macro_braces",
"clippy::option_option",
"clippy::path_buf_push_overwrite",
"clippy::ptr_as_ptr",
"clippy::rc_mutex",
"clippy::ref_option_ref",
"clippy::rest_pat_in_fully_bound_structs",
"clippy::same_functions_in_if_condition",
"clippy::semicolon_if_nothing_returned",
"clippy::single_match_else",
"clippy::str_to_string",
"clippy::string_add_assign",
"clippy::string_add",
"clippy::string_lit_as_bytes",
"clippy::string_to_string",
"clippy::todo",
"clippy::trailing_empty_array",
"clippy::trait_duplication_in_bounds",
"clippy::unimplemented",
"clippy::unnecessary_wraps",
"clippy::unnested_or_patterns",
"clippy::unused_peekable",
"clippy::unused_rounding",
# "clippy::unused_self",
"clippy::useless_transmute",
"clippy::verbose_file_reads",
"clippy::zero_sized_map_values",
"elided_lifetimes_in_paths",
"future_incompatible",
"nonstandard_style",
"rust_2018_idioms",
"rust_2021_prelude_collisions",
"rustdoc::missing_crate_level_docs",
"semicolon_in_expressions_from_macros",
"trivial_numeric_casts",
"unused_extern_crates",
"unused_import_braces",
"unused_lifetimes",
]
allow = [
# TODO(emilk): enable more lints
"clippy::cloned_instead_of_copied",
"clippy::derive_partial_eq_without_eq",
"clippy::type_complexity",
"clippy::undocumented_unsafe_blocks",
"trivial_casts",
"unsafe_op_in_unsafe_fn", # `unsafe_op_in_unsafe_fn` may become the default in future Rust versions: https://github.com/rust-lang/rust/issues/71668
"unused_qualifications",
]
+1 -1
View File
@@ -1,4 +1,4 @@
VERSION := $(shell grep -Pm1 'version = "(\d.\d.\d)"' daemon/Cargo.toml | cut -d'"' -f2) VERSION := $(shell /usr/bin/grep -Pm1 'version = "(\d.\d.\d)"' Cargo.toml | cut -d'"' -f2)
INSTALL = install INSTALL = install
INSTALL_PROGRAM = ${INSTALL} -D -m 0755 INSTALL_PROGRAM = ${INSTALL} -D -m 0755
+1
View File
@@ -1,5 +1,6 @@
[package] [package]
name = "asusctl" name = "asusctl"
license = "MPL-2.0"
authors = ["Luke D Jones <luke@ljones.dev>"] authors = ["Luke D Jones <luke@ljones.dev>"]
edition = "2021" edition = "2021"
version.workspace = true version.workspace = true
+1 -1
View File
@@ -20,7 +20,7 @@ fn main() {
} }
for c in (0..35).into_iter().step_by(step) { for c in (0..35).into_iter().step_by(step) {
for i in matrix.get_mut()[c].iter_mut() { for i in &mut matrix.get_mut()[c] {
*i = 50; *i = 50;
} }
} }
-1
View File
@@ -17,7 +17,6 @@ fn main() {
for (y, row) in tmp.iter_mut().enumerate() { for (y, row) in tmp.iter_mut().enumerate() {
if y % 2 == 0 && i + 1 != row.len() - 1 { if y % 2 == 0 && i + 1 != row.len() - 1 {
i += 1; i += 1;
dbg!(i);
} }
row[row.len() - i] = 0x22; row[row.len() - i] = 0x22;
if i > 5 { if i > 5 {
+1 -1
View File
@@ -35,7 +35,7 @@ fn main() -> Result<(), Box<dyn Error>> {
loop { loop {
matrix.angle += 0.05; matrix.angle += 0.05;
if matrix.angle > PI * 2.0 { if matrix.angle > PI * 2.0 {
matrix.angle = 0.0 matrix.angle = 0.0;
} }
matrix.update(); matrix.update();
+3 -3
View File
@@ -6,17 +6,17 @@ use rog_aura::{
KeyColourArray, KeyColourArray,
}; };
use rog_dbus::RogDbusClientBlocking; use rog_dbus::RogDbusClientBlocking;
use std::collections::LinkedList; use std::collections::VecDeque;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct Ball { struct Ball {
position: (f32, f32), position: (f32, f32),
direction: (f32, f32), direction: (f32, f32),
trail: LinkedList<(f32, f32)>, trail: VecDeque<(f32, f32)>,
} }
impl Ball { impl Ball {
fn new(x: f32, y: f32, trail_len: u32) -> Self { fn new(x: f32, y: f32, trail_len: u32) -> Self {
let mut trail = LinkedList::new(); let mut trail = VecDeque::new();
for _ in 1..=trail_len { for _ in 1..=trail_len {
trail.push_back((x, y)); trail.push_back((x, y));
} }
+1 -1
View File
@@ -105,7 +105,7 @@ impl ToString for LedBrightness {
Some(0x02) => "high", Some(0x02) => "high",
_ => "unknown", _ => "unknown",
}; };
s.to_string() s.to_owned()
} }
} }
+29 -34
View File
@@ -26,7 +26,7 @@ mod aura_cli;
mod cli_opts; mod cli_opts;
mod profiles_cli; mod profiles_cli;
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() {
let args: Vec<String> = args().skip(1).collect(); let args: Vec<String> = args().skip(1).collect();
let missing_argument_k = gumdrop::Error::missing_argument(Opt::Short('k')); let missing_argument_k = gumdrop::Error::missing_argument(Opt::Short('k'));
@@ -44,7 +44,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let (dbus, _) = RogDbusClientBlocking::new() let (dbus, _) = RogDbusClientBlocking::new()
.map_err(|e| { .map_err(|e| {
print_error_help(Box::new(e), None); print_error_help(&e, None);
std::process::exit(3); std::process::exit(3);
}) })
.unwrap(); .unwrap();
@@ -54,7 +54,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.supported() .supported()
.supported_functions() .supported_functions()
.map_err(|e| { .map_err(|e| {
print_error_help(Box::new(e), None); print_error_help(&e, None);
std::process::exit(4); std::process::exit(4);
}) })
.unwrap(); .unwrap();
@@ -63,17 +63,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
print_versions(); print_versions();
println!(); println!();
print_laptop_info(); print_laptop_info();
return Ok(());
} }
if let Err(err) = do_parsed(&parsed, &supported, &dbus) { if let Err(err) = do_parsed(&parsed, &supported, &dbus) {
print_error_help(err, Some(&supported)); print_error_help(&*err, Some(&supported));
} }
Ok(())
} }
fn print_error_help(err: Box<dyn std::error::Error>, supported: Option<&SupportedFunctions>) { fn print_error_help(err: &dyn std::error::Error, supported: Option<&SupportedFunctions>) {
check_service("asusd"); check_service("asusd");
println!("\nError: {}\n", err); println!("\nError: {}\n", err);
print_versions(); print_versions();
@@ -126,7 +123,7 @@ fn check_service(name: &str) -> bool {
fn do_parsed( fn do_parsed(
parsed: &CliStart, parsed: &CliStart,
supported: &SupportedFunctions, supported: &SupportedFunctions,
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
match &parsed.command { match &parsed.command {
Some(CliCommand::LedMode(mode)) => handle_led_mode(dbus, &supported.keyboard_led, mode)?, Some(CliCommand::LedMode(mode)) => handle_led_mode(dbus, &supported.keyboard_led, mode)?,
@@ -134,9 +131,9 @@ fn do_parsed(
Some(CliCommand::LedPow2(pow)) => handle_led_power2(dbus, &supported.keyboard_led, pow)?, Some(CliCommand::LedPow2(pow)) => handle_led_power2(dbus, &supported.keyboard_led, pow)?,
Some(CliCommand::Profile(cmd)) => handle_profile(dbus, &supported.platform_profile, cmd)?, Some(CliCommand::Profile(cmd)) => handle_profile(dbus, &supported.platform_profile, cmd)?,
Some(CliCommand::FanCurve(cmd)) => { Some(CliCommand::FanCurve(cmd)) => {
handle_fan_curve(dbus, &supported.platform_profile, cmd)? handle_fan_curve(dbus, &supported.platform_profile, cmd)?;
} }
Some(CliCommand::Graphics(_)) => do_gfx()?, Some(CliCommand::Graphics(_)) => do_gfx(),
Some(CliCommand::Anime(cmd)) => handle_anime(dbus, &supported.anime_ctrl, cmd)?, Some(CliCommand::Anime(cmd)) => handle_anime(dbus, &supported.anime_ctrl, cmd)?,
Some(CliCommand::Bios(cmd)) => handle_bios_option(dbus, &supported.rog_bios_ctrl, cmd)?, Some(CliCommand::Bios(cmd)) => handle_bios_option(dbus, &supported.rog_bios_ctrl, cmd)?,
None => { None => {
@@ -150,7 +147,7 @@ fn do_parsed(
println!("{}", CliStart::usage()); println!("{}", CliStart::usage());
println!(); println!();
if let Some(cmdlist) = CliStart::command_list() { if let Some(cmdlist) = CliStart::command_list() {
let commands: Vec<String> = cmdlist.lines().map(|s| s.to_string()).collect(); let commands: Vec<String> = cmdlist.lines().map(|s| s.to_owned()).collect();
for command in commands.iter().filter(|command| { for command in commands.iter().filter(|command| {
if !matches!( if !matches!(
supported.keyboard_led.prod_id, supported.keyboard_led.prod_id,
@@ -214,14 +211,13 @@ fn do_parsed(
Ok(()) Ok(())
} }
fn do_gfx() -> Result<(), Box<dyn std::error::Error>> { fn do_gfx() {
println!("Please use supergfxctl for graphics switching. supergfxctl is the result of making asusctl graphics switching generic so all laptops can use it"); println!("Please use supergfxctl for graphics switching. supergfxctl is the result of making asusctl graphics switching generic so all laptops can use it");
println!("This command will be removed in future"); println!("This command will be removed in future");
Ok(())
} }
fn handle_anime( fn handle_anime(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
_supported: &AnimeSupportedFunctions, _supported: &AnimeSupportedFunctions,
cmd: &AnimeCommand, cmd: &AnimeCommand,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -237,14 +233,14 @@ fn handle_anime(
} }
} }
if let Some(anime_turn) = cmd.enable { if let Some(anime_turn) = cmd.enable {
dbus.proxies().anime().set_on_off(anime_turn)? dbus.proxies().anime().set_on_off(anime_turn)?;
} }
if let Some(anime_boot) = cmd.boot_enable { if let Some(anime_boot) = cmd.boot_enable {
dbus.proxies().anime().set_boot_on_off(anime_boot)? dbus.proxies().anime().set_boot_on_off(anime_boot)?;
} }
if let Some(bright) = cmd.brightness { if let Some(bright) = cmd.brightness {
verify_brightness(bright); verify_brightness(bright);
dbus.proxies().anime().set_brightness(bright)? dbus.proxies().anime().set_brightness(bright)?;
} }
if cmd.clear { if cmd.clear {
let anime_type = get_anime_type()?; let anime_type = get_anime_type()?;
@@ -381,7 +377,7 @@ fn verify_brightness(brightness: f32) {
} }
fn handle_led_mode( fn handle_led_mode(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
supported: &LedSupportedFunctions, supported: &LedSupportedFunctions,
mode: &LedModeCommand, mode: &LedModeCommand,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -438,7 +434,7 @@ fn handle_led_mode(
} }
fn handle_led_power1( fn handle_led_power1(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
supported: &LedSupportedFunctions, supported: &LedSupportedFunctions,
power: &LedPowerCommand1, power: &LedPowerCommand1,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -473,7 +469,7 @@ fn handle_led_power1(
} }
fn handle_led_power_1_do_1866( fn handle_led_power_1_do_1866(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
power: &LedPowerCommand1, power: &LedPowerCommand1,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let mut enabled: Vec<AuraDev1866> = Vec::new(); let mut enabled: Vec<AuraDev1866> = Vec::new();
@@ -513,7 +509,7 @@ fn handle_led_power_1_do_1866(
} }
fn handle_led_power_1_do_tuf( fn handle_led_power_1_do_tuf(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
power: &LedPowerCommand1, power: &LedPowerCommand1,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let mut enabled: Vec<AuraDevTuf> = Vec::new(); let mut enabled: Vec<AuraDevTuf> = Vec::new();
@@ -552,7 +548,7 @@ fn handle_led_power_1_do_tuf(
} }
fn handle_led_power2( fn handle_led_power2(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
supported: &LedSupportedFunctions, supported: &LedSupportedFunctions,
power: &LedPowerCommand2, power: &LedPowerCommand2,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -564,8 +560,8 @@ fn handle_led_power2(
println!("Commands available"); println!("Commands available");
if let Some(cmdlist) = LedPowerCommand2::command_list() { if let Some(cmdlist) = LedPowerCommand2::command_list() {
let commands: Vec<String> = cmdlist.lines().map(|s| s.to_string()).collect(); let commands: Vec<String> = cmdlist.lines().map(|s| s.to_owned()).collect();
for command in commands.iter() { for command in &commands {
println!("{}", command); println!("{}", command);
} }
} }
@@ -581,7 +577,7 @@ fn handle_led_power2(
} }
if supported.prod_id != AuraDevice::X19B6 { if supported.prod_id != AuraDevice::X19B6 {
println!("This option applies only to keyboards with product ID 0x19b6") println!("This option applies only to keyboards with product ID 0x19b6");
} }
let mut enabled: Vec<AuraDev19b6> = Vec::new(); let mut enabled: Vec<AuraDev19b6> = Vec::new();
@@ -646,7 +642,7 @@ fn handle_led_power2(
} }
fn handle_profile( fn handle_profile(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
supported: &PlatformProfileFunctions, supported: &PlatformProfileFunctions,
cmd: &ProfileCommand, cmd: &ProfileCommand,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -675,7 +671,9 @@ fn handle_profile(
if cmd.list { if cmd.list {
let res = dbus.proxies().profile().profiles()?; let res = dbus.proxies().profile().profiles()?;
res.iter().for_each(|p| println!("{:?}", p)); for p in &res {
println!("{:?}", p);
}
} }
if cmd.profile_get { if cmd.profile_get {
@@ -687,7 +685,7 @@ fn handle_profile(
} }
fn handle_fan_curve( fn handle_fan_curve(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
supported: &PlatformProfileFunctions, supported: &PlatformProfileFunctions,
cmd: &FanCurveCommand, cmd: &FanCurveCommand,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -749,7 +747,7 @@ fn handle_fan_curve(
} }
fn handle_bios_option( fn handle_bios_option(
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
supported: &RogBiosSupportedFunctions, supported: &RogBiosSupportedFunctions,
cmd: &BiosCommand, cmd: &BiosCommand,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
@@ -764,10 +762,7 @@ fn handle_bios_option(
{ {
println!("Missing arg or command\n"); println!("Missing arg or command\n");
let usage: Vec<String> = BiosCommand::usage() let usage: Vec<String> = BiosCommand::usage().lines().map(|s| s.to_owned()).collect();
.lines()
.map(|s| s.to_string())
.collect();
for line in usage.iter().filter(|line| { for line in usage.iter().filter(|line| {
line.contains("sound") && supported.post_sound line.contains("sound") && supported.post_sound
+2 -1
View File
@@ -1,5 +1,6 @@
[package] [package]
name = "daemon-user" name = "daemon-user"
license = "MPL-2.0"
version.workspace = true version.workspace = true
authors = ["Luke D Jones <luke@ljones.dev>"] authors = ["Luke D Jones <luke@ljones.dev>"]
edition = "2021" edition = "2021"
@@ -27,4 +28,4 @@ rog_aura = { path = "../rog-aura" }
rog_dbus = { path = "../rog-dbus" } rog_dbus = { path = "../rog-dbus" }
rog_platform = { path = "../rog-platform" } rog_platform = { path = "../rog-platform" }
zbus.workspace = true zbus.workspace = true
+9 -9
View File
@@ -103,7 +103,7 @@ impl<'a> CtrlAnimeInner<'static> {
.write(output) .write(output)
.map_err(|e| AnimeError::Dbus(format!("{}", e))) .map_err(|e| AnimeError::Dbus(format!("{}", e)))
.map(|_| false) .map(|_| false)
})?; });
} }
ActionData::Image(image) => { ActionData::Image(image) => {
self.client self.client
@@ -124,10 +124,10 @@ impl<'a> CtrlAnimeInner<'static> {
sleep(Duration::from_millis(1)); sleep(Duration::from_millis(1));
} }
} }
ActionData::AudioEq => {} ActionData::AudioEq
ActionData::SystemInfo => {} | ActionData::SystemInfo
ActionData::TimeDate => {} | ActionData::TimeDate
ActionData::Matrix => {} | ActionData::Matrix => {}
} }
} }
@@ -143,7 +143,7 @@ pub struct CtrlAnime<'a> {
inner_early_return: Arc<AtomicBool>, inner_early_return: Arc<AtomicBool>,
} }
impl<'a> CtrlAnime<'static> { impl CtrlAnime<'static> {
pub fn new( pub fn new(
config: Arc<Mutex<UserAnimeConfig>>, config: Arc<Mutex<UserAnimeConfig>>,
inner: Arc<Mutex<CtrlAnimeInner<'static>>>, inner: Arc<Mutex<CtrlAnimeInner<'static>>>,
@@ -185,7 +185,7 @@ impl CtrlAnime<'static> {
pub fn insert_asus_gif( pub fn insert_asus_gif(
&mut self, &mut self,
index: u32, index: u32,
file: String, file: &str,
time: Timer, time: Timer,
brightness: f32, brightness: f32,
) -> zbus::fdo::Result<String> { ) -> zbus::fdo::Result<String> {
@@ -223,7 +223,7 @@ impl CtrlAnime<'static> {
pub fn insert_image_gif( pub fn insert_image_gif(
&mut self, &mut self,
index: u32, index: u32,
file: String, file: &str,
scale: f32, scale: f32,
angle: f32, angle: f32,
xy: (f32, f32), xy: (f32, f32),
@@ -269,7 +269,7 @@ impl CtrlAnime<'static> {
pub fn insert_image( pub fn insert_image(
&mut self, &mut self,
index: u32, index: u32,
file: String, file: &str,
scale: f32, scale: f32,
angle: f32, angle: f32,
xy: (f32, f32), xy: (f32, f32),
+1 -1
View File
@@ -13,7 +13,7 @@ pub enum Error {
impl fmt::Display for Error { impl fmt::Display for Error {
// This trait requires `fmt` with this exact signature. // This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Error::Io(err) => write!(f, "Failed to open: {}", err), Error::Io(err) => write!(f, "Failed to open: {}", err),
Error::ConfigLoadFail => write!(f, "Failed to load user config"), Error::ConfigLoadFail => write!(f, "Failed to load user config"),
+4 -4
View File
@@ -114,7 +114,7 @@ impl ConfigLoadSave<UserAnimeConfig> for UserAnimeConfig {
impl Default for UserAnimeConfig { impl Default for UserAnimeConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
name: "default".to_string(), name: "default".to_owned(),
anime: vec![ anime: vec![
ActionLoader::AsusImage { ActionLoader::AsusImage {
file: "/usr/share/asusd/anime/custom/diagonal-template.png".into(), file: "/usr/share/asusd/anime/custom/diagonal-template.png".into(),
@@ -233,7 +233,7 @@ impl Default for UserAuraConfig {
seq.push(key); seq.push(key);
Self { Self {
name: "default".to_string(), name: "default".to_owned(),
aura: seq, aura: seq,
} }
} }
@@ -251,8 +251,8 @@ pub struct UserConfig {
impl UserConfig { impl UserConfig {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
active_anime: Some("anime-default".to_string()), active_anime: Some("anime-default".to_owned()),
active_aura: Some("aura-default".to_string()), active_aura: Some("aura-default".to_owned()),
} }
} }
+4 -2
View File
@@ -1,7 +1,7 @@
[package] [package]
name = "daemon" name = "daemon"
version.workspace = true
license = "MPL-2.0" license = "MPL-2.0"
version.workspace = true
readme = "README.md" readme = "README.md"
authors = ["Luke <luke@ljones.dev>"] authors = ["Luke <luke@ljones.dev>"]
repository = "https://gitlab.com/asus-linux/asus-nb-ctrl" repository = "https://gitlab.com/asus-linux/asus-nb-ctrl"
@@ -43,4 +43,6 @@ toml.workspace = true
# Device control # Device control
sysfs-class.workspace = true # used for backlight control and baord ID sysfs-class.workspace = true # used for backlight control and baord ID
concat-idents.workspace = true concat-idents.workspace = true
systemd-zbus = "*"
+27 -3
View File
@@ -7,11 +7,12 @@ use std::path::PathBuf;
pub static CONFIG_PATH: &str = "/etc/asusd/asusd.conf"; pub static CONFIG_PATH: &str = "/etc/asusd/asusd.conf";
#[derive(Deserialize, Serialize, Default)] #[derive(Deserialize, Serialize, Default)]
#[serde(default)]
pub struct Config { pub struct Config {
/// Save charge limit for restoring on boot /// Save charge limit for restoring on boot
pub bat_charge_limit: u8, pub bat_charge_limit: u8,
pub panel_od: bool, pub panel_od: bool,
pub ac_command: String,
pub bat_command: String,
} }
impl Config { impl Config {
@@ -19,6 +20,8 @@ impl Config {
Config { Config {
bat_charge_limit: 100, bat_charge_limit: 100,
panel_od: false, panel_od: false,
ac_command: String::new(),
bat_command: String::new(),
} }
} }
@@ -37,12 +40,14 @@ impl Config {
config = Self::new(); config = Self::new();
} else if let Ok(data) = serde_json::from_str(&buf) { } else if let Ok(data) = serde_json::from_str(&buf) {
config = data; config = data;
} else if let Ok(data) = serde_json::from_str::<Config455>(&buf) {
config = data.into();
} else { } else {
warn!( warn!(
"Could not deserialise {}.\nWill rename to {}-old and recreate config", "Could not deserialise {}.\nWill rename to {}-old and recreate config",
CONFIG_PATH, CONFIG_PATH CONFIG_PATH, CONFIG_PATH
); );
let cfg_old = CONFIG_PATH.to_string() + "-old"; let cfg_old = CONFIG_PATH.to_owned() + "-old";
std::fs::rename(CONFIG_PATH, cfg_old).unwrap_or_else(|err| { std::fs::rename(CONFIG_PATH, cfg_old).unwrap_or_else(|err| {
panic!( panic!(
"Could not rename. Please remove {} then restart service: Error {}", "Could not rename. Please remove {} then restart service: Error {}",
@@ -52,7 +57,7 @@ impl Config {
config = Self::new(); config = Self::new();
} }
} else { } else {
config = Self::new() config = Self::new();
} }
config.write(); config.write();
config config
@@ -81,3 +86,22 @@ impl Config {
.unwrap_or_else(|err| error!("Could not write config: {}", err)); .unwrap_or_else(|err| error!("Could not write config: {}", err));
} }
} }
#[derive(Deserialize, Serialize, Default)]
#[serde(default)]
pub struct Config455 {
/// Save charge limit for restoring on boot
pub bat_charge_limit: u8,
pub panel_od: bool,
}
impl From<Config455> for Config {
fn from(c: Config455) -> Self {
Self {
bat_charge_limit: c.bat_charge_limit,
panel_od: c.panel_od,
ac_command: String::new(),
bat_command: String::new(),
}
}
}
+4 -4
View File
@@ -86,25 +86,25 @@ impl AnimeConfigCached {
anime_type: AnimeType, anime_type: AnimeType,
) -> Result<(), AnimeError> { ) -> Result<(), AnimeError> {
let mut sys = Vec::with_capacity(config.system.len()); let mut sys = Vec::with_capacity(config.system.len());
for ani in config.system.iter() { for ani in &config.system {
sys.push(ActionData::from_anime_action(anime_type, ani)?); sys.push(ActionData::from_anime_action(anime_type, ani)?);
} }
self.system = sys; self.system = sys;
let mut boot = Vec::with_capacity(config.boot.len()); let mut boot = Vec::with_capacity(config.boot.len());
for ani in config.boot.iter() { for ani in &config.boot {
boot.push(ActionData::from_anime_action(anime_type, ani)?); boot.push(ActionData::from_anime_action(anime_type, ani)?);
} }
self.boot = boot; self.boot = boot;
let mut wake = Vec::with_capacity(config.wake.len()); let mut wake = Vec::with_capacity(config.wake.len());
for ani in config.wake.iter() { for ani in &config.wake {
wake.push(ActionData::from_anime_action(anime_type, ani)?); wake.push(ActionData::from_anime_action(anime_type, ani)?);
} }
self.wake = wake; self.wake = wake;
let mut shutdown = Vec::with_capacity(config.shutdown.len()); let mut shutdown = Vec::with_capacity(config.shutdown.len());
for ani in config.shutdown.iter() { for ani in &config.shutdown {
shutdown.push(ActionData::from_anime_action(anime_type, ani)?); shutdown.push(ActionData::from_anime_action(anime_type, ani)?);
} }
self.shutdown = shutdown; self.shutdown = shutdown;
+17 -18
View File
@@ -1,5 +1,5 @@
pub mod config; pub mod config;
/// Implements CtrlTask, Reloadable, ZbusRun /// Implements `CtrlTask`, Reloadable, `ZbusRun`
pub mod trait_impls; pub mod trait_impls;
use self::config::{AnimeConfig, AnimeConfigCached}; use self::config::{AnimeConfig, AnimeConfigCached};
@@ -62,7 +62,7 @@ impl CtrlAnime {
/// one running - so the thread uses atomics to signal run/exit. /// one running - so the thread uses atomics to signal run/exit.
/// ///
/// Because this also writes to the usb device, other write tries (display only) *must* /// Because this also writes to the usb device, other write tries (display only) *must*
/// get the mutex lock and set the thread_exit atomic. /// get the mutex lock and set the `thread_exit` atomic.
fn run_thread(inner: Arc<Mutex<CtrlAnime>>, actions: Vec<ActionData>, mut once: bool) { fn run_thread(inner: Arc<Mutex<CtrlAnime>>, actions: Vec<ActionData>, mut once: bool) {
if actions.is_empty() { if actions.is_empty() {
warn!("AniMe system actions was empty"); warn!("AniMe system actions was empty");
@@ -106,13 +106,13 @@ impl CtrlAnime {
'main: loop { 'main: loop {
thread_running.store(true, Ordering::SeqCst); thread_running.store(true, Ordering::SeqCst);
for action in actions.iter() { for action in &actions {
if thread_exit.load(Ordering::SeqCst) { if thread_exit.load(Ordering::SeqCst) {
break 'main; break 'main;
} }
match action { match action {
ActionData::Animation(frames) => { ActionData::Animation(frames) => {
if let Err(err) = rog_anime::run_animation(frames, &|frame| { rog_anime::run_animation(frames, &|frame| {
if thread_exit.load(Ordering::Acquire) { if thread_exit.load(Ordering::Acquire) {
info!("rog-anime: frame-loop was asked to exit"); info!("rog-anime: frame-loop was asked to exit");
return Ok(true); // Do safe exit return Ok(true); // Do safe exit
@@ -130,15 +130,14 @@ impl CtrlAnime {
.ok(); .ok();
false // Don't exit yet false // Don't exit yet
}) })
.map(Ok) .map_or_else(
.unwrap_or_else(|| { || {
warn!("rog_anime::run_animation:callback failed"); warn!("rog_anime::run_animation:callback failed");
Err(AnimeError::NoFrames) Err(AnimeError::NoFrames)
}) },
}) { Ok,
warn!("rog_anime::run_animation:Animation {}", err); )
break 'main; });
};
} }
ActionData::Image(image) => { ActionData::Image(image) => {
once = false; once = false;
@@ -149,10 +148,10 @@ impl CtrlAnime {
} }
} }
ActionData::Pause(duration) => sleep(*duration), ActionData::Pause(duration) => sleep(*duration),
ActionData::AudioEq => {} ActionData::AudioEq
ActionData::SystemInfo => {} | ActionData::SystemInfo
ActionData::TimeDate => {} | ActionData::TimeDate
ActionData::Matrix => {} | ActionData::Matrix => {}
} }
} }
if thread_exit.load(Ordering::SeqCst) { if thread_exit.load(Ordering::SeqCst) {
@@ -194,7 +193,7 @@ impl CtrlAnime {
*led = bright as u8; *led = bright as u8;
} }
let data = AnimePacketType::try_from(buffer)?; let data = AnimePacketType::try_from(buffer)?;
for row in data.iter() { for row in &data {
self.node.write_bytes(row)?; self.node.write_bytes(row)?;
} }
self.node.write_bytes(&pkt_for_flush())?; self.node.write_bytes(&pkt_for_flush())?;
+20 -16
View File
@@ -47,7 +47,7 @@ impl CtrlAnimeZbus {
let mut lock = self.0.lock().await; let mut lock = self.0.lock().await;
let mut bright = bright; let mut bright = bright;
if bright < 0.0 { if bright < 0.0 {
bright = 0.0 bright = 0.0;
} else if bright > 1.0 { } else if bright > 1.0 {
bright = 1.0; bright = 1.0;
} }
@@ -149,7 +149,7 @@ impl crate::CtrlTask for CtrlAnimeZbus {
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> { async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
let run_action = let run_action =
|start: bool, lock: MutexGuard<CtrlAnime>, inner: Arc<Mutex<CtrlAnime>>| { |start: bool, lock: MutexGuard<'_, CtrlAnime>, inner: Arc<Mutex<CtrlAnime>>| {
if start { if start {
info!("CtrlAnimeTask running sleep animation"); info!("CtrlAnimeTask running sleep animation");
CtrlAnime::run_thread(inner, lock.cache.shutdown.clone(), true); CtrlAnime::run_thread(inner, lock.cache.shutdown.clone(), true);
@@ -166,28 +166,32 @@ impl crate::CtrlTask for CtrlAnimeZbus {
self.create_sys_event_tasks( self.create_sys_event_tasks(
// Loop is required to try an attempt to get the mutex *without* blocking // Loop is required to try an attempt to get the mutex *without* blocking
// other threads - it is possible to end up with deadlocks otherwise. // other threads - it is possible to end up with deadlocks otherwise.
move || loop { move || {
if let Some(lock) = inner1.try_lock() { let inner1 = inner1.clone();
async move {
let lock = inner1.lock().await;
run_action(true, lock, inner1.clone()); run_action(true, lock, inner1.clone());
break;
} }
}, },
move || loop { move || {
if let Some(lock) = inner2.try_lock() { let inner2 = inner2.clone();
run_action(false, lock, inner2.clone()); async move {
break; let lock = inner2.lock().await;
run_action(true, lock, inner2.clone());
} }
}, },
move || loop { move || {
if let Some(lock) = inner3.try_lock() { let inner3 = inner3.clone();
async move {
let lock = inner3.lock().await;
run_action(true, lock, inner3.clone()); run_action(true, lock, inner3.clone());
break;
} }
}, },
move || loop { move || {
if let Some(lock) = inner4.try_lock() { let inner4 = inner4.clone();
run_action(false, lock, inner4.clone()); async move {
break; let lock = inner4.lock().await;
run_action(true, lock, inner4.clone());
} }
}, },
) )
+20 -23
View File
@@ -127,7 +127,7 @@ pub struct AuraConfig {
impl Default for AuraConfig { impl Default for AuraConfig {
fn default() -> Self { fn default() -> Self {
let mut prod_id = AuraDevice::Unknown; let mut prod_id = AuraDevice::Unknown;
for prod in ASUS_KEYBOARD_DEVICES.iter() { for prod in &ASUS_KEYBOARD_DEVICES {
if HidRaw::new(prod).is_ok() { if HidRaw::new(prod).is_ok() {
prod_id = AuraDevice::from(*prod); prod_id = AuraDevice::from(*prod);
break; break;
@@ -242,7 +242,7 @@ impl AuraConfig {
colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]), colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]),
speed: Speed::Med, speed: Speed::Med,
direction: Direction::Left, direction: Direction::Left,
}) });
} }
if let Some(m) = config.multizone.as_mut() { if let Some(m) = config.multizone.as_mut() {
m.insert(*n, default); m.insert(*n, default);
@@ -287,34 +287,31 @@ impl AuraConfig {
/// Set the mode data, current mode, and if multizone enabled. /// Set the mode data, current mode, and if multizone enabled.
/// ///
/// Multipurpose, will accept AuraEffect with zones and put in the correct store. /// Multipurpose, will accept `AuraEffect` with zones and put in the correct store.
pub fn set_builtin(&mut self, effect: AuraEffect) { pub fn set_builtin(&mut self, effect: AuraEffect) {
self.current_mode = effect.mode; self.current_mode = effect.mode;
match effect.zone() { if effect.zone() == AuraZone::None {
AuraZone::None => { self.builtins.insert(*effect.mode(), effect);
self.builtins.insert(*effect.mode(), effect); self.multizone_on = false;
self.multizone_on = false; } else {
} if let Some(multi) = self.multizone.as_mut() {
_ => { if let Some(fx) = multi.get_mut(effect.mode()) {
if let Some(multi) = self.multizone.as_mut() { for fx in fx.iter_mut() {
if let Some(fx) = multi.get_mut(effect.mode()) { if fx.zone == effect.zone {
for fx in fx.iter_mut() { *fx = effect;
if fx.zone == effect.zone { return;
*fx = effect;
return;
}
} }
fx.push(effect);
} else {
multi.insert(*effect.mode(), vec![effect]);
} }
fx.push(effect);
} else { } else {
let mut tmp = BTreeMap::new(); multi.insert(*effect.mode(), vec![effect]);
tmp.insert(*effect.mode(), vec![effect]);
self.multizone = Some(tmp);
} }
self.multizone_on = true; } else {
let mut tmp = BTreeMap::new();
tmp.insert(*effect.mode(), vec![effect]);
self.multizone = Some(tmp);
} }
self.multizone_on = true;
} }
} }
+7 -7
View File
@@ -26,7 +26,7 @@ impl GetSupported for CtrlKbdLed {
let per_key_led_mode = laptop.per_key; let per_key_led_mode = laptop.per_key;
let mut prod_id = AuraDevice::Unknown; let mut prod_id = AuraDevice::Unknown;
for prod in ASUS_KEYBOARD_DEVICES.iter() { for prod in &ASUS_KEYBOARD_DEVICES {
if HidRaw::new(prod).is_ok() { if HidRaw::new(prod).is_ok() {
prod_id = AuraDevice::from(*prod); prod_id = AuraDevice::from(*prod);
break; break;
@@ -72,10 +72,10 @@ impl CtrlKbdLed {
pub fn new(supported_modes: LaptopLedData, config: AuraConfig) -> Result<Self, RogError> { pub fn new(supported_modes: LaptopLedData, config: AuraConfig) -> Result<Self, RogError> {
let mut led_prod = None; let mut led_prod = None;
let mut led_node = None; let mut led_node = None;
for prod in ASUS_KEYBOARD_DEVICES.iter() { for prod in &ASUS_KEYBOARD_DEVICES {
match HidRaw::new(prod) { match HidRaw::new(prod) {
Ok(node) => { Ok(node) => {
led_prod = Some(prod.to_string()); led_prod = Some((*prod).to_owned());
led_node = Some(node); led_node = Some(node);
info!("Looked for keyboard controller 0x{prod}: Found"); info!("Looked for keyboard controller 0x{prod}: Found");
break; break;
@@ -335,7 +335,7 @@ impl CtrlKbdLed {
colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]), colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]),
speed: Speed::Med, speed: Speed::Med,
direction: Direction::Left, direction: Direction::Left,
}) });
} }
if default.is_empty() { if default.is_empty() {
return Err(RogError::AuraEffectNotSupported); return Err(RogError::AuraEffectNotSupported);
@@ -370,7 +370,7 @@ mod tests {
// Checking to ensure set_mode errors when unsupported modes are tried // Checking to ensure set_mode errors when unsupported modes are tried
let config = AuraConfig::default(); let config = AuraConfig::default();
let supported_modes = LaptopLedData { let supported_modes = LaptopLedData {
prod_family: "".into(), prod_family: String::new(),
board_names: vec![], board_names: vec![],
standard: vec![AuraModeNum::Static], standard: vec![AuraModeNum::Static],
multizone: vec![], multizone: vec![],
@@ -432,7 +432,7 @@ mod tests {
// Checking to ensure set_mode errors when unsupported modes are tried // Checking to ensure set_mode errors when unsupported modes are tried
let config = AuraConfig::default(); let config = AuraConfig::default();
let supported_modes = LaptopLedData { let supported_modes = LaptopLedData {
prod_family: "".into(), prod_family: String::new(),
board_names: vec![], board_names: vec![],
standard: vec![AuraModeNum::Static], standard: vec![AuraModeNum::Static],
multizone: vec![], multizone: vec![],
@@ -470,7 +470,7 @@ mod tests {
// Checking to ensure set_mode errors when unsupported modes are tried // Checking to ensure set_mode errors when unsupported modes are tried
let config = AuraConfig::default(); let config = AuraConfig::default();
let supported_modes = LaptopLedData { let supported_modes = LaptopLedData {
prod_family: "".into(), prod_family: String::new(),
board_names: vec![], board_names: vec![],
standard: vec![AuraModeNum::Static], standard: vec![AuraModeNum::Static],
multizone: vec![AuraZone::Key1, AuraZone::Key2], multizone: vec![AuraZone::Key1, AuraZone::Key2],
+20 -16
View File
@@ -237,7 +237,7 @@ impl CtrlTask for CtrlKbdLedZbus {
} }
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> { async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
let load_save = |start: bool, mut lock: MutexGuard<CtrlKbdLed>| { let load_save = |start: bool, mut lock: MutexGuard<'_, CtrlKbdLed>| {
// If waking up // If waking up
if !start { if !start {
info!("CtrlKbdLedTask reloading brightness and modes"); info!("CtrlKbdLedTask reloading brightness and modes");
@@ -262,28 +262,32 @@ impl CtrlTask for CtrlKbdLedZbus {
self.create_sys_event_tasks( self.create_sys_event_tasks(
// Loop so that we do aquire the lock but also don't block other // Loop so that we do aquire the lock but also don't block other
// threads (prevents potential deadlocks) // threads (prevents potential deadlocks)
move || loop { move || {
if let Some(lock) = inner1.try_lock() { let inner1 = inner1.clone();
async move {
let lock = inner1.lock().await;
load_save(true, lock); load_save(true, lock);
break;
} }
}, },
move || loop { move || {
if let Some(lock) = inner2.try_lock() { let inner2 = inner2.clone();
async move {
let lock = inner2.lock().await;
load_save(false, lock); load_save(false, lock);
break;
} }
}, },
move || loop { move || {
if let Some(lock) = inner3.try_lock() { let inner3 = inner3.clone();
load_save(true, lock); async move {
break; let lock = inner3.lock().await;
} load_save(false, lock);
}, }
move || loop { },
if let Some(lock) = inner4.try_lock() { move || {
let inner4 = inner4.clone();
async move {
let lock = inner4.lock().await;
load_save(false, lock); load_save(false, lock);
break;
} }
}, },
) )
+15 -8
View File
@@ -319,7 +319,8 @@ impl CtrlPlatform {
task_watch_item!(panel_od platform); task_watch_item!(panel_od platform);
task_watch_item!(dgpu_disable platform); task_watch_item!(dgpu_disable platform);
task_watch_item!(egpu_enable platform); task_watch_item!(egpu_enable platform);
task_watch_item!(gpu_mux_mode platform); // NOTE: see note further below
//task_watch_item!(gpu_mux_mode platform);
} }
#[async_trait] #[async_trait]
@@ -332,10 +333,12 @@ impl CtrlTask for CtrlPlatform {
let platform1 = self.clone(); let platform1 = self.clone();
let platform2 = self.clone(); let platform2 = self.clone();
self.create_sys_event_tasks( self.create_sys_event_tasks(
move || {}, move || async { {} },
move || { move || {
info!("CtrlRogBios reloading panel_od"); let platform1 = platform1.clone();
if let Some(lock) = platform1.config.try_lock() { async move {
info!("CtrlRogBios reloading panel_od");
let lock = platform1.config.lock().await;
if platform1.platform.has_panel_od() { if platform1.platform.has_panel_od() {
platform1 platform1
.set_panel_overdrive(lock.panel_od) .set_panel_overdrive(lock.panel_od)
@@ -347,10 +350,12 @@ impl CtrlTask for CtrlPlatform {
} }
} }
}, },
move || {}, move || async { {} },
move || { move || {
info!("CtrlRogBios reloading panel_od"); let platform2 = platform2.clone();
if let Some(lock) = platform2.config.try_lock() { async move {
info!("CtrlRogBios reloading panel_od");
let lock = platform2.config.lock().await;
if platform2.platform.has_panel_od() { if platform2.platform.has_panel_od() {
platform2 platform2
.set_panel_overdrive(lock.panel_od) .set_panel_overdrive(lock.panel_od)
@@ -368,7 +373,9 @@ impl CtrlTask for CtrlPlatform {
self.watch_panel_od(signal_ctxt.clone()).await?; self.watch_panel_od(signal_ctxt.clone()).await?;
self.watch_dgpu_disable(signal_ctxt.clone()).await?; self.watch_dgpu_disable(signal_ctxt.clone()).await?;
self.watch_egpu_enable(signal_ctxt.clone()).await?; self.watch_egpu_enable(signal_ctxt.clone()).await?;
self.watch_gpu_mux_mode(signal_ctxt.clone()).await?; // NOTE: Can't have this as a watch because on a write to it, it reverts back to booted-with value
// as it does not actually change until reboot.
//self.watch_gpu_mux_mode(signal_ctxt.clone()).await?;
Ok(()) Ok(())
} }
+75 -36
View File
@@ -1,12 +1,13 @@
use crate::systemd::{do_systemd_unit_action, SystemdUnitAction};
use crate::{config::Config, error::RogError, GetSupported}; use crate::{config::Config, error::RogError, GetSupported};
use crate::{task_watch_item, CtrlTask}; use crate::{task_watch_item, CtrlTask};
use async_trait::async_trait; use async_trait::async_trait;
use log::{info, warn}; use log::{error, info, warn};
use rog_platform::power::AsusPower; use rog_platform::power::AsusPower;
use rog_platform::supported::ChargeSupportedFunctions; use rog_platform::supported::ChargeSupportedFunctions;
use std::process::Command;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use systemd_zbus::{ManagerProxy as SystemdProxy, Mode, UnitFileState};
use tokio::time::sleep; use tokio::time::sleep;
use zbus::dbus_interface; use zbus::dbus_interface;
use zbus::export::futures_util::lock::Mutex; use zbus::export::futures_util::lock::Mutex;
@@ -152,58 +153,58 @@ impl CtrlTask for CtrlPower {
} }
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> { async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
let conn = zbus::Connection::system().await?;
let sysd1 = SystemdProxy::new(&conn).await?;
let sysd2 = sysd1.clone();
let sysd3 = sysd1.clone();
let power1 = self.clone(); let power1 = self.clone();
let power2 = self.clone(); let power2 = self.clone();
self.create_sys_event_tasks( self.create_sys_event_tasks(
move || {}, move || async {},
move || { move || {
info!("CtrlCharge reloading charge limit"); let power = power1.clone();
if let Some(lock) = power1.config.try_lock() { let sysd = sysd1.clone();
power1 async move {
info!("CtrlCharge reloading charge limit");
let lock = power.config.lock().await;
power
.set(lock.bat_charge_limit) .set(lock.bat_charge_limit)
.map_err(|err| { .map_err(|err| {
warn!("CtrlCharge: set_limit {}", err); warn!("CtrlCharge: set_limit {}", err);
err err
}) })
.ok(); .ok();
}
if let Ok(value) = power1.power.get_online() { if let Ok(value) = power.power.get_online() {
let action = if value == 1 { do_nvidia_powerd_action(&sysd, value == 1).await;
SystemdUnitAction::Restart
} else {
SystemdUnitAction::Stop
};
if do_systemd_unit_action(action, NVIDIA_POWERD).is_ok() {
info!("CtrlPower task: did {action:?} on {NVIDIA_POWERD}");
} }
} }
}, },
move || {}, move || async {},
move || { move || {
info!("CtrlCharge reloading charge limit"); let power = power2.clone();
if let Some(lock) = power2.config.try_lock() { let sysd = sysd2.clone();
power2 async move {
info!("CtrlCharge reloading charge limit");
let lock = power.config.lock().await;
power
.set(lock.bat_charge_limit) .set(lock.bat_charge_limit)
.map_err(|err| { .map_err(|err| {
warn!("CtrlCharge: set_limit {}", err); warn!("CtrlCharge: set_limit {}", err);
err err
}) })
.ok(); .ok();
}
if let Ok(value) = power2.power.get_online() { if let Ok(value) = power.power.get_online() {
let action = if value == 1 { do_nvidia_powerd_action(&sysd, value == 1).await;
SystemdUnitAction::Restart
} else {
SystemdUnitAction::Stop
};
if do_systemd_unit_action(action, NVIDIA_POWERD).is_ok() {
info!("CtrlPower task: did {action:?} on {NVIDIA_POWERD}");
} }
} }
}, },
) )
.await; .await;
let config = self.config.clone();
self.watch_charge_control_end_threshold(signal_ctxt.clone()) self.watch_charge_control_end_threshold(signal_ctxt.clone())
.await?; .await?;
@@ -214,18 +215,36 @@ impl CtrlTask for CtrlPower {
if let Ok(value) = ctrl.power.get_online() { if let Ok(value) = ctrl.power.get_online() {
if online != value { if online != value {
online = value; online = value;
let action = if value == 1 { do_nvidia_powerd_action(&sysd3, value == 1).await;
SystemdUnitAction::Restart
} else {
SystemdUnitAction::Stop
};
if do_systemd_unit_action(action, NVIDIA_POWERD).is_ok() {
info!("CtrlPower task: did {action:?} on {NVIDIA_POWERD}");
}
Self::notify_mains_online(&signal_ctxt, value == 1) Self::notify_mains_online(&signal_ctxt, value == 1)
.await .await
.unwrap(); .unwrap();
let mut config = config.lock().await;
config.read();
let mut prog: Vec<&str> = Vec::new();
if value == 1 {
// AC ONLINE
prog = config.ac_command.split_whitespace().collect();
} else if value == 0 {
// BATTERY
prog = config.bat_command.split_whitespace().collect();
}
if prog.len() > 1 {
let mut cmd = Command::new(prog[0]);
for arg in prog.iter().skip(1) {
cmd.arg(*arg);
}
if let Err(e) = cmd.spawn() {
if value == 1 {
error!("AC power command error: {e}");
} else {
error!("Battery power command error: {e}");
}
}
}
} }
} }
// The inotify doesn't pick up events when the kernel changes internal value // The inotify doesn't pick up events when the kernel changes internal value
@@ -237,3 +256,23 @@ impl CtrlTask for CtrlPower {
Ok(()) Ok(())
} }
} }
async fn do_nvidia_powerd_action(proxy: &SystemdProxy<'_>, ac_on: bool) {
if let Ok(res) = proxy.get_unit_file_state(NVIDIA_POWERD).await {
if res == UnitFileState::Enabled {
if ac_on {
proxy
.stop_unit(NVIDIA_POWERD, Mode::Replace)
.await
.map_err(|e| error!("Error stopping {NVIDIA_POWERD}, {e:?}"))
.ok();
} else {
proxy
.start_unit(NVIDIA_POWERD, Mode::Replace)
.await
.map_err(|e| error!("Error stopping {NVIDIA_POWERD}, {e:?}"))
.ok();
}
}
}
}
+2 -1
View File
@@ -43,7 +43,8 @@ impl ProfileConfig {
"Could not deserialise {}.\nWill rename to {}-old and recreate config", "Could not deserialise {}.\nWill rename to {}-old and recreate config",
config_path, config_path config_path, config_path
); );
let cfg_old = config_path.clone() + "-old"; let mut cfg_old = config_path.clone();
cfg_old.push_str("-old");
std::fs::rename(config_path.clone(), cfg_old).unwrap_or_else(|err| { std::fs::rename(config_path.clone(), cfg_old).unwrap_or_else(|err| {
panic!( panic!(
"Could not rename. Please remove {} then restart service: Error {}", "Could not rename. Please remove {} then restart service: Error {}",
+1 -1
View File
@@ -1,4 +1,4 @@
pub mod config; pub mod config;
pub mod controller; pub mod controller;
/// Implements CtrlTask, Reloadable, ZbusRun /// Implements `CtrlTask`, Reloadable, `ZbusRun`
pub mod trait_impls; pub mod trait_impls;
+39 -9
View File
@@ -32,7 +32,7 @@ impl ProfileZbus {
return Ok(profiles); return Ok(profiles);
} }
Err(Error::Failed( Err(Error::Failed(
"Failed to get all profile details".to_string(), "Failed to get all profile details".to_owned(),
)) ))
} }
@@ -85,9 +85,9 @@ impl ProfileZbus {
let mut ctrl = self.0.lock().await; let mut ctrl = self.0.lock().await;
ctrl.config.read(); ctrl.config.read();
if let Some(curves) = &ctrl.config.fan_curves { if let Some(curves) = &ctrl.config.fan_curves {
return Ok(curves.get_enabled_curve_profiles().to_vec()); return Ok(curves.get_enabled_curve_profiles());
} }
Err(Error::Failed(UNSUPPORTED_MSG.to_string())) Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
} }
/// Set a profile fan curve enabled status. Will also activate a fan curve if in the /// Set a profile fan curve enabled status. Will also activate a fan curve if in the
@@ -109,7 +109,7 @@ impl ProfileZbus {
ctrl.save_config(); ctrl.save_config();
Ok(()) Ok(())
} else { } else {
Err(Error::Failed(UNSUPPORTED_MSG.to_string())) Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
} }
} }
@@ -121,7 +121,7 @@ impl ProfileZbus {
let curve = curves.get_fan_curves_for(profile); let curve = curves.get_fan_curves_for(profile);
return Ok(curve.clone()); return Ok(curve.clone());
} }
Err(Error::Failed(UNSUPPORTED_MSG.to_string())) Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
} }
/// Set the fan curve for the specified profile. /// Set the fan curve for the specified profile.
@@ -134,7 +134,7 @@ impl ProfileZbus {
.save_fan_curve(curve, profile) .save_fan_curve(curve, profile)
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?; .map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
} else { } else {
return Err(Error::Failed(UNSUPPORTED_MSG.to_string())); return Err(Error::Failed(UNSUPPORTED_MSG.to_owned()));
} }
ctrl.write_profile_curve_to_platform() ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("Profile::set_profile, {}", e)) .map_err(|e| warn!("Profile::set_profile, {}", e))
@@ -200,8 +200,36 @@ impl CtrlTask for ProfileZbus {
} }
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> { async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
// let ctrl = self.0.clone();
// let mut watch = self.0.lock().await.platform.monitor_platform_profile()?;
// let sig_ctx = signal_ctxt.clone();
// tokio::spawn(async move {
// let mut buffer = [0; 32];
// watch
// .event_stream(&mut buffer)
// .unwrap()
// .for_each(|_| async {
// let mut lock = ctrl.lock().await;
// let new_profile = Profile::get_active_profile().unwrap();
// if new_profile != lock.config.active_profile {
// lock.config.active_profile = new_profile;
// lock.write_profile_curve_to_platform().unwrap();
// lock.save_config();
// }
// Self::notify_profile(&sig_ctx, lock.config.active_profile)
// .await
// .ok();
// })
// .await;
// });
let ctrl = self.0.clone(); let ctrl = self.0.clone();
let mut watch = self.0.lock().await.platform.monitor_platform_profile()?; let mut watch = self
.0
.lock()
.await
.platform
.monitor_throttle_thermal_policy()?;
tokio::spawn(async move { tokio::spawn(async move {
let mut buffer = [0; 32]; let mut buffer = [0; 32];
@@ -210,13 +238,15 @@ impl CtrlTask for ProfileZbus {
.unwrap() .unwrap()
.for_each(|_| async { .for_each(|_| async {
let mut lock = ctrl.lock().await; let mut lock = ctrl.lock().await;
let new_profile = Profile::get_active_profile().unwrap(); let new_thermal = lock.platform.get_throttle_thermal_policy().unwrap();
let new_profile = Profile::from_throttle_thermal_policy(new_thermal);
if new_profile != lock.config.active_profile { if new_profile != lock.config.active_profile {
lock.config.active_profile = new_profile; lock.config.active_profile = new_profile;
lock.write_profile_curve_to_platform().unwrap(); lock.write_profile_curve_to_platform().unwrap();
lock.save_config(); lock.save_config();
Profile::set_profile(lock.config.active_profile).unwrap();
} }
Self::notify_profile(&signal_ctxt.clone(), lock.config.active_profile) Self::notify_profile(&signal_ctxt, lock.config.active_profile)
.await .await
.ok(); .ok();
}) })
+1 -2
View File
@@ -7,7 +7,6 @@ use std::time::Duration;
use ::zbus::export::futures_util::lock::Mutex; use ::zbus::export::futures_util::lock::Mutex;
use ::zbus::Connection; use ::zbus::Connection;
use daemon::ctrl_anime::CtrlAnime; use daemon::ctrl_anime::CtrlAnime;
use log::LevelFilter;
use log::{error, info, warn}; use log::{error, info, warn};
use tokio::time::sleep; use tokio::time::sleep;
use zbus::SignalContext; use zbus::SignalContext;
@@ -33,9 +32,9 @@ static PROFILE_CONFIG_PATH: &str = "/etc/asusd/profile.conf";
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut logger = env_logger::Builder::new(); let mut logger = env_logger::Builder::new();
logger logger
.parse_default_env()
.target(env_logger::Target::Stdout) .target(env_logger::Target::Stdout)
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args())) .format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
.filter(None, LevelFilter::Info)
.init(); .init();
let is_service = match env::var_os("IS_SERVICE") { let is_service = match env::var_os("IS_SERVICE") {
+2 -2
View File
@@ -37,7 +37,7 @@ pub enum RogError {
impl fmt::Display for RogError { impl fmt::Display for RogError {
// This trait requires `fmt` with this exact signature. // This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
RogError::ParseVendor => write!(f, "Parse gfx vendor error"), RogError::ParseVendor => write!(f, "Parse gfx vendor error"),
RogError::ParseLed => write!(f, "Parse LED error"), RogError::ParseLed => write!(f, "Parse LED error"),
@@ -51,7 +51,7 @@ impl fmt::Display for RogError {
RogError::DoTask(deets) => write!(f, "Task error: {}", deets), RogError::DoTask(deets) => write!(f, "Task error: {}", deets),
RogError::MissingFunction(deets) => write!(f, "Missing functionality: {}", deets), RogError::MissingFunction(deets) => write!(f, "Missing functionality: {}", deets),
RogError::MissingLedBrightNode(path, error) => write!(f, "Led node at {} is missing, please check you have the required patch or dkms module installed: {}", path, error), RogError::MissingLedBrightNode(path, error) => write!(f, "Led node at {} is missing, please check you have the required patch or dkms module installed: {}", path, error),
RogError::ReloadFail(deets) => write!(f, "Task error: {}", deets), RogError::ReloadFail(deets) => write!(f, "Reload error: {}", deets),
RogError::Profiles(deets) => write!(f, "Profile error: {}", deets), RogError::Profiles(deets) => write!(f, "Profile error: {}", deets),
RogError::Initramfs(detail) => write!(f, "Initiramfs error: {}", detail), RogError::Initramfs(detail) => write!(f, "Initiramfs error: {}", detail),
RogError::Modprobe(detail) => write!(f, "Modprobe error: {}", detail), RogError::Modprobe(detail) => write!(f, "Modprobe error: {}", detail),
+1 -1
View File
@@ -71,7 +71,7 @@ impl LaptopLedData {
} }
impl LedSupportFile { impl LedSupportFile {
/// Consumes the LEDModes /// Consumes the `LEDModes`
fn matcher(self, prod_family: &str, board_name: &str) -> Option<LaptopLedData> { fn matcher(self, prod_family: &str, board_name: &str) -> Option<LaptopLedData> {
for config in self.led_data { for config in self.led_data {
if prod_family.contains(&config.prod_family) { if prod_family.contains(&config.prod_family) {
+36 -14
View File
@@ -1,7 +1,7 @@
#![deny(unused_must_use)] #![deny(unused_must_use)]
/// Configuration loading, saving /// Configuration loading, saving
pub mod config; pub mod config;
/// Control of AniMe matrix display /// Control of anime matrix display
pub mod ctrl_anime; pub mod ctrl_anime;
/// Keyboard LED brightness control, RGB, and LED display modes /// Keyboard LED brightness control, RGB, and LED display modes
pub mod ctrl_aura; pub mod ctrl_aura;
@@ -14,16 +14,16 @@ pub mod ctrl_profiles;
/// Laptop matching to determine capabilities /// Laptop matching to determine capabilities
pub mod laptops; pub mod laptops;
pub mod systemd;
/// Fetch all supported functions for the laptop /// Fetch all supported functions for the laptop
pub mod ctrl_supported; pub mod ctrl_supported;
pub mod error; pub mod error;
use std::future::Future;
use crate::error::RogError; use crate::error::RogError;
use async_trait::async_trait; use async_trait::async_trait;
use log::warn; use log::{debug, warn};
use logind_zbus::manager::ManagerProxy; use logind_zbus::manager::ManagerProxy;
use zbus::{export::futures_util::StreamExt, zvariant::ObjectPath, Connection, SignalContext}; use zbus::{export::futures_util::StreamExt, zvariant::ObjectPath, Connection, SignalContext};
@@ -134,13 +134,31 @@ pub trait CtrlTask {
/// ///
/// The closures can potentially block, so execution time should be the minimal possible /// The closures can potentially block, so execution time should be the minimal possible
/// such as save a variable. /// such as save a variable.
async fn create_sys_event_tasks( async fn create_sys_event_tasks<
Fut1,
Fut2,
Fut3,
Fut4,
F1: Send + 'static,
F2: Send + 'static,
F3: Send + 'static,
F4: Send + 'static,
>(
&self, &self,
mut on_sleep: impl FnMut() + Send + 'static, mut on_sleep: F1,
mut on_wake: impl FnMut() + Send + 'static, mut on_wake: F2,
mut on_shutdown: impl FnMut() + Send + 'static, mut on_shutdown: F3,
mut on_boot: impl FnMut() + Send + 'static, mut on_boot: F4,
) { ) where
F1: FnMut() -> Fut1,
F2: FnMut() -> Fut2,
F3: FnMut() -> Fut3,
F4: FnMut() -> Fut4,
Fut1: Future<Output = ()> + Send,
Fut2: Future<Output = ()> + Send,
Fut3: Future<Output = ()> + Send,
Fut4: Future<Output = ()> + Send,
{
let connection = Connection::system() let connection = Connection::system()
.await .await
.expect("Controller could not create dbus connection"); .expect("Controller could not create dbus connection");
@@ -154,9 +172,11 @@ pub trait CtrlTask {
while let Some(event) = notif.next().await { while let Some(event) = notif.next().await {
if let Ok(args) = event.args() { if let Ok(args) = event.args() {
if args.start { if args.start {
on_sleep(); debug!("Doing on_sleep()");
on_sleep().await;
} else if !args.start() { } else if !args.start() {
on_wake(); debug!("Doing on_wake()");
on_wake().await;
} }
} }
} }
@@ -172,9 +192,11 @@ pub trait CtrlTask {
while let Some(event) = notif.next().await { while let Some(event) = notif.next().await {
if let Ok(args) = event.args() { if let Ok(args) = event.args() {
if args.start { if args.start {
on_shutdown(); debug!("Doing on_shutdown()");
on_shutdown().await;
} else if !args.start() { } else if !args.start() {
on_boot(); debug!("Doing on_boot()");
on_boot().await;
} }
} }
} }
-90
View File
@@ -1,90 +0,0 @@
use std::process::Command;
use crate::error::RogError;
/// An action for `systemctl`
#[derive(Debug, Copy, Clone)]
pub enum SystemdUnitAction {
Stop,
Start,
Restart,
}
impl From<SystemdUnitAction> for &str {
fn from(s: SystemdUnitAction) -> Self {
match s {
SystemdUnitAction::Stop => "stop",
SystemdUnitAction::Start => "start",
SystemdUnitAction::Restart => "restart",
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum SystemdUnitState {
Active,
Inactive,
}
impl From<SystemdUnitState> for &str {
fn from(s: SystemdUnitState) -> Self {
match s {
SystemdUnitState::Active => "active",
SystemdUnitState::Inactive => "inactive",
}
}
}
/// Change the state of a systemd unit. Blocks while running command.
pub fn do_systemd_unit_action(action: SystemdUnitAction, unit: &str) -> Result<(), RogError> {
let mut cmd = Command::new("systemctl");
cmd.arg(<&str>::from(action));
cmd.arg(unit);
let status = cmd
.status()
.map_err(|err| RogError::Command(format!("{:?}", cmd), err))?;
if !status.success() {
let msg = format!("systemctl {action:?} {unit} failed: {status:?}",);
return Err(RogError::SystemdUnitAction(msg));
}
Ok(())
}
/// Get systemd unit state. Blocks while command is run.
pub fn is_systemd_unit_state(state: SystemdUnitState, unit: &str) -> Result<bool, RogError> {
let mut cmd = Command::new("systemctl");
cmd.arg("is-active");
cmd.arg(unit);
let output = cmd
.output()
.map_err(|err| RogError::Command(format!("{:?}", cmd), err))?;
if output.stdout.starts_with(<&str>::from(state).as_bytes()) {
return Ok(true);
}
Ok(false)
}
/// Wait for a systemd unit to change to `state`. Checks state every 250ms for 3 seconds. Blocks while running wait.
pub fn wait_systemd_unit_state(state: SystemdUnitState, unit: &str) -> Result<(), RogError> {
let mut cmd = Command::new("systemctl");
cmd.arg("is-active");
cmd.arg(unit);
let mut count = 0;
while count <= (4 * 3) {
// 3 seconds max
let output = cmd
.output()
.map_err(|err| RogError::Command(format!("{:?}", cmd), err))?;
if output.stdout.starts_with(<&str>::from(state).as_bytes()) {
return Ok(());
}
// fine to block here, nobody doing shit now
std::thread::sleep(std::time::Duration::from_millis(250));
count += 1;
}
Err(RogError::SystemdUnitWaitTimeout(<&str>::from(state).into()))
}
+9 -2
View File
@@ -1,3 +1,10 @@
[[led_data]]
prod_family = "ASUS TUF Gaming F15"
board_names = ["FX506HC"]
standard = ["Static", "Breathe", "Strobe", "Pulse"]
multizone = []
per_key = false
[[led_data]] [[led_data]]
prod_family = "TUF" prod_family = "TUF"
board_names = ["FA507"] board_names = ["FA507"]
@@ -78,7 +85,7 @@ per_key = true
[[led_data]] [[led_data]]
prod_family = "ROG Strix" prod_family = "ROG Strix"
board_names = ["G513QE", "GX531", "G512LV", "G712LV", "G712LW", "G513IH", "G513QY", "G713QM", "G512", "G713RW"] board_names = ["G513QE", "GX531", "G512LV", "G712LV", "G712LW", "G513IH", "G513QY", "G713QM", "G512", "G713RM", "G713RW"]
standard = ["Static", "Breathe", "Strobe", "Rainbow", "Pulse"] standard = ["Static", "Breathe", "Strobe", "Rainbow", "Pulse"]
multizone = ["Key1", "Key2", "Key3", "Key4"] multizone = ["Key1", "Key2", "Key3", "Key4"]
per_key = false per_key = false
@@ -184,7 +191,7 @@ per_key = false
[[led_data]] [[led_data]]
prod_family = "ROG Strix" prod_family = "ROG Strix"
board_names = ["G513IC", "G513RC"] board_names = ["G513IC", "G513RC", "G513RM"]
standard = ["Static", "Breathe", "Strobe", "Rainbow", "Pulse"] standard = ["Static", "Breathe", "Strobe", "Rainbow", "Pulse"]
multizone = [] multizone = []
per_key = false per_key = false
+1
View File
@@ -6,6 +6,7 @@ Before=multi-user.target
[Service] [Service]
Environment=IS_SERVICE=1 Environment=IS_SERVICE=1
Environment=RUST_LOG="info"
ExecStartPre=/bin/sleep 2 ExecStartPre=/bin/sleep 2
ExecStart=/usr/bin/asusd ExecStart=/usr/bin/asusd
Restart=on-failure Restart=on-failure
+69
View File
@@ -0,0 +1,69 @@
# https://embarkstudios.github.io/cargo-deny/
targets = [
{ triple = "aarch64-apple-darwin" },
{ triple = "aarch64-linux-android" },
{ triple = "wasm32-unknown-unknown" },
{ triple = "x86_64-apple-darwin" },
{ triple = "x86_64-pc-windows-msvc" },
{ triple = "x86_64-unknown-linux-gnu" },
{ triple = "x86_64-unknown-linux-musl" },
]
[advisories]
vulnerability = "deny"
unmaintained = "warn"
yanked = "deny"
ignore = [
"RUSTSEC-2020-0071", # https://rustsec.org/advisories/RUSTSEC-2020-0071 - chrono/time: Potential segfault in the time crate
"RUSTSEC-2020-0159", # https://rustsec.org/advisories/RUSTSEC-2020-0159 - chrono/time: Potential segfault in localtime_r invocations
"RUSTSEC-2021-0127", # https://rustsec.org/advisories/RUSTSEC-2021-0127 - https://github.com/bheisler/criterion.rs/issues/534
]
[bans]
multiple-versions = "deny"
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
deny = [
{ name = "openssl" }, # prefer rustls
{ name = "openssl-sys" }, # prefer rustls
]
skip-tree = [
{ name = "criterion" }, # dev-dependency
{ name = "glium" }, # legacy crate, lots of old dependencies
{ name = "rfd" }, # example dependency
{ name = "three-d" }, # example dependency
]
[licenses]
unlicensed = "deny"
allow-osi-fsf-free = "neither"
confidence-threshold = 0.92 # We want really high confidence when inferring licenses from text
copyleft = "deny"
allow = [
"Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)
"BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd)
"BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised)
"BSL-1.0", # https://tldrlegal.com/license/boost-software-license-1.0-explained
"CC0-1.0", # https://creativecommons.org/publicdomain/zero/1.0/
"ISC", # https://tldrlegal.com/license/-isc-license
"LicenseRef-UFL-1.0", # https://tldrlegal.com/license/ubuntu-font-license,-1.0 - no official SPDX, see https://github.com/emilk/egui/issues/2321
"MIT", # https://tldrlegal.com/license/mit-license
"MPL-2.0", # https://www.mozilla.org/en-US/MPL/2.0/FAQ/ - see Q11
"OFL-1.1", # https://spdx.org/licenses/OFL-1.1.html
"OpenSSL", # https://www.openssl.org/source/license.html
"Unicode-DFS-2016", # https://spdx.org/licenses/Unicode-DFS-2016.html
"Zlib", # https://tldrlegal.com/license/zlib-libpng-license-(zlib)
]
[[licenses.clarify]]
name = "webpki"
expression = "ISC"
license-files = [{ path = "LICENSE", hash = 0x001c7e6c }]
[[licenses.clarify]]
name = "ring"
expression = "MIT AND ISC AND OpenSSL"
license-files = [{ path = "LICENSE", hash = 0xbd0eed23 }]
+4 -2
View File
@@ -1,7 +1,7 @@
[package] [package]
name = "rog_anime" name = "rog_anime"
version.workspace = true
license = "MPL-2.0" license = "MPL-2.0"
version.workspace = true
readme = "README.md" readme = "README.md"
authors = ["Luke <luke@ljones.dev>"] authors = ["Luke <luke@ljones.dev>"]
repository = "https://gitlab.com/asus-linux/asus-nb-ctrl" repository = "https://gitlab.com/asus-linux/asus-nb-ctrl"
@@ -30,4 +30,6 @@ glam.workspace = true
zbus = { workspace = true, optional = true } zbus = { workspace = true, optional = true }
sysfs-class = { workspace = true, optional = true } sysfs-class = { workspace = true, optional = true }
uhid-virt = "^0.0.5"
+6 -10
View File
@@ -47,8 +47,7 @@ impl AnimeType {
/// The width of diagonal images /// The width of diagonal images
pub fn width(&self) -> usize { pub fn width(&self) -> usize {
match self { match self {
AnimeType::GA401 => 74, AnimeType::GA401 | AnimeType::GA402 => 74,
AnimeType::GA402 => 74,
} }
} }
@@ -103,8 +102,8 @@ impl AnimeDataBuffer {
/// Create from a vector of bytes /// Create from a vector of bytes
/// ///
/// # Panics /// # Errors
/// Will panic if the vector length is not `ANIME_DATA_LEN` /// Will error if the vector length is not `ANIME_DATA_LEN`
#[inline] #[inline]
pub fn from_vec(anime: AnimeType, data: Vec<u8>) -> Result<Self> { pub fn from_vec(anime: AnimeType, data: Vec<u8>) -> Result<Self> {
if data.len() != anime.data_length() { if data.len() != anime.data_length() {
@@ -147,10 +146,7 @@ impl TryFrom<AnimeDataBuffer> for AnimePacketType {
/// This runs the animations as a blocking loop by using the `callback` to write data /// This runs the animations as a blocking loop by using the `callback` to write data
/// ///
/// If `callback` is `Ok(true)` then `run_animation` will exit the animation loop early. /// If `callback` is `Ok(true)` then `run_animation` will exit the animation loop early.
pub fn run_animation( pub fn run_animation(frames: &AnimeGif, callback: &dyn Fn(AnimeDataBuffer) -> Result<bool>) {
frames: &AnimeGif,
callback: &dyn Fn(AnimeDataBuffer) -> Result<bool>,
) -> Result<()> {
let mut count = 0; let mut count = 0;
let start = Instant::now(); let start = Instant::now();
@@ -215,9 +211,10 @@ pub fn run_animation(
} }
} }
// TODO: Log this error
if matches!(callback(output), Ok(true)) { if matches!(callback(output), Ok(true)) {
info!("rog-anime: frame-loop callback asked to exit early"); info!("rog-anime: frame-loop callback asked to exit early");
return Ok(()); return;
} }
if timed && Instant::now().duration_since(start) > run_time { if timed && Instant::now().duration_since(start) > run_time {
@@ -232,5 +229,4 @@ pub fn run_animation(
} }
} }
} }
Ok(())
} }
+18 -14
View File
@@ -52,39 +52,43 @@ impl AnimeDiagonal {
let mut matrix = AnimeDiagonal::new(anime_type, duration); let mut matrix = AnimeDiagonal::new(anime_type, duration);
match raster { match &raster {
png_pong::PngRaster::Gray8(ras) => { png_pong::PngRaster::Gray8(ras) => {
Self::pixels_from_8bit(ras, &mut matrix, bright, true) Self::pixels_from_8bit(ras, &mut matrix, bright, true);
} }
png_pong::PngRaster::Graya8(ras) => { png_pong::PngRaster::Graya8(ras) => {
Self::pixels_from_8bit(ras, &mut matrix, bright, true) Self::pixels_from_8bit(ras, &mut matrix, bright, true);
} }
png_pong::PngRaster::Rgb8(ras) => { png_pong::PngRaster::Rgb8(ras) => {
Self::pixels_from_8bit(ras, &mut matrix, bright, false) Self::pixels_from_8bit(ras, &mut matrix, bright, false);
} }
png_pong::PngRaster::Rgba8(ras) => { png_pong::PngRaster::Rgba8(ras) => {
Self::pixels_from_8bit(ras, &mut matrix, bright, false) Self::pixels_from_8bit(ras, &mut matrix, bright, false);
} }
png_pong::PngRaster::Gray16(ras) => { png_pong::PngRaster::Gray16(ras) => {
Self::pixels_from_16bit(ras, &mut matrix, bright, true) Self::pixels_from_16bit(ras, &mut matrix, bright, true);
} }
png_pong::PngRaster::Rgb16(ras) => { png_pong::PngRaster::Rgb16(ras) => {
Self::pixels_from_16bit(ras, &mut matrix, bright, false) Self::pixels_from_16bit(ras, &mut matrix, bright, false);
} }
png_pong::PngRaster::Graya16(ras) => { png_pong::PngRaster::Graya16(ras) => {
Self::pixels_from_16bit(ras, &mut matrix, bright, true) Self::pixels_from_16bit(ras, &mut matrix, bright, true);
} }
png_pong::PngRaster::Rgba16(ras) => { png_pong::PngRaster::Rgba16(ras) => {
Self::pixels_from_16bit(ras, &mut matrix, bright, false) Self::pixels_from_16bit(ras, &mut matrix, bright, false);
} }
_ => return Err(AnimeError::Format), png_pong::PngRaster::Palette(..) => return Err(AnimeError::Format),
}; };
Ok(matrix) Ok(matrix)
} }
fn pixels_from_8bit<P>(ras: pix::Raster<P>, matrix: &mut AnimeDiagonal, bright: f32, grey: bool) fn pixels_from_8bit<P>(
where ras: &pix::Raster<P>,
matrix: &mut AnimeDiagonal,
bright: f32,
grey: bool,
) where
P: pix::el::Pixel<Chan = pix::chan::Ch8>, P: pix::el::Pixel<Chan = pix::chan::Ch8>,
{ {
let width = ras.width(); let width = ras.width();
@@ -105,7 +109,7 @@ impl AnimeDiagonal {
} }
fn pixels_from_16bit<P>( fn pixels_from_16bit<P>(
ras: pix::Raster<P>, ras: &pix::Raster<P>,
matrix: &mut AnimeDiagonal, matrix: &mut AnimeDiagonal,
bright: f32, bright: f32,
grey: bool, grey: bool,
@@ -136,7 +140,7 @@ impl AnimeDiagonal {
} }
} }
/// Do conversion from the nested Vec in AnimeMatrix to the two required /// Do conversion from the nested Vec in `AnimeMatrix` to the two required
/// packets suitable for sending over USB /// packets suitable for sending over USB
fn to_ga401_packets(&self) -> Result<AnimeDataBuffer> { fn to_ga401_packets(&self) -> Result<AnimeDataBuffer> {
let mut buf = vec![0u8; AnimeType::GA401.data_length()]; let mut buf = vec![0u8; AnimeType::GA401.data_length()];
+1 -1
View File
@@ -26,7 +26,7 @@ pub enum AnimeError {
impl fmt::Display for AnimeError { impl fmt::Display for AnimeError {
#[inline] #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
AnimeError::NoFrames => write!(f, "No frames in PNG"), AnimeError::NoFrames => write!(f, "No frames in PNG"),
AnimeError::Io(e) => write!(f, "Could not open: {}", e), AnimeError::Io(e) => write!(f, "Could not open: {}", e),
+1 -1
View File
@@ -93,7 +93,7 @@ impl AnimeGrid {
impl TryFrom<AnimeGrid> for AnimeDataBuffer { impl TryFrom<AnimeGrid> for AnimeDataBuffer {
type Error = AnimeError; type Error = AnimeError;
/// Do conversion from the nested Vec in AniMeMatrix to the two required /// Do conversion from the nested Vec in anime matrix to the two required
/// packets suitable for sending over USB /// packets suitable for sending over USB
fn try_from(anime: AnimeGrid) -> Result<Self> { fn try_from(anime: AnimeGrid) -> Result<Self> {
let mut buf = vec![0u8; anime.anime_type.data_length()]; let mut buf = vec![0u8; anime.anime_type.data_length()];
+9 -9
View File
@@ -30,7 +30,7 @@ impl Default for Pixel {
/// is to be used to sample an image and set the LED brightness. /// is to be used to sample an image and set the LED brightness.
/// ///
/// The position of the Led in `LedPositions` determines the placement in the final /// The position of the Led in `LedPositions` determines the placement in the final
/// data packets when written to the AniMe. /// data packets when written to the `AniMe`.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub struct Led(f32, f32, u8); pub struct Led(f32, f32, u8);
@@ -58,7 +58,7 @@ impl Led {
/// Container of `Led`, each of which specifies a position within the image /// Container of `Led`, each of which specifies a position within the image
/// The main use of this is to position and sample colours for the final image /// The main use of this is to position and sample colours for the final image
/// to show on AniMe /// to show on `AniMe`
pub struct AnimeImage { pub struct AnimeImage {
pub scale: Vec2, pub scale: Vec2,
/// Angle in radians /// Angle in radians
@@ -294,8 +294,8 @@ impl AnimeImage {
let x0 = led_from_px.mul_vec3(pos + Vec3::new(0.0, -0.5, 0.0)); let x0 = led_from_px.mul_vec3(pos + Vec3::new(0.0, -0.5, 0.0));
const GROUP: [f32; 4] = [0.0, 0.5, 1.0, 1.5]; const GROUP: [f32; 4] = [0.0, 0.5, 1.0, 1.5];
for u in GROUP.iter() { for u in &GROUP {
for v in GROUP.iter() { for v in &GROUP {
let sample = x0 + *u * du + *v * dv; let sample = x0 + *u * du + *v * dv;
let x = sample.x as i32; let x = sample.x as i32;
@@ -399,7 +399,7 @@ impl AnimeImage {
let png_pong::Step { raster, delay: _ } = decoder.last().ok_or(AnimeError::NoFrames)??; let png_pong::Step { raster, delay: _ } = decoder.last().ok_or(AnimeError::NoFrames)??;
let width; let width;
let pixels = match raster { let pixels = match &raster {
png_pong::PngRaster::Gray8(ras) => { png_pong::PngRaster::Gray8(ras) => {
width = ras.width(); width = ras.width();
Self::pixels_from_8bit(ras, true) Self::pixels_from_8bit(ras, true)
@@ -432,7 +432,7 @@ impl AnimeImage {
width = ras.width(); width = ras.width();
Self::pixels_from_16bit(ras, false) Self::pixels_from_16bit(ras, false)
} }
_ => return Err(AnimeError::Format), png_pong::PngRaster::Palette(..) => return Err(AnimeError::Format),
}; };
let mut matrix = AnimeImage::new( let mut matrix = AnimeImage::new(
@@ -449,7 +449,7 @@ impl AnimeImage {
Ok(matrix) Ok(matrix)
} }
fn pixels_from_8bit<P>(ras: pix::Raster<P>, grey: bool) -> Vec<Pixel> fn pixels_from_8bit<P>(ras: &pix::Raster<P>, grey: bool) -> Vec<Pixel>
where where
P: pix::el::Pixel<Chan = pix::chan::Ch8>, P: pix::el::Pixel<Chan = pix::chan::Ch8>,
{ {
@@ -468,7 +468,7 @@ impl AnimeImage {
.collect() .collect()
} }
fn pixels_from_16bit<P>(ras: pix::Raster<P>, grey: bool) -> Vec<Pixel> fn pixels_from_16bit<P>(ras: &pix::Raster<P>, grey: bool) -> Vec<Pixel>
where where
P: pix::el::Pixel<Chan = pix::chan::Ch16>, P: pix::el::Pixel<Chan = pix::chan::Ch16>,
{ {
@@ -491,7 +491,7 @@ impl AnimeImage {
impl TryFrom<&AnimeImage> for AnimeDataBuffer { impl TryFrom<&AnimeImage> for AnimeDataBuffer {
type Error = AnimeError; type Error = AnimeError;
/// Do conversion from the nested Vec in AnimeDataBuffer to the two required /// Do conversion from the nested Vec in `AnimeDataBuffer` to the two required
/// packets suitable for sending over USB /// packets suitable for sending over USB
fn try_from(leds: &AnimeImage) -> Result<Self> { fn try_from(leds: &AnimeImage) -> Result<Self> {
let mut l: Vec<u8> = leds let mut l: Vec<u8> = leds
+2 -2
View File
@@ -7,11 +7,11 @@ pub use data::*;
mod grid; mod grid;
pub use grid::*; pub use grid::*;
/// Transform a PNG image for displaying on AniMe matrix display /// Transform a PNG image for displaying on `AniMe` matrix display
mod image; mod image;
pub use image::*; pub use image::*;
/// A grid of data that is intended to be read out and displayed on the ANiMe as /// A grid of data that is intended to be read out and displayed on the `AniMe` as
/// a diagonal /// a diagonal
mod diagonal; mod diagonal;
pub use diagonal::*; pub use diagonal::*;
+3 -3
View File
@@ -7,7 +7,7 @@ use crate::{
error::Result, AnimTime, AnimeDataBuffer, AnimeDiagonal, AnimeGif, AnimeImage, AnimeType, error::Result, AnimTime, AnimeDataBuffer, AnimeDiagonal, AnimeGif, AnimeImage, AnimeType,
}; };
/// All the possible AniMe actions that can be used. This enum is intended to be /// All the possible `AniMe` actions that can be used. This enum is intended to be
/// a helper for loading up `ActionData`. /// a helper for loading up `ActionData`.
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub enum ActionLoader { pub enum ActionLoader {
@@ -44,7 +44,7 @@ pub enum ActionLoader {
Pause(Duration), Pause(Duration),
} }
/// All the possible AniMe actions that can be used. The enum is intended to be /// All the possible `AniMe` actions that can be used. The enum is intended to be
/// used in a array allowing the user to cycle through a series of actions. /// used in a array allowing the user to cycle through a series of actions.
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub enum ActionData { pub enum ActionData {
@@ -194,7 +194,7 @@ impl Sequences {
None None
} }
pub fn iter(&self) -> ActionIterator { pub fn iter(&self) -> ActionIterator<'_> {
ActionIterator { ActionIterator {
actions: self, actions: self,
next_idx: 0, next_idx: 0,
+2 -2
View File
@@ -1,4 +1,4 @@
//! Utils for writing to the AniMe USB device //! Utils for writing to the `AniMe` USB device
//! //!
//! Use of the device requires a few steps: //! Use of the device requires a few steps:
//! 1. Initialise the device by writing the two packets from `get_init_packets()` //! 1. Initialise the device by writing the two packets from `get_init_packets()`
@@ -63,7 +63,7 @@ pub const fn pkt_for_flush() -> [u8; PACKET_SIZE] {
} }
/// Get the packet required for setting the device to on, on boot. Requires /// Get the packet required for setting the device to on, on boot. Requires
/// pkt_for_apply()` to be written after. /// `pkt_for_apply()` to be written after.
#[inline] #[inline]
pub const fn pkt_for_set_boot(status: bool) -> [u8; PACKET_SIZE] { pub const fn pkt_for_set_boot(status: bool) -> [u8; PACKET_SIZE] {
let mut pkt = [0; PACKET_SIZE]; let mut pkt = [0; PACKET_SIZE];
+2 -2
View File
@@ -1,7 +1,7 @@
[package] [package]
name = "rog_aura" name = "rog_aura"
version.workspace = true
license = "MPL-2.0" license = "MPL-2.0"
version.workspace = true
readme = "README.md" readme = "README.md"
authors = ["Luke <luke@ljones.dev>"] authors = ["Luke <luke@ljones.dev>"]
repository = "https://gitlab.com/asus-linux/asusctl" repository = "https://gitlab.com/asus-linux/asusctl"
@@ -23,4 +23,4 @@ toml = { workspace = true, optional = true }
zbus = { workspace = true, optional = true } zbus = { workspace = true, optional = true }
[dev-dependencies] [dev-dependencies]
serde_json.workspace = true serde_json.workspace = true
+20 -43
View File
@@ -25,7 +25,6 @@ impl From<u32> for LedBrightness {
match bright { match bright {
0 => LedBrightness::Off, 0 => LedBrightness::Off,
1 => LedBrightness::Low, 1 => LedBrightness::Low,
2 => LedBrightness::Med,
3 => LedBrightness::High, 3 => LedBrightness::High,
_ => LedBrightness::Med, _ => LedBrightness::Med,
} }
@@ -179,21 +178,7 @@ impl Display for AuraModeNum {
impl From<AuraModeNum> for String { impl From<AuraModeNum> for String {
fn from(mode: AuraModeNum) -> Self { fn from(mode: AuraModeNum) -> Self {
match mode { <&str>::from(&mode).to_owned()
AuraModeNum::Static => "Static",
AuraModeNum::Breathe => "Breathe",
AuraModeNum::Strobe => "Strobe",
AuraModeNum::Rainbow => "Rainbow",
AuraModeNum::Star => "Stars",
AuraModeNum::Rain => "Rain",
AuraModeNum::Highlight => "Highlight",
AuraModeNum::Laser => "Laser",
AuraModeNum::Ripple => "Ripple",
AuraModeNum::Pulse => "Pulse",
AuraModeNum::Comet => "Comet",
AuraModeNum::Flash => "Flash",
}
.to_string()
} }
} }
@@ -218,7 +203,6 @@ impl From<&AuraModeNum> for &str {
impl From<&str> for AuraModeNum { impl From<&str> for AuraModeNum {
fn from(mode: &str) -> Self { fn from(mode: &str) -> Self {
match mode { match mode {
"Static" => AuraModeNum::Static,
"Breathe" => AuraModeNum::Breathe, "Breathe" => AuraModeNum::Breathe,
"Strobe" => AuraModeNum::Strobe, "Strobe" => AuraModeNum::Strobe,
"Rainbow" => AuraModeNum::Rainbow, "Rainbow" => AuraModeNum::Rainbow,
@@ -238,7 +222,6 @@ impl From<&str> for AuraModeNum {
impl From<u8> for AuraModeNum { impl From<u8> for AuraModeNum {
fn from(mode: u8) -> Self { fn from(mode: u8) -> Self {
match mode { match mode {
0 => AuraModeNum::Static,
1 => AuraModeNum::Breathe, 1 => AuraModeNum::Breathe,
2 => AuraModeNum::Strobe, 2 => AuraModeNum::Strobe,
3 => AuraModeNum::Rainbow, 3 => AuraModeNum::Rainbow,
@@ -284,22 +267,14 @@ impl FromStr for AuraZone {
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_lowercase(); let s = s.to_lowercase();
match s.to_ascii_lowercase().as_str() { match s.to_ascii_lowercase().as_str() {
"0" => Ok(AuraZone::None), "0" | "none" => Ok(AuraZone::None),
"none" => Ok(AuraZone::None), "1" | "one" => Ok(AuraZone::Key1),
"1" => Ok(AuraZone::Key1), "2" | "two" => Ok(AuraZone::Key2),
"one" => Ok(AuraZone::Key1), "3" | "three" => Ok(AuraZone::Key3),
"2" => Ok(AuraZone::Key2), "4" | "four" => Ok(AuraZone::Key4),
"two" => Ok(AuraZone::Key2), "5" | "logo" => Ok(AuraZone::Logo),
"3" => Ok(AuraZone::Key3), "6" | "lightbar-left" => Ok(AuraZone::BarLeft),
"three" => Ok(AuraZone::Key3), "7" | "lightbar-right" => Ok(AuraZone::BarRight),
"4" => Ok(AuraZone::Key4),
"four" => Ok(AuraZone::Key4),
"5" => Ok(AuraZone::Logo),
"logo" => Ok(AuraZone::Logo),
"6" => Ok(AuraZone::BarLeft),
"lightbar-left" => Ok(AuraZone::BarLeft),
"7" => Ok(AuraZone::BarRight),
"lightbar-right" => Ok(AuraZone::BarRight),
_ => Err(Error::ParseSpeed), _ => Err(Error::ParseSpeed),
} }
} }
@@ -395,18 +370,20 @@ impl AuraEffect {
/// factory mode accepts only one colour. /// factory mode accepts only one colour.
pub const fn allowed_parameters(mode: AuraModeNum) -> AuraParameters { pub const fn allowed_parameters(mode: AuraModeNum) -> AuraParameters {
match mode { match mode {
AuraModeNum::Static => AuraParameters::new(true, true, false, false, false), AuraModeNum::Static
| AuraModeNum::Highlight
| AuraModeNum::Pulse
| AuraModeNum::Comet
| AuraModeNum::Flash => AuraParameters::new(true, true, false, false, false),
AuraModeNum::Breathe => AuraParameters::new(true, true, true, true, false), AuraModeNum::Breathe => AuraParameters::new(true, true, true, true, false),
AuraModeNum::Strobe => AuraParameters::new(true, false, false, true, false), AuraModeNum::Strobe | AuraModeNum::Rain => {
AuraParameters::new(true, false, false, true, false)
}
AuraModeNum::Rainbow => AuraParameters::new(true, false, false, true, true), AuraModeNum::Rainbow => AuraParameters::new(true, false, false, true, true),
AuraModeNum::Star => AuraParameters::new(true, true, true, true, true), AuraModeNum::Star => AuraParameters::new(true, true, true, true, true),
AuraModeNum::Rain => AuraParameters::new(true, false, false, true, false), AuraModeNum::Laser | AuraModeNum::Ripple => {
AuraModeNum::Highlight => AuraParameters::new(true, true, false, false, false), AuraParameters::new(true, true, false, true, false)
AuraModeNum::Laser => AuraParameters::new(true, true, false, true, false), }
AuraModeNum::Ripple => AuraParameters::new(true, true, false, true, false),
AuraModeNum::Pulse => AuraParameters::new(true, true, false, false, false),
AuraModeNum::Comet => AuraParameters::new(true, true, false, false, false),
AuraModeNum::Flash => AuraParameters::new(true, true, false, false, false),
} }
} }
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub enum Error {
impl fmt::Display for Error { impl fmt::Display for Error {
// This trait requires `fmt` with this exact signature. // This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Error::ParseColour => write!(f, "Could not parse colour"), Error::ParseColour => write!(f, "Could not parse colour"),
Error::ParseSpeed => write!(f, "Could not parse speed"), Error::ParseSpeed => write!(f, "Could not parse speed"),
+11 -11
View File
@@ -139,17 +139,17 @@ impl From<&Key> for &str {
Key::MediaStop => "Media Stop", Key::MediaStop => "Media Stop",
Key::MediaNext => "Media Next", Key::MediaNext => "Media Next",
Key::MediaPrev => "Media Previous", Key::MediaPrev => "Media Previous",
Key::NormalBlank => "", Key::NormalBlank
Key::NormalSpacer => "", | Key::NormalSpacer
Key::FuncBlank => "", | Key::FuncBlank
Key::FuncSpacer => "", | Key::FuncSpacer
Key::ArrowBlank => "", | Key::ArrowBlank
Key::ArrowSpacer => "", | Key::ArrowSpacer
Key::ArrowRegularBlank => "", | Key::ArrowRegularBlank
Key::ArrowRegularSpacer => "", | Key::ArrowRegularSpacer
Key::ArrowSplitBlank => "", | Key::ArrowSplitBlank
Key::ArrowSplitSpacer => "", | Key::ArrowSplitSpacer
Key::RowEndSpacer => "", | Key::RowEndSpacer => "",
} }
} }
} }
+14 -12
View File
@@ -203,17 +203,22 @@ pub enum KeyShape {
impl KeyShape { impl KeyShape {
pub const fn width(&self) -> f32 { pub const fn width(&self) -> f32 {
match self { match self {
Self::Tilde => 0.8, Self::Tilde | Self::Arrow => 0.8,
Self::Normal => 1.0, Self::Normal
Self::NormalBlank => 1.0, | Self::NormalBlank
Self::NormalSpacer => 1.0, | Self::NormalSpacer
Self::Func => 1.0, | Self::Func
Self::FuncBlank => 1.0, | Self::FuncBlank
| Self::Space5
| Self::ArrowBlank
| Self::ArrowSpacer
| Self::ArrowSplit
| Self::ArrowSplitBlank
| Self::ArrowSplitSpacer => 1.0,
Self::FuncSpacer => 0.6, Self::FuncSpacer => 0.6,
Self::Space => 5.0, Self::Space => 5.0,
Self::Space5 => 1.0,
Self::LCtrlMed => 1.1, Self::LCtrlMed => 1.1,
Self::LShift => 2.0, Self::LShift | Self::Backspace => 2.0,
Self::LShift3 => 0.67, Self::LShift3 => 0.67,
Self::RShift => 2.8, Self::RShift => 2.8,
Self::RshiftSmall => 1.8, Self::RshiftSmall => 1.8,
@@ -222,12 +227,9 @@ impl KeyShape {
Self::Return3 => 0.7333, Self::Return3 => 0.7333,
Self::Tab => 1.4, Self::Tab => 1.4,
Self::Caps => 1.6, Self::Caps => 1.6,
Self::Backspace => 2.0,
Self::Backspace3 => 0.666, Self::Backspace3 => 0.666,
Self::ArrowRegularBlank | Self::ArrowRegularSpacer => 0.7, Self::ArrowRegularBlank | Self::ArrowRegularSpacer => 0.7,
Self::Arrow => 0.8,
Self::ArrowBlank | Self::ArrowSpacer => 1.0,
Self::ArrowSplit | Self::ArrowSplitBlank | Self::ArrowSplitSpacer => 1.0,
Self::RowEndSpacer => 0.1, Self::RowEndSpacer => 0.1,
} }
} }
+1 -1
View File
@@ -6,7 +6,7 @@ impl KeyLayout {
pub fn g513_layout() -> Self { pub fn g513_layout() -> Self {
Self { Self {
matches: vec!["G513".into()], matches: vec!["G513".into()],
locale: "US".to_string(), locale: "US".to_owned(),
rows: vec![ rows: vec![
KeyRow::new( KeyRow::new(
0.8, 0.8,
+1 -1
View File
@@ -5,7 +5,7 @@ impl KeyLayout {
pub fn ga401_layout() -> Self { pub fn ga401_layout() -> Self {
Self { Self {
matches: vec!["GA401".into(), "GA402".into()], matches: vec!["GA401".into(), "GA402".into()],
locale: "US".to_string(), locale: "US".to_owned(),
rows: vec![ rows: vec![
KeyRow::new( KeyRow::new(
0.8, 0.8,
+1 -1
View File
@@ -5,7 +5,7 @@ impl KeyLayout {
pub fn gx502_layout() -> Self { pub fn gx502_layout() -> Self {
Self { Self {
matches: vec!["GX502".into(), "GU502".into()], matches: vec!["GX502".into(), "GU502".into()],
locale: "US".to_string(), locale: "US".to_owned(),
rows: vec![ rows: vec![
KeyRow::new( KeyRow::new(
0.8, 0.8,
+2 -2
View File
@@ -43,7 +43,7 @@ impl KeyLayout {
pub fn matches(&self, board_name: &str) -> bool { pub fn matches(&self, board_name: &str) -> bool {
let board = board_name.to_ascii_uppercase(); let board = board_name.to_ascii_uppercase();
for tmp in self.matches.iter() { for tmp in &self.matches {
if board.contains(tmp.as_str()) { if board.contains(tmp.as_str()) {
return true; return true;
} }
@@ -91,7 +91,7 @@ impl KeyRow {
Self { height, row } Self { height, row }
} }
pub fn row(&self) -> Iter<Key> { pub fn row(&self) -> Iter<'_, Key> {
self.row.iter() self.row.iter()
} }
+1 -2
View File
@@ -43,8 +43,7 @@ impl ZonedColourArray {
pub fn rgb_for_zone(&mut self, zone: PerZone) -> &mut [u8] { pub fn rgb_for_zone(&mut self, zone: PerZone) -> &mut [u8] {
match zone { match zone {
PerZone::None => &mut self.0[9..=11], PerZone::None | PerZone::KeyboardLeft => &mut self.0[9..=11],
PerZone::KeyboardLeft => &mut self.0[9..=11],
PerZone::KeyboardCenterLeft => &mut self.0[12..=14], PerZone::KeyboardCenterLeft => &mut self.0[12..=14],
PerZone::KeyboardCenterRight => &mut self.0[15..=17], PerZone::KeyboardCenterRight => &mut self.0[15..=17],
PerZone::KeyboardRight => &mut self.0[18..=20], PerZone::KeyboardRight => &mut self.0[18..=20],
+3 -3
View File
@@ -9,7 +9,7 @@ use serde_derive::{Deserialize, Serialize};
// static mut RNDINDEX: usize = 0; // static mut RNDINDEX: usize = 0;
static mut PRNDINDEX: usize = 0; static mut PRNDINDEX: usize = 0;
/// Pseudo random table ripped straight out of Room4Doom /// Pseudo random table ripped straight out of room4doom
pub const RNDTABLE: [i32; 256] = [ pub const RNDTABLE: [i32; 256] = [
0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66, 74, 21, 211, 47, 80, 242, 154, 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66, 74, 21, 211, 47, 80, 242, 154,
27, 205, 128, 161, 89, 77, 36, 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188, 27, 205, 128, 161, 89, 77, 36, 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188,
@@ -88,7 +88,7 @@ impl Sequences {
} }
pub fn next_state(&mut self, layout: &KeyLayout) { pub fn next_state(&mut self, layout: &KeyLayout) {
for effect in self.0.iter_mut() { for effect in &mut self.0 {
effect.next_state(layout); effect.next_state(layout);
} }
} }
@@ -97,7 +97,7 @@ impl Sequences {
let mut keys = KeyColourArray::new(); let mut keys = KeyColourArray::new();
let mut zones = ZonedColourArray::new(); let mut zones = ZonedColourArray::new();
let mut is_per_key = false; let mut is_per_key = false;
for effect in self.0.iter() { for effect in &self.0 {
match effect.get_led_type() { match effect.get_led_type() {
LedType::Key(key) => { LedType::Key(key) => {
is_per_key = true; is_per_key = true;
+8 -12
View File
@@ -36,14 +36,10 @@ impl From<&str> for AuraDevice {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
match s.to_lowercase().as_str() { match s.to_lowercase().as_str() {
"tuf" => AuraDevice::Tuf, "tuf" => AuraDevice::Tuf,
"1866" => AuraDevice::X1866, "1866" | "0x1866" => AuraDevice::X1866,
"1869" => AuraDevice::X1869, "1869" | "0x1869" => AuraDevice::X1869,
"1854" => AuraDevice::X1854, "1854" | "0x1854" => AuraDevice::X1854,
"19b6" => AuraDevice::X19B6, "19b6" | "0x19b6" => AuraDevice::X19B6,
"0x1866" => AuraDevice::X1866,
"0x1869" => AuraDevice::X1869,
"0x1854" => AuraDevice::X1854,
"0x19b6" => AuraDevice::X19B6,
_ => AuraDevice::Unknown, _ => AuraDevice::Unknown,
} }
} }
@@ -108,9 +104,9 @@ impl From<AuraDev1866> for u32 {
impl AuraDev1866 { impl AuraDev1866 {
pub fn to_bytes(control: &[Self]) -> [u8; 3] { pub fn to_bytes(control: &[Self]) -> [u8; 3] {
let mut a: u32 = 0; let mut a: u32 = 0;
control.iter().for_each(|n| { for n in control {
a |= *n as u32; a |= *n as u32;
}); }
[ [
((a & 0xff0000) >> 16) as u8, ((a & 0xff0000) >> 16) as u8,
((a & 0xff00) >> 8) as u8, ((a & 0xff00) >> 8) as u8,
@@ -197,9 +193,9 @@ impl From<AuraDev19b6> for u32 {
impl AuraDev19b6 { impl AuraDev19b6 {
pub fn to_bytes(control: &[Self]) -> [u8; 3] { pub fn to_bytes(control: &[Self]) -> [u8; 3] {
let mut a: u32 = 0; let mut a: u32 = 0;
control.iter().for_each(|n| { for n in control {
a |= *n as u32; a |= *n as u32;
}); }
[ [
(a & 0xff) as u8, (a & 0xff) as u8,
((a & 0xff00) >> 8) as u8, ((a & 0xff00) >> 8) as u8,
+6 -7
View File
@@ -1,5 +1,6 @@
[package] [package]
name = "rog-control-center" name = "rog-control-center"
license = "MPL-2.0"
version.workspace = true version.workspace = true
authors = ["Luke D. Jones <luke@ljones.dev>"] authors = ["Luke D. Jones <luke@ljones.dev>"]
edition = "2021" edition = "2021"
@@ -8,12 +9,11 @@ edition = "2021"
mocking = [] mocking = []
[dependencies] [dependencies]
egui = { git = "https://github.com/flukejones/egui" } egui = { git = "https://github.com/flukejones/egui", branch = "wayland_dark_theme" }
eframe= { git = "https://github.com/flukejones/egui" } eframe = { git = "https://github.com/flukejones/egui", branch = "wayland_dark_theme" }
#eframe= { git = "https://github.com/emilk/egui", default-features = false, features = ["dark-light", "default_fonts", "wgpu"] }
libappindicator = "0.7" # Tray icon libappindicator = "0.7" # Tray icon
gtk = "0.15" gtk = "0.15.5"
daemon = { path = "../daemon" } daemon = { path = "../daemon" }
rog_anime = { path = "../rog-anime" } rog_anime = { path = "../rog-anime" }
@@ -22,7 +22,6 @@ rog_aura = { path = "../rog-aura" }
rog_profiles = { path = "../rog-profiles" } rog_profiles = { path = "../rog-profiles" }
rog_platform = { path = "../rog-platform" } rog_platform = { path = "../rog-platform" }
supergfxctl = { git = "https://gitlab.com/asus-linux/supergfxctl.git", default-features = false } supergfxctl = { git = "https://gitlab.com/asus-linux/supergfxctl.git", default-features = false }
#supergfxctl = { path = "../../supergfxctl", default-features = false }
log.workspace = true log.workspace = true
env_logger.workspace = true env_logger.workspace = true
@@ -38,5 +37,5 @@ notify-rust.workspace = true
png_pong.workspace = true png_pong.workspace = true
nix = "^0.25" nix = "^0.26.1"
tempfile = "3.2.0" tempfile = "3.3.0"
+30 -3
View File
@@ -4,19 +4,20 @@ use std::{
fs::{create_dir, OpenOptions}, fs::{create_dir, OpenOptions},
io::{Read, Write}, io::{Read, Write},
}; };
//use log::{error, info, warn};
use crate::{error::Error, notify::EnabledNotifications}; use crate::{error::Error, update_and_notify::EnabledNotifications};
const CFG_DIR: &str = "rog"; const CFG_DIR: &str = "rog";
const CFG_FILE_NAME: &str = "rog-control-center.cfg"; const CFG_FILE_NAME: &str = "rog-control-center.cfg";
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Config { pub struct Config {
pub run_in_background: bool, pub run_in_background: bool,
pub startup_in_background: bool, pub startup_in_background: bool,
pub ac_command: String,
pub bat_command: String,
pub enable_notifications: bool, pub enable_notifications: bool,
// This field must be last
pub enabled_notifications: EnabledNotifications, pub enabled_notifications: EnabledNotifications,
} }
@@ -27,6 +28,8 @@ impl Default for Config {
startup_in_background: false, startup_in_background: false,
enable_notifications: true, enable_notifications: true,
enabled_notifications: EnabledNotifications::default(), enabled_notifications: EnabledNotifications::default(),
ac_command: String::new(),
bat_command: String::new(),
} }
} }
} }
@@ -67,6 +70,9 @@ impl Config {
} else if let Ok(data) = toml::from_str::<Config>(&buf) { } else if let Ok(data) = toml::from_str::<Config>(&buf) {
info!("Loaded config file {path:?}"); info!("Loaded config file {path:?}");
return Ok(data); return Ok(data);
} else if let Ok(data) = toml::from_str::<Config455>(&buf) {
info!("Loaded old v4.5.5 config file {path:?}");
return Ok(data.into());
} }
} }
Err(Error::ConfigLoadFail) Err(Error::ConfigLoadFail)
@@ -100,3 +106,24 @@ impl Config {
Ok(()) Ok(())
} }
} }
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config455 {
pub run_in_background: bool,
pub startup_in_background: bool,
pub enable_notifications: bool,
pub enabled_notifications: EnabledNotifications,
}
impl From<Config455> for Config {
fn from(c: Config455) -> Self {
Self {
run_in_background: c.run_in_background,
startup_in_background: c.startup_in_background,
enable_notifications: c.enable_notifications,
enabled_notifications: c.enabled_notifications,
ac_command: String::new(),
bat_command: String::new(),
}
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ pub enum Error {
impl fmt::Display for Error { impl fmt::Display for Error {
// This trait requires `fmt` with this exact signature. // This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Error::Io(err) => write!(f, "Failed to open: {}", err), Error::Io(err) => write!(f, "Failed to open: {}", err),
Error::Nix(err) => write!(f, "Error: {}", err), Error::Nix(err) => write!(f, "Error: {}", err),
+1 -1
View File
@@ -13,11 +13,11 @@ pub mod config;
pub mod error; pub mod error;
#[cfg(feature = "mocking")] #[cfg(feature = "mocking")]
pub mod mocking; pub mod mocking;
pub mod notify;
pub mod pages; pub mod pages;
pub mod startup_error; pub mod startup_error;
pub mod system_state; pub mod system_state;
pub mod tray; pub mod tray;
pub mod update_and_notify;
pub mod widgets; pub mod widgets;
#[cfg(feature = "mocking")] #[cfg(feature = "mocking")]
+10 -9
View File
@@ -1,12 +1,12 @@
use eframe::{IconData, NativeOptions}; use eframe::{IconData, NativeOptions};
use log::{error, info, LevelFilter}; use log::{error, info};
use rog_aura::layouts::KeyLayout; use rog_aura::layouts::KeyLayout;
use rog_control_center::notify::EnabledNotifications;
use rog_control_center::tray::init_tray; use rog_control_center::tray::init_tray;
use rog_control_center::update_and_notify::EnabledNotifications;
use rog_control_center::{ use rog_control_center::{
config::Config, error::Result, get_ipc_file, notify::start_notifications, on_tmp_dir_exists, config::Config, error::Result, get_ipc_file, on_tmp_dir_exists, print_versions,
print_versions, startup_error::AppErrorShow, system_state::SystemState, RogApp, startup_error::AppErrorShow, system_state::SystemState, update_and_notify::start_notifications,
RogDbusClientBlocking, SHOWING_GUI, SHOW_GUI, RogApp, RogDbusClientBlocking, SHOWING_GUI, SHOW_GUI,
}; };
use rog_platform::supported::SupportedFunctions; use rog_platform::supported::SupportedFunctions;
use std::sync::Mutex; use std::sync::Mutex;
@@ -29,9 +29,9 @@ fn main() -> Result<()> {
print_versions(); print_versions();
let mut logger = env_logger::Builder::new(); let mut logger = env_logger::Builder::new();
logger logger
.parse_default_env()
.target(env_logger::Target::Stdout) .target(env_logger::Target::Stdout)
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args())) .format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
.filter(None, LevelFilter::Info)
.init(); .init();
// start tokio // start tokio
@@ -118,7 +118,7 @@ fn main() -> Result<()> {
Err(_) => on_tmp_dir_exists().unwrap(), Err(_) => on_tmp_dir_exists().unwrap(),
}; };
let states = setup_page_state_and_notifs(layout, enabled_notifications, &supported)?; let states = setup_page_state_and_notifs(layout, enabled_notifications, &config, &supported)?;
init_tray(supported, states.clone()); init_tray(supported, states.clone());
@@ -153,6 +153,7 @@ fn main() -> Result<()> {
fn setup_page_state_and_notifs( fn setup_page_state_and_notifs(
keyboard_layout: KeyLayout, keyboard_layout: KeyLayout,
enabled_notifications: Arc<Mutex<EnabledNotifications>>, enabled_notifications: Arc<Mutex<EnabledNotifications>>,
config: &Config,
supported: &SupportedFunctions, supported: &SupportedFunctions,
) -> Result<Arc<Mutex<SystemState>>> { ) -> Result<Arc<Mutex<SystemState>>> {
let page_states = Arc::new(Mutex::new(SystemState::new( let page_states = Arc::new(Mutex::new(SystemState::new(
@@ -161,7 +162,7 @@ fn setup_page_state_and_notifs(
supported, supported,
)?)); )?));
start_notifications(page_states.clone(), enabled_notifications)?; start_notifications(config, page_states.clone(), enabled_notifications)?;
Ok(page_states) Ok(page_states)
} }
@@ -206,7 +207,7 @@ fn load_icon() -> IconData {
} }
} }
} else { } else {
error!("Missing {APP_ICON_PATH}") error!("Missing {APP_ICON_PATH}");
} }
IconData { IconData {
@@ -22,7 +22,7 @@ impl RogApp {
ui, ui,
); );
fan_graphs(supported, &mut states.profiles, &mut states.fan_curves, &states.asus_dbus, &mut states.error, ui); fan_graphs(supported, &mut states.fan_curves, &states.asus_dbus, &mut states.error, ui);
}); });
} }
@@ -30,7 +30,7 @@ impl RogApp {
supported: &SupportedFunctions, supported: &SupportedFunctions,
profiles: &mut ProfilesState, profiles: &mut ProfilesState,
curves: &mut FanCurvesState, curves: &mut FanCurvesState,
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
do_error: &mut Option<String>, do_error: &mut Option<String>,
ui: &mut Ui, ui: &mut Ui,
) { ) {
@@ -62,7 +62,7 @@ impl RogApp {
}; };
profiles.list.sort(); profiles.list.sort();
for f in profiles.list.iter() { for f in &profiles.list {
item(*f, curves, curves.enabled.contains(f)); item(*f, curves, curves.enabled.contains(f));
} }
}); });
+93 -37
View File
@@ -12,9 +12,10 @@ use supergfxctl::{
zbus_proxy::DaemonProxyBlocking as GfxProxyBlocking, zbus_proxy::DaemonProxyBlocking as GfxProxyBlocking,
}; };
use crate::{error::Result, notify::EnabledNotifications, RogDbusClientBlocking}; use crate::{error::Result, update_and_notify::EnabledNotifications, RogDbusClientBlocking};
use log::error;
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct BiosState { pub struct BiosState {
/// To be shared to a thread that checks notifications. /// To be shared to a thread that checks notifications.
/// It's a bit general in that it won't provide *what* was /// It's a bit general in that it won't provide *what* was
@@ -27,7 +28,7 @@ pub struct BiosState {
} }
impl BiosState { impl BiosState {
pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking) -> Result<Self> { pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking<'_>) -> Result<Self> {
Ok(Self { Ok(Self {
post_sound: if supported.rog_bios_ctrl.post_sound { post_sound: if supported.rog_bios_ctrl.post_sound {
dbus.proxies().rog_bios().post_boot_sound()? != 0 dbus.proxies().rog_bios().post_boot_sound()? != 0
@@ -51,14 +52,14 @@ impl BiosState {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct ProfilesState { pub struct ProfilesState {
pub list: Vec<Profile>, pub list: Vec<Profile>,
pub current: Profile, pub current: Profile,
} }
impl ProfilesState { impl ProfilesState {
pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking) -> Result<Self> { pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking<'_>) -> Result<Self> {
Ok(Self { Ok(Self {
list: if supported.platform_profile.platform_profile { list: if supported.platform_profile.platform_profile {
let mut list = dbus.proxies().profile().profiles()?; let mut list = dbus.proxies().profile().profiles()?;
@@ -76,7 +77,7 @@ impl ProfilesState {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct FanCurvesState { pub struct FanCurvesState {
pub show_curve: Profile, pub show_curve: Profile,
pub show_graph: FanCurvePU, pub show_graph: FanCurvePU,
@@ -86,26 +87,25 @@ pub struct FanCurvesState {
} }
impl FanCurvesState { impl FanCurvesState {
pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking) -> Result<Self> { pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking<'_>) -> Result<Self> {
let profiles = if supported.platform_profile.platform_profile { let profiles = if supported.platform_profile.platform_profile {
dbus.proxies().profile().profiles()? dbus.proxies().profile().profiles()?
} else { } else {
vec![Profile::Balanced, Profile::Quiet, Profile::Performance] vec![Profile::Balanced, Profile::Quiet, Profile::Performance]
}; };
let enabled = if supported.platform_profile.fan_curves { let enabled = if supported.platform_profile.fan_curves {
HashSet::from_iter( dbus.proxies()
dbus.proxies() .profile()
.profile() .enabled_fan_profiles()?
.enabled_fan_profiles()? .iter()
.iter() .cloned()
.cloned(), .collect::<HashSet<_>>()
)
} else { } else {
HashSet::from([Profile::Balanced, Profile::Quiet, Profile::Performance]) HashSet::from([Profile::Balanced, Profile::Quiet, Profile::Performance])
}; };
let mut curves: BTreeMap<Profile, FanCurveSet> = BTreeMap::new(); let mut curves: BTreeMap<Profile, FanCurveSet> = BTreeMap::new();
profiles.iter().for_each(|p| { for p in &profiles {
if supported.platform_profile.fan_curves { if supported.platform_profile.fan_curves {
if let Ok(curve) = dbus.proxies().profile().fan_curve_data(*p) { if let Ok(curve) = dbus.proxies().profile().fan_curve_data(*p) {
curves.insert(*p, curve); curves.insert(*p, curve);
@@ -118,7 +118,7 @@ impl FanCurvesState {
curve.gpu.temp = [20, 30, 40, 50, 70, 80, 90, 100]; curve.gpu.temp = [20, 30, 40, 50, 70, 80, 90, 100];
curves.insert(*p, curve); curves.insert(*p, curve);
} }
}); }
let show_curve = if supported.platform_profile.fan_curves { let show_curve = if supported.platform_profile.fan_curves {
dbus.proxies().profile().active_profile()? dbus.proxies().profile().active_profile()?
@@ -136,7 +136,7 @@ impl FanCurvesState {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct AuraState { pub struct AuraState {
pub current_mode: AuraModeNum, pub current_mode: AuraModeNum,
pub modes: BTreeMap<AuraModeNum, AuraEffect>, pub modes: BTreeMap<AuraModeNum, AuraEffect>,
@@ -149,7 +149,7 @@ pub struct AuraState {
} }
impl AuraState { impl AuraState {
pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking) -> Result<Self> { pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking<'_>) -> Result<Self> {
Ok(Self { Ok(Self {
current_mode: if !supported.keyboard_led.stock_led_modes.is_empty() { current_mode: if !supported.keyboard_led.stock_led_modes.is_empty() {
dbus.proxies().led().led_mode().unwrap_or_default() dbus.proxies().led().led_mode().unwrap_or_default()
@@ -189,7 +189,7 @@ impl AuraState {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct AnimeState { pub struct AnimeState {
pub bright: u8, pub bright: u8,
pub boot: bool, pub boot: bool,
@@ -198,7 +198,7 @@ pub struct AnimeState {
} }
impl AnimeState { impl AnimeState {
pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking) -> Result<Self> { pub fn new(supported: &SupportedFunctions, dbus: &RogDbusClientBlocking<'_>) -> Result<Self> {
Ok(Self { Ok(Self {
boot: if supported.anime_ctrl.0 { boot: if supported.anime_ctrl.0 {
dbus.proxies().anime().boot_enabled()? dbus.proxies().anime().boot_enabled()?
@@ -219,27 +219,39 @@ impl AnimeState {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct GfxState { pub struct GfxState {
pub has_supergfx: bool,
pub mode: GfxMode, pub mode: GfxMode,
pub power_status: GfxPower, pub power_status: GfxPower,
} }
impl GfxState { impl GfxState {
pub fn new(_supported: &SupportedFunctions, dbus: &GfxProxyBlocking) -> Result<Self> { pub fn new(_supported: &SupportedFunctions, dbus: &GfxProxyBlocking<'_>) -> Result<Self> {
Ok(Self { Ok(Self {
mode: dbus.mode()?, has_supergfx: dbus.mode().is_ok(),
power_status: dbus.power()?, mode: dbus.mode().unwrap_or(GfxMode::None),
power_status: dbus.power().unwrap_or(GfxPower::Unknown),
}) })
} }
} }
#[derive(Clone, Debug)] impl Default for GfxState {
fn default() -> Self {
Self {
has_supergfx: false,
mode: GfxMode::None,
power_status: GfxPower::Unknown,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct PowerState { pub struct PowerState {
pub charge_limit: u8, pub charge_limit: u8,
pub ac_power: bool, pub ac_power: bool,
} }
impl PowerState { impl PowerState {
pub fn new(_supported: &SupportedFunctions, dbus: &RogDbusClientBlocking) -> Result<Self> { pub fn new(_supported: &SupportedFunctions, dbus: &RogDbusClientBlocking<'_>) -> Result<Self> {
Ok(Self { Ok(Self {
charge_limit: dbus.proxies().charge().charge_control_end_threshold()?, charge_limit: dbus.proxies().charge().charge_control_end_threshold()?,
ac_power: dbus.proxies().charge().mains_online()?, ac_power: dbus.proxies().charge().mains_online()?,
@@ -277,19 +289,62 @@ impl SystemState {
enabled_notifications: Arc<Mutex<EnabledNotifications>>, enabled_notifications: Arc<Mutex<EnabledNotifications>>,
supported: &SupportedFunctions, supported: &SupportedFunctions,
) -> Result<Self> { ) -> Result<Self> {
let (asus_dbus, conn) = RogDbusClientBlocking::new().unwrap(); let (asus_dbus, conn) = RogDbusClientBlocking::new()?;
let gfx_dbus = GfxProxyBlocking::new(&conn).unwrap(); let mut error = None;
let gfx_dbus = GfxProxyBlocking::new(&conn).expect("Couldn't connect to supergfxd");
Ok(Self { Ok(Self {
keyboard_layout, keyboard_layout,
enabled_notifications, enabled_notifications,
power_state: PowerState::new(supported, &asus_dbus)?, power_state: PowerState::new(supported, &asus_dbus)
bios: BiosState::new(supported, &asus_dbus)?, .map_err(|e| {
aura: AuraState::new(supported, &asus_dbus)?, let e = format!("Could not get PowerState state: {e}");
anime: AnimeState::new(supported, &asus_dbus)?, error!("{e}");
profiles: ProfilesState::new(supported, &asus_dbus)?, error = Some(e);
fan_curves: FanCurvesState::new(supported, &asus_dbus)?, })
gfx_state: GfxState::new(supported, &gfx_dbus)?, .unwrap_or_default(),
error: None, bios: BiosState::new(supported, &asus_dbus)
.map_err(|e| {
let e = format!("Could not get BiosState state: {e}");
error!("{e}");
error = Some(e);
})
.unwrap_or_default(),
aura: AuraState::new(supported, &asus_dbus)
.map_err(|e| {
let e = format!("Could not get AuraState state: {e}");
error!("{e}");
error = Some(e);
})
.unwrap_or_default(),
anime: AnimeState::new(supported, &asus_dbus)
.map_err(|e| {
let e = format!("Could not get AanimeState state: {e}");
error!("{e}");
error = Some(e);
})
.unwrap_or_default(),
profiles: ProfilesState::new(supported, &asus_dbus)
.map_err(|e| {
let e = format!("Could not get ProfilesState state: {e}");
error!("{e}");
error = Some(e);
})
.unwrap_or_default(),
fan_curves: FanCurvesState::new(supported, &asus_dbus)
.map_err(|e| {
let e = format!("Could not get FanCurvesState state: {e}");
error!("{e}");
error = Some(e);
})
.unwrap_or_default(),
gfx_state: GfxState::new(supported, &gfx_dbus)
.map_err(|e| {
let e = format!("Could not get supergfxd state: {e}");
error!("{e}");
error = Some(e);
})
.unwrap_or_default(),
error,
tray_should_update: true, tray_should_update: true,
app_should_update: true, app_should_update: true,
asus_dbus, asus_dbus,
@@ -305,8 +360,8 @@ impl SystemState {
impl Default for SystemState { impl Default for SystemState {
fn default() -> Self { fn default() -> Self {
let (asus_dbus, conn) = RogDbusClientBlocking::new().unwrap(); let (asus_dbus, conn) = RogDbusClientBlocking::new().expect("Couldn't connect to asusd");
let gfx_dbus = GfxProxyBlocking::new(&conn).unwrap(); let gfx_dbus = GfxProxyBlocking::new(&conn).expect("Couldn't connect to supergfxd");
Self { Self {
keyboard_layout: KeyLayout::ga401_layout(), keyboard_layout: KeyLayout::ga401_layout(),
@@ -349,6 +404,7 @@ impl Default for SystemState {
drag_delta: Default::default(), drag_delta: Default::default(),
}, },
gfx_state: GfxState { gfx_state: GfxState {
has_supergfx: false,
mode: GfxMode::None, mode: GfxMode::None,
power_status: GfxPower::Unknown, power_status: GfxPower::Unknown,
}, },
+156 -31
View File
@@ -4,6 +4,7 @@
use std::{ use std::{
io::Write, io::Write,
sync::{ sync::{
atomic::{AtomicBool, Ordering},
mpsc::{channel, Receiver}, mpsc::{channel, Receiver},
Arc, Mutex, Arc, Mutex,
}, },
@@ -21,7 +22,7 @@ use supergfxctl::{
zbus_proxy::DaemonProxyBlocking as GfxProxyBlocking, zbus_proxy::DaemonProxyBlocking as GfxProxyBlocking,
}; };
use log::{debug, error, info, trace}; use log::{debug, error, info, trace, warn};
const TRAY_APP_ICON: &str = "rog-control-center"; const TRAY_APP_ICON: &str = "rog-control-center";
const TRAY_LABEL: &str = "ROG Control Center"; const TRAY_LABEL: &str = "ROG Control Center";
@@ -128,13 +129,18 @@ impl ROGTray {
self.menu.show_all(); self.menu.show_all();
} }
fn add_radio_sub_menu(&mut self, header_label: &str, active_label: &str, sub_menu: RadioGroup) { fn add_radio_sub_menu(
&mut self,
header_label: &str,
active_label: &str,
sub_menu: &RadioGroup,
) {
let header_item = gtk::MenuItem::with_label(header_label); let header_item = gtk::MenuItem::with_label(header_label);
header_item.show_all(); header_item.show_all();
self.menu.add(&header_item); self.menu.add(&header_item);
let menu = gtk::Menu::new(); let menu = gtk::Menu::new();
for item in sub_menu.0.iter() { for item in &sub_menu.0 {
if let Some(label) = item.label() { if let Some(label) = item.label() {
item.set_active(label == active_label); item.set_active(label == active_label);
} else { } else {
@@ -197,7 +203,7 @@ impl ROGTray {
} }
fn _set_status(&mut self, status: AppIndicatorStatus) { fn _set_status(&mut self, status: AppIndicatorStatus) {
self.tray.set_status(status) self.tray.set_status(status);
} }
fn menu_add_base(&mut self) { fn menu_add_base(&mut self) {
@@ -236,7 +242,10 @@ impl ROGTray {
} }
fn menu_add_gpu(&mut self, supported: &SupportedFunctions, current_mode: GfxMode) { fn menu_add_gpu(&mut self, supported: &SupportedFunctions, current_mode: GfxMode) {
let set_mux_off = Arc::new(AtomicBool::new(false));
let gfx_dbus = self.gfx_proxy.clone(); let gfx_dbus = self.gfx_proxy.clone();
let set_mux_off1 = set_mux_off.clone();
let mut gpu_menu = RadioGroup::new("Integrated", move |_| { let mut gpu_menu = RadioGroup::new("Integrated", move |_| {
let mode = gfx_dbus let mode = gfx_dbus
.mode() .mode()
@@ -254,9 +263,11 @@ impl ROGTray {
}) })
.ok(); .ok();
} }
set_mux_off1.store(true, Ordering::Relaxed);
}); });
let gfx_dbus = self.gfx_proxy.clone(); let gfx_dbus = self.gfx_proxy.clone();
let set_mux_off1 = set_mux_off.clone();
gpu_menu.add("Hybrid", move |_| { gpu_menu.add("Hybrid", move |_| {
let mode = gfx_dbus let mode = gfx_dbus
.mode() .mode()
@@ -274,7 +285,33 @@ impl ROGTray {
}) })
.ok(); .ok();
} }
set_mux_off1.store(true, Ordering::Relaxed);
}); });
if supported.rog_bios_ctrl.egpu_enable {
let set_mux_off1 = set_mux_off.clone();
let gfx_dbus = self.gfx_proxy.clone();
gpu_menu.add("eGPU", move |_| {
let mode = gfx_dbus
.mode()
.map_err(|e| {
error!("ROGTray: mode: {e}");
e
})
.unwrap_or(GfxMode::None);
if mode != GfxMode::Egpu {
gfx_dbus
.set_mode(&GfxMode::Egpu)
.map_err(|e| {
error!("ROGTray: set_mode: {e}");
e
})
.ok();
}
set_mux_off1.store(true, Ordering::Relaxed);
});
}
let mut reboot_required = false;
if supported.rog_bios_ctrl.gpu_mux { if supported.rog_bios_ctrl.gpu_mux {
let gfx_dbus = self.bios_proxy.clone(); let gfx_dbus = self.bios_proxy.clone();
gpu_menu.add("Ultimate (Reboot required)", move |_| { gpu_menu.add("Ultimate (Reboot required)", move |_| {
@@ -295,37 +332,97 @@ impl ROGTray {
.ok(); .ok();
} }
}); });
}
if supported.rog_bios_ctrl.egpu_enable { if set_mux_off.load(Ordering::Relaxed) {
let gfx_dbus = self.gfx_proxy.clone(); warn!("Selected non-dgpu mode, must set MUX to optimus");
gpu_menu.add("eGPU", move |_| { self.bios_proxy
let mode = gfx_dbus .set_gpu_mux_mode(GpuMode::Optimus)
.mode()
.map_err(|e| { .map_err(|e| {
error!("ROGTray: mode: {e}"); error!("ROGTray: set_mode: {e}");
e e
}) })
.unwrap_or(GfxMode::None); .ok();
if mode != GfxMode::Egpu { }
gfx_dbus
.set_mode(&GfxMode::Egpu) if let Ok(mode) = self.bios_proxy.gpu_mux_mode() {
.map_err(|e| { let mode = match mode {
error!("ROGTray: set_mode: {e}"); GpuMode::Discrete => GfxMode::AsusMuxDiscreet,
e _ => GfxMode::Hybrid,
}) };
.ok(); reboot_required = mode != current_mode;
} }
});
} }
let active = match current_mode { let active = match current_mode {
GfxMode::AsusMuxDiscreet => "Discreet".to_string(), GfxMode::AsusMuxDiscreet => "Discreet".to_owned(),
_ => current_mode.to_string(), _ => current_mode.to_string(),
}; };
let reboot_required = if reboot_required {
"(Reboot required)"
} else {
""
};
self.add_radio_sub_menu( self.add_radio_sub_menu(
&format!("GPU Mode: {current_mode}"), &format!("GPU Mode: {active} {reboot_required}"),
active.as_str(), active.as_str(),
gpu_menu, &gpu_menu,
);
debug!("ROGTray: appended gpu menu");
}
fn menu_add_mux(&mut self, current_mode: GfxMode) {
let gfx_dbus = self.bios_proxy.clone();
let mut reboot_required = false;
if let Ok(mode) = gfx_dbus.gpu_mux_mode() {
let mode = match mode {
GpuMode::Discrete => GfxMode::AsusMuxDiscreet,
_ => GfxMode::Hybrid,
};
reboot_required = mode != current_mode;
}
let mut gpu_menu = RadioGroup::new("Optimus", move |_| {
gfx_dbus
.set_gpu_mux_mode(GpuMode::Optimus)
.map_err(|e| {
error!("ROGTray: set_mode: {e}");
e
})
.ok();
debug!("Setting GPU mode: {}", GpuMode::Optimus);
});
let gfx_dbus = self.bios_proxy.clone();
gpu_menu.add("Ultimate", move |_| {
gfx_dbus
.set_gpu_mux_mode(GpuMode::Discrete)
.map_err(|e| {
error!("ROGTray: set_mode: {e}");
e
})
.ok();
debug!("Setting GPU mode: {}", GpuMode::Discrete);
});
let active = match current_mode {
GfxMode::AsusMuxDiscreet => "Ultimate".to_owned(),
GfxMode::Hybrid => "Optimus".to_owned(),
_ => current_mode.to_string(),
};
debug!("Current active GPU mode: {}", active);
let reboot_required = if reboot_required {
"(Reboot required)"
} else {
""
};
self.add_radio_sub_menu(
&format!("GPU Mode: {active} {reboot_required}"),
active.as_str(),
&gpu_menu,
); );
debug!("ROGTray: appended gpu menu"); debug!("ROGTray: appended gpu menu");
@@ -346,6 +443,7 @@ impl ROGTray {
fn rebuild_and_update( fn rebuild_and_update(
&mut self, &mut self,
supported: &SupportedFunctions, supported: &SupportedFunctions,
has_supergfx: bool,
current_gfx_mode: GfxMode, current_gfx_mode: GfxMode,
charge_limit: u8, charge_limit: u8,
panel_od: bool, panel_od: bool,
@@ -354,7 +452,11 @@ impl ROGTray {
self.menu_add_base(); self.menu_add_base();
self.menu_add_charge_limit(supported, charge_limit); self.menu_add_charge_limit(supported, charge_limit);
self.menu_add_panel_od(supported, panel_od); self.menu_add_panel_od(supported, panel_od);
self.menu_add_gpu(supported, current_gfx_mode); if has_supergfx {
self.menu_add_gpu(supported, current_gfx_mode);
} else if supported.rog_bios_ctrl.gpu_mux {
self.menu_add_mux(current_gfx_mode);
}
self.menu_update(); self.menu_update();
} }
} }
@@ -366,6 +468,12 @@ pub fn init_tray(
let (send, recv) = channel(); let (send, recv) = channel();
let _send = Arc::new(Mutex::new(send)); let _send = Arc::new(Mutex::new(send));
let has_supergfx = if let Ok(lock) = states.try_lock() {
lock.gfx_state.has_supergfx
} else {
false
};
std::thread::spawn(move || { std::thread::spawn(move || {
if gtk::init() if gtk::init()
.map_err(|e| { .map_err(|e| {
@@ -391,16 +499,26 @@ pub fn init_tray(
return; return;
} }
}; };
tray.rebuild_and_update(&supported, GfxMode::Hybrid, 100, false); tray.rebuild_and_update(&supported, has_supergfx, GfxMode::Hybrid, 100, false);
tray.set_icon(TRAY_APP_ICON); tray.set_icon(TRAY_APP_ICON);
info!("Started ROGTray"); info!("Started ROGTray");
loop { loop {
if let Ok(mut lock) = states.lock() { if let Ok(mut lock) = states.lock() {
if lock.tray_should_update { if lock.tray_should_update {
// Supergfx ends up adding some complexity to handle if it isn't available
let current_gpu_mode = if lock.gfx_state.has_supergfx {
lock.gfx_state.mode
} else {
match lock.bios.dedicated_gfx {
GpuMode::Discrete => GfxMode::AsusMuxDiscreet,
_ => GfxMode::Hybrid,
}
};
tray.rebuild_and_update( tray.rebuild_and_update(
&supported, &supported,
lock.gfx_state.mode, has_supergfx,
current_gpu_mode,
lock.power_state.charge_limit, lock.power_state.charge_limit,
lock.bios.panel_overdrive, lock.bios.panel_overdrive,
); );
@@ -408,12 +526,19 @@ pub fn init_tray(
debug!("ROGTray: rebuilt menus due to state change"); debug!("ROGTray: rebuilt menus due to state change");
match lock.gfx_state.power_status { match lock.gfx_state.power_status {
GfxPower::Active => tray.set_icon("asus_notif_red"),
GfxPower::Suspended => tray.set_icon("asus_notif_blue"), GfxPower::Suspended => tray.set_icon("asus_notif_blue"),
GfxPower::Off => tray.set_icon("asus_notif_green"), GfxPower::Off => tray.set_icon("asus_notif_green"),
GfxPower::AsusDisabled => tray.set_icon("asus_notif_white"), GfxPower::AsusDisabled => tray.set_icon("asus_notif_white"),
GfxPower::AsusMuxDiscreet => tray.set_icon("asus_notif_red"), GfxPower::AsusMuxDiscreet | GfxPower::Active => {
GfxPower::Unknown => tray.set_icon("gpu-integrated"), tray.set_icon("asus_notif_red");
}
GfxPower::Unknown => {
if has_supergfx {
tray.set_icon("gpu-integrated");
} else {
tray.set_icon("asus_notif_red");
}
}
}; };
} }
} }
@@ -1,5 +1,9 @@
//! `update_and_notify` is responsible for both notifications *and* updating stored statuses
//! about the system state. This is done through either direct, intoify, zbus notifications
//! or similar methods.
use crate::{config::Config, error::Result, system_state::SystemState}; use crate::{config::Config, error::Result, system_state::SystemState};
use log::{error, info, trace}; use log::{error, info, trace, warn};
use notify_rust::{Hint, Notification, NotificationHandle, Urgency}; use notify_rust::{Hint, Notification, NotificationHandle, Urgency};
use rog_dbus::{ use rog_dbus::{
zbus_anime::AnimeProxy, zbus_led::LedProxy, zbus_platform::RogBiosProxy, zbus_anime::AnimeProxy, zbus_led::LedProxy, zbus_platform::RogBiosProxy,
@@ -12,12 +16,17 @@ use std::{
fmt::Display, fmt::Display,
process::Command, process::Command,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
time::Duration,
}; };
use supergfxctl::{pci_device::GfxPower, zbus_proxy::DaemonProxy as SuperProxy}; use supergfxctl::{pci_device::GfxPower, zbus_proxy::DaemonProxy as SuperProxy};
use tokio::time::sleep;
use zbus::export::futures_util::{future, StreamExt}; use zbus::export::futures_util::{future, StreamExt};
const NOTIF_HEADER: &str = "ROG Control"; const NOTIF_HEADER: &str = "ROG Control";
static mut POWER_AC_CMD: Option<Command> = None;
static mut POWER_BAT_CMD: Option<Command> = None;
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)] #[serde(default)]
pub struct EnabledNotifications { pub struct EnabledNotifications {
@@ -48,7 +57,7 @@ impl Default for EnabledNotifications {
receive_notify_charge_control_end_threshold: true, receive_notify_charge_control_end_threshold: true,
receive_notify_mains_online: false, receive_notify_mains_online: false,
receive_notify_profile: true, receive_notify_profile: true,
receive_notify_led: false, receive_notify_led: true,
receive_power_states: false, receive_power_states: false,
receive_notify_gfx: false, receive_notify_gfx: false,
receive_notify_gfx_status: false, receive_notify_gfx_status: false,
@@ -125,11 +134,36 @@ macro_rules! recv_notif {
type SharedHandle = Arc<Mutex<Option<NotificationHandle>>>; type SharedHandle = Arc<Mutex<Option<NotificationHandle>>>;
pub fn start_notifications( pub fn start_notifications(
config: &Config,
page_states: Arc<Mutex<SystemState>>, page_states: Arc<Mutex<SystemState>>,
enabled_notifications: Arc<Mutex<EnabledNotifications>>, enabled_notifications: Arc<Mutex<EnabledNotifications>>,
) -> Result<()> { ) -> Result<()> {
let last_notification: SharedHandle = Arc::new(Mutex::new(None)); let last_notification: SharedHandle = Arc::new(Mutex::new(None));
// Setup the AC/BAT commands that will run on poweer status change
unsafe {
let prog: Vec<&str> = config.ac_command.split_whitespace().collect();
if prog.len() > 1 {
let mut cmd = Command::new(prog[0]);
for arg in prog.iter().skip(1) {
cmd.arg(*arg);
}
POWER_AC_CMD = Some(cmd);
}
}
unsafe {
let prog: Vec<&str> = config.bat_command.split_whitespace().collect();
if prog.len() > 1 {
let mut cmd = Command::new(prog[0]);
for arg in prog.iter().skip(1) {
cmd.arg(*arg);
}
POWER_BAT_CMD = Some(cmd);
}
}
// BIOS notif // BIOS notif
recv_notif!( recv_notif!(
RogBiosProxy, RogBiosProxy,
@@ -179,18 +213,6 @@ pub fn start_notifications(
do_notification do_notification
); );
recv_notif!(
RogBiosProxy,
receive_notify_gpu_mux_mode,
last_notification,
enabled_notifications,
page_states,
(bios.dedicated_gfx),
(mode),
"Reboot required. BIOS GPU MUX mode set to",
do_mux_notification
);
// Charge notif // Charge notif
recv_notif!( recv_notif!(
PowerProxy, PowerProxy,
@@ -271,104 +293,148 @@ pub fn start_notifications(
}; };
}); });
recv_notif!( let page_states1 = page_states.clone();
SuperProxy, let last_notification1 = last_notification.clone();
receive_notify_gfx,
last_notification,
enabled_notifications,
page_states,
(gfx_state.mode),
(mode),
"Gfx mode changed to",
do_notification
);
// recv_notif!(
// SuperProxy,
// receive_notify_action,
// bios_notified,
// last_gfx_action_notif,
// enabled_notifications,
// [action],
// "Gfx mode change requires",
// do_gfx_action_notif
// );
tokio::spawn(async move { tokio::spawn(async move {
let conn = zbus::Connection::system() let conn = zbus::Connection::system()
.await .await
.map_err(|e| { .map_err(|e| {
error!("zbus signal: receive_notify_action: {e}"); error!("zbus signal: receive_notify_gpu_mux_mode: {e}");
e e
}) })
.unwrap(); .unwrap();
let proxy = SuperProxy::new(&conn) let proxy = RogBiosProxy::new(&conn)
.await .await
.map_err(|e| { .map_err(|e| {
error!("zbus signal: receive_notify_action: {e}"); error!("zbus signal: receive_notify_gpu_mux_mode: {e}");
e e
}) })
.unwrap(); .unwrap();
if let Ok(mut p) = proxy.receive_notify_action().await {
info!("Started zbus signal thread: receive_notify_action");
while let Some(e) = p.next().await {
if let Ok(out) = e.args() {
let action = out.action();
do_gfx_action_notif("Gfx mode change requires", &format!("{action:?}",))
.map_err(|e| {
error!("zbus signal: do_gfx_action_notif: {e}");
e
})
.unwrap();
}
}
};
});
let notifs_enabled1 = enabled_notifications; let mut actual_mux_mode = GpuMode::Error;
let last_notif = last_notification; if let Ok(mode) = proxy.gpu_mux_mode().await {
tokio::spawn(async move { actual_mux_mode = mode;
let conn = zbus::Connection::system() }
.await
.map_err(|e| { if let Ok(mut p) = proxy.receive_notify_gpu_mux_mode().await {
error!("zbus signal: receive_notify_gfx_status: {e}"); info!("Started zbus signal thread: receive_power_states");
e
})
.unwrap();
let proxy = SuperProxy::new(&conn)
.await
.map_err(|e| {
error!("zbus signal: receive_notify_gfx_status: {e}");
e
})
.unwrap();
if let Ok(mut p) = proxy.receive_notify_gfx_status().await {
info!("Started zbus signal thread: receive_notify_gfx_status");
while let Some(e) = p.next().await { while let Some(e) = p.next().await {
if let Ok(out) = e.args() { if let Ok(out) = e.args() {
let status = out.status; if out.mode == actual_mux_mode {
if status != GfxPower::Unknown { continue;
if let Ok(config) = notifs_enabled1.lock() { }
if config.all_enabled && config.receive_notify_gfx_status { if let Ok(mut lock) = page_states1.lock() {
// Required check because status cycles through active/unknown/suspended lock.bios.dedicated_gfx = out.mode;
if let Ok(ref mut lock) = last_notif.lock() { lock.set_notified();
notify!( }
do_gpu_status_notif("dGPU status changed:", &status), if let Ok(ref mut lock) = last_notification1.lock() {
lock if let Some(notif) = lock.take() {
); notif.close();
}
}
}
if let Ok(mut lock) = page_states.lock() {
lock.gfx_state.power_status = status;
lock.set_notified();
} }
} }
do_mux_notification("Reboot required. BIOS GPU MUX mode set to", &out.mode)
.ok();
} }
} }
}; };
}); });
if let Ok(lock) = page_states.try_lock() {
use supergfxctl::pci_device::Device;
let dev = Device::find().unwrap_or_default();
let mut found_dgpu = false; // just for logging
for dev in dev {
if dev.is_dgpu() {
let notifs_enabled1 = enabled_notifications.clone();
let last_notif = last_notification.clone();
let page_states1 = page_states.clone();
// Plain old thread is perfectly fine since most of this is potentially blocking
tokio::spawn(async move {
let mut last_status = GfxPower::Unknown;
loop {
if let Ok(status) = dev.get_runtime_status() {
if status != GfxPower::Unknown && status != last_status {
if let Ok(config) = notifs_enabled1.lock() {
if config.all_enabled && config.receive_notify_gfx_status {
// Required check because status cycles through active/unknown/suspended
if let Ok(ref mut lock) = last_notif.lock() {
notify!(
do_gpu_status_notif(
"dGPU status changed:",
&status
),
lock
);
}
}
}
if let Ok(mut lock) = page_states1.lock() {
lock.gfx_state.power_status = status;
lock.set_notified();
}
last_status = status;
}
}
sleep(Duration::from_millis(500)).await;
}
});
found_dgpu = true;
break;
}
}
if !found_dgpu {
warn!("Did not find a dGPU on this system, dGPU status won't be avilable");
}
if lock.gfx_state.has_supergfx {
recv_notif!(
SuperProxy,
receive_notify_gfx,
last_notification,
enabled_notifications,
page_states,
(gfx_state.mode),
(mode),
"Gfx mode changed to",
do_notification
);
tokio::spawn(async move {
let conn = zbus::Connection::system()
.await
.map_err(|e| {
error!("zbus signal: receive_notify_action: {e}");
e
})
.unwrap();
let proxy = SuperProxy::new(&conn)
.await
.map_err(|e| {
error!("zbus signal: receive_notify_action: {e}");
e
})
.unwrap();
if let Ok(mut p) = proxy.receive_notify_action().await {
info!("Started zbus signal thread: receive_notify_action");
while let Some(e) = p.next().await {
if let Ok(out) = e.args() {
let action = out.action();
do_gfx_action_notif(
"Gfx mode change requires",
&format!("{action:?}",),
)
.map_err(|e| {
error!("zbus signal: do_gfx_action_notif: {e}");
e
})
.unwrap();
}
}
};
});
}
}
Ok(()) Ok(())
} }
@@ -397,9 +463,23 @@ where
fn ac_power_notification(message: &str, on: &bool) -> Result<NotificationHandle> { fn ac_power_notification(message: &str, on: &bool) -> Result<NotificationHandle> {
let data = if *on { let data = if *on {
"plugged".to_string() unsafe {
if let Some(cmd) = POWER_AC_CMD.as_mut() {
if let Err(e) = cmd.spawn() {
error!("AC power command error: {e}");
}
}
}
"plugged".to_owned()
} else { } else {
"unplugged".to_string() unsafe {
if let Some(cmd) = POWER_BAT_CMD.as_mut() {
if let Err(e) = cmd.spawn() {
error!("Battery power command error: {e}");
}
}
}
"unplugged".to_owned()
}; };
Ok(base_notification(message, &data).show()?) Ok(base_notification(message, &data).show()?)
} }
@@ -417,13 +497,12 @@ fn do_thermal_notif(message: &str, profile: &Profile) -> Result<NotificationHand
fn do_gpu_status_notif(message: &str, data: &GfxPower) -> Result<NotificationHandle> { fn do_gpu_status_notif(message: &str, data: &GfxPower) -> Result<NotificationHandle> {
// eww // eww
let mut notif = base_notification(message, &<&str>::from(data).to_string()); let mut notif = base_notification(message, &<&str>::from(data).to_owned());
let icon = match data { let icon = match data {
GfxPower::Active => "asus_notif_red",
GfxPower::Suspended => "asus_notif_blue", GfxPower::Suspended => "asus_notif_blue",
GfxPower::Off => "asus_notif_green", GfxPower::Off => "asus_notif_green",
GfxPower::AsusDisabled => "asus_notif_white", GfxPower::AsusDisabled => "asus_notif_white",
GfxPower::AsusMuxDiscreet => "asus_notif_red", GfxPower::AsusMuxDiscreet | GfxPower::Active => "asus_notif_red",
GfxPower::Unknown => "gpu-integrated", GfxPower::Unknown => "gpu-integrated",
}; };
notif.icon(icon); notif.icon(icon);
@@ -452,11 +531,25 @@ where
Ok(()) Ok(())
} }
/// Actual GpuMode unused as data is never correct until switched by reboot /// Actual `GpuMode` unused as data is never correct until switched by reboot
fn do_mux_notification(message: &str, _: &GpuMode) -> Result<NotificationHandle> { fn do_mux_notification(message: &str, m: &GpuMode) -> Result<()> {
let mut notif = base_notification(message, &""); let mut notif = base_notification(message, &m.to_string());
notif.action("gnome-session-quit", "Reboot");
notif.urgency(Urgency::Critical); notif.urgency(Urgency::Critical);
notif.icon("system-reboot-symbolic"); notif.icon("system-reboot-symbolic");
notif.hint(Hint::Transient(true)); notif.hint(Hint::Transient(true));
Ok(notif.show()?) let handle = notif.show()?;
std::thread::spawn(|| {
handle.wait_for_action(|id| {
if id == "gnome-session-quit" {
let mut cmd = Command::new("gnome-session-quit");
cmd.arg("--reboot");
cmd.spawn().ok();
} else if id == "__closed" {
// TODO: cancel the switching
}
})
});
Ok(())
} }
+16 -6
View File
@@ -12,7 +12,8 @@ pub fn app_settings(config: &mut Config, states: &mut SystemState, ui: &mut Ui)
Default::default() Default::default()
}; };
if ui ui.label("Application settings");
let app_changed = ui
.checkbox(&mut config.run_in_background, "Run in Background") .checkbox(&mut config.run_in_background, "Run in Background")
.clicked() .clicked()
|| ui || ui
@@ -23,11 +24,19 @@ pub fn app_settings(config: &mut Config, states: &mut SystemState, ui: &mut Ui)
&mut enabled_notifications.all_enabled, &mut enabled_notifications.all_enabled,
"Enable Notifications", "Enable Notifications",
) )
.clicked() .clicked();
ui.label("Notification settings");
let notif_changed = ui
.checkbox(
&mut enabled_notifications.receive_notify_gfx_status,
"Enable dGPU status notification",
)
.clicked()
|| ui || ui
.checkbox( .checkbox(
&mut enabled_notifications.receive_notify_gfx_status, &mut enabled_notifications.receive_notify_led,
"Enable dGPU status notification", "Enable LED mode change notification",
) )
.clicked() .clicked()
|| ui || ui
@@ -71,8 +80,9 @@ pub fn app_settings(config: &mut Config, states: &mut SystemState, ui: &mut Ui)
&mut enabled_notifications.receive_notify_post_boot_sound, &mut enabled_notifications.receive_notify_post_boot_sound,
"Enable BIOS post sound notification", "Enable BIOS post sound notification",
) )
.clicked() .clicked();
{
if app_changed || notif_changed {
if let Ok(mut lock) = states.enabled_notifications.lock() { if let Ok(mut lock) = states.enabled_notifications.lock() {
// Replace inner content before save // Replace inner content before save
*lock = enabled_notifications; *lock = enabled_notifications;
+1 -1
View File
@@ -12,7 +12,7 @@ pub fn aura_power_group(supported: &SupportedFunctions, states: &mut SystemState
match supported.keyboard_led.prod_id { match supported.keyboard_led.prod_id {
AuraDevice::X1854 | AuraDevice::X1869 | AuraDevice::X1866 => { AuraDevice::X1854 | AuraDevice::X1869 | AuraDevice::X1866 => {
aura_power1(supported, states, ui) aura_power1(supported, states, ui);
} }
AuraDevice::X19B6 => aura_power2(supported, states, ui), AuraDevice::X19B6 => aura_power2(supported, states, ui),
AuraDevice::Tuf => aura_power1(supported, states, ui), AuraDevice::Tuf => aura_power1(supported, states, ui),
+60 -21
View File
@@ -2,16 +2,12 @@ use egui::{plot::Points, Ui};
use rog_platform::supported::SupportedFunctions; use rog_platform::supported::SupportedFunctions;
use rog_profiles::{FanCurvePU, Profile}; use rog_profiles::{FanCurvePU, Profile};
use crate::{ use crate::{system_state::FanCurvesState, RogDbusClientBlocking};
system_state::{FanCurvesState, ProfilesState},
RogDbusClientBlocking,
};
pub fn fan_graphs( pub fn fan_graphs(
supported: &SupportedFunctions, supported: &SupportedFunctions,
profiles: &mut ProfilesState,
curves: &mut FanCurvesState, curves: &mut FanCurvesState,
dbus: &RogDbusClientBlocking, dbus: &RogDbusClientBlocking<'_>,
do_error: &mut Option<String>, do_error: &mut Option<String>,
ui: &mut Ui, ui: &mut Ui,
) { ) {
@@ -36,14 +32,14 @@ pub fn fan_graphs(
}; };
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
for a in curves.curves.iter() { for a in &curves.curves {
item(*a.0, ui); item(*a.0, ui);
} }
}); });
let curve = curves.curves.get_mut(&curves.show_curve).unwrap(); let curve = curves.curves.get_mut(&curves.show_curve).unwrap();
use egui::plot::{Line, Plot, PlotPoints}; use egui::plot::{Line, Plot};
let data = if curves.show_graph == FanCurvePU::CPU { let data = if curves.show_graph == FanCurvePU::CPU {
&mut curve.cpu &mut curve.cpu
@@ -51,14 +47,40 @@ pub fn fan_graphs(
&mut curve.gpu &mut curve.gpu
}; };
let points = data.temp.iter().enumerate().map(|(idx, x)| { let mut points: Vec<[f64; 2]> = data
let x = *x as f64; .temp
let y = ((data.pwm[idx] as u32) * 100 / 255) as f64; .iter()
[x, y] .enumerate()
}); .map(|(idx, x)| {
let x = *x as f64;
let y = ((data.pwm[idx] as u32) * 100 / 255) as f64;
[x, y]
})
.collect();
let line = Line::new(PlotPoints::from_iter(points.clone())).width(2.0); for i in 0..points.len() - 1 {
let points = Points::new(PlotPoints::from_iter(points)).radius(3.0); if i > 0 && i < points.len() - 1 {
if points[i][0] < points[i - 1][0] {
points[i][0] = points[i - 1][0] + 1.0;
data.temp[i] = points[i - 1][0] as u8;
}
if points[i][0] >= points[i + 1][0] {
points[i + 1][0] = points[i][0] + 1.0;
data.temp[i + 1] = points[i][0] as u8;
}
if points[i][1] < points[i - 1][1] {
points[i][1] = points[i - 1][1] + 1.0;
data.pwm[i] = (points[i - 1][1] * 255.0 / 100.0 + 1.0).floor() as u8;
}
if points[i][1] >= points[i + 1][1] {
points[i + 1][1] = points[i][1] + 1.0;
data.pwm[i + 1] = (points[i][1] * 255.0 / 100.0 + 1.0).floor() as u8;
}
}
}
let line = Line::new(points.clone()).width(2.0);
let points = Points::new(points).radius(3.0);
Plot::new("fan_curves") Plot::new("fan_curves")
.view_aspect(1.666) .view_aspect(1.666)
@@ -85,7 +107,7 @@ pub fn fan_graphs(
let mut idx = 0; let mut idx = 0;
if let Some(point) = plot_ui.pointer_coordinate() { if let Some(point) = plot_ui.pointer_coordinate() {
let mut x: i32 = 255; let mut x: i32 = point.x as i32;
for (i, n) in data.temp.iter().enumerate() { for (i, n) in data.temp.iter().enumerate() {
let tmp = x.min((point.x as i32 - *n as i32).abs()); let tmp = x.min((point.x as i32 - *n as i32).abs());
if tmp < x { if tmp < x {
@@ -107,30 +129,47 @@ pub fn fan_graphs(
} }
} }
plot_ui.line(line); plot_ui.line(line);
plot_ui.points(points) plot_ui.points(points);
}); });
let mut set = false; let mut set = false;
let mut clear = false;
let mut reset = false; let mut reset = false;
ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| {
set = ui.add(egui::Button::new("Apply Fan-curve")).clicked(); set = ui.add(egui::Button::new("Apply Profile")).clicked();
reset = ui.add(egui::Button::new("Reset Profile")).clicked(); clear = ui.add(egui::Button::new("Clear Profile Changes")).clicked();
reset = ui.add(egui::Button::new("Factory Reset Profile")).clicked();
}); });
if set { if set {
dbus.proxies() dbus.proxies()
.profile() .profile()
.set_fan_curve(profiles.current, data.clone()) .set_fan_curve(curves.show_curve, data.clone())
.map_err(|err| { .map_err(|err| {
*do_error = Some(err.to_string()); *do_error = Some(err.to_string());
}) })
.ok(); .ok();
} }
if clear {
if let Ok(curve) = dbus
.proxies()
.profile()
.fan_curve_data(curves.show_curve)
.map_err(|err| {
*do_error = Some(err.to_string());
})
{
if let Some(value) = curves.curves.get_mut(&curves.show_curve) {
*value = curve;
}
}
}
if reset { if reset {
dbus.proxies() dbus.proxies()
.profile() .profile()
.reset_profile_curves(profiles.current) .reset_profile_curves(curves.show_curve)
.map_err(|err| { .map_err(|err| {
*do_error = Some(err.to_string()); *do_error = Some(err.to_string());
}) })
+16 -5
View File
@@ -17,7 +17,7 @@ pub fn platform_profile(states: &mut SystemState, ui: &mut Ui) {
}; };
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
for a in states.profiles.list.iter() { for a in &states.profiles.list {
item(*a, ui); item(*a, ui);
} }
}); });
@@ -46,7 +46,7 @@ pub fn rog_bios_group(supported: &SupportedFunctions, states: &mut SystemState,
.asus_dbus .asus_dbus
.proxies() .proxies()
.charge() .charge()
.set_charge_control_end_threshold(states.power_state.charge_limit as u8) .set_charge_control_end_threshold(states.power_state.charge_limit)
.map_err(|err| { .map_err(|err| {
states.error = Some(err.to_string()); states.error = Some(err.to_string());
}) })
@@ -93,6 +93,13 @@ pub fn rog_bios_group(supported: &SupportedFunctions, states: &mut SystemState,
if supported.rog_bios_ctrl.gpu_mux { if supported.rog_bios_ctrl.gpu_mux {
let mut changed = false; let mut changed = false;
let mut dedicated_gfx = states.bios.dedicated_gfx;
let mut reboot_required = false;
if let Ok(mode) = states.asus_dbus.proxies().rog_bios().gpu_mux_mode() {
reboot_required = mode != states.bios.dedicated_gfx;
}
ui.group(|ui| { ui.group(|ui| {
ui.vertical(|ui| { ui.vertical(|ui| {
ui.horizontal_wrapped(|ui| ui.label("GPU MUX mode")); ui.horizontal_wrapped(|ui| ui.label("GPU MUX mode"));
@@ -100,19 +107,23 @@ pub fn rog_bios_group(supported: &SupportedFunctions, states: &mut SystemState,
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
changed = ui changed = ui
.selectable_value( .selectable_value(
&mut states.bios.dedicated_gfx, &mut dedicated_gfx,
GpuMode::Discrete, GpuMode::Discrete,
"Dedicated (Ultimate)", "Dedicated (Ultimate)",
) )
.clicked() .clicked()
|| ui || ui
.selectable_value( .selectable_value(
&mut states.bios.dedicated_gfx, &mut dedicated_gfx,
GpuMode::Optimus, GpuMode::Optimus,
"Optimus (Hybrid)", "Optimus (Hybrid)",
) )
.clicked(); .clicked();
}); });
if reboot_required {
ui.horizontal_wrapped(|ui| ui.heading("REBOOT REQUIRED"));
}
}); });
}); });
@@ -121,7 +132,7 @@ pub fn rog_bios_group(supported: &SupportedFunctions, states: &mut SystemState,
.asus_dbus .asus_dbus
.proxies() .proxies()
.rog_bios() .rog_bios()
.set_gpu_mux_mode(states.bios.dedicated_gfx) .set_gpu_mux_mode(dedicated_gfx)
.map_err(|err| { .map_err(|err| {
states.error = Some(err.to_string()); states.error = Some(err.to_string());
}) })
+2 -2
View File
@@ -81,7 +81,7 @@ impl<'a> RogDbusClientBlocking<'a> {
Ok((RogDbusClientBlocking { proxies }, conn)) Ok((RogDbusClientBlocking { proxies }, conn))
} }
pub fn proxies(&self) -> &DbusProxiesBlocking { pub fn proxies(&self) -> &DbusProxiesBlocking<'_> {
&self.proxies &self.proxies
} }
} }
@@ -150,7 +150,7 @@ impl<'a> RogDbusClient<'a> {
Ok((RogDbusClient { proxies }, conn)) Ok((RogDbusClient { proxies }, conn))
} }
pub fn proxies(&self) -> &DbusProxies { pub fn proxies(&self) -> &DbusProxies<'_> {
&self.proxies &self.proxies
} }
} }
+2 -1
View File
@@ -1,5 +1,6 @@
[package] [package]
name = "rog_platform" name = "rog_platform"
license = "MPL-2.0"
version.workspace = true version.workspace = true
edition = "2021" edition = "2021"
@@ -14,4 +15,4 @@ concat-idents.workspace = true
udev.workspace = true udev.workspace = true
inotify.workspace = true inotify.workspace = true
rusb.workspace = true rusb.workspace = true
+1 -1
View File
@@ -23,7 +23,7 @@ pub enum PlatformError {
impl fmt::Display for PlatformError { impl fmt::Display for PlatformError {
// This trait requires `fmt` with this exact signature. // This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
PlatformError::ParseVendor => write!(f, "Parse gfx vendor error"), PlatformError::ParseVendor => write!(f, "Parse gfx vendor error"),
PlatformError::ParseNum => write!(f, "Parse number error"), PlatformError::ParseNum => write!(f, "Parse number error"),
+4 -4
View File
@@ -19,7 +19,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub(crate) fn to_device(sys_path: &Path) -> Result<Device> { pub(crate) fn to_device(sys_path: &Path) -> Result<Device> {
Device::from_syspath(sys_path) Device::from_syspath(sys_path)
.map_err(|e| PlatformError::Udev("Couldn't transform syspath to device".to_string(), e)) .map_err(|e| PlatformError::Udev("Couldn't transform syspath to device".to_owned(), e))
} }
pub fn has_attr(device: &Device, attr_name: &str) -> bool { pub fn has_attr(device: &Device, attr_name: &str) -> bool {
@@ -39,7 +39,7 @@ pub fn read_attr_bool(device: &Device, attr_name: &str) -> Result<bool> {
} }
return Ok(true); return Ok(true);
} }
Err(PlatformError::AttrNotFound(attr_name.to_string())) Err(PlatformError::AttrNotFound(attr_name.to_owned()))
} }
pub fn write_attr_bool(device: &mut Device, attr: &str, value: bool) -> Result<()> { pub fn write_attr_bool(device: &mut Device, attr: &str, value: bool) -> Result<()> {
@@ -53,7 +53,7 @@ pub fn read_attr_u8(device: &Device, attr_name: &str) -> Result<u8> {
let tmp = value.to_string_lossy(); let tmp = value.to_string_lossy();
return tmp.parse::<u8>().map_err(|_| PlatformError::ParseNum); return tmp.parse::<u8>().map_err(|_| PlatformError::ParseNum);
} }
Err(PlatformError::AttrNotFound(attr_name.to_string())) Err(PlatformError::AttrNotFound(attr_name.to_owned()))
} }
pub fn write_attr_u8(device: &mut Device, attr: &str, value: u8) -> Result<()> { pub fn write_attr_u8(device: &mut Device, attr: &str, value: u8) -> Result<()> {
@@ -71,7 +71,7 @@ pub fn read_attr_u8_array(device: &Device, attr_name: &str) -> Result<Vec<u8>> {
.collect(); .collect();
return Ok(tmp); return Ok(tmp);
} }
Err(PlatformError::AttrNotFound(attr_name.to_string())) Err(PlatformError::AttrNotFound(attr_name.to_owned()))
} }
pub fn write_attr_u8_array(device: &mut Device, attr: &str, values: &[u8]) -> Result<()> { pub fn write_attr_u8_array(device: &mut Device, attr: &str, values: &[u8]) -> Result<()> {
+8 -7
View File
@@ -11,12 +11,12 @@ use crate::{
}; };
/// The "platform" device provides access to things like: /// The "platform" device provides access to things like:
/// - dgpu_disable /// - `dgpu_disable`
/// - egpu_enable /// - `egpu_enable`
/// - panel_od /// - `panel_od`
/// - gpu_mux /// - `gpu_mux`
/// - keyboard_mode, set keyboard RGB mode and speed /// - `keyboard_mode`, set keyboard RGB mode and speed
/// - keyboard_state, set keyboard power states /// - `keyboard_state`, set keyboard power states
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)] #[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
pub struct AsusPlatform { pub struct AsusPlatform {
path: PathBuf, path: PathBuf,
@@ -65,12 +65,13 @@ impl AsusPlatform {
attr_u8!("platform_profile", pp_path); attr_u8!("platform_profile", pp_path);
} }
#[derive(Serialize, Deserialize, Type, Debug, PartialEq, Eq, Clone, Copy)] #[derive(Serialize, Deserialize, Default, Type, Debug, PartialEq, Eq, Clone, Copy)]
pub enum GpuMode { pub enum GpuMode {
Discrete, Discrete,
Optimus, Optimus,
Integrated, Integrated,
Egpu, Egpu,
#[default]
Error, Error,
NotSupported, NotSupported,
} }
+6 -6
View File
@@ -9,12 +9,12 @@ use crate::{
}; };
/// The "platform" device provides access to things like: /// The "platform" device provides access to things like:
/// - dgpu_disable /// - `dgpu_disable`
/// - egpu_enable /// - `egpu_enable`
/// - panel_od /// - `panel_od`
/// - gpu_mux /// - `gpu_mux`
/// - keyboard_mode, set keyboard RGB mode and speed /// - `keyboard_mode`, set keyboard RGB mode and speed
/// - keyboard_state, set keyboard power states /// - `keyboard_state`, set keyboard power states
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)] #[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
pub struct AsusPower { pub struct AsusPower {
mains: PathBuf, mains: PathBuf,
+2 -2
View File
@@ -11,7 +11,7 @@ impl USBRaw {
for device in rusb::devices()?.iter() { for device in rusb::devices()?.iter() {
let device_desc = device.device_descriptor()?; let device_desc = device.device_descriptor()?;
if device_desc.vendor_id() == 0x0b05 && device_desc.product_id() == id_product { if device_desc.vendor_id() == 0x0b05 && device_desc.product_id() == id_product {
let handle = Self::get_dev_handle(device)?; let handle = Self::get_dev_handle(&device)?;
return Ok(Self(handle)); return Ok(Self(handle));
} }
} }
@@ -23,7 +23,7 @@ impl USBRaw {
} }
fn get_dev_handle( fn get_dev_handle(
device: Device<rusb::GlobalContext>, device: &Device<rusb::GlobalContext>,
) -> Result<DeviceHandle<rusb::GlobalContext>> { ) -> Result<DeviceHandle<rusb::GlobalContext>> {
// We don't expect this ID to ever change // We don't expect this ID to ever change
let mut device = device.open()?; let mut device = device.open()?;
+2 -1
View File
@@ -1,5 +1,6 @@
[package] [package]
name = "rog_profiles" name = "rog_profiles"
license = "MPL-2.0"
version.workspace = true version.workspace = true
authors = ["Luke D. Jones <luke@ljones.dev>"] authors = ["Luke D. Jones <luke@ljones.dev>"]
edition = "2021" edition = "2021"
@@ -13,4 +14,4 @@ udev.workspace = true
serde.workspace = true serde.workspace = true
serde_derive.workspace = true serde_derive.workspace = true
zbus = { workspace = true, optional = true } zbus = { workspace = true, optional = true }
+13 -6
View File
@@ -72,6 +72,14 @@ impl Profile {
file.write_all(<&str>::from(profile).as_bytes())?; file.write_all(<&str>::from(profile).as_bytes())?;
Ok(()) Ok(())
} }
pub fn from_throttle_thermal_policy(num: u8) -> Self {
match num {
1 => Self::Performance,
2 => Self::Quiet,
_ => Self::Balanced,
}
}
} }
impl Default for Profile { impl Default for Profile {
@@ -93,7 +101,6 @@ impl From<Profile> for &str {
impl From<&str> for Profile { impl From<&str> for Profile {
fn from(profile: &str) -> Profile { fn from(profile: &str) -> Profile {
match profile.to_ascii_lowercase().trim() { match profile.to_ascii_lowercase().trim() {
"balanced" => Profile::Balanced,
"performance" => Profile::Performance, "performance" => Profile::Performance,
"quiet" => Profile::Quiet, "quiet" => Profile::Quiet,
_ => Profile::Balanced, _ => Profile::Balanced,
@@ -202,7 +209,7 @@ impl FanCurveProfiles {
/// Reset the stored (self) and device curve to the defaults of the platform. /// Reset the stored (self) and device curve to the defaults of the platform.
/// ///
/// Each platform_profile has a different default and the defualt can be read /// Each `platform_profile` has a different default and the defualt can be read
/// only for the currently active profile. /// only for the currently active profile.
pub fn set_active_curve_to_defaults( pub fn set_active_curve_to_defaults(
&mut self, &mut self,
@@ -296,12 +303,12 @@ impl FanCurveProfiles {
FanCurvePU::GPU => &self.balanced.gpu, FanCurvePU::GPU => &self.balanced.gpu,
}, },
Profile::Performance => match pu { Profile::Performance => match pu {
FanCurvePU::CPU => &self.balanced.cpu, FanCurvePU::CPU => &self.performance.cpu,
FanCurvePU::GPU => &self.balanced.gpu, FanCurvePU::GPU => &self.performance.gpu,
}, },
Profile::Quiet => match pu { Profile::Quiet => match pu {
FanCurvePU::CPU => &self.balanced.cpu, FanCurvePU::CPU => &self.quiet.cpu,
FanCurvePU::GPU => &self.balanced.gpu, FanCurvePU::GPU => &self.quiet.gpu,
}, },
} }
} }
+9
View File
@@ -0,0 +1,9 @@
# If you see this, run "rustup self update" to get rustup 1.23 or newer.
# NOTE: above comment is for older `rustup` (before TOML support was added),
# which will treat the first line as the toolchain name, and therefore show it
# to the user in the error, instead of "error: invalid channel name '[toolchain]'".
[toolchain]
channel = "1.65.0"
components = [ "rustfmt", "clippy" ]