Skip to content

Commit

Permalink
moved half the shit to the notifier (renamed to proxy), turns out you…
Browse files Browse the repository at this point in the history
… can't do much from a windows service
  • Loading branch information
F0903 committed Sep 7, 2024
1 parent f37cf6d commit 85c5b65
Show file tree
Hide file tree
Showing 20 changed files with 124 additions and 134 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["shared", "notification_provider"]
members = ["shared", "autopower_proxy"]

[workspace.package]
version = "3.0.0"
Expand Down Expand Up @@ -28,6 +28,7 @@ codegen-units = 1
[workspace.dependencies]
bincode = "^1.3"
serde = { version = "^1.0", features = ["derive"] }
serde_json = "^1.0"
windows = { version = "^0.58" }

[dependencies]
Expand All @@ -39,8 +40,5 @@ windows = { workspace = true, features = [
"Win32_System_Power",
"Win32_System_Services",
"Win32_System_Threading",
"Win32_UI_WindowsAndMessaging",
"Win32_Graphics_Gdi",
] }
serde = { workspace = true }
serde_json = "^1.0"
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "autopower_notification_provider"
name = "autopower_proxy"
version.workspace = true
edition.workspace = true
publish.workspace = true
Expand All @@ -20,5 +20,9 @@ windows = { workspace = true, features = [
"Win32_System_IO",
"Win32_System_Com",
"Win32_System_Console",
"Win32_Graphics_Gdi",
"Win32_System_Power",
"Win32_System_Registry",
] }
serde = { workspace = true }
serde_json = { workspace = true }
File renamed without changes.
2 changes: 1 addition & 1 deletion src/config/mod.rs → autopower_proxy/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ mod config_error;
mod power_scheme;
mod state_config;

use autopower_shared::logging::Logger;
pub use config_error::ConfigError;
pub use power_scheme::PowerScheme;
use state_config::StateConfig;

