automatically update config when changed

This commit is contained in:
Ferdinand Schober
2026-03-26 13:27:05 +01:00
parent 2e1b5278ce
commit eb8c2d091b
6 changed files with 267 additions and 38 deletions

View File

@@ -49,7 +49,7 @@ pub(crate) enum CaptureType {
EnterOnly,
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Debug)]
enum CaptureRequest {
/// capture must release the mouse
Release,
@@ -59,6 +59,8 @@ enum CaptureRequest {
Destroy(CaptureHandle),
/// reenable input capture
Reenable,
/// set release bind
SetReleaseBind(Vec<scancode::Linux>),
}
impl Capture {
@@ -131,6 +133,10 @@ impl Capture {
pub(crate) async fn event(&mut self) -> ICaptureEvent {
self.event_rx.recv().await.expect("channel closed")
}
pub(crate) fn set_release_bind(&mut self, bind: Vec<scancode::Linux>) {
let _ = self.request_tx.send(CaptureRequest::SetReleaseBind(bind));
}
}
/// debounce a statement `$st`, i.e. the statement is executed only if the
@@ -205,6 +211,9 @@ impl CaptureTask {
CaptureRequest::Create(h, p, t) => self.add_capture(h, p, t),
CaptureRequest::Destroy(h) => self.remove_capture(h),
CaptureRequest::Release => { /* nothing to do */ }
CaptureRequest::SetReleaseBind(bind) => {
self.release_bind.borrow_mut().clone_from(&bind);
}
},
_ = self.cancellation_token.cancelled() => return,
}
@@ -295,6 +304,9 @@ impl CaptureTask {
self.remove_capture(h);
capture.destroy(h).await?;
}
CaptureRequest::SetReleaseBind(bind) => {
self.release_bind.borrow_mut().clone_from(&bind);
}
},
_ = self.cancellation_token.cancelled() => break,
}

View File

@@ -9,6 +9,8 @@ use slab::Slab;
use lan_mouse_ipc::{ClientConfig, ClientHandle, ClientState, Position};
use crate::config::ConfigClient;
#[derive(Clone, Default)]
pub struct ClientManager {
clients: Rc<RefCell<Slab<(ClientConfig, ClientState)>>>,
@@ -24,6 +26,25 @@ impl ClientManager {
.collect::<Vec<_>>()
}
pub fn add_with_config(&self, config_client: ConfigClient) -> ClientHandle {
let config = ClientConfig {
hostname: config_client.hostname,
fix_ips: config_client.ips.into_iter().collect(),
port: config_client.port,
pos: config_client.pos,
cmd: config_client.enter_hook,
};
let state = ClientState {
active: config_client.active,
ips: HashSet::from_iter(config.fix_ips.iter().cloned()),
..Default::default()
};
let handle = self.add_client();
self.set_config(handle, config);
self.set_state(handle, state);
handle
}
/// add a new client to this manager
pub fn add_client(&self) -> ClientHandle {
self.clients.borrow_mut().insert(Default::default()) as ClientHandle
@@ -230,6 +251,15 @@ impl ClientManager {
.and_then(|(c, _)| c.cmd.clone())
}
/// returns all clients that are currently registered
pub(crate) fn registered_clients(&self) -> Vec<ClientHandle> {
self.clients
.borrow()
.iter()
.map(|(h, _)| h as ClientHandle)
.collect()
}
/// returns all clients that are currently active
pub(crate) fn active_clients(&self) -> Vec<ClientHandle> {
self.clients

View File

@@ -1,6 +1,7 @@
use crate::capture_test::TestCaptureArgs;
use crate::emulation_test::TestEmulationArgs;
use clap::{Parser, Subcommand, ValueEnum};
use notify::{EventKind, RecommendedWatcher, Watcher};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env::{self, VarError};
@@ -46,7 +47,7 @@ fn default_path() -> Result<PathBuf, VarError> {
Ok(PathBuf::from(default_path))
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
struct ConfigToml {
capture_backend: Option<CaptureBackend>,
emulation_backend: Option<EmulationBackend>,
@@ -244,8 +245,14 @@ pub struct Config {
cert_path: PathBuf,
/// path to the config file used
config_path: PathBuf,
/// path to config directory (parent of above)
config_dir: PathBuf,
/// the (optional) toml config and it's path
config_toml: Option<ConfigToml>,
// filesystem watcher
watcher: notify::RecommendedWatcher,
// channel for filesystem events
watch_rx: tokio::sync::mpsc::Receiver<Result<notify::Event, notify::Error>>,
}
pub struct ConfigClient {
@@ -311,6 +318,8 @@ pub enum ConfigError {
Io(#[from] io::Error),
#[error(transparent)]
Var(#[from] VarError),
#[error(transparent)]
Watcher(#[from] notify::Error),
}
const DEFAULT_RELEASE_KEYS: [scancode::Linux; 4] =
@@ -342,12 +351,55 @@ impl Config {
.or(config_toml.as_ref().and_then(|c| c.cert_path.clone()))
.unwrap_or(default_path()?.join(CERT_FILE_NAME));
Ok(Config {
let (tx, watch_rx) = tokio::sync::mpsc::channel(16);
let watcher = RecommendedWatcher::new(
move |res| {
let _ = tx.blocking_send(res);
},
notify::Config::default(),
)?;
let config_dir = config_path
.parent()
.expect("config directory")
.to_path_buf();
let mut config = Config {
args,
cert_path,
config_path,
config_dir,
config_toml,
})
watcher,
watch_rx,
};
config.watch()?;
Ok(config)
}
fn watch(&mut self) -> Result<(), notify::Error> {
self.watcher
.watch(&self.config_dir, notify::RecursiveMode::NonRecursive)?;
Ok(())
}
fn unwatch(&mut self) -> Result<(), notify::Error> {
self.watcher.unwatch(&self.config_dir)?;
Ok(())
}
pub async fn changed(&mut self) -> Result<(), notify::Error> {
loop {
let event = self.watch_rx.recv().await.expect("channel closed");
let event = event.expect("filesystem event");
if event.paths.contains(&self.config_path)
&& matches!(
event.kind,
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
)
&& self.read_from_disk()?
{
return Ok(());
}
}
}
/// the command to run
@@ -428,9 +480,6 @@ impl Config {
/// set authorized keys
pub fn set_authorized_keys(&mut self, fingerprints: HashMap<String, String>) {
if fingerprints.is_empty() {
return;
}
if self.config_toml.is_none() {
self.config_toml = Default::default();
}
@@ -440,38 +489,58 @@ impl Config {
.authorized_fingerprints = Some(fingerprints);
}
pub fn write_back(&self) -> Result<(), io::Error> {
log::info!("writing config to {:?}", &self.config_path);
/* load the current configuration file */
let current_config = match fs::read_to_string(&self.config_path) {
Ok(c) => c.parse::<DocumentMut>().unwrap_or_default(),
pub fn read_from_disk(&mut self) -> Result<bool, io::Error> {
log::info!("reading config from {:?}", &self.config_path);
let current_config = fs::read_to_string(&self.config_path)?;
let current_config = match current_config.parse::<DocumentMut>() {
Ok(c) => c,
Err(e) => {
log::info!("{:?} {e} => creating new config", self.config_path());
Default::default()
log::warn!("{:?} {e}", self.config_path());
return Ok(false);
}
};
let _current_config =
toml_edit::de::from_document::<ConfigToml>(current_config).unwrap_or_default();
let mut changed = false;
match toml_edit::de::from_document::<ConfigToml>(current_config) {
Ok(current_config) => {
changed = self
.config_toml
.as_ref()
.is_none_or(|c| c != &current_config);
self.config_toml.replace(current_config);
}
Err(e) => log::warn!("{:?} {e}", self.config_path()),
};
Ok(changed)
}
pub fn write_back(&mut self) -> Result<(), io::Error> {
log::info!("writing config to {:?}", &self.config_path);
/* the new config */
let new_config = self.config_toml.clone().unwrap_or_default();
// let new_config = toml_edit::ser::to_document::<ConfigToml>(&new_config).expect("fixme");
let new_config = toml_edit::ser::to_string_pretty(&new_config).expect("config");
/*
* TODO merge documents => eventually we might want to split this up into clients configured
* TODO merge with current config file to preserve comments
* => eventually we might want to split this up into clients configured
* via the config file and clients managed through the GUI / frontend.
* The latter should be saved to $XDG_DATA_HOME instead of $XDG_CONFIG_HOME,
* and clients configured through .config could be made permanent.
* For now we just override the config file.
*/
let _ = self.unwatch();
/* write new config to file */
if let Some(p) = self.config_path().parent() {
fs::create_dir_all(p)?;
}
let mut f = File::create(self.config_path())?;
f.write_all(new_config.as_bytes())?;
{
let mut f = File::create(self.config_path())?;
f.write_all(new_config.as_bytes())?;
f.sync_all()?;
}
let _ = self.watch();
Ok(())
}

View File

@@ -11,8 +11,8 @@ use crate::{
use futures::StreamExt;
use hickory_resolver::ResolveError;
use lan_mouse_ipc::{
AsyncFrontendListener, ClientConfig, ClientHandle, ClientState, FrontendEvent, FrontendRequest,
IpcError, IpcListenerCreationError, Position, Status,
AsyncFrontendListener, ClientHandle, FrontendEvent, FrontendRequest, IpcError,
IpcListenerCreationError, Position, Status,
};
use log;
use std::{
@@ -83,21 +83,7 @@ impl Service {
pub async fn new(config: Config) -> Result<Self, ServiceError> {
let client_manager = ClientManager::default();
for client in config.clients() {
let config = ClientConfig {
hostname: client.hostname,
fix_ips: client.ips.into_iter().collect(),
port: client.port,
pos: client.pos,
cmd: client.enter_hook,
};
let state = ClientState {
active: client.active,
ips: HashSet::from_iter(config.fix_ips.iter().cloned()),
..Default::default()
};
let handle = client_manager.add_client();
client_manager.set_config(handle, config);
client_manager.set_state(handle, state);
client_manager.add_with_config(client);
}
// load certificate
@@ -164,6 +150,7 @@ impl Service {
event = self.emulation.event() => self.handle_emulation_event(event),
event = self.capture.event() => self.handle_capture_event(event),
event = self.resolver.event() => self.handle_resolver_event(event),
_ = self.config.changed() => self.handle_config_change(),
r = signal::ctrl_c() => break r.expect("failed to wait for CTRL+C"),
}
}
@@ -255,6 +242,30 @@ impl Service {
}
}
fn handle_config_change(&mut self) {
for h in self.client_manager.registered_clients() {
self.remove_client(h);
}
for c in self.config.clients() {
let handle = self.client_manager.add_with_config(c);
log::info!("added client {handle}");
let (c, s) = self.client_manager.get_state(handle).unwrap();
if s.active {
self.client_manager.deactivate_client(handle);
self.activate_client(handle);
}
self.notify_frontend(FrontendEvent::Created(handle, c, s));
}
let release_bind = self.config.release_bind();
self.capture.set_release_bind(release_bind);
let authorized_keys = self.config.authorized_fingerprints();
self.authorized_keys
.write()
.unwrap()
.clone_from(&authorized_keys);
self.sync_frontend();
}
async fn handle_frontend_pending(&mut self) {
while let Some(event) = self.pending_frontend_events.pop_front() {
self.frontend_listener.broadcast(event).await;
@@ -477,7 +488,7 @@ impl Service {
}
fn activate_client(&mut self, handle: ClientHandle) {
log::debug!("activating client");
log::debug!("activating client {handle}");
/* resolve dns on activate */
self.resolve(handle);