use crate::display::RefreshRateMode;
use autopower_shared::logging::Logger;
use serde::{Deserialize, Serialize};
use std::{
fs::File,
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::PowerScheme;
use crate::{
display::{set_display_refresh_rate, RefreshRateMode},
notification_provider::NotificationProvider,
toast::Toast,
};
use serde::{Deserialize, Serialize};
use windows::Win32::System::Power::PowerSetActiveScheme;
Expand All @@ -18,15 +18,13 @@ pub struct StateConfig {
}

impl StateConfig {
pub fn change_to(&self, notif_provider: &mut NotificationProvider) -> Result<()> {
unsafe {
PowerSetActiveScheme(None, Some(&self.power_scheme.to_guid())).ok()?;
pub fn change_to(&self) -> Result<()> {
if self.send_notification {
Toast::new("AutoPower", format!("Switching to {}", self.state_name)).send()?;
}

if self.send_notification {
notif_provider
.send_display_command("AutoPower", &format!("Switching to {}.", self.state_name))
.map_err(|e| format!("Could not send notification!\n{}", e))?;
unsafe {
PowerSetActiveScheme(None, Some(&self.power_scheme.to_guid())).ok()?;
}

if self.change_refresh_rate {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RefreshRateMode {
Max,
Value(u32),
Expand Down
41 changes: 20 additions & 21 deletions notification_provider/src/main.rs → autopower_proxy/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,50 @@
#![windows_subsystem = "windows"]

mod config;
mod display;
mod toast;

use config::PowerConfig;

use autopower_shared::{
logging::Logger,
notification_command::NotificationCommand,
pipe::{Client, Pipe, PIPE_NAME},
proxy_command::{PowerConfigSelection, ProxyCommand},
stream::Read,
};
use toast::Toast;
use windows::Win32::System::Com::CoInitialize;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

const LOGGER: Logger = Logger::new("main", "autopower_notifier");
const LOGGER: Logger = Logger::new("main", "autopower_proxy");

fn execute_display_command(command: NotificationCommand) -> Result<()> {
let mut cmd_lines = command.content.lines();
let title = cmd_lines.next().expect("Could not get next cmd line!");
let content = cmd_lines
.next()
.expect("Could not get next second cmd line!");
let toast = Toast::new(title, content);
toast.send()?;
Ok(())
fn change_power_config(selection: PowerConfigSelection) -> Result<()> {
let config = PowerConfig::get_or_create()?;
match selection {
PowerConfigSelection::Wired => config.get_wired_config().change_to(),
PowerConfigSelection::Battery => config.get_battery_config().change_to(),
}
}

fn execute_command(command: NotificationCommand) -> Result<()> {
match command.name.as_str() {
"display" => execute_display_command(command),
_ => Ok(()),
fn execute_command(command: ProxyCommand) -> Result<()> {
match command {
ProxyCommand::ChangePowerConfig(selection) => change_power_config(selection),
}
}

fn read_notification_command(input: &mut Pipe<Client, Read>) -> Result<NotificationCommand> {
fn read_command(input: &mut Pipe<Client, Read>) -> Result<ProxyCommand> {
LOGGER.debug(format!("Waiting for input..."));
let object = input.read_to()?;
LOGGER.debug(format!("Input object:\n{}", object));
LOGGER.debug(format!("Input object:\n{:?}", object));
Ok(object)
}

fn input_loop() -> Result<()> {
let mut input = Pipe::create_client_retrying(PIPE_NAME)
.map_err(|e| format!("Could not create client pipe!\n{}", e))?;
LOGGER.debug("notification_provider: waiting for input...");
LOGGER.debug("Waiting for input...");
loop {
let command = match read_notification_command(&mut input) {
let command = match read_command(&mut input) {
Ok(x) => x,
Err(e) => {
LOGGER.error(format!("Could not read command!\n{}", e));
Expand All @@ -67,7 +66,7 @@ fn run() -> Result<()> {
}

fn main() -> Result<()> {
LOGGER.debug("Starting notification provider...");
LOGGER.debug("Starting proxy...");
std::panic::set_hook(Box::new(|info| {
LOGGER.error(info);
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ use windows::{

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

pub struct Toast<'a> {
title: &'a str,
description: &'a str,
#[derive(Debug)]
pub struct Toast {
title: String,
description: String,
}

impl<'a> Toast<'a> {
pub fn new(title: &'a str, description: &'a str) -> Self {
Self { title, description }
impl Toast {
pub fn new(title: impl ToString, description: impl ToString) -> Self {
Self {
title: title.to_string(),
description: description.to_string(),
}
}

fn create_notifcation(&self) -> Result<ToastNotification> {
Expand All @@ -30,7 +34,7 @@ impl<'a> Toast<'a> {
.Item(i)
.map_err(|e| format!("Could not get item!\n{}", e))?;
let node = &toast_xml
.CreateTextNode(&HSTRING::from(self.description))
.CreateTextNode(&HSTRING::from(&self.description))
.map_err(|e| format!("Could not create text node!\n{}", e))?;
elem.AppendChild(node)
.map_err(|e| format!("Could not append child!\n{}", e))?;
Expand All @@ -47,7 +51,7 @@ impl<'a> Toast<'a> {
.SetExpiresOnReboot(true)
.map_err(|e| format!("Could not set expire on reboot!\n{}", e))?;

let title = to_h_string(self.title)?;
let title = to_h_string(&self.title)?;
let notifier = ToastNotificationManager::CreateToastNotifierWithId(&title)
.map_err(|e| format!("Could not create toast notifier with id!\n{}", e))?;
notifier
Expand Down
2 changes: 2 additions & 0 deletions shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ windows = { workspace = true, features = [
"Win32_Storage_FileSystem",
"Win32_System_IO",
"Win32_Security",
"Win32_UI_WindowsAndMessaging",
] }
serde_json = { workspace = true }
serde = { workspace = true }
bincode = { workspace = true }
2 changes: 1 addition & 1 deletion shared/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod logging;
pub mod notification_command;
pub mod pipe;
pub mod proxy_command;
pub mod stream;
pub mod util;
pub mod winstr;
Expand Down
15 changes: 0 additions & 15 deletions shared/src/notification_command.rs

This file was deleted.

2 changes: 1 addition & 1 deletion shared/src/pipe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

pub const PIPE_BUFFER_SIZE: usize = 1024;
pub const PIPE_PATH_ROOT: &str = "\\\\.\\pipe\\";
pub const PIPE_NAME: &str = "AutoPowerNotificationPipe";
pub const PIPE_NAME: &str = "AutoPowerProxy";

const LOGGER: Logger = Logger::new("pipe", "autopower_shared");

Expand Down
12 changes: 12 additions & 0 deletions shared/src/proxy_command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
pub enum PowerConfigSelection {
Wired,
Battery,
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
pub enum ProxyCommand {
ChangePowerConfig(PowerConfigSelection),
}
4 changes: 1 addition & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use autopower_shared::logging::Logger;

mod config;
mod display;
mod handler_data;
mod notification_provider;
mod proxy;
mod services;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
Expand Down
42 changes: 0 additions & 42 deletions src/notification_provider.rs

This file was deleted.

34 changes: 34 additions & 0 deletions src/proxy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use autopower_shared::{
logging::Logger,
pipe::{Pipe, Server, PIPE_NAME},
proxy_command::ProxyCommand,
stream::Write,
};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

const LOGGER: Logger = Logger::new("notifications", "autopower");

pub struct Proxy {
pipe: Pipe<Server, Write>,
}

impl Proxy {
pub fn create() -> Result<Self> {
LOGGER.debug("Creating pipe...");
let pipe = Pipe::create_server(PIPE_NAME)?;
LOGGER.debug("Created pipe, waiting for connection...");
pipe.connect()?;
Ok(Proxy { pipe })
}
pub fn send_command(&mut self, command: ProxyCommand) -> Result<()> {
LOGGER.debug(format!("Sent command:\n{:?}", command));
self.pipe.write_as(command)?;
Ok(())
}

pub fn terminate(&mut self) -> Result<()> {
LOGGER.debug("Terminating proxy...");
self.pipe.close()
}
}
Loading

0 comments on commit 85c5b65

Please sign in to comment.