Compare commits

..

1 Commits

Author SHA1 Message Date
Ferdinand Schober
9c5ff85f46 include commit-hash in version 2024-09-02 19:24:43 +02:00
53 changed files with 1214 additions and 1704 deletions

View File

@@ -55,9 +55,7 @@ jobs:
# choco install msys2 # choco install msys2
# choco install visualstudio2022-workload-vctools # choco install visualstudio2022-workload-vctools
# choco install pkgconfiglite # choco install pkgconfiglite
py -m venv .venv pipx install gvsbuild
.venv\Scripts\activate.ps1
py -m pip install gvsbuild
# see https://github.com/wingtk/gvsbuild/pull/1004 # see https://github.com/wingtk/gvsbuild/pull/1004
Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin" Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin"
Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin" Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin"

View File

@@ -66,9 +66,7 @@ jobs:
# choco install msys2 # choco install msys2
# choco install visualstudio2022-workload-vctools # choco install visualstudio2022-workload-vctools
# choco install pkgconfiglite # choco install pkgconfiglite
py -m venv .venv pipx install gvsbuild
.venv\Scripts\activate.ps1
py -m pip install gvsbuild
# see https://github.com/wingtk/gvsbuild/pull/1004 # see https://github.com/wingtk/gvsbuild/pull/1004
Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin" Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin"
Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin" Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin"

View File

@@ -51,9 +51,7 @@ jobs:
# choco install msys2 # choco install msys2
# choco install visualstudio2022-workload-vctools # choco install visualstudio2022-workload-vctools
# choco install pkgconfiglite # choco install pkgconfiglite
py -m venv .venv pipx install gvsbuild
.venv\Scripts\activate.ps1
py -m pip install gvsbuild
# see https://github.com/wingtk/gvsbuild/pull/1004 # see https://github.com/wingtk/gvsbuild/pull/1004
Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin" Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin"
Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin" Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin"

57
Cargo.lock generated
View File

@@ -1226,7 +1226,6 @@ version = "0.2.1"
dependencies = [ dependencies = [
"ashpd", "ashpd",
"async-trait", "async-trait",
"bitflags 2.6.0",
"core-graphics", "core-graphics",
"futures", "futures",
"input-event", "input-event",
@@ -1314,17 +1313,21 @@ dependencies = [
name = "lan-mouse" name = "lan-mouse"
version = "0.9.1" version = "0.9.1"
dependencies = [ dependencies = [
"anyhow",
"async-channel",
"clap", "clap",
"endi",
"env_logger", "env_logger",
"futures", "futures",
"glib-build-tools",
"gtk4",
"hickory-resolver", "hickory-resolver",
"hostname 0.4.0",
"input-capture", "input-capture",
"input-emulation", "input-emulation",
"input-event", "input-event",
"lan-mouse-cli",
"lan-mouse-gtk",
"lan-mouse-ipc",
"lan-mouse-proto", "lan-mouse-proto",
"libadwaita",
"libc", "libc",
"local-channel", "local-channel",
"log", "log",
@@ -1337,41 +1340,6 @@ dependencies = [
"toml", "toml",
] ]
[[package]]
name = "lan-mouse-cli"
version = "0.1.0"
dependencies = [
"futures",
"lan-mouse-ipc",
"tokio",
]
[[package]]
name = "lan-mouse-gtk"
version = "0.1.0"
dependencies = [
"async-channel",
"glib-build-tools",
"gtk4",
"hostname 0.4.0",
"lan-mouse-ipc",
"libadwaita",
"log",
]
[[package]]
name = "lan-mouse-ipc"
version = "0.1.0"
dependencies = [
"futures",
"log",
"serde",
"serde_json",
"thiserror",
"tokio",
"tokio-stream",
]
[[package]] [[package]]
name = "lan-mouse-proto" name = "lan-mouse-proto"
version = "0.1.0" version = "0.1.0"
@@ -2122,17 +2090,6 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "tokio-stream"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]] [[package]]
name = "tokio-util" name = "tokio-util"
version = "0.7.11" version = "0.7.11"

View File

@@ -1,13 +1,5 @@
[workspace] [workspace]
members = [ members = ["input-capture", "input-emulation", "input-event", "lan-mouse-proto"]
"input-capture",
"input-emulation",
"input-event",
"lan-mouse-ipc",
"lan-mouse-cli",
"lan-mouse-gtk",
"lan-mouse-proto",
]
[package] [package]
name = "lan-mouse" name = "lan-mouse"
@@ -25,14 +17,12 @@ lto = "fat"
input-event = { path = "input-event", version = "0.2.1" } input-event = { path = "input-event", version = "0.2.1" }
input-emulation = { path = "input-emulation", version = "0.2.1", default-features = false } input-emulation = { path = "input-emulation", version = "0.2.1", default-features = false }
input-capture = { path = "input-capture", version = "0.2.0", default-features = false } input-capture = { path = "input-capture", version = "0.2.0", default-features = false }
lan-mouse-cli = { path = "lan-mouse-cli", version = "0.1.0" }
lan-mouse-gtk = { path = "lan-mouse-gtk", version = "0.1.0", optional = true }
lan-mouse-ipc = { path = "lan-mouse-ipc", version = "0.1.0" }
lan-mouse-proto = { path = "lan-mouse-proto", version = "0.1.0" } lan-mouse-proto = { path = "lan-mouse-proto", version = "0.1.0" }
hickory-resolver = "0.24.1" hickory-resolver = "0.24.1"
toml = "0.8" toml = "0.8"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
anyhow = "1.0.71"
log = "0.4.20" log = "0.4.20"
env_logger = "0.11.3" env_logger = "0.11.3"
serde_json = "1.0.107" serde_json = "1.0.107"
@@ -48,7 +38,16 @@ tokio = { version = "1.32.0", features = [
] } ] }
futures = "0.3.28" futures = "0.3.28"
clap = { version = "4.4.11", features = ["derive"] } clap = { version = "4.4.11", features = ["derive"] }
gtk = { package = "gtk4", version = "0.9.0", features = [
"v4_2",
], optional = true }
adw = { package = "libadwaita", version = "0.7.0", features = [
"v1_1",
], optional = true }
async-channel = { version = "2.1.1", optional = true }
hostname = "0.4.0"
slab = "0.4.9" slab = "0.4.9"
endi = "1.1.0"
thiserror = "1.0.61" thiserror = "1.0.61"
tokio-util = "0.7.11" tokio-util = "0.7.11"
local-channel = "0.1.5" local-channel = "0.1.5"
@@ -56,10 +55,13 @@ local-channel = "0.1.5"
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2.148" libc = "0.2.148"
[build-dependencies]
glib-build-tools = { version = "0.20.0", optional = true }
[features] [features]
default = ["wayland", "x11", "xdg_desktop_portal", "libei", "gtk"] default = ["wayland", "x11", "xdg_desktop_portal", "libei", "gtk"]
wayland = ["input-capture/wayland", "input-emulation/wayland"] wayland = ["input-capture/wayland", "input-emulation/wayland"]
x11 = ["input-capture/x11", "input-emulation/x11"] x11 = ["input-capture/x11", "input-emulation/x11"]
xdg_desktop_portal = ["input-emulation/xdg_desktop_portal"] xdg_desktop_portal = ["input-emulation/xdg_desktop_portal"]
libei = ["input-event/libei", "input-capture/libei", "input-emulation/libei"] libei = ["input-event/libei", "input-capture/libei", "input-emulation/libei"]
gtk = ["dep:lan-mouse-gtk"] gtk = ["dep:gtk", "dep:adw", "dep:async-channel", "dep:glib-build-tools"]

View File

@@ -20,7 +20,7 @@ Focus lies on performance and a clean, manageable implementation that can easily
***blazingly fast™*** because it's written in rust. ***blazingly fast™*** because it's written in rust.
For an alternative (with slightly different goals) you may check out [Synergy 1 Community Edition](https://github.com/symless/synergy) or [Input Leap](https://github.com/input-leap) (Synergy fork). For an alternative (with slightly different goals) you may check out [Input Leap](https://github.com/input-leap).
> [!WARNING] > [!WARNING]
@@ -94,13 +94,6 @@ paru -S lan-mouse-bin
- nixpkgs: [search.nixos.org](https://search.nixos.org/packages?channel=unstable&show=lan-mouse&from=0&size=50&sort=relevance&type=packages&query=lan-mouse) - nixpkgs: [search.nixos.org](https://search.nixos.org/packages?channel=unstable&show=lan-mouse&from=0&size=50&sort=relevance&type=packages&query=lan-mouse)
- flake: [README.md](./nix/README.md) - flake: [README.md](./nix/README.md)
### Building from source with Nix
In the root of the project to build Lan Mouse, run
```sh
nix-build
```
You can find the executable in `result/bin/lan-mouse` .
### Manual Installation ### Manual Installation
@@ -123,7 +116,7 @@ sudo cp target/release/lan-mouse /usr/local/bin/
# install app icon # install app icon
sudo mkdir -p /usr/local/share/icons/hicolor/scalable/apps sudo mkdir -p /usr/local/share/icons/hicolor/scalable/apps
sudo cp lan-mouse-gtk/resources/de.feschber.LanMouse.svg /usr/local/share/icons/hicolor/scalable/apps sudo cp resources/de.feschber.LanMouse.svg /usr/local/share/icons/hicolor/scalable/apps
# update icon cache # update icon cache
gtk-update-icon-cache /usr/local/share/icons/hicolor/ gtk-update-icon-cache /usr/local/share/icons/hicolor/

View File

@@ -12,4 +12,12 @@ fn main() {
let git_describe = String::from_utf8(git_describe.stdout).unwrap(); let git_describe = String::from_utf8(git_describe.stdout).unwrap();
println!("cargo::rustc-env=GIT_DESCRIBE={git_describe}"); println!("cargo::rustc-env=GIT_DESCRIBE={git_describe}");
// composite_templates
#[cfg(feature = "gtk")]
glib_build_tools::compile_resources(
&["resources"],
"resources/resources.gresource.xml",
"lan-mouse.gresource",
);
} }

View File

@@ -1,3 +0,0 @@
{ pkgs ? import <nixpkgs> { }
}:
pkgs.callPackage nix/default.nix { }

46
flake.lock generated
View File

@@ -1,12 +1,30 @@
{ {
"nodes": { "nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1705309234,
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1728018373, "lastModified": 1716293225,
"narHash": "sha256-NOiTvBbRLIOe5F6RbHaAh6++BNjsb149fGZd1T4+KBg=", "narHash": "sha256-pU9ViBVE3XYb70xZx+jK6SEVphvt7xMTbm6yDIF4xPs=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "bc947f541ae55e999ffdb4013441347d83b00feb", "rev": "3eaeaeb6b1e08a016380c279f8846e0bd8808916",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -24,16 +42,17 @@
}, },
"rust-overlay": { "rust-overlay": {
"inputs": { "inputs": {
"flake-utils": "flake-utils",
"nixpkgs": [ "nixpkgs": [
"nixpkgs" "nixpkgs"
] ]
}, },
"locked": { "locked": {
"lastModified": 1728181869, "lastModified": 1716257780,
"narHash": "sha256-sQXHXsjIcGEoIHkB+RO6BZdrPfB+43V1TEpyoWRI3ww=", "narHash": "sha256-R+NjvJzKEkTVCmdrKRfPE4liX/KMGVqGUwwS5H8ET8A=",
"owner": "oxalica", "owner": "oxalica",
"repo": "rust-overlay", "repo": "rust-overlay",
"rev": "cd46aa3906c14790ef5cbe278d9e54f2c38f95c0", "rev": "4e5e3d2c5c9b2721bd266f9e43c14e96811b89d2",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -41,6 +60,21 @@
"repo": "rust-overlay", "repo": "rust-overlay",
"type": "github" "type": "github"
} }
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
} }
}, },
"root": "root", "root": "root",

View File

@@ -1,28 +1,16 @@
use std::f64::consts::PI;
use std::pin::Pin; use std::pin::Pin;
use std::task::{ready, Context, Poll}; use std::task::{Context, Poll};
use std::time::Duration;
use async_trait::async_trait; use async_trait::async_trait;
use futures_core::Stream; use futures_core::Stream;
use input_event::PointerEvent;
use tokio::time::{self, Instant, Interval};
use super::{Capture, CaptureError, CaptureEvent, Position}; use super::{Capture, CaptureError, CaptureEvent, CaptureHandle, Position};
pub struct DummyInputCapture { pub struct DummyInputCapture {}
start: Option<Instant>,
interval: Interval,
offset: (i32, i32),
}
impl DummyInputCapture { impl DummyInputCapture {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {}
start: None,
interval: time::interval(Duration::from_millis(1)),
offset: (0, 0),
}
} }
} }
@@ -34,11 +22,11 @@ impl Default for DummyInputCapture {
#[async_trait] #[async_trait]
impl Capture for DummyInputCapture { impl Capture for DummyInputCapture {
async fn create(&mut self, _pos: Position) -> Result<(), CaptureError> { async fn create(&mut self, _handle: CaptureHandle, _pos: Position) -> Result<(), CaptureError> {
Ok(()) Ok(())
} }
async fn destroy(&mut self, _pos: Position) -> Result<(), CaptureError> { async fn destroy(&mut self, _handle: CaptureHandle) -> Result<(), CaptureError> {
Ok(()) Ok(())
} }
@@ -51,36 +39,10 @@ impl Capture for DummyInputCapture {
} }
} }
const FREQUENCY_HZ: f64 = 1.0;
const RADIUS: f64 = 100.0;
impl Stream for DummyInputCapture { impl Stream for DummyInputCapture {
type Item = Result<(Position, CaptureEvent), CaptureError>; type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let current = ready!(self.interval.poll_tick(cx)); Poll::Pending
let event = match self.start {
None => {
self.start.replace(current);
CaptureEvent::Begin
}
Some(start) => {
let elapsed = start.elapsed();
let elapsed_sec_f64 = elapsed.as_secs_f64();
let second_fraction = elapsed_sec_f64 - elapsed_sec_f64 as u64 as f64;
let radians = second_fraction * 2. * PI * FREQUENCY_HZ;
let offset = (radians.cos() * RADIUS * 2., (radians * 2.).sin() * RADIUS);
let offset = (offset.0 as i32, offset.1 as i32);
let relative_motion = (offset.0 - self.offset.0, offset.1 - self.offset.1);
self.offset = offset;
let (dx, dy) = (relative_motion.0 as f64, relative_motion.1 as f64);
CaptureEvent::Input(input_event::Event::Pointer(PointerEvent::Motion {
time: 0,
dx,
dy,
}))
}
};
Poll::Ready(Some(Ok((Position::Left, event))))
} }
} }

View File

@@ -93,7 +93,7 @@ pub enum CaptureCreationError {
#[error("error creating windows capture backend")] #[error("error creating windows capture backend")]
Windows, Windows,
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
#[error("error creating macos capture backend: `{0}`")] #[error("error creating macos capture backend")]
MacOS(#[from] MacosCaptureCreationError), MacOS(#[from] MacosCaptureCreationError),
} }
@@ -165,9 +165,6 @@ pub enum X11InputCaptureCreationError {
pub enum MacosCaptureCreationError { pub enum MacosCaptureCreationError {
#[error("event source creation failed!")] #[error("event source creation failed!")]
EventSourceCreation, EventSourceCreation,
#[cfg(target_os = "macos")]
#[error("event tap creation failed")]
EventTapCreation,
#[error("failed to set CG Cursor property")] #[error("failed to set CG Cursor property")]
CGCursorProperty, CGCursorProperty,
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]

View File

@@ -1,9 +1,4 @@
use std::{ use std::{collections::HashSet, fmt::Display, task::Poll};
collections::{HashMap, HashSet, VecDeque},
fmt::Display,
mem::swap,
task::{ready, Poll},
};
use async_trait::async_trait; use async_trait::async_trait;
use futures::StreamExt; use futures::StreamExt;
@@ -117,48 +112,19 @@ impl Display for Backend {
} }
pub struct InputCapture { pub struct InputCapture {
/// capture backend
capture: Box<dyn Capture>, capture: Box<dyn Capture>,
/// keys pressed by active capture
pressed_keys: HashSet<scancode::Linux>, pressed_keys: HashSet<scancode::Linux>,
/// map from position to ids
position_map: HashMap<Position, Vec<CaptureHandle>>,
/// map from id to position
id_map: HashMap<CaptureHandle, Position>,
/// pending events
pending: VecDeque<(CaptureHandle, CaptureEvent)>,
} }
impl InputCapture { impl InputCapture {
/// create a new client with the given id /// create a new client with the given id
pub async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError> { pub async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
if let Some(v) = self.position_map.get_mut(&pos) { self.capture.create(id, pos).await
v.push(id);
Ok(())
} else {
self.position_map.insert(pos, vec![id]);
self.id_map.insert(id, pos);
self.capture.create(pos).await
}
} }
/// destroy the client with the given id, if it exists /// destroy the client with the given id, if it exists
pub async fn destroy(&mut self, id: CaptureHandle) -> Result<(), CaptureError> { pub async fn destroy(&mut self, id: CaptureHandle) -> Result<(), CaptureError> {
if let Some(pos) = self.id_map.remove(&id) { self.capture.destroy(id).await
let destroy = if let Some(v) = self.position_map.get_mut(&pos) {
v.retain(|&i| i != id);
// we were the last id registered at this position
v.is_empty()
} else {
// nothing to destroy
false
};
if destroy {
self.position_map.remove(&pos);
self.capture.destroy(pos).await?;
}
}
Ok(())
} }
/// release mouse /// release mouse
@@ -177,9 +143,6 @@ impl InputCapture {
let capture = create(backend).await?; let capture = create(backend).await?;
Ok(Self { Ok(Self {
capture, capture,
id_map: Default::default(),
pending: Default::default(),
position_map: Default::default(),
pressed_keys: HashSet::new(), pressed_keys: HashSet::new(),
}) })
} }
@@ -207,65 +170,29 @@ impl Stream for InputCapture {
mut self: std::pin::Pin<&mut Self>, mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>, cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> { ) -> Poll<Option<Self::Item>> {
if let Some(e) = self.pending.pop_front() { match self.capture.poll_next_unpin(cx) {
return Poll::Ready(Some(Ok(e))); Poll::Ready(e) => {
} if let Some(Ok((
_,
// ready CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { key, state, .. })),
let event = ready!(self.capture.poll_next_unpin(cx)); ))) = e
// stream closed
let event = match event {
Some(e) => e,
None => return Poll::Ready(None),
};
// error occurred
let (pos, event) = match event {
Ok(e) => e,
Err(e) => return Poll::Ready(Some(Err(e))),
};
// handle key presses
if let CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { key, state, .. })) = event {
self.update_pressed_keys(key, state);
}
let len = self
.position_map
.get(&pos)
.map(|ids| ids.len())
.unwrap_or(0);
match len {
0 => Poll::Pending,
1 => Poll::Ready(Some(Ok((
self.position_map.get(&pos).expect("no id")[0],
event,
)))),
_ => {
let mut position_map = HashMap::new();
swap(&mut self.position_map, &mut position_map);
{ {
for &id in position_map.get(&pos).expect("position") { self.update_pressed_keys(key, state);
self.pending.push_back((id, event));
}
} }
swap(&mut self.position_map, &mut position_map); Poll::Ready(e)
Poll::Ready(Some(Ok(self.pending.pop_front().expect("event"))))
} }
Poll::Pending => Poll::Pending,
} }
} }
} }
#[async_trait] #[async_trait]
trait Capture: Stream<Item = Result<(Position, CaptureEvent), CaptureError>> + Unpin { trait Capture: Stream<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>> + Unpin {
/// create a new client with the given id /// create a new client with the given id
async fn create(&mut self, pos: Position) -> Result<(), CaptureError>; async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError>;
/// destroy the client with the given id, if it exists /// destroy the client with the given id, if it exists
async fn destroy(&mut self, pos: Position) -> Result<(), CaptureError>; async fn destroy(&mut self, id: CaptureHandle) -> Result<(), CaptureError>;
/// release mouse /// release mouse
async fn release(&mut self) -> Result<(), CaptureError>; async fn release(&mut self) -> Result<(), CaptureError>;
@@ -277,14 +204,14 @@ trait Capture: Stream<Item = Result<(Position, CaptureEvent), CaptureError>> + U
async fn create_backend( async fn create_backend(
backend: Backend, backend: Backend,
) -> Result< ) -> Result<
Box<dyn Capture<Item = Result<(Position, CaptureEvent), CaptureError>>>, Box<dyn Capture<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>>>,
CaptureCreationError, CaptureCreationError,
> { > {
match backend { match backend {
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))] #[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
Backend::InputCapturePortal => Ok(Box::new(libei::LibeiInputCapture::new().await?)), Backend::InputCapturePortal => Ok(Box::new(libei::LibeiInputCapture::new().await?)),
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))] #[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
Backend::LayerShell => Ok(Box::new(wayland::LayerShellInputCapture::new()?)), Backend::LayerShell => Ok(Box::new(wayland::WaylandInputCapture::new()?)),
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))] #[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
Backend::X11 => Ok(Box::new(x11::X11InputCapture::new()?)), Backend::X11 => Ok(Box::new(x11::X11InputCapture::new()?)),
#[cfg(windows)] #[cfg(windows)]
@@ -298,7 +225,7 @@ async fn create_backend(
async fn create( async fn create(
backend: Option<Backend>, backend: Option<Backend>,
) -> Result< ) -> Result<
Box<dyn Capture<Item = Result<(Position, CaptureEvent), CaptureError>>>, Box<dyn Capture<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>>>,
CaptureCreationError, CaptureCreationError,
> { > {
if let Some(backend) = backend { if let Some(backend) = backend {

View File

@@ -40,7 +40,7 @@ use crate::CaptureEvent;
use super::{ use super::{
error::{CaptureError, LibeiCaptureCreationError, ReisConvertEventStreamError}, error::{CaptureError, LibeiCaptureCreationError, ReisConvertEventStreamError},
Capture as LanMouseInputCapture, Position, Capture as LanMouseInputCapture, CaptureHandle, Position,
}; };
/* there is a bug in xdg-remote-desktop-portal-gnome / mutter that /* there is a bug in xdg-remote-desktop-portal-gnome / mutter that
@@ -50,15 +50,15 @@ use super::{
/// events that necessitate restarting the capture session /// events that necessitate restarting the capture session
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
enum LibeiNotifyEvent { enum LibeiNotifyEvent {
Create(Position), Create(CaptureHandle, Position),
Destroy(Position), Destroy(CaptureHandle),
} }
#[allow(dead_code)] #[allow(dead_code)]
pub struct LibeiInputCapture<'a> { pub struct LibeiInputCapture<'a> {
input_capture: Pin<Box<InputCapture<'a>>>, input_capture: Pin<Box<InputCapture<'a>>>,
capture_task: JoinHandle<Result<(), CaptureError>>, capture_task: JoinHandle<Result<(), CaptureError>>,
event_rx: Receiver<(Position, CaptureEvent)>, event_rx: Receiver<(CaptureHandle, CaptureEvent)>,
notify_capture: Sender<LibeiNotifyEvent>, notify_capture: Sender<LibeiNotifyEvent>,
notify_release: Arc<Notify>, notify_release: Arc<Notify>,
cancellation_token: CancellationToken, cancellation_token: CancellationToken,
@@ -117,13 +117,13 @@ impl From<ICBarrier> for Barrier {
fn select_barriers( fn select_barriers(
zones: &Zones, zones: &Zones,
clients: &[Position], clients: &[(CaptureHandle, Position)],
next_barrier_id: &mut u32, next_barrier_id: &mut u32,
) -> (Vec<ICBarrier>, HashMap<BarrierID, Position>) { ) -> (Vec<ICBarrier>, HashMap<BarrierID, CaptureHandle>) {
let mut pos_for_barrier = HashMap::new(); let mut client_for_barrier = HashMap::new();
let mut barriers: Vec<ICBarrier> = vec![]; let mut barriers: Vec<ICBarrier> = vec![];
for pos in clients { for (handle, pos) in clients {
let mut client_barriers = zones let mut client_barriers = zones
.regions() .regions()
.iter() .iter()
@@ -131,21 +131,21 @@ fn select_barriers(
let id = *next_barrier_id; let id = *next_barrier_id;
*next_barrier_id = id + 1; *next_barrier_id = id + 1;
let position = pos_to_barrier(r, *pos); let position = pos_to_barrier(r, *pos);
pos_for_barrier.insert(id, *pos); client_for_barrier.insert(id, *handle);
ICBarrier::new(id, position) ICBarrier::new(id, position)
}) })
.collect(); .collect();
barriers.append(&mut client_barriers); barriers.append(&mut client_barriers);
} }
(barriers, pos_for_barrier) (barriers, client_for_barrier)
} }
async fn update_barriers( async fn update_barriers(
input_capture: &InputCapture<'_>, input_capture: &InputCapture<'_>,
session: &Session<'_, InputCapture<'_>>, session: &Session<'_, InputCapture<'_>>,
active_clients: &[Position], active_clients: &[(CaptureHandle, Position)],
next_barrier_id: &mut u32, next_barrier_id: &mut u32,
) -> Result<(Vec<ICBarrier>, HashMap<BarrierID, Position>), ashpd::Error> { ) -> Result<(Vec<ICBarrier>, HashMap<BarrierID, CaptureHandle>), ashpd::Error> {
let zones = input_capture.zones(session).await?.response()?; let zones = input_capture.zones(session).await?.response()?;
log::debug!("zones: {zones:?}"); log::debug!("zones: {zones:?}");
@@ -203,9 +203,9 @@ async fn connect_to_eis(
async fn libei_event_handler( async fn libei_event_handler(
mut ei_event_stream: EiConvertEventStream, mut ei_event_stream: EiConvertEventStream,
context: ei::Context, context: ei::Context,
event_tx: Sender<(Position, CaptureEvent)>, event_tx: Sender<(CaptureHandle, CaptureEvent)>,
release_session: Arc<Notify>, release_session: Arc<Notify>,
current_pos: Rc<Cell<Option<Position>>>, current_client: Rc<Cell<Option<CaptureHandle>>>,
) -> Result<(), CaptureError> { ) -> Result<(), CaptureError> {
loop { loop {
let ei_event = ei_event_stream let ei_event = ei_event_stream
@@ -214,7 +214,7 @@ async fn libei_event_handler(
.ok_or(CaptureError::EndOfStream)? .ok_or(CaptureError::EndOfStream)?
.map_err(ReisConvertEventStreamError::from)?; .map_err(ReisConvertEventStreamError::from)?;
log::trace!("from ei: {ei_event:?}"); log::trace!("from ei: {ei_event:?}");
let client = current_pos.get(); let client = current_client.get();
handle_ei_event(ei_event, client, &context, &event_tx, &release_session).await?; handle_ei_event(ei_event, client, &context, &event_tx, &release_session).await?;
} }
} }
@@ -260,14 +260,14 @@ async fn do_capture(
mut capture_event: Receiver<LibeiNotifyEvent>, mut capture_event: Receiver<LibeiNotifyEvent>,
notify_release: Arc<Notify>, notify_release: Arc<Notify>,
session: Option<(Session<'_, InputCapture<'_>>, BitFlags<Capabilities>)>, session: Option<(Session<'_, InputCapture<'_>>, BitFlags<Capabilities>)>,
event_tx: Sender<(Position, CaptureEvent)>, event_tx: Sender<(CaptureHandle, CaptureEvent)>,
cancellation_token: CancellationToken, cancellation_token: CancellationToken,
) -> Result<(), CaptureError> { ) -> Result<(), CaptureError> {
let mut session = session.map(|s| s.0); let mut session = session.map(|s| s.0);
/* safety: libei_task does not outlive Self */ /* safety: libei_task does not outlive Self */
let input_capture = unsafe { &*input_capture }; let input_capture = unsafe { &*input_capture };
let mut active_clients: Vec<Position> = vec![]; let mut active_clients: Vec<(CaptureHandle, Position)> = vec![];
let mut next_barrier_id = 1u32; let mut next_barrier_id = 1u32;
let mut zones_changed = input_capture.receive_zones_changed().await?; let mut zones_changed = input_capture.receive_zones_changed().await?;
@@ -341,8 +341,8 @@ async fn do_capture(
// update clients if requested // update clients if requested
if let Some(event) = capture_event_occured.take() { if let Some(event) = capture_event_occured.take() {
match event { match event {
LibeiNotifyEvent::Create(p) => active_clients.push(p), LibeiNotifyEvent::Create(c, p) => active_clients.push((c, p)),
LibeiNotifyEvent::Destroy(p) => active_clients.retain(|&pos| pos != p), LibeiNotifyEvent::Destroy(c) => active_clients.retain(|(h, _)| *h != c),
} }
} }
@@ -356,21 +356,21 @@ async fn do_capture(
async fn do_capture_session( async fn do_capture_session(
input_capture: &InputCapture<'_>, input_capture: &InputCapture<'_>,
session: &mut Session<'_, InputCapture<'_>>, session: &mut Session<'_, InputCapture<'_>>,
event_tx: &Sender<(Position, CaptureEvent)>, event_tx: &Sender<(CaptureHandle, CaptureEvent)>,
active_clients: &[Position], active_clients: &[(CaptureHandle, Position)],
next_barrier_id: &mut u32, next_barrier_id: &mut u32,
notify_release: &Notify, notify_release: &Notify,
cancel: (CancellationToken, CancellationToken), cancel: (CancellationToken, CancellationToken),
) -> Result<(), CaptureError> { ) -> Result<(), CaptureError> {
let (cancel_session, cancel_update) = cancel; let (cancel_session, cancel_update) = cancel;
// current client // current client
let current_pos = Rc::new(Cell::new(None)); let current_client = Rc::new(Cell::new(None));
// connect to eis server // connect to eis server
let (context, ei_event_stream) = connect_to_eis(input_capture, session).await?; let (context, ei_event_stream) = connect_to_eis(input_capture, session).await?;
// set barriers // set barriers
let (barriers, pos_for_barrier_id) = let (barriers, client_for_barrier_id) =
update_barriers(input_capture, session, active_clients, next_barrier_id).await?; update_barriers(input_capture, session, active_clients, next_barrier_id).await?;
log::debug!("enabling session"); log::debug!("enabling session");
@@ -382,7 +382,7 @@ async fn do_capture_session(
// async event task // async event task
let cancel_ei_handler = CancellationToken::new(); let cancel_ei_handler = CancellationToken::new();
let event_chan = event_tx.clone(); let event_chan = event_tx.clone();
let pos = current_pos.clone(); let client = current_client.clone();
let cancel_session_clone = cancel_session.clone(); let cancel_session_clone = cancel_session.clone();
let release_session_clone = release_session.clone(); let release_session_clone = release_session.clone();
let cancel_ei_handler_clone = cancel_ei_handler.clone(); let cancel_ei_handler_clone = cancel_ei_handler.clone();
@@ -393,7 +393,7 @@ async fn do_capture_session(
context, context,
event_chan, event_chan,
release_session_clone, release_session_clone,
pos, client,
) => { ) => {
log::debug!("libei exited: {r:?} cancelling session task"); log::debug!("libei exited: {r:?} cancelling session task");
cancel_session_clone.cancel(); cancel_session_clone.cancel();
@@ -421,11 +421,11 @@ async fn do_capture_session(
}; };
// find client corresponding to barrier // find client corresponding to barrier
let pos = *pos_for_barrier_id.get(&barrier_id).expect("invalid barrier id"); let client = *client_for_barrier_id.get(&barrier_id).expect("invalid barrier id");
current_pos.replace(Some(pos)); current_client.replace(Some(client));
// client entered => send event // client entered => send event
event_tx.send((pos, CaptureEvent::Begin)).await.expect("no channel"); event_tx.send((client, CaptureEvent::Begin)).await.expect("no channel");
tokio::select! { tokio::select! {
_ = notify_release.notified() => { /* capture release */ _ = notify_release.notified() => { /* capture release */
@@ -441,7 +441,7 @@ async fn do_capture_session(
}, },
} }
release_capture(input_capture, session, activated, pos).await?; release_capture(input_capture, session, activated, client, active_clients).await?;
} }
_ = notify_release.notified() => { /* capture release -> we are not capturing anyway, so ignore */ _ = notify_release.notified() => { /* capture release -> we are not capturing anyway, so ignore */
@@ -484,7 +484,8 @@ async fn release_capture<'a>(
input_capture: &InputCapture<'a>, input_capture: &InputCapture<'a>,
session: &Session<'a, InputCapture<'a>>, session: &Session<'a, InputCapture<'a>>,
activated: Activated, activated: Activated,
current_pos: Position, current_client: CaptureHandle,
active_clients: &[(CaptureHandle, Position)],
) -> Result<(), CaptureError> { ) -> Result<(), CaptureError> {
if let Some(activation_id) = activated.activation_id() { if let Some(activation_id) = activated.activation_id() {
log::debug!("releasing input capture {activation_id}"); log::debug!("releasing input capture {activation_id}");
@@ -493,7 +494,13 @@ async fn release_capture<'a>(
.cursor_position() .cursor_position()
.expect("compositor did not report cursor position!"); .expect("compositor did not report cursor position!");
log::debug!("client entered @ ({x}, {y})"); log::debug!("client entered @ ({x}, {y})");
let (dx, dy) = match current_pos { let pos = active_clients
.iter()
.filter(|(c, _)| *c == current_client)
.map(|(_, p)| p)
.next()
.unwrap(); // FIXME
let (dx, dy) = match pos {
// offset cursor position to not enter again immediately // offset cursor position to not enter again immediately
Position::Left => (1., 0.), Position::Left => (1., 0.),
Position::Right => (-1., 0.), Position::Right => (-1., 0.),
@@ -547,9 +554,9 @@ static ALL_CAPABILITIES: &[DeviceCapability] = &[
async fn handle_ei_event( async fn handle_ei_event(
ei_event: EiEvent, ei_event: EiEvent,
current_client: Option<Position>, current_client: Option<CaptureHandle>,
context: &ei::Context, context: &ei::Context,
event_tx: &Sender<(Position, CaptureEvent)>, event_tx: &Sender<(CaptureHandle, CaptureEvent)>,
release_session: &Notify, release_session: &Notify,
) -> Result<(), CaptureError> { ) -> Result<(), CaptureError> {
match ei_event { match ei_event {
@@ -568,9 +575,9 @@ async fn handle_ei_event(
return Err(CaptureError::Disconnected(format!("{:?}", d.reason))) return Err(CaptureError::Disconnected(format!("{:?}", d.reason)))
} }
_ => { _ => {
if let Some(pos) = current_client { if let Some(handle) = current_client {
for event in Event::from_ei_event(ei_event) { for event in Event::from_ei_event(ei_event) {
event_tx.send((pos, CaptureEvent::Input(event))).await.expect("no channel"); event_tx.send((handle, CaptureEvent::Input(event))).await.expect("no channel");
} }
} }
} }
@@ -580,18 +587,18 @@ async fn handle_ei_event(
#[async_trait] #[async_trait]
impl<'a> LanMouseInputCapture for LibeiInputCapture<'a> { impl<'a> LanMouseInputCapture for LibeiInputCapture<'a> {
async fn create(&mut self, pos: Position) -> Result<(), CaptureError> { async fn create(&mut self, handle: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
let _ = self let _ = self
.notify_capture .notify_capture
.send(LibeiNotifyEvent::Create(pos)) .send(LibeiNotifyEvent::Create(handle, pos))
.await; .await;
Ok(()) Ok(())
} }
async fn destroy(&mut self, pos: Position) -> Result<(), CaptureError> { async fn destroy(&mut self, handle: CaptureHandle) -> Result<(), CaptureError> {
let _ = self let _ = self
.notify_capture .notify_capture
.send(LibeiNotifyEvent::Destroy(pos)) .send(LibeiNotifyEvent::Destroy(handle))
.await; .await;
Ok(()) Ok(())
} }
@@ -622,7 +629,7 @@ impl<'a> Drop for LibeiInputCapture<'a> {
} }
impl<'a> Stream for LibeiInputCapture<'a> { impl<'a> Stream for LibeiInputCapture<'a> {
type Item = Result<(Position, CaptureEvent), CaptureError>; type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.capture_task.poll_unpin(cx) { match self.capture_task.poll_unpin(cx) {

View File

@@ -1,4 +1,6 @@
use super::{error::MacosCaptureCreationError, Capture, CaptureError, CaptureEvent, Position}; use super::{
error::MacosCaptureCreationError, Capture, CaptureError, CaptureEvent, CaptureHandle, Position,
};
use async_trait::async_trait; use async_trait::async_trait;
use bitflags::bitflags; use bitflags::bitflags;
use core_foundation::base::{kCFAllocatorDefault, CFRelease}; use core_foundation::base::{kCFAllocatorDefault, CFRelease};
@@ -18,14 +20,14 @@ use input_event::{Event, KeyboardEvent, PointerEvent, BTN_LEFT, BTN_MIDDLE, BTN_
use keycode::{KeyMap, KeyMapping}; use keycode::{KeyMap, KeyMapping};
use libc::c_void; use libc::c_void;
use once_cell::unsync::Lazy; use once_cell::unsync::Lazy;
use std::collections::HashSet; use std::collections::HashMap;
use std::ffi::{c_char, CString}; use std::ffi::{c_char, CString};
use std::pin::Pin; use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use std::task::{ready, Context, Poll}; use std::task::{ready, Context, Poll};
use std::thread::{self}; use std::thread::{self};
use tokio::sync::mpsc::{self, Receiver, Sender}; use tokio::sync::mpsc::{Receiver, Sender};
use tokio::sync::{oneshot, Mutex}; use tokio::sync::Mutex;
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct Bounds { struct Bounds {
@@ -37,44 +39,44 @@ struct Bounds {
#[derive(Debug)] #[derive(Debug)]
struct InputCaptureState { struct InputCaptureState {
active_clients: Lazy<HashSet<Position>>, client_for_pos: Lazy<HashMap<Position, CaptureHandle>>,
current_pos: Option<Position>, current_client: Option<(CaptureHandle, Position)>,
bounds: Bounds, bounds: Bounds,
} }
#[derive(Debug)] #[derive(Debug)]
enum ProducerEvent { enum ProducerEvent {
Release, Release,
Create(Position), Create(CaptureHandle, Position),
Destroy(Position), Destroy(CaptureHandle),
Grab(Position), Grab((CaptureHandle, Position)),
EventTapDisabled, EventTapDisabled,
} }
impl InputCaptureState { impl InputCaptureState {
fn new() -> Result<Self, MacosCaptureCreationError> { fn new() -> Result<Self, MacosCaptureCreationError> {
let mut res = Self { let mut res = Self {
active_clients: Lazy::new(HashSet::new), client_for_pos: Lazy::new(HashMap::new),
current_pos: None, current_client: None,
bounds: Bounds::default(), bounds: Bounds::default(),
}; };
res.update_bounds()?; res.update_bounds()?;
Ok(res) Ok(res)
} }
fn crossed(&mut self, event: &CGEvent) -> Option<Position> { fn crossed(&mut self, event: &CGEvent) -> Option<(CaptureHandle, Position)> {
let location = event.location(); let location = event.location();
let relative_x = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_X); let relative_x = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_X);
let relative_y = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_Y); let relative_y = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_Y);
for &position in self.active_clients.iter() { for (position, client) in self.client_for_pos.iter() {
if (position == Position::Left && (location.x + relative_x) <= self.bounds.xmin) if (position == &Position::Left && (location.x + relative_x) <= self.bounds.xmin)
|| (position == Position::Right && (location.x + relative_x) >= self.bounds.xmax) || (position == &Position::Right && (location.x + relative_x) >= self.bounds.xmax)
|| (position == Position::Top && (location.y + relative_y) <= self.bounds.ymin) || (position == &Position::Top && (location.y + relative_y) <= self.bounds.ymin)
|| (position == Position::Bottom && (location.y + relative_y) >= self.bounds.ymax) || (position == &Position::Bottom && (location.y + relative_y) >= self.bounds.ymax)
{ {
log::debug!("Crossed barrier into position: {position:?}"); log::debug!("Crossed barrier into client: {client}, {position:?}");
return Some(position); return Some((*client, *position));
} }
} }
None None
@@ -100,7 +102,7 @@ impl InputCaptureState {
// to the edge of the screen, the cursor will be hidden but we dont want it to appear in a // to the edge of the screen, the cursor will be hidden but we dont want it to appear in a
// random location when we exit the client // random location when we exit the client
fn reset_mouse_position(&self, event: &CGEvent) -> Result<(), CaptureError> { fn reset_mouse_position(&self, event: &CGEvent) -> Result<(), CaptureError> {
if let Some(pos) = self.current_pos { if let Some((_, pos)) = self.current_client {
let location = event.location(); let location = event.location();
let edge_offset = 1.0; let edge_offset = 1.0;
@@ -144,31 +146,40 @@ impl InputCaptureState {
log::debug!("handling event: {producer_event:?}"); log::debug!("handling event: {producer_event:?}");
match producer_event { match producer_event {
ProducerEvent::Release => { ProducerEvent::Release => {
if self.current_pos.is_some() { if self.current_client.is_some() {
CGDisplay::show_cursor(&CGDisplay::main()) CGDisplay::show_cursor(&CGDisplay::main())
.map_err(CaptureError::CoreGraphics)?; .map_err(CaptureError::CoreGraphics)?;
self.current_pos = None; self.current_client = None;
} }
} }
ProducerEvent::Grab(pos) => { ProducerEvent::Grab(client) => {
if self.current_pos.is_none() { if self.current_client.is_none() {
CGDisplay::hide_cursor(&CGDisplay::main()) CGDisplay::hide_cursor(&CGDisplay::main())
.map_err(CaptureError::CoreGraphics)?; .map_err(CaptureError::CoreGraphics)?;
self.current_pos = Some(pos); self.current_client = Some(client);
} }
} }
ProducerEvent::Create(p) => { ProducerEvent::Create(c, p) => {
self.active_clients.insert(p); self.client_for_pos.insert(p, c);
} }
ProducerEvent::Destroy(p) => { ProducerEvent::Destroy(c) => {
if let Some(current) = self.current_pos { for pos in [
if current == p { Position::Left,
CGDisplay::show_cursor(&CGDisplay::main()) Position::Right,
.map_err(CaptureError::CoreGraphics)?; Position::Top,
self.current_pos = None; Position::Bottom,
}; ] {
if let Some((current_c, _)) = self.current_client {
if current_c == c {
CGDisplay::show_cursor(&CGDisplay::main())
.map_err(CaptureError::CoreGraphics)?;
self.current_client = None;
};
}
if self.client_for_pos.get(&pos).copied() == Some(c) {
self.client_for_pos.remove(&pos);
}
} }
self.active_clients.remove(&p);
} }
ProducerEvent::EventTapDisabled => return Err(CaptureError::EventTapDisabled), ProducerEvent::EventTapDisabled => return Err(CaptureError::EventTapDisabled),
}; };
@@ -322,11 +333,12 @@ fn get_events(
Ok(()) Ok(())
} }
fn create_event_tap<'a>( fn event_tap_thread(
client_state: Arc<Mutex<InputCaptureState>>, client_state: Arc<Mutex<InputCaptureState>>,
event_tx: Sender<(CaptureHandle, CaptureEvent)>,
notify_tx: Sender<ProducerEvent>, notify_tx: Sender<ProducerEvent>,
event_tx: Sender<(Position, CaptureEvent)>, exit: tokio::sync::oneshot::Sender<Result<(), &'static str>>,
) -> Result<CGEventTap<'a>, MacosCaptureCreationError> { ) {
let cg_events_of_interest: Vec<CGEventType> = vec![ let cg_events_of_interest: Vec<CGEventType> = vec![
CGEventType::LeftMouseDown, CGEventType::LeftMouseDown,
CGEventType::LeftMouseUp, CGEventType::LeftMouseUp,
@@ -344,11 +356,15 @@ fn create_event_tap<'a>(
CGEventType::FlagsChanged, CGEventType::FlagsChanged,
]; ];
let event_tap_callback = let tap = CGEventTap::new(
move |_proxy: CGEventTapProxy, event_type: CGEventType, cg_ev: &CGEvent| { CGEventTapLocation::Session,
CGEventTapPlacement::HeadInsertEventTap,
CGEventTapOptions::Default,
cg_events_of_interest,
|_proxy: CGEventTapProxy, event_type: CGEventType, cg_ev: &CGEvent| {
log::trace!("Got event from tap: {event_type:?}"); log::trace!("Got event from tap: {event_type:?}");
let mut state = client_state.blocking_lock(); let mut state = client_state.blocking_lock();
let mut pos = None; let mut client = None;
let mut res_events = vec![]; let mut res_events = vec![];
if matches!( if matches!(
@@ -364,8 +380,8 @@ fn create_event_tap<'a>(
} }
// Are we in a client? // Are we in a client?
if let Some(current_pos) = state.current_pos { if let Some((current_client, _)) = state.current_client {
pos = Some(current_pos); client = Some(current_client);
get_events(&event_type, cg_ev, &mut res_events).unwrap_or_else(|e| { get_events(&event_type, cg_ev, &mut res_events).unwrap_or_else(|e| {
log::error!("Failed to get events: {e}"); log::error!("Failed to get events: {e}");
}); });
@@ -379,19 +395,19 @@ fn create_event_tap<'a>(
} }
// Did we cross a barrier? // Did we cross a barrier?
else if matches!(event_type, CGEventType::MouseMoved) { else if matches!(event_type, CGEventType::MouseMoved) {
if let Some(new_pos) = state.crossed(cg_ev) { if let Some((new_client, pos)) = state.crossed(cg_ev) {
pos = Some(new_pos); client = Some(new_client);
res_events.push(CaptureEvent::Begin); res_events.push(CaptureEvent::Begin);
notify_tx notify_tx
.blocking_send(ProducerEvent::Grab(new_pos)) .blocking_send(ProducerEvent::Grab((new_client, pos)))
.expect("Failed to send notification"); .expect("Failed to send notification");
} }
} }
if let Some(pos) = pos { if let Some(client) = client {
res_events.iter().for_each(|e| { res_events.iter().for_each(|e| {
event_tx event_tx
.blocking_send((pos, *e)) .blocking_send((client, *e))
.expect("Failed to send event"); .expect("Failed to send event");
}); });
// Returning None should stop the event from being processed // Returning None should stop the event from being processed
@@ -399,16 +415,9 @@ fn create_event_tap<'a>(
cg_ev.set_type(CGEventType::Null); cg_ev.set_type(CGEventType::Null);
} }
Some(cg_ev.to_owned()) Some(cg_ev.to_owned())
}; },
let tap = CGEventTap::new(
CGEventTapLocation::Session,
CGEventTapPlacement::HeadInsertEventTap,
CGEventTapOptions::Default,
cg_events_of_interest,
event_tap_callback,
) )
.map_err(|_| MacosCaptureCreationError::EventTapCreation)?; .expect("Failed creating tap");
let tap_source: CFRunLoopSource = tap let tap_source: CFRunLoopSource = tap
.mach_port .mach_port
@@ -419,43 +428,22 @@ fn create_event_tap<'a>(
CFRunLoop::get_current().add_source(&tap_source, kCFRunLoopCommonModes); CFRunLoop::get_current().add_source(&tap_source, kCFRunLoopCommonModes);
} }
Ok(tap)
}
fn event_tap_thread(
client_state: Arc<Mutex<InputCaptureState>>,
event_tx: Sender<(Position, CaptureEvent)>,
notify_tx: Sender<ProducerEvent>,
ready: std::sync::mpsc::Sender<Result<(), MacosCaptureCreationError>>,
exit: oneshot::Sender<Result<(), &'static str>>,
) {
let _tap = match create_event_tap(client_state, notify_tx, event_tx) {
Err(e) => {
ready.send(Err(e)).expect("channel closed");
return;
}
Ok(tap) => {
ready.send(Ok(())).expect("channel closed");
tap
}
};
CFRunLoop::run_current(); CFRunLoop::run_current();
let _ = exit.send(Err("tap thread exited")); let _ = exit.send(Err("tap thread exited"));
} }
pub struct MacOSInputCapture { pub struct MacOSInputCapture {
event_rx: Receiver<(Position, CaptureEvent)>, event_rx: Receiver<(CaptureHandle, CaptureEvent)>,
notify_tx: Sender<ProducerEvent>, notify_tx: Sender<ProducerEvent>,
} }
impl MacOSInputCapture { impl MacOSInputCapture {
pub async fn new() -> Result<Self, MacosCaptureCreationError> { pub async fn new() -> Result<Self, MacosCaptureCreationError> {
let state = Arc::new(Mutex::new(InputCaptureState::new()?)); let state = Arc::new(Mutex::new(InputCaptureState::new()?));
let (event_tx, event_rx) = mpsc::channel(32); let (event_tx, event_rx) = tokio::sync::mpsc::channel(32);
let (notify_tx, mut notify_rx) = mpsc::channel(32); let (notify_tx, mut notify_rx) = tokio::sync::mpsc::channel(32);
let (ready_tx, ready_rx) = std::sync::mpsc::channel(); let (tap_exit_tx, mut tap_exit_rx) = tokio::sync::oneshot::channel();
let (tap_exit_tx, mut tap_exit_rx) = oneshot::channel();
unsafe { unsafe {
configure_cf_settings()?; configure_cf_settings()?;
@@ -469,14 +457,10 @@ impl MacOSInputCapture {
event_tap_thread_state, event_tap_thread_state,
event_tx, event_tx,
event_tap_notify, event_tap_notify,
ready_tx,
tap_exit_tx, tap_exit_tx,
) )
}); });
// wait for event tap creation result
ready_rx.recv().expect("channel closed")?;
let _tap_task: tokio::task::JoinHandle<()> = tokio::task::spawn_local(async move { let _tap_task: tokio::task::JoinHandle<()> = tokio::task::spawn_local(async move {
loop { loop {
tokio::select! { tokio::select! {
@@ -507,21 +491,21 @@ impl MacOSInputCapture {
#[async_trait] #[async_trait]
impl Capture for MacOSInputCapture { impl Capture for MacOSInputCapture {
async fn create(&mut self, pos: Position) -> Result<(), CaptureError> { async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
let notify_tx = self.notify_tx.clone(); let notify_tx = self.notify_tx.clone();
tokio::task::spawn_local(async move { tokio::task::spawn_local(async move {
log::debug!("creating capture, {pos}"); log::debug!("creating client {id}, {pos}");
let _ = notify_tx.send(ProducerEvent::Create(pos)).await; let _ = notify_tx.send(ProducerEvent::Create(id, pos)).await;
log::debug!("done !"); log::debug!("done !");
}); });
Ok(()) Ok(())
} }
async fn destroy(&mut self, pos: Position) -> Result<(), CaptureError> { async fn destroy(&mut self, id: CaptureHandle) -> Result<(), CaptureError> {
let notify_tx = self.notify_tx.clone(); let notify_tx = self.notify_tx.clone();
tokio::task::spawn_local(async move { tokio::task::spawn_local(async move {
log::debug!("destroying capture {pos}"); log::debug!("destroying client {id}");
let _ = notify_tx.send(ProducerEvent::Destroy(pos)).await; let _ = notify_tx.send(ProducerEvent::Destroy(id)).await;
log::debug!("done !"); log::debug!("done !");
}); });
Ok(()) Ok(())
@@ -542,7 +526,7 @@ impl Capture for MacOSInputCapture {
} }
impl Stream for MacOSInputCapture { impl Stream for MacOSInputCapture {
type Item = Result<(Position, CaptureEvent), CaptureError>; type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match ready!(self.event_rx.poll_recv(cx)) { match ready!(self.event_rx.poll_recv(cx)) {

View File

@@ -64,14 +64,14 @@ use crate::{CaptureError, CaptureEvent};
use super::{ use super::{
error::{LayerShellCaptureCreationError, WaylandBindError}, error::{LayerShellCaptureCreationError, WaylandBindError},
Capture, Position, Capture, CaptureHandle, Position,
}; };
struct Globals { struct Globals {
compositor: wl_compositor::WlCompositor, compositor: wl_compositor::WlCompositor,
pointer_constraints: ZwpPointerConstraintsV1, pointer_constraints: ZwpPointerConstraintsV1,
relative_pointer_manager: ZwpRelativePointerManagerV1, relative_pointer_manager: ZwpRelativePointerManagerV1,
shortcut_inhibit_manager: Option<ZwpKeyboardShortcutsInhibitManagerV1>, shortcut_inhibit_manager: ZwpKeyboardShortcutsInhibitManagerV1,
seat: wl_seat::WlSeat, seat: wl_seat::WlSeat,
shm: wl_shm::WlShm, shm: wl_shm::WlShm,
layer_shell: ZwlrLayerShellV1, layer_shell: ZwlrLayerShellV1,
@@ -102,13 +102,13 @@ struct State {
pointer_lock: Option<ZwpLockedPointerV1>, pointer_lock: Option<ZwpLockedPointerV1>,
rel_pointer: Option<ZwpRelativePointerV1>, rel_pointer: Option<ZwpRelativePointerV1>,
shortcut_inhibitor: Option<ZwpKeyboardShortcutsInhibitorV1>, shortcut_inhibitor: Option<ZwpKeyboardShortcutsInhibitorV1>,
active_windows: Vec<Arc<Window>>, client_for_window: Vec<(Arc<Window>, CaptureHandle)>,
focused: Option<Arc<Window>>, focused: Option<(Arc<Window>, CaptureHandle)>,
g: Globals, g: Globals,
wayland_fd: RawFd, wayland_fd: RawFd,
read_guard: Option<ReadEventsGuard>, read_guard: Option<ReadEventsGuard>,
qh: QueueHandle<Self>, qh: QueueHandle<Self>,
pending_events: VecDeque<(Position, CaptureEvent)>, pending_events: VecDeque<(CaptureHandle, CaptureEvent)>,
output_info: Vec<(WlOutput, OutputInfo)>, output_info: Vec<(WlOutput, OutputInfo)>,
scroll_discrete_pending: bool, scroll_discrete_pending: bool,
} }
@@ -124,7 +124,7 @@ impl AsRawFd for Inner {
} }
} }
pub struct LayerShellInputCapture(AsyncFd<Inner>); pub struct WaylandInputCapture(AsyncFd<Inner>);
struct Window { struct Window {
buffer: wl_buffer::WlBuffer, buffer: wl_buffer::WlBuffer,
@@ -256,7 +256,7 @@ fn draw(f: &mut File, (width, height): (u32, u32)) {
} }
} }
impl LayerShellInputCapture { impl WaylandInputCapture {
pub fn new() -> std::result::Result<Self, LayerShellCaptureCreationError> { pub fn new() -> std::result::Result<Self, LayerShellCaptureCreationError> {
let conn = Connection::connect_to_env()?; let conn = Connection::connect_to_env()?;
let (g, mut queue) = registry_queue_init::<State>(&conn)?; let (g, mut queue) = registry_queue_init::<State>(&conn)?;
@@ -285,18 +285,9 @@ impl LayerShellInputCapture {
let relative_pointer_manager: ZwpRelativePointerManagerV1 = g let relative_pointer_manager: ZwpRelativePointerManagerV1 = g
.bind(&qh, 1..=1, ()) .bind(&qh, 1..=1, ())
.map_err(|e| WaylandBindError::new(e, "zwp_relative_pointer_manager_v1"))?; .map_err(|e| WaylandBindError::new(e, "zwp_relative_pointer_manager_v1"))?;
let shortcut_inhibit_manager: Result< let shortcut_inhibit_manager: ZwpKeyboardShortcutsInhibitManagerV1 = g
ZwpKeyboardShortcutsInhibitManagerV1,
WaylandBindError,
> = g
.bind(&qh, 1..=1, ()) .bind(&qh, 1..=1, ())
.map_err(|e| WaylandBindError::new(e, "zwp_keyboard_shortcuts_inhibit_manager_v1")); .map_err(|e| WaylandBindError::new(e, "zwp_keyboard_shortcuts_inhibit_manager_v1"))?;
// layer-shell backend still works without this protocol so we make it an optional dependency
if let Err(e) = &shortcut_inhibit_manager {
log::warn!("shortcut_inhibit_manager not supported: {e}\nkeybinds handled by the compositor will not be passed
to the client");
}
let shortcut_inhibit_manager = shortcut_inhibit_manager.ok();
let outputs = vec![]; let outputs = vec![];
let g = Globals { let g = Globals {
@@ -323,7 +314,7 @@ impl LayerShellInputCapture {
pointer_lock: None, pointer_lock: None,
rel_pointer: None, rel_pointer: None,
shortcut_inhibitor: None, shortcut_inhibitor: None,
active_windows: Vec::new(), client_for_window: Vec::new(),
focused: None, focused: None,
qh, qh,
wayland_fd, wayland_fd,
@@ -370,18 +361,23 @@ impl LayerShellInputCapture {
let inner = AsyncFd::new(Inner { queue, state })?; let inner = AsyncFd::new(Inner { queue, state })?;
Ok(LayerShellInputCapture(inner)) Ok(WaylandInputCapture(inner))
} }
fn add_client(&mut self, pos: Position) { fn add_client(&mut self, handle: CaptureHandle, pos: Position) {
self.0.get_mut().state.add_client(pos); self.0.get_mut().state.add_client(handle, pos);
} }
fn delete_client(&mut self, pos: Position) { fn delete_client(&mut self, handle: CaptureHandle) {
let inner = self.0.get_mut(); let inner = self.0.get_mut();
// remove all windows corresponding to this client // remove all windows corresponding to this client
while let Some(i) = inner.state.active_windows.iter().position(|w| w.pos == pos) { while let Some(i) = inner
inner.state.active_windows.remove(i); .state
.client_for_window
.iter()
.position(|(_, c)| *c == handle)
{
inner.state.client_for_window.remove(i);
inner.state.focused = None; inner.state.focused = None;
} }
} }
@@ -395,7 +391,7 @@ impl State {
serial: u32, serial: u32,
qh: &QueueHandle<State>, qh: &QueueHandle<State>,
) { ) {
let window = self.focused.as_ref().unwrap(); let (window, _) = self.focused.as_ref().unwrap();
// hide the cursor // hide the cursor
pointer.set_cursor(serial, None, 0, 0); pointer.set_cursor(serial, None, 0, 0);
@@ -428,17 +424,19 @@ impl State {
} }
// capture modifier keys // capture modifier keys
if let Some(shortcut_inhibit_manager) = &self.g.shortcut_inhibit_manager { if self.shortcut_inhibitor.is_none() {
if self.shortcut_inhibitor.is_none() { self.shortcut_inhibitor = Some(self.g.shortcut_inhibit_manager.inhibit_shortcuts(
self.shortcut_inhibitor = surface,
Some(shortcut_inhibit_manager.inhibit_shortcuts(surface, &self.g.seat, qh, ())); &self.g.seat,
} qh,
(),
));
} }
} }
fn ungrab(&mut self) { fn ungrab(&mut self) {
// get focused client // get focused client
let window = match self.focused.as_ref() { let (window, _client) = match self.focused.as_ref() {
Some(focused) => focused, Some(focused) => focused,
None => return, None => return,
}; };
@@ -468,23 +466,27 @@ impl State {
} }
} }
fn add_client(&mut self, pos: Position) { fn add_client(&mut self, client: CaptureHandle, pos: Position) {
let outputs = get_output_configuration(self, pos); let outputs = get_output_configuration(self, pos);
log::debug!("outputs: {outputs:?}"); log::debug!("outputs: {outputs:?}");
outputs.iter().for_each(|(o, i)| { outputs.iter().for_each(|(o, i)| {
let window = Window::new(self, &self.qh, o, pos, i.size); let window = Window::new(self, &self.qh, o, pos, i.size);
let window = Arc::new(window); let window = Arc::new(window);
self.active_windows.push(window); self.client_for_window.push((window, client));
}); });
} }
fn update_windows(&mut self) { fn update_windows(&mut self) {
log::debug!("updating windows"); log::debug!("updating windows");
log::debug!("output info: {:?}", self.output_info); log::debug!("output info: {:?}", self.output_info);
let clients: Vec<_> = self.active_windows.drain(..).map(|w| w.pos).collect(); let clients: Vec<_> = self
for pos in clients { .client_for_window
self.add_client(pos); .drain(..)
.map(|(w, c)| (c, w.pos))
.collect();
for (client, pos) in clients {
self.add_client(client, pos);
} }
} }
} }
@@ -557,15 +559,15 @@ impl Inner {
} }
#[async_trait] #[async_trait]
impl Capture for LayerShellInputCapture { impl Capture for WaylandInputCapture {
async fn create(&mut self, pos: Position) -> Result<(), CaptureError> { async fn create(&mut self, handle: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
self.add_client(pos); self.add_client(handle, pos);
let inner = self.0.get_mut(); let inner = self.0.get_mut();
Ok(inner.flush_events()?) Ok(inner.flush_events()?)
} }
async fn destroy(&mut self, pos: Position) -> Result<(), CaptureError> { async fn destroy(&mut self, handle: CaptureHandle) -> Result<(), CaptureError> {
self.delete_client(pos); self.delete_client(handle);
let inner = self.0.get_mut(); let inner = self.0.get_mut();
Ok(inner.flush_events()?) Ok(inner.flush_events()?)
} }
@@ -582,8 +584,8 @@ impl Capture for LayerShellInputCapture {
} }
} }
impl Stream for LayerShellInputCapture { impl Stream for WaylandInputCapture {
type Item = Result<(Position, CaptureEvent), CaptureError>; type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Some(event) = self.0.get_mut().state.pending_events.pop_front() { if let Some(event) = self.0.get_mut().state.pending_events.pop_front() {
@@ -648,16 +650,10 @@ impl Dispatch<wl_seat::WlSeat, ()> for State {
capabilities: WEnum::Value(capabilities), capabilities: WEnum::Value(capabilities),
} = event } = event
{ {
if capabilities.contains(wl_seat::Capability::Pointer) { if capabilities.contains(wl_seat::Capability::Pointer) && state.pointer.is_none() {
if let Some(p) = state.pointer.take() {
p.release();
}
state.pointer.replace(seat.get_pointer(qh, ())); state.pointer.replace(seat.get_pointer(qh, ()));
} }
if capabilities.contains(wl_seat::Capability::Keyboard) { if capabilities.contains(wl_seat::Capability::Keyboard) && state.keyboard.is_none() {
if let Some(k) = state.keyboard.take() {
k.release();
}
seat.get_keyboard(qh, ()); seat.get_keyboard(qh, ());
} }
} }
@@ -682,20 +678,23 @@ impl Dispatch<WlPointer, ()> for State {
} => { } => {
// get client corresponding to the focused surface // get client corresponding to the focused surface
{ {
if let Some(window) = app.active_windows.iter().find(|w| w.surface == surface) { if let Some((window, client)) = app
app.focused = Some(window.clone()); .client_for_window
.iter()
.find(|(w, _c)| w.surface == surface)
{
app.focused = Some((window.clone(), *client));
app.grab(&surface, pointer, serial, qh); app.grab(&surface, pointer, serial, qh);
} else { } else {
return; return;
} }
} }
let pos = app let (_, client) = app
.active_windows .client_for_window
.iter() .iter()
.find(|w| w.surface == surface) .find(|(w, _c)| w.surface == surface)
.map(|w| w.pos)
.unwrap(); .unwrap();
app.pending_events.push_back((pos, CaptureEvent::Begin)); app.pending_events.push_back((*client, CaptureEvent::Begin));
} }
wl_pointer::Event::Leave { .. } => { wl_pointer::Event::Leave { .. } => {
/* There are rare cases, where when a window is opened in /* There are rare cases, where when a window is opened in
@@ -716,9 +715,9 @@ impl Dispatch<WlPointer, ()> for State {
button, button,
state, state,
} => { } => {
let window = app.focused.as_ref().unwrap(); let (_, client) = app.focused.as_ref().unwrap();
app.pending_events.push_back(( app.pending_events.push_back((
window.pos, *client,
CaptureEvent::Input(Event::Pointer(PointerEvent::Button { CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time, time,
button, button,
@@ -727,7 +726,7 @@ impl Dispatch<WlPointer, ()> for State {
)); ));
} }
wl_pointer::Event::Axis { time, axis, value } => { wl_pointer::Event::Axis { time, axis, value } => {
let window = app.focused.as_ref().unwrap(); let (_, client) = app.focused.as_ref().unwrap();
if app.scroll_discrete_pending { if app.scroll_discrete_pending {
// each axisvalue120 event is coupled with // each axisvalue120 event is coupled with
// a corresponding axis event, which needs to // a corresponding axis event, which needs to
@@ -735,7 +734,7 @@ impl Dispatch<WlPointer, ()> for State {
app.scroll_discrete_pending = false; app.scroll_discrete_pending = false;
} else { } else {
app.pending_events.push_back(( app.pending_events.push_back((
window.pos, *client,
CaptureEvent::Input(Event::Pointer(PointerEvent::Axis { CaptureEvent::Input(Event::Pointer(PointerEvent::Axis {
time, time,
axis: u32::from(axis) as u8, axis: u32::from(axis) as u8,
@@ -745,10 +744,10 @@ impl Dispatch<WlPointer, ()> for State {
} }
} }
wl_pointer::Event::AxisValue120 { axis, value120 } => { wl_pointer::Event::AxisValue120 { axis, value120 } => {
let window = app.focused.as_ref().unwrap(); let (_, client) = app.focused.as_ref().unwrap();
app.scroll_discrete_pending = true; app.scroll_discrete_pending = true;
app.pending_events.push_back(( app.pending_events.push_back((
window.pos, *client,
CaptureEvent::Input(Event::Pointer(PointerEvent::AxisDiscrete120 { CaptureEvent::Input(Event::Pointer(PointerEvent::AxisDiscrete120 {
axis: u32::from(axis) as u8, axis: u32::from(axis) as u8,
value: value120, value: value120,
@@ -774,7 +773,10 @@ impl Dispatch<WlKeyboard, ()> for State {
_: &Connection, _: &Connection,
_: &QueueHandle<Self>, _: &QueueHandle<Self>,
) { ) {
let window = &app.focused; let (_window, client) = match &app.focused {
Some(focused) => (Some(&focused.0), Some(&focused.1)),
None => (None, None),
};
match event { match event {
wl_keyboard::Event::Key { wl_keyboard::Event::Key {
serial: _, serial: _,
@@ -782,9 +784,9 @@ impl Dispatch<WlKeyboard, ()> for State {
key, key,
state, state,
} => { } => {
if let Some(window) = window { if let Some(client) = client {
app.pending_events.push_back(( app.pending_events.push_back((
window.pos, *client,
CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key {
time, time,
key, key,
@@ -800,9 +802,9 @@ impl Dispatch<WlKeyboard, ()> for State {
mods_locked, mods_locked,
group, group,
} => { } => {
if let Some(window) = window { if let Some(client) = client {
app.pending_events.push_back(( app.pending_events.push_back((
window.pos, *client,
CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Modifiers { CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Modifiers {
depressed: mods_depressed, depressed: mods_depressed,
latched: mods_latched, latched: mods_latched,
@@ -834,10 +836,10 @@ impl Dispatch<ZwpRelativePointerV1, ()> for State {
.. ..
} = event } = event
{ {
if let Some(window) = &app.focused { if let Some((_window, client)) = &app.focused {
let time = (((utime_hi as u64) << 32 | utime_lo as u64) / 1000) as u32; let time = (((utime_hi as u64) << 32 | utime_lo as u64) / 1000) as u32;
app.pending_events.push_back(( app.pending_events.push_back((
window.pos, *client,
CaptureEvent::Input(Event::Pointer(PointerEvent::Motion { time, dx, dy })), CaptureEvent::Input(Event::Pointer(PointerEvent::Motion { time, dx, dy })),
)); ));
} }
@@ -855,10 +857,10 @@ impl Dispatch<ZwlrLayerSurfaceV1, ()> for State {
_: &QueueHandle<Self>, _: &QueueHandle<Self>,
) { ) {
if let zwlr_layer_surface_v1::Event::Configure { serial, .. } = event { if let zwlr_layer_surface_v1::Event::Configure { serial, .. } = event {
if let Some(window) = app if let Some((window, _client)) = app
.active_windows .client_for_window
.iter() .iter()
.find(|w| &w.layer_surface == layer_surface) .find(|(w, _c)| &w.layer_surface == layer_surface)
{ {
// client corresponding to the layer_surface // client corresponding to the layer_surface
let surface = &window.surface; let surface = &window.surface;

View File

@@ -3,12 +3,12 @@ use core::task::{Context, Poll};
use futures::Stream; use futures::Stream;
use once_cell::unsync::Lazy; use once_cell::unsync::Lazy;
use std::collections::HashSet; use std::collections::HashMap;
use std::ptr::{addr_of, addr_of_mut}; use std::ptr::{addr_of, addr_of_mut};
use futures::executor::block_on; use futures::executor::block_on;
use std::default::Default; use std::default::Default;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{mpsc, Mutex}; use std::sync::{mpsc, Mutex};
use std::task::ready; use std::task::ready;
use std::{pin::Pin, thread}; use std::{pin::Pin, thread};
@@ -37,15 +37,15 @@ use input_event::{
Event, KeyboardEvent, PointerEvent, BTN_BACK, BTN_FORWARD, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT, Event, KeyboardEvent, PointerEvent, BTN_BACK, BTN_FORWARD, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT,
}; };
use super::{Capture, CaptureError, CaptureEvent, Position}; use super::{Capture, CaptureError, CaptureEvent, CaptureHandle, Position};
enum Request { enum Request {
Create(Position), Create(CaptureHandle, Position),
Destroy(Position), Destroy(CaptureHandle),
} }
pub struct WindowsInputCapture { pub struct WindowsInputCapture {
event_rx: Receiver<(Position, CaptureEvent)>, event_rx: Receiver<(CaptureHandle, CaptureEvent)>,
msg_thread: Option<std::thread::JoinHandle<()>>, msg_thread: Option<std::thread::JoinHandle<()>>,
} }
@@ -65,22 +65,22 @@ unsafe fn signal_message_thread(event_type: EventType) {
#[async_trait] #[async_trait]
impl Capture for WindowsInputCapture { impl Capture for WindowsInputCapture {
async fn create(&mut self, pos: Position) -> Result<(), CaptureError> { async fn create(&mut self, handle: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
unsafe { unsafe {
{ {
let mut requests = REQUEST_BUFFER.lock().unwrap(); let mut requests = REQUEST_BUFFER.lock().unwrap();
requests.push(Request::Create(pos)); requests.push(Request::Create(handle, pos));
} }
signal_message_thread(EventType::Request); signal_message_thread(EventType::Request);
} }
Ok(()) Ok(())
} }
async fn destroy(&mut self, pos: Position) -> Result<(), CaptureError> { async fn destroy(&mut self, handle: CaptureHandle) -> Result<(), CaptureError> {
unsafe { unsafe {
{ {
let mut requests = REQUEST_BUFFER.lock().unwrap(); let mut requests = REQUEST_BUFFER.lock().unwrap();
requests.push(Request::Destroy(pos)); requests.push(Request::Destroy(handle));
} }
signal_message_thread(EventType::Request); signal_message_thread(EventType::Request);
} }
@@ -98,9 +98,9 @@ impl Capture for WindowsInputCapture {
} }
static mut REQUEST_BUFFER: Mutex<Vec<Request>> = Mutex::new(Vec::new()); static mut REQUEST_BUFFER: Mutex<Vec<Request>> = Mutex::new(Vec::new());
static mut ACTIVE_CLIENT: Option<Position> = None; static mut ACTIVE_CLIENT: Option<CaptureHandle> = None;
static mut CLIENTS: Lazy<HashSet<Position>> = Lazy::new(HashSet::new); static mut CLIENT_FOR_POS: Lazy<HashMap<Position, CaptureHandle>> = Lazy::new(HashMap::new);
static mut EVENT_TX: Option<Sender<(Position, CaptureEvent)>> = None; static mut EVENT_TX: Option<Sender<(CaptureHandle, CaptureEvent)>> = None;
static mut EVENT_THREAD_ID: AtomicU32 = AtomicU32::new(0); static mut EVENT_THREAD_ID: AtomicU32 = AtomicU32::new(0);
unsafe fn set_event_tid(tid: u32) { unsafe fn set_event_tid(tid: u32) {
EVENT_THREAD_ID.store(tid, Ordering::SeqCst); EVENT_THREAD_ID.store(tid, Ordering::SeqCst);
@@ -281,12 +281,12 @@ unsafe fn check_client_activation(wparam: WPARAM, lparam: LPARAM) -> bool {
}; };
/* check if a client is registered for the barrier */ /* check if a client is registered for the barrier */
if !CLIENTS.contains(&pos) { let Some(client) = CLIENT_FOR_POS.get(&pos) else {
return ret; return ret;
} };
/* update active client and entry point */ /* update active client and entry point */
ACTIVE_CLIENT.replace(pos); ACTIVE_CLIENT.replace(*client);
ENTRY_POINT = clamp_to_display_bounds(prev_pos, curr_pos); ENTRY_POINT = clamp_to_display_bounds(prev_pos, curr_pos);
/* notify main thread */ /* notify main thread */
@@ -305,7 +305,7 @@ unsafe extern "system" fn mouse_proc(ncode: i32, wparam: WPARAM, lparam: LPARAM)
} }
/* get active client if any */ /* get active client if any */
let Some(pos) = ACTIVE_CLIENT else { let Some(client) = ACTIVE_CLIENT else {
return LRESULT(1); return LRESULT(1);
}; };
@@ -313,7 +313,7 @@ unsafe extern "system" fn mouse_proc(ncode: i32, wparam: WPARAM, lparam: LPARAM)
let Some(pointer_event) = to_mouse_event(wparam, lparam) else { let Some(pointer_event) = to_mouse_event(wparam, lparam) else {
return LRESULT(1); return LRESULT(1);
}; };
let event = (pos, CaptureEvent::Input(Event::Pointer(pointer_event))); let event = (client, CaptureEvent::Input(Event::Pointer(pointer_event)));
/* notify mainthread (drop events if sending too fast) */ /* notify mainthread (drop events if sending too fast) */
if let Err(e) = EVENT_TX.as_ref().unwrap().try_send(event) { if let Err(e) = EVENT_TX.as_ref().unwrap().try_send(event) {
@@ -493,8 +493,6 @@ fn get_msg() -> Option<MSG> {
} }
} }
static WINDOW_CLASS_REGISTERED: AtomicBool = AtomicBool::new(false);
fn message_thread(ready_tx: mpsc::Sender<()>) { fn message_thread(ready_tx: mpsc::Sender<()>) {
unsafe { unsafe {
set_event_tid(GetCurrentThreadId()); set_event_tid(GetCurrentThreadId());
@@ -515,15 +513,9 @@ fn message_thread(ready_tx: mpsc::Sender<()>) {
..Default::default() ..Default::default()
}; };
if WINDOW_CLASS_REGISTERED let ret = RegisterClassW(&window_class);
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) if ret == 0 {
.is_ok() panic!("RegisterClassW");
{
/* register window class if not yet done so */
let ret = RegisterClassW(&window_class);
if ret == 0 {
panic!("RegisterClassW");
}
} }
/* window is used ro receive WM_DISPLAYCHANGE messages */ /* window is used ro receive WM_DISPLAYCHANGE messages */
@@ -583,16 +575,23 @@ fn message_thread(ready_tx: mpsc::Sender<()>) {
fn update_clients(request: Request) { fn update_clients(request: Request) {
match request { match request {
Request::Create(pos) => { Request::Create(handle, pos) => {
unsafe { CLIENTS.insert(pos) }; unsafe { CLIENT_FOR_POS.insert(pos, handle) };
} }
Request::Destroy(pos) => unsafe { Request::Destroy(handle) => unsafe {
if let Some(active_pos) = ACTIVE_CLIENT { for pos in [
if pos == active_pos { Position::Left,
let _ = ACTIVE_CLIENT.take(); Position::Right,
Position::Top,
Position::Bottom,
] {
if ACTIVE_CLIENT == Some(handle) {
ACTIVE_CLIENT.take();
}
if CLIENT_FOR_POS.get(&pos).copied() == Some(handle) {
CLIENT_FOR_POS.remove(&pos);
} }
} }
CLIENTS.remove(&pos);
}, },
} }
} }
@@ -615,7 +614,7 @@ impl WindowsInputCapture {
} }
impl Stream for WindowsInputCapture { impl Stream for WindowsInputCapture {
type Item = Result<(Position, CaptureEvent), CaptureError>; type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match ready!(self.event_rx.poll_recv(cx)) { match ready!(self.event_rx.poll_recv(cx)) {
None => Poll::Ready(None), None => Poll::Ready(None),

View File

@@ -3,7 +3,10 @@ use std::task::Poll;
use async_trait::async_trait; use async_trait::async_trait;
use futures_core::Stream; use futures_core::Stream;
use super::{error::X11InputCaptureCreationError, Capture, CaptureError, CaptureEvent, Position}; use super::{
error::X11InputCaptureCreationError, Capture, CaptureError, CaptureEvent, CaptureHandle,
Position,
};
pub struct X11InputCapture {} pub struct X11InputCapture {}
@@ -15,11 +18,11 @@ impl X11InputCapture {
#[async_trait] #[async_trait]
impl Capture for X11InputCapture { impl Capture for X11InputCapture {
async fn create(&mut self, _pos: Position) -> Result<(), CaptureError> { async fn create(&mut self, _id: CaptureHandle, _pos: Position) -> Result<(), CaptureError> {
Ok(()) Ok(())
} }
async fn destroy(&mut self, _pos: Position) -> Result<(), CaptureError> { async fn destroy(&mut self, _id: CaptureHandle) -> Result<(), CaptureError> {
Ok(()) Ok(())
} }
@@ -33,7 +36,7 @@ impl Capture for X11InputCapture {
} }
impl Stream for X11InputCapture { impl Stream for X11InputCapture {
type Item = Result<(Position, CaptureEvent), CaptureError>; type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next( fn poll_next(
self: std::pin::Pin<&mut Self>, self: std::pin::Pin<&mut Self>,

View File

@@ -44,7 +44,6 @@ ashpd = { version = "0.9", default-features = false, features = [
reis = { version = "0.2", features = ["tokio"], optional = true } reis = { version = "0.2", features = ["tokio"], optional = true }
[target.'cfg(target_os="macos")'.dependencies] [target.'cfg(target_os="macos")'.dependencies]
bitflags = "2.5.0"
core-graphics = { version = "0.23", features = ["highsierra"] } core-graphics = { version = "0.23", features = ["highsierra"] }
keycode = "0.4.0" keycode = "0.4.0"

View File

@@ -1,23 +1,15 @@
use super::{error::EmulationError, Emulation, EmulationHandle}; use super::{error::EmulationError, Emulation, EmulationHandle};
use async_trait::async_trait; use async_trait::async_trait;
use bitflags::bitflags; use core_graphics::display::{CGDisplayBounds, CGMainDisplayID, CGPoint};
use core_graphics::base::CGFloat;
use core_graphics::display::{
CGDirectDisplayID, CGDisplayBounds, CGGetDisplaysWithRect, CGPoint, CGRect, CGSize,
};
use core_graphics::event::{ use core_graphics::event::{
CGEvent, CGEventFlags, CGEventTapLocation, CGEventType, CGKeyCode, CGMouseButton, EventField, CGEvent, CGEventTapLocation, CGEventType, CGKeyCode, CGMouseButton, EventField, ScrollEventUnit,
ScrollEventUnit,
}; };
use core_graphics::event_source::{CGEventSource, CGEventSourceStateID}; use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
use input_event::{scancode, Event, KeyboardEvent, PointerEvent}; use input_event::{Event, KeyboardEvent, PointerEvent};
use keycode::{KeyMap, KeyMapping}; use keycode::{KeyMap, KeyMapping};
use std::cell::Cell;
use std::ops::{Index, IndexMut}; use std::ops::{Index, IndexMut};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tokio::{sync::Notify, task::JoinHandle}; use tokio::task::AbortHandle;
use super::error::MacOSEmulationCreationError; use super::error::MacOSEmulationCreationError;
@@ -26,10 +18,8 @@ const DEFAULT_REPEAT_INTERVAL: Duration = Duration::from_millis(32);
pub(crate) struct MacOSEmulation { pub(crate) struct MacOSEmulation {
event_source: CGEventSource, event_source: CGEventSource,
repeat_task: Option<JoinHandle<()>>, repeat_task: Option<AbortHandle>,
button_state: ButtonState, button_state: ButtonState,
modifier_state: Rc<Cell<XMods>>,
notify_repeat_task: Arc<Notify>,
} }
struct ButtonState { struct ButtonState {
@@ -75,8 +65,6 @@ impl MacOSEmulation {
event_source, event_source,
button_state, button_state,
repeat_task: None, repeat_task: None,
notify_repeat_task: Arc::new(Notify::new()),
modifier_state: Rc::new(Cell::new(XMods::empty())),
}) })
} }
@@ -88,40 +76,25 @@ impl MacOSEmulation {
async fn spawn_repeat_task(&mut self, key: u16) { async fn spawn_repeat_task(&mut self, key: u16) {
// there can only be one repeating key and it's // there can only be one repeating key and it's
// always the last to be pressed // always the last to be pressed
self.cancel_repeat_task().await; self.kill_repeat_task();
let event_source = self.event_source.clone(); let event_source = self.event_source.clone();
let notify = self.notify_repeat_task.clone();
let modifiers = self.modifier_state.clone();
let repeat_task = tokio::task::spawn_local(async move { let repeat_task = tokio::task::spawn_local(async move {
let stop = tokio::select! { tokio::time::sleep(DEFAULT_REPEAT_DELAY).await;
_ = tokio::time::sleep(DEFAULT_REPEAT_DELAY) => false, loop {
_ = notify.notified() => true, key_event(event_source.clone(), key, 1);
}; tokio::time::sleep(DEFAULT_REPEAT_INTERVAL).await;
if !stop {
loop {
key_event(event_source.clone(), key, 1, modifiers.get());
tokio::select! {
_ = tokio::time::sleep(DEFAULT_REPEAT_INTERVAL) => {},
_ = notify.notified() => break,
}
}
} }
// release key when cancelled
update_modifiers(&modifiers, key as u32, 0);
key_event(event_source.clone(), key, 0, modifiers.get());
}); });
self.repeat_task = Some(repeat_task); self.repeat_task = Some(repeat_task.abort_handle());
} }
fn kill_repeat_task(&mut self) {
async fn cancel_repeat_task(&mut self) {
if let Some(task) = self.repeat_task.take() { if let Some(task) = self.repeat_task.take() {
self.notify_repeat_task.notify_waiters(); task.abort();
let _ = task.await;
} }
} }
} }
fn key_event(event_source: CGEventSource, key: u16, state: u8, modifiers: XMods) { fn key_event(event_source: CGEventSource, key: u16, state: u8) {
let event = match CGEvent::new_keyboard_event(event_source, key, state != 0) { let event = match CGEvent::new_keyboard_event(event_source, key, state != 0) {
Ok(e) => e, Ok(e) => e,
Err(_) => { Err(_) => {
@@ -129,92 +102,7 @@ fn key_event(event_source: CGEventSource, key: u16, state: u8, modifiers: XMods)
return; return;
} }
}; };
event.set_flags(to_cgevent_flags(modifiers));
event.post(CGEventTapLocation::HID); event.post(CGEventTapLocation::HID);
log::trace!("key event: {key} {state}");
}
fn modifier_event(event_source: CGEventSource, depressed: XMods) {
let Ok(event) = CGEvent::new(event_source) else {
log::warn!("could not create CGEvent");
return;
};
let flags = to_cgevent_flags(depressed);
event.set_type(CGEventType::FlagsChanged);
event.set_flags(flags);
event.post(CGEventTapLocation::HID);
log::trace!("modifiers updated: {depressed:?}");
}
fn get_display_at_point(x: CGFloat, y: CGFloat) -> Option<CGDirectDisplayID> {
let mut displays: [CGDirectDisplayID; 16] = [0; 16];
let mut display_count: u32 = 0;
let rect = CGRect::new(&CGPoint::new(x, y), &CGSize::new(0.0, 0.0));
let error = unsafe {
CGGetDisplaysWithRect(
rect,
1,
displays.as_mut_ptr(),
&mut display_count as *mut u32,
)
};
if error != 0 {
log::warn!("error getting displays at point ({}, {}): {}", x, y, error);
return Option::None;
}
if display_count == 0 {
log::debug!("no displays found at point ({}, {})", x, y);
return Option::None;
}
return displays.first().copied();
}
fn get_display_bounds(display: CGDirectDisplayID) -> (CGFloat, CGFloat, CGFloat, CGFloat) {
unsafe {
let bounds = CGDisplayBounds(display);
let min_x = bounds.origin.x;
let max_x = bounds.origin.x + bounds.size.width;
let min_y = bounds.origin.y;
let max_y = bounds.origin.y + bounds.size.height;
(min_x as f64, min_y as f64, max_x as f64, max_y as f64)
}
}
fn clamp_to_screen_space(
current_x: CGFloat,
current_y: CGFloat,
dx: CGFloat,
dy: CGFloat,
) -> (CGFloat, CGFloat) {
// Check which display the mouse is currently on
// Determine what the location of the mouse would be after applying the move
// Get the display at the new location
// If the point is not on a display
// Clamp the mouse to the current display
// Else If the point is on a display
// Clamp the mouse to the new display
let current_display = match get_display_at_point(current_x, current_y) {
Some(display) => display,
None => {
log::warn!("could not get current display!");
return (current_x, current_y);
}
};
let new_x = current_x + dx;
let new_y = current_y + dy;
let final_display = get_display_at_point(new_x, new_y).unwrap_or(current_display);
let (min_x, min_y, max_x, max_y) = get_display_bounds(final_display);
(
new_x.clamp(min_x, max_x - 1.),
new_y.clamp(min_y, max_y - 1.),
)
} }
#[async_trait] #[async_trait]
@@ -227,6 +115,16 @@ impl Emulation for MacOSEmulation {
match event { match event {
Event::Pointer(pointer_event) => match pointer_event { Event::Pointer(pointer_event) => match pointer_event {
PointerEvent::Motion { time: _, dx, dy } => { PointerEvent::Motion { time: _, dx, dy } => {
// FIXME secondary displays?
let (min_x, min_y, max_x, max_y) = unsafe {
let display = CGMainDisplayID();
let bounds = CGDisplayBounds(display);
let min_x = bounds.origin.x;
let max_x = bounds.origin.x + bounds.size.width;
let min_y = bounds.origin.y;
let max_y = bounds.origin.y + bounds.size.height;
(min_x as f64, min_y as f64, max_x as f64, max_y as f64)
};
let mut mouse_location = match self.get_mouse_location() { let mut mouse_location = match self.get_mouse_location() {
Some(l) => l, Some(l) => l,
None => { None => {
@@ -235,11 +133,8 @@ impl Emulation for MacOSEmulation {
} }
}; };
let (new_mouse_x, new_mouse_y) = mouse_location.x = (mouse_location.x + dx).clamp(min_x, max_x - 1.);
clamp_to_screen_space(mouse_location.x, mouse_location.y, dx, dy); mouse_location.y = (mouse_location.y + dy).clamp(min_y, max_y - 1.);
mouse_location.x = new_mouse_x;
mouse_location.y = new_mouse_y;
let mut event_type = CGEventType::MouseMoved; let mut event_type = CGEventType::MouseMoved;
if self.button_state.left { if self.button_state.left {
@@ -384,25 +279,11 @@ impl Emulation for MacOSEmulation {
match state { match state {
// pressed // pressed
1 => self.spawn_repeat_task(code).await, 1 => self.spawn_repeat_task(code).await,
_ => self.cancel_repeat_task().await, _ => self.kill_repeat_task(),
} }
update_modifiers(&self.modifier_state, key, state); key_event(self.event_source.clone(), code, state)
key_event(
self.event_source.clone(),
code,
state,
self.modifier_state.get(),
);
}
KeyboardEvent::Modifiers {
depressed,
latched,
locked,
group,
} => {
set_modifiers(&self.modifier_state, depressed, latched, locked, group);
modifier_event(self.event_source.clone(), self.modifier_state.get());
} }
KeyboardEvent::Modifiers { .. } => {}
}, },
} }
// FIXME // FIXME
@@ -415,81 +296,3 @@ impl Emulation for MacOSEmulation {
async fn terminate(&mut self) {} async fn terminate(&mut self) {}
} }
fn update_modifiers(modifiers: &Cell<XMods>, key: u32, state: u8) -> bool {
if let Ok(key) = scancode::Linux::try_from(key) {
let mask = match key {
scancode::Linux::KeyLeftShift | scancode::Linux::KeyRightShift => XMods::ShiftMask,
scancode::Linux::KeyCapsLock => XMods::LockMask,
scancode::Linux::KeyLeftCtrl | scancode::Linux::KeyRightCtrl => XMods::ControlMask,
scancode::Linux::KeyLeftAlt | scancode::Linux::KeyRightalt => XMods::Mod1Mask,
scancode::Linux::KeyLeftMeta | scancode::Linux::KeyRightmeta => XMods::Mod4Mask,
_ => XMods::empty(),
};
// unchanged
if mask.is_empty() {
return false;
}
let mut mods = modifiers.get();
match state {
1 => mods.insert(mask),
_ => mods.remove(mask),
}
modifiers.set(mods);
true
} else {
false
}
}
fn set_modifiers(
active_modifiers: &Cell<XMods>,
depressed: u32,
latched: u32,
locked: u32,
group: u32,
) {
let depressed = XMods::from_bits(depressed).unwrap_or_default();
let _latched = XMods::from_bits(latched).unwrap_or_default();
let _locked = XMods::from_bits(locked).unwrap_or_default();
let _group = XMods::from_bits(group).unwrap_or_default();
// we only care about the depressed modifiers for now
active_modifiers.replace(depressed);
}
fn to_cgevent_flags(depressed: XMods) -> CGEventFlags {
let mut flags = CGEventFlags::empty();
if depressed.contains(XMods::ShiftMask) {
flags |= CGEventFlags::CGEventFlagShift;
}
if depressed.contains(XMods::LockMask) {
flags |= CGEventFlags::CGEventFlagAlphaShift;
}
if depressed.contains(XMods::ControlMask) {
flags |= CGEventFlags::CGEventFlagControl;
}
if depressed.contains(XMods::Mod1Mask) {
flags |= CGEventFlags::CGEventFlagAlternate;
}
if depressed.contains(XMods::Mod4Mask) {
flags |= CGEventFlags::CGEventFlagCommand;
}
flags
}
// From X11/X.h
bitflags! {
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct XMods: u32 {
const ShiftMask = (1<<0);
const LockMask = (1<<1);
const ControlMask = (1<<2);
const Mod1Mask = (1<<3);
const Mod2Mask = (1<<4);
const Mod3Mask = (1<<5);
const Mod4Mask = (1<<6);
const Mod5Mask = (1<<7);
}
}

View File

@@ -1,18 +0,0 @@
[package]
name = "lan-mouse-cli"
description = "CLI Frontend for lan-mouse"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
[dependencies]
futures = "0.3.30"
lan-mouse-ipc = { path = "../lan-mouse-ipc", version = "0.1.0" }
tokio = { version = "1.32.0", features = [
"io-util",
"io-std",
"macros",
"net",
"rt",
] }

View File

@@ -1,18 +0,0 @@
[package]
name = "lan-mouse-gtk"
description = "GTK4 / Libadwaita Frontend for lan-mouse"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
[dependencies]
gtk = { package = "gtk4", version = "0.9.0", features = ["v4_2"] }
adw = { package = "libadwaita", version = "0.7.0", features = ["v1_1"] }
async-channel = { version = "2.1.1" }
hostname = "0.4.0"
log = "0.4.20"
lan-mouse-ipc = { path = "../lan-mouse-ipc", version = "0.1.0" }
[build-dependencies]
glib-build-tools = { version = "0.20.0" }

View File

@@ -1,8 +0,0 @@
fn main() {
// composite_templates
glib_build_tools::compile_resources(
&["resources"],
"resources/resources.gresource.xml",
"lan-mouse.gresource",
);
}

View File

@@ -1,16 +0,0 @@
[package]
name = "lan-mouse-ipc"
description = "library for communication between lan-mouse service and frontends"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
[dependencies]
futures = "0.3.30"
log = "0.4.22"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.107"
thiserror = "1.0.63"
tokio = { version = "1.32.0", features = ["net", "io-util", "time"] }
tokio-stream = { version = "0.1.15", features = ["io-util"] }

View File

@@ -1,89 +0,0 @@
use crate::{ConnectionError, FrontendEvent, FrontendRequest, IpcError};
use std::{
cmp::min,
io::{self, prelude::*, BufReader, LineWriter, Lines},
thread,
time::Duration,
};
#[cfg(unix)]
use std::os::unix::net::UnixStream;
#[cfg(windows)]
use std::net::TcpStream;
pub struct FrontendEventReader {
#[cfg(unix)]
lines: Lines<BufReader<UnixStream>>,
#[cfg(windows)]
lines: Lines<BufReader<TcpStream>>,
}
pub struct FrontendRequestWriter {
#[cfg(unix)]
line_writer: LineWriter<UnixStream>,
#[cfg(windows)]
line_writer: LineWriter<TcpStream>,
}
impl FrontendEventReader {
pub fn next_event(&mut self) -> Option<Result<FrontendEvent, IpcError>> {
match self.lines.next()? {
Err(e) => Some(Err(e.into())),
Ok(l) => Some(serde_json::from_str(l.as_str()).map_err(|e| e.into())),
}
}
}
impl FrontendRequestWriter {
pub fn request(&mut self, request: FrontendRequest) -> Result<(), io::Error> {
let mut json = serde_json::to_string(&request).unwrap();
log::debug!("requesting: {json}");
json.push('\n');
self.line_writer.write_all(json.as_bytes())?;
Ok(())
}
}
pub fn connect() -> Result<(FrontendEventReader, FrontendRequestWriter), ConnectionError> {
let rx = wait_for_service()?;
let tx = rx.try_clone()?;
let buf_reader = BufReader::new(rx);
let lines = buf_reader.lines();
let line_writer = LineWriter::new(tx);
let reader = FrontendEventReader { lines };
let writer = FrontendRequestWriter { line_writer };
Ok((reader, writer))
}
/// wait for the lan-mouse socket to come online
#[cfg(unix)]
fn wait_for_service() -> Result<UnixStream, ConnectionError> {
let socket_path = crate::default_socket_path()?;
let mut duration = Duration::from_millis(10);
loop {
if let Ok(stream) = UnixStream::connect(&socket_path) {
break Ok(stream);
}
// a signaling mechanism or inotify could be used to
// improve this
thread::sleep(exponential_back_off(&mut duration));
}
}
#[cfg(windows)]
fn wait_for_service() -> Result<TcpStream, ConnectionError> {
let mut duration = Duration::from_millis(10);
loop {
if let Ok(stream) = TcpStream::connect("127.0.0.1:5252") {
break Ok(stream);
}
thread::sleep(exponential_back_off(&mut duration));
}
}
fn exponential_back_off(duration: &mut Duration) -> Duration {
let new = duration.saturating_mul(2);
*duration = min(new, Duration::from_secs(1));
*duration
}

View File

@@ -1,104 +0,0 @@
use crate::{ConnectionError, FrontendEvent, FrontendRequest, IpcError};
use std::{
cmp::min,
io,
task::{ready, Poll},
time::Duration,
};
use futures::{Stream, StreamExt};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};
use tokio_stream::wrappers::LinesStream;
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
use tokio::net::TcpStream;
pub struct AsyncFrontendEventReader {
#[cfg(unix)]
lines_stream: LinesStream<BufReader<ReadHalf<UnixStream>>>,
#[cfg(windows)]
lines_stream: LinesStream<BufReader<ReadHalf<TcpStream>>>,
}
pub struct AsyncFrontendRequestWriter {
#[cfg(unix)]
tx: WriteHalf<UnixStream>,
#[cfg(windows)]
tx: WriteHalf<TcpStream>,
}
impl Stream for AsyncFrontendEventReader {
type Item = Result<FrontendEvent, IpcError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let line = ready!(self.lines_stream.poll_next_unpin(cx));
let event = line.map(|l| {
l.map_err(Into::<IpcError>::into)
.and_then(|l| serde_json::from_str(l.as_str()).map_err(|e| e.into()))
});
Poll::Ready(event)
}
}
impl AsyncFrontendRequestWriter {
pub async fn request(&mut self, request: FrontendRequest) -> Result<(), io::Error> {
let mut json = serde_json::to_string(&request).unwrap();
log::debug!("requesting: {json}");
json.push('\n');
self.tx.write_all(json.as_bytes()).await?;
Ok(())
}
}
pub async fn connect_async(
) -> Result<(AsyncFrontendEventReader, AsyncFrontendRequestWriter), ConnectionError> {
let stream = wait_for_service().await?;
#[cfg(unix)]
let (rx, tx): (ReadHalf<UnixStream>, WriteHalf<UnixStream>) = tokio::io::split(stream);
#[cfg(windows)]
let (rx, tx): (ReadHalf<TcpStream>, WriteHalf<TcpStream>) = tokio::io::split(stream);
let buf_reader = BufReader::new(rx);
let lines = buf_reader.lines();
let lines_stream = LinesStream::new(lines);
let reader = AsyncFrontendEventReader { lines_stream };
let writer = AsyncFrontendRequestWriter { tx };
Ok((reader, writer))
}
/// wait for the lan-mouse socket to come online
#[cfg(unix)]
async fn wait_for_service() -> Result<UnixStream, ConnectionError> {
let socket_path = crate::default_socket_path()?;
let mut duration = Duration::from_millis(10);
loop {
if let Ok(stream) = UnixStream::connect(&socket_path).await {
break Ok(stream);
}
// a signaling mechanism or inotify could be used to
// improve this
tokio::time::sleep(exponential_back_off(&mut duration)).await;
}
}
#[cfg(windows)]
async fn wait_for_service() -> Result<TcpStream, ConnectionError> {
let mut duration = Duration::from_millis(10);
loop {
if let Ok(stream) = TcpStream::connect("127.0.0.1:5252").await {
break Ok(stream);
}
tokio::time::sleep(exponential_back_off(&mut duration)).await;
}
}
fn exponential_back_off(duration: &mut Duration) -> Duration {
let new = duration.saturating_mul(2);
*duration = min(new, Duration::from_secs(1));
*duration
}

View File

@@ -1,264 +0,0 @@
use std::{
collections::HashSet,
env::VarError,
fmt::Display,
io,
net::{IpAddr, SocketAddr},
str::FromStr,
};
use thiserror::Error;
#[cfg(unix)]
use std::{
env,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
mod connect;
mod connect_async;
mod listen;
pub use connect::{connect, FrontendEventReader, FrontendRequestWriter};
pub use connect_async::{connect_async, AsyncFrontendEventReader, AsyncFrontendRequestWriter};
pub use listen::AsyncFrontendListener;
#[derive(Debug, Error)]
pub enum ConnectionError {
#[error(transparent)]
SocketPath(#[from] SocketPathError),
#[error(transparent)]
Io(#[from] io::Error),
}
#[derive(Debug, Error)]
pub enum ListenerCreationError {
#[error("could not determine socket-path: `{0}`")]
SocketPath(#[from] SocketPathError),
#[error("service already running!")]
AlreadyRunning,
#[error("failed to bind lan-mouse socket: `{0}`")]
Bind(io::Error),
}
#[derive(Debug, Error)]
pub enum IpcError {
#[error("io error occured: `{0}`")]
Io(#[from] io::Error),
#[error("invalid json: `{0}`")]
Json(#[from] serde_json::Error),
#[error(transparent)]
Connection(#[from] ConnectionError),
#[error(transparent)]
Listen(#[from] ListenerCreationError),
}
pub const DEFAULT_PORT: u16 = 4242;
#[derive(Debug, Default, Eq, Hash, PartialEq, Clone, Copy, Serialize, Deserialize)]
pub enum Position {
#[default]
Left,
Right,
Top,
Bottom,
}
#[derive(Debug, Error)]
#[error("not a valid position: {pos}")]
pub struct PositionParseError {
pos: String,
}
impl FromStr for Position {
type Err = PositionParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"left" => Ok(Self::Left),
"right" => Ok(Self::Right),
"top" => Ok(Self::Top),
"bottom" => Ok(Self::Bottom),
_ => Err(PositionParseError { pos: s.into() }),
}
}
}
impl Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Position::Left => "left",
Position::Right => "right",
Position::Top => "top",
Position::Bottom => "bottom",
}
)
}
}
impl TryFrom<&str> for Position {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
"left" => Ok(Position::Left),
"right" => Ok(Position::Right),
"top" => Ok(Position::Top),
"bottom" => Ok(Position::Bottom),
_ => Err(()),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
/// hostname of this client
pub hostname: Option<String>,
/// fix ips, determined by the user
pub fix_ips: Vec<IpAddr>,
/// both active_addr and addrs can be None / empty so port needs to be stored seperately
pub port: u16,
/// position of a client on screen
pub pos: Position,
/// enter hook
pub cmd: Option<String>,
}
impl Default for ClientConfig {
fn default() -> Self {
Self {
port: DEFAULT_PORT,
hostname: Default::default(),
fix_ips: Default::default(),
pos: Default::default(),
cmd: None,
}
}
}
pub type ClientHandle = u64;
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ClientState {
/// events should be sent to and received from the client
pub active: bool,
/// `active` address of the client, used to send data to.
/// This should generally be the socket address where data
/// was last received from.
pub active_addr: Option<SocketAddr>,
/// tracks whether or not the client is responding to pings
pub alive: bool,
/// ips from dns
pub dns_ips: Vec<IpAddr>,
/// all ip addresses associated with a particular client
/// e.g. Laptops usually have at least an ethernet and a wifi port
/// which have different ip addresses
pub ips: HashSet<IpAddr>,
/// client has pressed keys
pub has_pressed_keys: bool,
/// dns resolving in progress
pub resolving: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FrontendEvent {
/// client state has changed, new state must be requested via [`FrontendRequest::GetState`]
Changed(ClientHandle),
/// a client was created
Created(ClientHandle, ClientConfig, ClientState),
/// no such client
NoSuchClient(ClientHandle),
/// state changed
State(ClientHandle, ClientConfig, ClientState),
/// the client was deleted
Deleted(ClientHandle),
/// new port, reason of failure (if failed)
PortChanged(u16, Option<String>),
/// list of all clients, used for initial state synchronization
Enumerate(Vec<(ClientHandle, ClientConfig, ClientState)>),
/// an error occured
Error(String),
/// capture status
CaptureStatus(Status),
/// emulation status
EmulationStatus(Status),
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum FrontendRequest {
/// activate/deactivate client
Activate(ClientHandle, bool),
/// add a new client
Create,
/// change the listen port (recreate udp listener)
ChangePort(u16),
/// remove a client
Delete(ClientHandle),
/// request an enumeration of all clients
Enumerate(),
/// resolve dns
ResolveDns(ClientHandle),
/// update hostname
UpdateHostname(ClientHandle, Option<String>),
/// update port
UpdatePort(ClientHandle, u16),
/// update position
UpdatePosition(ClientHandle, Position),
/// update fix-ips
UpdateFixIps(ClientHandle, Vec<IpAddr>),
/// request the state of the given client
GetState(ClientHandle),
/// request reenabling input capture
EnableCapture,
/// request reenabling input emulation
EnableEmulation,
/// synchronize all state
Sync,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
pub enum Status {
#[default]
Disabled,
Enabled,
}
impl From<Status> for bool {
fn from(status: Status) -> Self {
match status {
Status::Enabled => true,
Status::Disabled => false,
}
}
}
#[cfg(unix)]
const LAN_MOUSE_SOCKET_NAME: &str = "lan-mouse-socket.sock";
#[derive(Debug, Error)]
pub enum SocketPathError {
#[error("could not determine $XDG_RUNTIME_DIR: `{0}`")]
XdgRuntimeDirNotFound(VarError),
#[error("could not determine $HOME: `{0}`")]
HomeDirNotFound(VarError),
}
#[cfg(all(unix, not(target_os = "macos")))]
pub fn default_socket_path() -> Result<PathBuf, SocketPathError> {
let xdg_runtime_dir =
env::var("XDG_RUNTIME_DIR").map_err(SocketPathError::XdgRuntimeDirNotFound)?;
Ok(Path::new(xdg_runtime_dir.as_str()).join(LAN_MOUSE_SOCKET_NAME))
}
#[cfg(all(unix, target_os = "macos"))]
pub fn default_socket_path() -> Result<PathBuf, SocketPathError> {
let home = env::var("HOME").map_err(SocketPathError::HomeDirNotFound)?;
Ok(Path::new(home.as_str())
.join("Library")
.join("Caches")
.join(LAN_MOUSE_SOCKET_NAME))
}

View File

@@ -1,147 +0,0 @@
use futures::{stream::SelectAll, Stream, StreamExt};
#[cfg(unix)]
use std::path::PathBuf;
use std::{
io::ErrorKind,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};
use tokio_stream::wrappers::LinesStream;
#[cfg(unix)]
use tokio::net::UnixListener;
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
use tokio::net::TcpListener;
#[cfg(windows)]
use tokio::net::TcpStream;
use crate::{FrontendEvent, FrontendRequest, IpcError, ListenerCreationError};
pub struct AsyncFrontendListener {
#[cfg(windows)]
listener: TcpListener,
#[cfg(unix)]
listener: UnixListener,
#[cfg(unix)]
socket_path: PathBuf,
#[cfg(unix)]
line_streams: SelectAll<LinesStream<BufReader<ReadHalf<UnixStream>>>>,
#[cfg(windows)]
line_streams: SelectAll<LinesStream<BufReader<ReadHalf<TcpStream>>>>,
#[cfg(unix)]
tx_streams: Vec<WriteHalf<UnixStream>>,
#[cfg(windows)]
tx_streams: Vec<WriteHalf<TcpStream>>,
}
impl AsyncFrontendListener {
pub async fn new() -> Result<Self, ListenerCreationError> {
#[cfg(unix)]
let (socket_path, listener) = {
let socket_path = crate::default_socket_path()?;
log::debug!("remove socket: {:?}", socket_path);
if socket_path.exists() {
// try to connect to see if some other instance
// of lan-mouse is already running
match UnixStream::connect(&socket_path).await {
// connected -> lan-mouse is already running
Ok(_) => return Err(ListenerCreationError::AlreadyRunning),
// lan-mouse is not running but a socket was left behind
Err(e) => {
log::debug!("{socket_path:?}: {e} - removing left behind socket");
let _ = std::fs::remove_file(&socket_path);
}
}
}
let listener = match UnixListener::bind(&socket_path) {
Ok(ls) => ls,
// some other lan-mouse instance has bound the socket in the meantime
Err(e) if e.kind() == ErrorKind::AddrInUse => {
return Err(ListenerCreationError::AlreadyRunning)
}
Err(e) => return Err(ListenerCreationError::Bind(e)),
};
(socket_path, listener)
};
#[cfg(windows)]
let listener = match TcpListener::bind("127.0.0.1:5252").await {
Ok(ls) => ls,
// some other lan-mouse instance has bound the socket in the meantime
Err(e) if e.kind() == ErrorKind::AddrInUse => {
return Err(ListenerCreationError::AlreadyRunning)
}
Err(e) => return Err(ListenerCreationError::Bind(e)),
};
let adapter = Self {
listener,
#[cfg(unix)]
socket_path,
line_streams: SelectAll::new(),
tx_streams: vec![],
};
Ok(adapter)
}
pub async fn broadcast(&mut self, notify: FrontendEvent) {
// encode event
let mut json = serde_json::to_string(&notify).unwrap();
json.push('\n');
let mut keep = vec![];
// TODO do simultaneously
for tx in self.tx_streams.iter_mut() {
// write len + payload
if tx.write(json.as_bytes()).await.is_err() {
keep.push(false);
continue;
}
keep.push(true);
}
// could not find a better solution because async
let mut keep = keep.into_iter();
self.tx_streams.retain(|_| keep.next().unwrap());
}
}
#[cfg(unix)]
impl Drop for AsyncFrontendListener {
fn drop(&mut self) {
log::debug!("remove socket: {:?}", self.socket_path);
let _ = std::fs::remove_file(&self.socket_path);
}
}
impl Stream for AsyncFrontendListener {
type Item = Result<FrontendRequest, IpcError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Poll::Ready(Some(Ok(l))) = self.line_streams.poll_next_unpin(cx) {
let request = serde_json::from_str(l.as_str()).map_err(|e| e.into());
return Poll::Ready(Some(request));
}
let mut sync = false;
while let Poll::Ready(Ok((stream, _))) = self.listener.poll_accept(cx) {
let (rx, tx) = tokio::io::split(stream);
let buf_reader = BufReader::new(rx);
let lines = buf_reader.lines();
let lines = LinesStream::new(lines);
self.line_streams.push(lines);
self.tx_streams.push(tx);
sync = true;
}
if sync {
Poll::Ready(Some(Ok(FrontendRequest::Sync)))
} else {
Poll::Pending
}
}
}

View File

@@ -44,9 +44,6 @@ rustPlatform.buildRustPackage {
postInstall = '' postInstall = ''
wrapProgram "$out/bin/lan-mouse" \ wrapProgram "$out/bin/lan-mouse" \
--set GDK_PIXBUF_MODULE_FILE ${pkgs.librsvg.out}/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache --set GDK_PIXBUF_MODULE_FILE ${pkgs.librsvg.out}/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache
install -Dm444 *.desktop -t $out/share/applications
install -Dm444 lan-mouse-gtk/resources/*.svg -t $out/share/icons/hicolor/scalable/apps
''; '';
meta = with lib; { meta = with lib; {

View File

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@@ -2,16 +2,27 @@ use crate::config::Config;
use futures::StreamExt; use futures::StreamExt;
use input_capture::{self, CaptureError, CaptureEvent, InputCapture, InputCaptureError, Position}; use input_capture::{self, CaptureError, CaptureEvent, InputCapture, InputCaptureError, Position};
use input_event::{Event, KeyboardEvent}; use input_event::{Event, KeyboardEvent};
use tokio::task::LocalSet;
pub async fn run(config: Config) -> Result<(), InputCaptureError> { pub fn run() -> anyhow::Result<()> {
log::info!("running input capture test"); log::info!("running input capture test");
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()?;
let config = Config::new()?;
Ok(runtime.block_on(LocalSet::new().run_until(input_capture_test(config)))?)
}
async fn input_capture_test(config: Config) -> Result<(), InputCaptureError> {
log::info!("creating input capture"); log::info!("creating input capture");
let backend = config.capture_backend.map(|b| b.into()); let backend = config.capture_backend.map(|b| b.into());
loop { loop {
let mut input_capture = InputCapture::new(backend).await?; let mut input_capture = InputCapture::new(backend).await?;
log::info!("creating clients"); log::info!("creating clients");
input_capture.create(0, Position::Left).await?; input_capture.create(0, Position::Left).await?;
input_capture.create(4, Position::Left).await?;
input_capture.create(1, Position::Right).await?; input_capture.create(1, Position::Right).await?;
input_capture.create(2, Position::Top).await?; input_capture.create(2, Position::Top).await?;
input_capture.create(3, Position::Bottom).await?; input_capture.create(3, Position::Bottom).await?;
@@ -29,13 +40,12 @@ async fn do_capture(input_capture: &mut InputCapture) -> Result<(), CaptureError
.await .await
.ok_or(CaptureError::EndOfStream)??; .ok_or(CaptureError::EndOfStream)??;
let pos = match client { let pos = match client {
0 | 4 => Position::Left, 0 => Position::Left,
1 => Position::Right, 1 => Position::Right,
2 => Position::Top, 2 => Position::Top,
3 => Position::Bottom, _ => Position::Bottom,
_ => panic!(),
}; };
log::info!("position: {client} ({pos}), event: {event}"); log::info!("position: {pos}, event: {event}");
if let CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { key: 1, .. })) = event { if let CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { key: 1, .. })) = event {
input_capture.release().await?; input_capture.release().await?;
break Ok(()); break Ok(());

View File

@@ -1,8 +1,135 @@
use std::net::SocketAddr; use std::{
collections::HashSet,
fmt::Display,
net::{IpAddr, SocketAddr},
str::FromStr,
};
use serde::{Deserialize, Serialize};
use slab::Slab; use slab::Slab;
use thiserror::Error;
use lan_mouse_ipc::{ClientConfig, ClientHandle, ClientState, Position}; use crate::config::DEFAULT_PORT;
use input_capture;
#[derive(Debug, Default, Eq, Hash, PartialEq, Clone, Copy, Serialize, Deserialize)]
pub enum Position {
#[default]
Left,
Right,
Top,
Bottom,
}
impl From<Position> for input_capture::Position {
fn from(position: Position) -> input_capture::Position {
match position {
Position::Left => input_capture::Position::Left,
Position::Right => input_capture::Position::Right,
Position::Top => input_capture::Position::Top,
Position::Bottom => input_capture::Position::Bottom,
}
}
}
#[derive(Debug, Error)]
#[error("not a valid position: {pos}")]
pub struct PositionParseError {
pos: String,
}
impl FromStr for Position {
type Err = PositionParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"left" => Ok(Self::Left),
"right" => Ok(Self::Right),
"top" => Ok(Self::Top),
"bottom" => Ok(Self::Bottom),
_ => Err(PositionParseError { pos: s.into() }),
}
}
}
impl Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Position::Left => "left",
Position::Right => "right",
Position::Top => "top",
Position::Bottom => "bottom",
}
)
}
}
impl TryFrom<&str> for Position {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
"left" => Ok(Position::Left),
"right" => Ok(Position::Right),
"top" => Ok(Position::Top),
"bottom" => Ok(Position::Bottom),
_ => Err(()),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
/// hostname of this client
pub hostname: Option<String>,
/// fix ips, determined by the user
pub fix_ips: Vec<IpAddr>,
/// both active_addr and addrs can be None / empty so port needs to be stored seperately
pub port: u16,
/// position of a client on screen
pub pos: Position,
/// enter hook
pub cmd: Option<String>,
}
impl Default for ClientConfig {
fn default() -> Self {
Self {
port: DEFAULT_PORT,
hostname: Default::default(),
fix_ips: Default::default(),
pos: Default::default(),
cmd: None,
}
}
}
pub type ClientHandle = u64;
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ClientState {
/// events should be sent to and received from the client
pub active: bool,
/// `active` address of the client, used to send data to.
/// This should generally be the socket address where data
/// was last received from.
pub active_addr: Option<SocketAddr>,
/// tracks whether or not the client is responding to pings
pub alive: bool,
/// ips from dns
pub dns_ips: Vec<IpAddr>,
/// all ip addresses associated with a particular client
/// e.g. Laptops usually have at least an ethernet and a wifi port
/// which have different ip addresses
pub ips: HashSet<IpAddr>,
/// client has pressed keys
pub has_pressed_keys: bool,
/// dns resolving in progress
pub resolving: bool,
}
#[derive(Default)] #[derive(Default)]
pub struct ClientManager { pub struct ClientManager {

View File

@@ -1,20 +1,22 @@
use anyhow::Result;
use clap::{Parser, ValueEnum}; use clap::{Parser, ValueEnum};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::env::{self, VarError}; use std::collections::HashSet;
use std::env;
use std::fmt::Display; use std::fmt::Display;
use std::fs;
use std::net::IpAddr; use std::net::IpAddr;
use std::{collections::HashSet, io}; use std::{error::Error, fs};
use thiserror::Error;
use toml; use toml;
use lan_mouse_ipc::{Position, DEFAULT_PORT}; use crate::client::Position;
use input_event::scancode::{ use input_event::scancode::{
self, self,
Linux::{KeyLeftAlt, KeyLeftCtrl, KeyLeftMeta, KeyLeftShift}, Linux::{KeyLeftAlt, KeyLeftCtrl, KeyLeftMeta, KeyLeftShift},
}; };
pub const DEFAULT_PORT: u16 = 4242;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct ConfigToml { pub struct ConfigToml {
pub capture_backend: Option<CaptureBackend>, pub capture_backend: Option<CaptureBackend>,
@@ -40,7 +42,7 @@ pub struct TomlClient {
} }
impl ConfigToml { impl ConfigToml {
pub fn new(path: &str) -> Result<ConfigToml, ConfigError> { pub fn new(path: &str) -> Result<ConfigToml, Box<dyn Error>> {
let config = fs::read_to_string(path)?; let config = fs::read_to_string(path)?;
log::info!("using config: \"{path}\""); log::info!("using config: \"{path}\"");
Ok(toml::from_str::<_>(&config)?) Ok(toml::from_str::<_>(&config)?)
@@ -229,21 +231,11 @@ pub struct ConfigClient {
pub enter_hook: Option<String>, pub enter_hook: Option<String>,
} }
#[derive(Debug, Error)]
pub enum ConfigError {
#[error(transparent)]
Toml(#[from] toml::de::Error),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Var(#[from] VarError),
}
const DEFAULT_RELEASE_KEYS: [scancode::Linux; 4] = const DEFAULT_RELEASE_KEYS: [scancode::Linux; 4] =
[KeyLeftCtrl, KeyLeftShift, KeyLeftMeta, KeyLeftAlt]; [KeyLeftCtrl, KeyLeftShift, KeyLeftMeta, KeyLeftAlt];
impl Config { impl Config {
pub fn new() -> Result<Self, ConfigError> { pub fn new() -> Result<Self> {
let args = CliArgs::parse(); let args = CliArgs::parse();
let config_file = "config.toml"; let config_file = "config.toml";
#[cfg(unix)] #[cfg(unix)]

View File

@@ -3,8 +3,7 @@ use std::net::IpAddr;
use hickory_resolver::{error::ResolveError, TokioAsyncResolver}; use hickory_resolver::{error::ResolveError, TokioAsyncResolver};
use crate::server::Server; use crate::{client::ClientHandle, server::Server};
use lan_mouse_ipc::ClientHandle;
pub(crate) struct DnsResolver { pub(crate) struct DnsResolver {
resolver: TokioAsyncResolver, resolver: TokioAsyncResolver,

View File

@@ -1,19 +1,30 @@
use crate::config::Config; use crate::config::Config;
use input_emulation::{InputEmulation, InputEmulationError}; use anyhow::Result;
use input_emulation::InputEmulation;
use input_event::{Event, PointerEvent}; use input_event::{Event, PointerEvent};
use std::f64::consts::PI; use std::f64::consts::PI;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tokio::task::LocalSet;
pub fn run() -> Result<()> {
log::info!("running input emulation test");
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()?;
let config = Config::new()?;
runtime.block_on(LocalSet::new().run_until(input_emulation_test(config)))
}
const FREQUENCY_HZ: f64 = 1.0; const FREQUENCY_HZ: f64 = 1.0;
const RADIUS: f64 = 100.0; const RADIUS: f64 = 100.0;
pub async fn run(config: Config) -> Result<(), InputEmulationError> { async fn input_emulation_test(config: Config) -> Result<()> {
log::info!("running input emulation test");
let backend = config.emulation_backend.map(|b| b.into()); let backend = config.emulation_backend.map(|b| b.into());
let mut emulation = InputEmulation::new(backend).await?; let mut emulation = InputEmulation::new(backend).await?;
emulation.create(0).await; emulation.create(0).await;
let start = Instant::now(); let start = Instant::now();
let mut offset = (0, 0); let mut offset = (0, 0);
loop { loop {

307
src/frontend.rs Normal file
View File

@@ -0,0 +1,307 @@
use anyhow::{anyhow, Result};
use std::{cmp::min, io::ErrorKind, net::IpAddr, str, time::Duration};
#[cfg(unix)]
use std::{
env,
path::{Path, PathBuf},
};
use tokio::io::ReadHalf;
use tokio::io::{AsyncReadExt, AsyncWriteExt, WriteHalf};
#[cfg(unix)]
use tokio::net::UnixListener;
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
use tokio::net::TcpListener;
#[cfg(windows)]
use tokio::net::TcpStream;
use serde::{Deserialize, Serialize};
use crate::{
client::{ClientConfig, ClientHandle, ClientState, Position},
config::{Config, Frontend},
};
/// cli frontend
pub mod cli;
/// gtk frontend
#[cfg(feature = "gtk")]
pub mod gtk;
pub fn run_frontend(config: &Config) -> Result<()> {
match config.frontend {
#[cfg(feature = "gtk")]
Frontend::Gtk => {
gtk::run();
}
#[cfg(not(feature = "gtk"))]
Frontend::Gtk => panic!("gtk frontend requested but feature not enabled!"),
Frontend::Cli => {
cli::run()?;
}
};
Ok(())
}
fn exponential_back_off(duration: &mut Duration) -> &Duration {
let new = duration.saturating_mul(2);
*duration = min(new, Duration::from_secs(1));
duration
}
/// wait for the lan-mouse socket to come online
#[cfg(unix)]
pub fn wait_for_service() -> Result<std::os::unix::net::UnixStream> {
let socket_path = FrontendListener::socket_path()?;
let mut duration = Duration::from_millis(1);
loop {
use std::os::unix::net::UnixStream;
if let Ok(stream) = UnixStream::connect(&socket_path) {
break Ok(stream);
}
// a signaling mechanism or inotify could be used to
// improve this
std::thread::sleep(*exponential_back_off(&mut duration));
}
}
#[cfg(windows)]
pub fn wait_for_service() -> Result<std::net::TcpStream> {
let mut duration = Duration::from_millis(1);
loop {
use std::net::TcpStream;
if let Ok(stream) = TcpStream::connect("127.0.0.1:5252") {
break Ok(stream);
}
std::thread::sleep(*exponential_back_off(&mut duration));
}
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum FrontendRequest {
/// activate/deactivate client
Activate(ClientHandle, bool),
/// add a new client
Create,
/// change the listen port (recreate udp listener)
ChangePort(u16),
/// remove a client
Delete(ClientHandle),
/// request an enumeration of all clients
Enumerate(),
/// resolve dns
ResolveDns(ClientHandle),
/// update hostname
UpdateHostname(ClientHandle, Option<String>),
/// update port
UpdatePort(ClientHandle, u16),
/// update position
UpdatePosition(ClientHandle, Position),
/// update fix-ips
UpdateFixIps(ClientHandle, Vec<IpAddr>),
/// request the state of the given client
GetState(ClientHandle),
/// request reenabling input capture
EnableCapture,
/// request reenabling input emulation
EnableEmulation,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
pub enum Status {
#[default]
Disabled,
Enabled,
}
impl From<Status> for bool {
fn from(status: Status) -> Self {
match status {
Status::Enabled => true,
Status::Disabled => false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FrontendEvent {
/// a client was created
Created(ClientHandle, ClientConfig, ClientState),
/// no such client
NoSuchClient(ClientHandle),
/// state changed
State(ClientHandle, ClientConfig, ClientState),
/// the client was deleted
Deleted(ClientHandle),
/// new port, reason of failure (if failed)
PortChanged(u16, Option<String>),
/// list of all clients, used for initial state synchronization
Enumerate(Vec<(ClientHandle, ClientConfig, ClientState)>),
/// an error occured
Error(String),
/// capture status
CaptureStatus(Status),
/// emulation status
EmulationStatus(Status),
}
pub struct FrontendListener {
#[cfg(windows)]
listener: TcpListener,
#[cfg(unix)]
listener: UnixListener,
#[cfg(unix)]
socket_path: PathBuf,
#[cfg(unix)]
tx_streams: Vec<WriteHalf<UnixStream>>,
#[cfg(windows)]
tx_streams: Vec<WriteHalf<TcpStream>>,
}
impl FrontendListener {
#[cfg(all(unix, not(target_os = "macos")))]
pub fn socket_path() -> Result<PathBuf> {
let xdg_runtime_dir = match env::var("XDG_RUNTIME_DIR") {
Ok(d) => d,
Err(e) => return Err(anyhow!("could not find XDG_RUNTIME_DIR: {e}")),
};
let xdg_runtime_dir = Path::new(xdg_runtime_dir.as_str());
Ok(xdg_runtime_dir.join("lan-mouse-socket.sock"))
}
#[cfg(all(unix, target_os = "macos"))]
pub fn socket_path() -> Result<PathBuf> {
let home = match env::var("HOME") {
Ok(d) => d,
Err(e) => return Err(anyhow!("could not find HOME: {e}")),
};
let home = Path::new(home.as_str());
let path = home
.join("Library")
.join("Caches")
.join("lan-mouse-socket.sock");
Ok(path)
}
pub async fn new() -> Option<Result<Self>> {
#[cfg(unix)]
let (socket_path, listener) = {
let socket_path = match Self::socket_path() {
Ok(path) => path,
Err(e) => return Some(Err(e)),
};
log::debug!("remove socket: {:?}", socket_path);
if socket_path.exists() {
// try to connect to see if some other instance
// of lan-mouse is already running
match UnixStream::connect(&socket_path).await {
// connected -> lan-mouse is already running
Ok(_) => return None,
// lan-mouse is not running but a socket was left behind
Err(e) => {
log::debug!("{socket_path:?}: {e} - removing left behind socket");
let _ = std::fs::remove_file(&socket_path);
}
}
}
let listener = match UnixListener::bind(&socket_path) {
Ok(ls) => ls,
// some other lan-mouse instance has bound the socket in the meantime
Err(e) if e.kind() == ErrorKind::AddrInUse => return None,
Err(e) => return Some(Err(anyhow!("failed to bind lan-mouse-socket: {e}"))),
};
(socket_path, listener)
};
#[cfg(windows)]
let listener = match TcpListener::bind("127.0.0.1:5252").await {
Ok(ls) => ls,
// some other lan-mouse instance has bound the socket in the meantime
Err(e) if e.kind() == ErrorKind::AddrInUse => return None,
Err(e) => return Some(Err(anyhow!("failed to bind lan-mouse-socket: {e}"))),
};
let adapter = Self {
listener,
#[cfg(unix)]
socket_path,
tx_streams: vec![],
};
Some(Ok(adapter))
}
#[cfg(unix)]
pub async fn accept(&mut self) -> Result<ReadHalf<UnixStream>> {
let stream = self.listener.accept().await?.0;
let (rx, tx) = tokio::io::split(stream);
self.tx_streams.push(tx);
Ok(rx)
}
#[cfg(windows)]
pub async fn accept(&mut self) -> Result<ReadHalf<TcpStream>> {
let stream = self.listener.accept().await?.0;
let (rx, tx) = tokio::io::split(stream);
self.tx_streams.push(tx);
Ok(rx)
}
pub(crate) async fn broadcast(&mut self, notify: FrontendEvent) {
// encode event
let json = serde_json::to_string(&notify).unwrap();
let payload = json.as_bytes();
let len = payload.len().to_be_bytes();
log::debug!("broadcasting event to streams: {json}");
let mut keep = vec![];
// TODO do simultaneously
for tx in self.tx_streams.iter_mut() {
// write len + payload
if tx.write(&len).await.is_err() {
keep.push(false);
continue;
}
if tx.write(payload).await.is_err() {
keep.push(false);
continue;
}
keep.push(true);
}
// could not find a better solution because async
let mut keep = keep.into_iter();
self.tx_streams.retain(|_| keep.next().unwrap());
}
}
#[cfg(unix)]
impl Drop for FrontendListener {
fn drop(&mut self) {
log::debug!("remove socket: {:?}", self.socket_path);
let _ = std::fs::remove_file(&self.socket_path);
}
}
#[cfg(unix)]
pub async fn wait_for_request(stream: &mut ReadHalf<UnixStream>) -> Result<FrontendRequest> {
let len = stream.read_u64().await?;
assert!(len <= 256);
let mut buf = [0u8; 256];
stream.read_exact(&mut buf[..len as usize]).await?;
Ok(serde_json::from_slice(&buf[..len as usize])?)
}
#[cfg(windows)]
pub async fn wait_for_request(stream: &mut ReadHalf<TcpStream>) -> Result<FrontendRequest> {
let len = stream.read_u64().await?;
let mut buf = [0u8; 256];
stream.read_exact(&mut buf[..len as usize]).await?;
Ok(serde_json::from_slice(&buf[..len as usize])?)
}

View File

@@ -1,65 +1,78 @@
use futures::StreamExt; use anyhow::{anyhow, Result};
use tokio::{ use tokio::{
io::{AsyncBufReadExt, BufReader}, io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
task::LocalSet, task::LocalSet,
}; };
#[cfg(windows)]
use tokio::net::tcp::{ReadHalf, WriteHalf};
#[cfg(unix)]
use tokio::net::unix::{ReadHalf, WriteHalf};
use std::io::{self, Write}; use std::io::{self, Write};
use crate::{
client::{ClientConfig, ClientHandle, ClientState},
config::DEFAULT_PORT,
};
use self::command::{Command, CommandType}; use self::command::{Command, CommandType};
use lan_mouse_ipc::{ use super::{FrontendEvent, FrontendRequest};
AsyncFrontendEventReader, AsyncFrontendRequestWriter, ClientConfig, ClientHandle, ClientState,
FrontendEvent, FrontendRequest, IpcError, DEFAULT_PORT,
};
mod command; mod command;
pub fn run() -> Result<(), IpcError> { pub fn run() -> Result<()> {
let Ok(stream) = super::wait_for_service() else {
return Err(anyhow!("Could not connect to lan-mouse-socket"));
};
let runtime = tokio::runtime::Builder::new_current_thread() let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io() .enable_io()
.enable_time() .enable_time()
.build()?; .build()?;
runtime.block_on(LocalSet::new().run_until(async move { runtime.block_on(LocalSet::new().run_until(async move {
let (rx, tx) = lan_mouse_ipc::connect_async().await?; stream.set_nonblocking(true)?;
#[cfg(unix)]
let mut stream = tokio::net::UnixStream::from_std(stream)?;
#[cfg(windows)]
let mut stream = tokio::net::TcpStream::from_std(stream)?;
let (rx, tx) = stream.split();
let mut cli = Cli::new(rx, tx); let mut cli = Cli::new(rx, tx);
cli.run().await cli.run().await
}))?; }))?;
Ok(()) Ok(())
} }
struct Cli { struct Cli<'a> {
clients: Vec<(ClientHandle, ClientConfig, ClientState)>, clients: Vec<(ClientHandle, ClientConfig, ClientState)>,
changed: Option<ClientHandle>, rx: ReadHalf<'a>,
rx: AsyncFrontendEventReader, tx: WriteHalf<'a>,
tx: AsyncFrontendRequestWriter,
} }
impl Cli { impl<'a> Cli<'a> {
fn new(rx: AsyncFrontendEventReader, tx: AsyncFrontendRequestWriter) -> Cli { fn new(rx: ReadHalf<'a>, tx: WriteHalf<'a>) -> Cli<'a> {
Self { Self {
clients: vec![], clients: vec![],
changed: None,
rx, rx,
tx, tx,
} }
} }
async fn run(&mut self) -> Result<(), IpcError> { async fn run(&mut self) -> Result<()> {
let stdin = tokio::io::stdin(); let stdin = tokio::io::stdin();
let stdin = BufReader::new(stdin); let stdin = BufReader::new(stdin);
let mut stdin = stdin.lines(); let mut stdin = stdin.lines();
/* initial state sync */ /* initial state sync */
let request = FrontendRequest::Enumerate();
self.send_request(request).await?;
self.clients = loop { self.clients = loop {
match self.rx.next().await { let event = self.await_event().await?;
Some(Ok(e)) => { if let FrontendEvent::Enumerate(clients) = event {
if let FrontendEvent::Enumerate(clients) = e { break clients;
break clients;
}
}
Some(Err(e)) => return Err(e),
None => return Ok(()),
} }
}; };
@@ -79,23 +92,18 @@ impl Cli {
}; };
self.execute(cmd).await?; self.execute(cmd).await?;
} }
event = self.rx.next() => { event = self.await_event() => {
if let Some(event) = event { let event = event?;
self.handle_event(event?); self.handle_event(event);
} else {
break Ok(());
}
} }
} }
if let Some(handle) = self.changed.take() {
self.update_client(handle).await?;
}
} }
} }
async fn update_client(&mut self, handle: ClientHandle) -> Result<(), IpcError> { async fn update_client(&mut self, handle: ClientHandle) -> Result<()> {
self.tx.request(FrontendRequest::GetState(handle)).await?; self.send_request(FrontendRequest::GetState(handle)).await?;
while let Some(Ok(event)) = self.rx.next().await { loop {
let event = self.await_event().await?;
self.handle_event(event.clone()); self.handle_event(event.clone());
if let FrontendEvent::State(_, _, _) | FrontendEvent::NoSuchClient(_) = event { if let FrontendEvent::State(_, _, _) | FrontendEvent::NoSuchClient(_) = event {
break; break;
@@ -104,23 +112,22 @@ impl Cli {
Ok(()) Ok(())
} }
async fn execute(&mut self, cmd: Command) -> Result<(), IpcError> { async fn execute(&mut self, cmd: Command) -> Result<()> {
match cmd { match cmd {
Command::None => {} Command::None => {}
Command::Connect(pos, host, port) => { Command::Connect(pos, host, port) => {
let request = FrontendRequest::Create; let request = FrontendRequest::Create;
self.tx.request(request).await?; self.send_request(request).await?;
let handle = loop { let handle = loop {
if let Some(Ok(event)) = self.rx.next().await { let event = self.await_event().await?;
match event { match event {
FrontendEvent::Created(h, c, s) => { FrontendEvent::Created(h, c, s) => {
self.clients.push((h, c, s)); self.clients.push((h, c, s));
break h; break h;
} }
_ => { _ => {
self.handle_event(event); self.handle_event(event);
continue; continue;
}
} }
} }
}; };
@@ -129,36 +136,35 @@ impl Cli {
FrontendRequest::UpdatePort(handle, port.unwrap_or(DEFAULT_PORT)), FrontendRequest::UpdatePort(handle, port.unwrap_or(DEFAULT_PORT)),
FrontendRequest::UpdatePosition(handle, pos), FrontendRequest::UpdatePosition(handle, pos),
] { ] {
self.tx.request(request).await?; self.send_request(request).await?;
} }
self.update_client(handle).await?; self.update_client(handle).await?;
} }
Command::Disconnect(id) => { Command::Disconnect(id) => {
self.tx.request(FrontendRequest::Delete(id)).await?; self.send_request(FrontendRequest::Delete(id)).await?;
loop { loop {
if let Some(Ok(event)) = self.rx.next().await { let event = self.await_event().await?;
self.handle_event(event.clone()); self.handle_event(event.clone());
if let FrontendEvent::Deleted(_) = event { if let FrontendEvent::Deleted(_) = event {
self.handle_event(event); self.handle_event(event);
break; break;
}
} }
} }
} }
Command::Activate(id) => { Command::Activate(id) => {
self.tx.request(FrontendRequest::Activate(id, true)).await?; self.send_request(FrontendRequest::Activate(id, true))
.await?;
self.update_client(id).await?; self.update_client(id).await?;
} }
Command::Deactivate(id) => { Command::Deactivate(id) => {
self.tx self.send_request(FrontendRequest::Activate(id, false))
.request(FrontendRequest::Activate(id, false))
.await?; .await?;
self.update_client(id).await?; self.update_client(id).await?;
} }
Command::List => { Command::List => {
self.tx.request(FrontendRequest::Enumerate()).await?; self.send_request(FrontendRequest::Enumerate()).await?;
while let Some(e) = self.rx.next().await { loop {
let event = e?; let event = self.await_event().await?;
self.handle_event(event.clone()); self.handle_event(event.clone());
if let FrontendEvent::Enumerate(_) = event { if let FrontendEvent::Enumerate(_) = event {
break; break;
@@ -167,12 +173,12 @@ impl Cli {
} }
Command::SetHost(handle, host) => { Command::SetHost(handle, host) => {
let request = FrontendRequest::UpdateHostname(handle, Some(host.clone())); let request = FrontendRequest::UpdateHostname(handle, Some(host.clone()));
self.tx.request(request).await?; self.send_request(request).await?;
self.update_client(handle).await?; self.update_client(handle).await?;
} }
Command::SetPort(handle, port) => { Command::SetPort(handle, port) => {
let request = FrontendRequest::UpdatePort(handle, port.unwrap_or(DEFAULT_PORT)); let request = FrontendRequest::UpdatePort(handle, port.unwrap_or(DEFAULT_PORT));
self.tx.request(request).await?; self.send_request(request).await?;
self.update_client(handle).await?; self.update_client(handle).await?;
} }
Command::Help => { Command::Help => {
@@ -209,7 +215,6 @@ impl Cli {
fn handle_event(&mut self, event: FrontendEvent) { fn handle_event(&mut self, event: FrontendEvent) {
match event { match event {
FrontendEvent::Changed(h) => self.changed = Some(h),
FrontendEvent::Created(h, c, s) => { FrontendEvent::Created(h, c, s) => {
eprint!("client added ({h}): "); eprint!("client added ({h}): ");
print_config(&c); print_config(&c);
@@ -286,6 +291,23 @@ impl Cli {
eprintln!(); eprintln!();
} }
} }
async fn send_request(&mut self, request: FrontendRequest) -> io::Result<()> {
let json = serde_json::to_string(&request).unwrap();
let bytes = json.as_bytes();
let len = bytes.len();
self.tx.write_u64(len as u64).await?;
self.tx.write_all(bytes).await?;
Ok(())
}
async fn await_event(&mut self) -> Result<FrontendEvent> {
let len = self.rx.read_u64().await?;
let mut buf = vec![0u8; len as usize];
self.rx.read_exact(&mut buf).await?;
let event: FrontendEvent = serde_json::from_slice(&buf)?;
Ok(event)
}
} }
fn prompt() -> io::Result<()> { fn prompt() -> io::Result<()> {

View File

@@ -3,7 +3,7 @@ use std::{
str::{FromStr, SplitWhitespace}, str::{FromStr, SplitWhitespace},
}; };
use lan_mouse_ipc::{ClientHandle, Position}; use crate::client::{ClientHandle, Position};
pub(super) enum CommandType { pub(super) enum CommandType {
NoCommand, NoCommand,

View File

@@ -2,13 +2,16 @@ mod client_object;
mod client_row; mod client_row;
mod window; mod window;
use std::{env, process, str}; use std::{
env,
io::{ErrorKind, Read},
process, str,
};
use window::Window; use crate::frontend::gtk::window::Window;
use lan_mouse_ipc::{FrontendEvent, FrontendRequest};
use adw::Application; use adw::Application;
use endi::{Endian, ReadBytes};
use gtk::{ use gtk::{
gdk::Display, glib::clone, prelude::*, subclass::prelude::ObjectSubclassIsExt, IconTheme, gdk::Display, glib::clone, prelude::*, subclass::prelude::ObjectSubclassIsExt, IconTheme,
}; };
@@ -16,6 +19,8 @@ use gtk::{gio, glib, prelude::ApplicationExt};
use self::client_object::ClientObject; use self::client_object::ClientObject;
use super::FrontendEvent;
pub fn run() -> glib::ExitCode { pub fn run() -> glib::ExitCode {
log::debug!("running gtk frontend"); log::debug!("running gtk frontend");
#[cfg(windows)] #[cfg(windows)]
@@ -60,8 +65,15 @@ fn load_icons() {
fn build_ui(app: &Application) { fn build_ui(app: &Application) {
log::debug!("connecting to lan-mouse-socket"); log::debug!("connecting to lan-mouse-socket");
let (mut frontend_rx, frontend_tx) = match lan_mouse_ipc::connect() { let mut rx = match super::wait_for_service() {
Ok(conn) => conn, Ok(stream) => stream,
Err(e) => {
log::error!("could not connect to lan-mouse-socket: {e}");
process::exit(1);
}
};
let tx = match rx.try_clone() {
Ok(sock) => sock,
Err(e) => { Err(e) => {
log::error!("{e}"); log::error!("{e}");
process::exit(1); process::exit(1);
@@ -72,18 +84,35 @@ fn build_ui(app: &Application) {
let (sender, receiver) = async_channel::bounded(10); let (sender, receiver) = async_channel::bounded(10);
gio::spawn_blocking(move || { gio::spawn_blocking(move || {
while let Some(e) = frontend_rx.next_event() { match loop {
match e { // read length
Ok(e) => sender.send_blocking(e).unwrap(), let len = match rx.read_u64(Endian::Big) {
Err(e) => { Ok(l) => l,
log::error!("{e}"); Err(e) if e.kind() == ErrorKind::UnexpectedEof => break Ok(()),
break; Err(e) => break Err(e),
} };
// read payload
let mut buf = vec![0u8; len as usize];
match rx.read_exact(&mut buf) {
Ok(_) => (),
Err(e) if e.kind() == ErrorKind::UnexpectedEof => break Ok(()),
Err(e) => break Err(e),
};
// parse json
let json = str::from_utf8(&buf).unwrap();
match serde_json::from_str(json) {
Ok(notify) => sender.send_blocking(notify).unwrap(),
Err(e) => log::error!("{e}"),
} }
} {
Ok(()) => {}
Err(e) => log::error!("{e}"),
} }
}); });
let window = Window::new(app, frontend_tx); let window = Window::new(app, tx);
glib::spawn_future_local(clone!( glib::spawn_future_local(clone!(
#[weak] #[weak]
@@ -92,9 +121,6 @@ fn build_ui(app: &Application) {
loop { loop {
let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1)); let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1));
match notify { match notify {
FrontendEvent::Changed(handle) => {
window.request(FrontendRequest::GetState(handle));
}
FrontendEvent::Created(handle, client, state) => { FrontendEvent::Created(handle, client, state) => {
window.new_client(handle, client, state); window.new_client(handle, client, state);
} }

View File

@@ -3,7 +3,7 @@ mod imp;
use adw::subclass::prelude::*; use adw::subclass::prelude::*;
use gtk::glib::{self, Object}; use gtk::glib::{self, Object};
use lan_mouse_ipc::{ClientConfig, ClientHandle, ClientState}; use crate::client::{ClientConfig, ClientHandle, ClientState};
glib::wrapper! { glib::wrapper! {
pub struct ClientObject(ObjectSubclass<imp::ClientObject>); pub struct ClientObject(ObjectSubclass<imp::ClientObject>);

View File

@@ -5,7 +5,7 @@ use gtk::glib;
use gtk::prelude::*; use gtk::prelude::*;
use gtk::subclass::prelude::*; use gtk::subclass::prelude::*;
use lan_mouse_ipc::ClientHandle; use crate::client::ClientHandle;
use super::ClientData; use super::ClientData;

View File

@@ -4,7 +4,7 @@ use adw::prelude::*;
use adw::subclass::prelude::*; use adw::subclass::prelude::*;
use gtk::glib::{self, Object}; use gtk::glib::{self, Object};
use lan_mouse_ipc::DEFAULT_PORT; use crate::config::DEFAULT_PORT;
use super::ClientObject; use super::ClientObject;

View File

@@ -1,7 +1,16 @@
mod imp; mod imp;
use std::io::Write;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
#[cfg(windows)]
use std::net::TcpStream;
use adw::prelude::*; use adw::prelude::*;
use adw::subclass::prelude::*; use adw::subclass::prelude::*;
use endi::{Endian, WriteBytes};
use glib::{clone, Object}; use glib::{clone, Object};
use gtk::{ use gtk::{
gio, gio,
@@ -9,12 +18,13 @@ use gtk::{
ListBox, NoSelection, ListBox, NoSelection,
}; };
use lan_mouse_ipc::{ use crate::{
ClientConfig, ClientHandle, ClientState, FrontendRequest, FrontendRequestWriter, Position, client::{ClientConfig, ClientHandle, ClientState, Position},
DEFAULT_PORT, config::DEFAULT_PORT,
frontend::{gtk::client_object::ClientObject, FrontendRequest},
}; };
use super::{client_object::ClientObject, client_row::ClientRow}; use super::client_row::ClientRow;
glib::wrapper! { glib::wrapper! {
pub struct Window(ObjectSubclass<imp::Window>) pub struct Window(ObjectSubclass<imp::Window>)
@@ -24,13 +34,13 @@ glib::wrapper! {
} }
impl Window { impl Window {
pub(crate) fn new(app: &adw::Application, conn: FrontendRequestWriter) -> Self { pub(crate) fn new(
app: &adw::Application,
#[cfg(unix)] tx: UnixStream,
#[cfg(windows)] tx: TcpStream,
) -> Self {
let window: Self = Object::builder().property("application", app).build(); let window: Self = Object::builder().property("application", app).build();
window window.imp().stream.borrow_mut().replace(tx);
.imp()
.frontend_request_writer
.borrow_mut()
.replace(conn);
window window
} }
@@ -247,11 +257,7 @@ impl Window {
} }
pub fn request_client_state(&self, client: &ClientObject) { pub fn request_client_state(&self, client: &ClientObject) {
self.request_client_state_for(client.handle()); self.request(FrontendRequest::GetState(client.handle()));
}
pub fn request_client_state_for(&self, handle: ClientHandle) {
self.request(FrontendRequest::GetState(handle));
} }
pub fn request_client_create(&self) { pub fn request_client_create(&self) {
@@ -286,10 +292,16 @@ impl Window {
self.request(FrontendRequest::Delete(client.handle())); self.request(FrontendRequest::Delete(client.handle()));
} }
pub fn request(&self, request: FrontendRequest) { pub fn request(&self, event: FrontendRequest) {
let mut requester = self.imp().frontend_request_writer.borrow_mut(); let json = serde_json::to_string(&event).unwrap();
let requester = requester.as_mut().unwrap(); log::debug!("requesting: {json}");
if let Err(e) = requester.request(request) { let mut stream = self.imp().stream.borrow_mut();
let stream = stream.as_mut().unwrap();
let bytes = json.as_bytes();
if let Err(e) = stream.write_u64(Endian::Big, bytes.len() as u64) {
log::error!("error sending message: {e}");
};
if let Err(e) = stream.write(bytes) {
log::error!("error sending message: {e}"); log::error!("error sending message: {e}");
}; };
} }

View File

@@ -1,12 +1,17 @@
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
#[cfg(windows)]
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use adw::subclass::prelude::*; use adw::subclass::prelude::*;
use adw::{prelude::*, ActionRow, PreferencesGroup, ToastOverlay}; use adw::{prelude::*, ActionRow, PreferencesGroup, ToastOverlay};
use glib::subclass::InitializingObject; use glib::subclass::InitializingObject;
use gtk::glib::clone; use gtk::glib::clone;
use gtk::{gdk, gio, glib, Button, CompositeTemplate, Entry, Label, ListBox}; use gtk::{gdk, gio, glib, Button, CompositeTemplate, Entry, Label, ListBox};
use lan_mouse_ipc::{FrontendRequestWriter, DEFAULT_PORT}; use crate::config::DEFAULT_PORT;
#[derive(CompositeTemplate, Default)] #[derive(CompositeTemplate, Default)]
#[template(resource = "/de/feschber/LanMouse/window.ui")] #[template(resource = "/de/feschber/LanMouse/window.ui")]
@@ -36,7 +41,10 @@ pub struct Window {
#[template_child] #[template_child]
pub input_capture_button: TemplateChild<Button>, pub input_capture_button: TemplateChild<Button>,
pub clients: RefCell<Option<gio::ListStore>>, pub clients: RefCell<Option<gio::ListStore>>,
pub frontend_request_writer: RefCell<Option<FrontendRequestWriter>>, #[cfg(unix)]
pub stream: RefCell<Option<UnixStream>>,
#[cfg(windows)]
pub stream: RefCell<Option<TcpStream>>,
pub port: Cell<u16>, pub port: Cell<u16>,
pub capture_active: Cell<bool>, pub capture_active: Cell<bool>,
pub emulation_active: Cell<bool>, pub emulation_active: Cell<bool>,

View File

@@ -5,3 +5,4 @@ pub mod server;
pub mod capture_test; pub mod capture_test;
pub mod emulation_test; pub mod emulation_test;
pub mod frontend;

View File

@@ -1,36 +1,10 @@
use env_logger::Env; use anyhow::Result;
use input_capture::InputCaptureError; use std::process::{self, Child, Command};
use input_emulation::InputEmulationError;
use lan_mouse::{
capture_test,
config::{Config, ConfigError, Frontend},
emulation_test,
server::{Server, ServiceError},
};
use lan_mouse_ipc::IpcError;
use std::{
future::Future,
io,
process::{self, Child, Command},
};
use thiserror::Error;
use tokio::task::LocalSet;
#[derive(Debug, Error)] use env_logger::Env;
enum LanMouseError { use lan_mouse::{capture_test, config::Config, emulation_test, frontend, server::Server};
#[error(transparent)]
Service(#[from] ServiceError), use tokio::task::LocalSet;
#[error(transparent)]
IpcError(#[from] IpcError),
#[error(transparent)]
Config(#[from] ConfigError),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Capture(#[from] InputCaptureError),
#[error(transparent)]
Emulation(#[from] InputEmulationError),
}
pub fn main() { pub fn main() {
// init logging // init logging
@@ -43,24 +17,32 @@ pub fn main() {
} }
} }
fn run() -> Result<(), LanMouseError> { pub fn start_service() -> Result<Child> {
let child = Command::new(std::env::current_exe()?)
.args(std::env::args().skip(1))
.arg("--daemon")
.spawn()?;
Ok(child)
}
pub fn run() -> Result<()> {
// parse config file + cli args // parse config file + cli args
let config = Config::new()?; let config = Config::new()?;
log::debug!("{config:?}"); log::debug!("{config:?}");
log::info!("release bind: {:?}", config.release_bind); log::info!("release bind: {:?}", config.release_bind);
if config.test_capture { if config.test_capture {
run_async(capture_test::run(config))?; capture_test::run()?;
} else if config.test_emulation { } else if config.test_emulation {
run_async(emulation_test::run(config))?; emulation_test::run()?;
} else if config.daemon { } else if config.daemon {
// if daemon is specified we run the service // if daemon is specified we run the service
run_async(run_service(config))?; run_service(config)?;
} else { } else {
// otherwise start the service as a child process and // otherwise start the service as a child process and
// run a frontend // run a frontend
let mut service = start_service()?; let mut service = start_service()?;
run_frontend(&config)?; frontend::run_frontend(&config)?;
#[cfg(unix)] #[cfg(unix)]
{ {
// on unix we give the service a chance to terminate gracefully // on unix we give the service a chance to terminate gracefully
@@ -73,14 +55,10 @@ fn run() -> Result<(), LanMouseError> {
service.kill()?; service.kill()?;
} }
Ok(()) anyhow::Ok(())
} }
fn run_async<F, E>(f: F) -> Result<(), LanMouseError> fn run_service(config: Config) -> Result<()> {
where
F: Future<Output = Result<(), E>>,
LanMouseError: From<E>,
{
// create single threaded tokio runtime // create single threaded tokio runtime
let runtime = tokio::runtime::Builder::new_current_thread() let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io() .enable_io()
@@ -88,35 +66,15 @@ where
.build()?; .build()?;
// run async event loop // run async event loop
Ok(runtime.block_on(LocalSet::new().run_until(f))?) runtime.block_on(LocalSet::new().run_until(async {
} // run main loop
log::info!("Press {:?} to release the mouse", config.release_bind);
fn start_service() -> Result<Child, io::Error> { let mut server = Server::new(config);
let child = Command::new(std::env::current_exe()?) server.run().await?;
.args(std::env::args().skip(1))
.arg("--daemon")
.spawn()?;
Ok(child)
}
async fn run_service(config: Config) -> Result<(), ServiceError> { log::debug!("service exiting");
log::info!("Press {:?} to release the mouse", config.release_bind); anyhow::Ok(())
Server::new(config).run().await?; }))?;
log::info!("service exited!");
Ok(())
}
fn run_frontend(config: &Config) -> Result<(), IpcError> {
match config.frontend {
#[cfg(feature = "gtk")]
Frontend::Gtk => {
lan_mouse_gtk::run();
}
#[cfg(not(feature = "gtk"))]
Frontend::Gtk => panic!("gtk frontend requested but feature not enabled!"),
Frontend::Cli => {
lan_mouse_cli::run()?;
}
};
Ok(()) Ok(())
} }

View File

@@ -1,27 +1,30 @@
use capture_task::CaptureRequest; use capture_task::CaptureRequest;
use emulation_task::EmulationRequest; use emulation_task::EmulationRequest;
use futures::StreamExt;
use hickory_resolver::error::ResolveError;
use local_channel::mpsc::{channel, Sender}; use local_channel::mpsc::{channel, Sender};
use log; use log;
use std::{ use std::{
cell::{Cell, RefCell}, cell::{Cell, RefCell},
collections::{HashSet, VecDeque}, collections::{HashSet, VecDeque},
io, io::ErrorKind,
net::{IpAddr, SocketAddr}, net::{IpAddr, SocketAddr},
rc::Rc, rc::Rc,
}; };
use thiserror::Error; use tokio::{io::ReadHalf, join, signal, sync::Notify, task::JoinHandle};
use tokio::{join, signal, sync::Notify};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use crate::{client::ClientManager, config::Config, dns::DnsResolver}; use crate::{
client::{ClientConfig, ClientHandle, ClientManager, ClientState, Position},
use lan_mouse_ipc::{ config::Config,
AsyncFrontendListener, ClientConfig, ClientHandle, ClientState, FrontendEvent, FrontendRequest, dns::DnsResolver,
ListenerCreationError, Position, Status, frontend::{self, FrontendEvent, FrontendListener, FrontendRequest, Status},
}; };
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
use tokio::net::TcpStream;
mod capture_task; mod capture_task;
mod emulation_task; mod emulation_task;
mod network_task; mod network_task;
@@ -38,16 +41,6 @@ enum State {
AwaitAck, AwaitAck,
} }
#[derive(Debug, Error)]
pub enum ServiceError {
#[error(transparent)]
Dns(#[from] ResolveError),
#[error(transparent)]
Listen(#[from] ListenerCreationError),
#[error(transparent)]
Io(#[from] io::Error),
}
#[derive(Clone)] #[derive(Clone)]
pub struct Server { pub struct Server {
active_client: Rc<Cell<Option<ClientHandle>>>, active_client: Rc<Cell<Option<ClientHandle>>>,
@@ -58,6 +51,7 @@ pub struct Server {
notifies: Rc<Notifies>, notifies: Rc<Notifies>,
config: Rc<Config>, config: Rc<Config>,
pending_frontend_events: Rc<RefCell<VecDeque<FrontendEvent>>>, pending_frontend_events: Rc<RefCell<VecDeque<FrontendEvent>>>,
pending_dns_requests: Rc<RefCell<VecDeque<ClientHandle>>>,
capture_status: Rc<Cell<Status>>, capture_status: Rc<Cell<Status>>,
emulation_status: Rc<Cell<Status>>, emulation_status: Rc<Cell<Status>>,
} }
@@ -69,6 +63,7 @@ struct Notifies {
ping: Notify, ping: Notify,
port_changed: Notify, port_changed: Notify,
frontend_event_pending: Notify, frontend_event_pending: Notify,
dns_request_pending: Notify,
cancel: CancellationToken, cancel: CancellationToken,
} }
@@ -112,32 +107,40 @@ impl Server {
release_bind, release_bind,
notifies, notifies,
pending_frontend_events: Rc::new(RefCell::new(VecDeque::new())), pending_frontend_events: Rc::new(RefCell::new(VecDeque::new())),
pending_dns_requests: Rc::new(RefCell::new(VecDeque::new())),
capture_status: Default::default(), capture_status: Default::default(),
emulation_status: Default::default(), emulation_status: Default::default(),
} }
} }
pub async fn run(&mut self) -> Result<(), ServiceError> { pub async fn run(&mut self) -> anyhow::Result<()> {
// create frontend communication adapter, exit if already running // create frontend communication adapter, exit if already running
let mut frontend = match AsyncFrontendListener::new().await { let mut frontend = match FrontendListener::new().await {
Ok(f) => f, Some(f) => f?,
Err(ListenerCreationError::AlreadyRunning) => { None => {
log::info!("service already running, exiting"); log::info!("service already running, exiting");
return Ok(()); return Ok(());
} }
e => e?,
}; };
let (capture_tx, capture_rx) = channel(); /* requests for input capture */ let (capture_tx, capture_rx) = channel(); /* requests for input capture */
let (emulation_tx, emulation_rx) = channel(); /* emulation requests */ let (emulation_tx, emulation_rx) = channel(); /* emulation requests */
let (udp_recv_tx, udp_recv_rx) = channel(); /* udp receiver */ let (udp_recv_tx, udp_recv_rx) = channel(); /* udp receiver */
let (udp_send_tx, udp_send_rx) = channel(); /* udp sender */ let (udp_send_tx, udp_send_rx) = channel(); /* udp sender */
let (request_tx, mut request_rx) = channel(); /* frontend requests */
let (dns_tx, dns_rx) = channel(); /* dns requests */ let (dns_tx, dns_rx) = channel(); /* dns requests */
// udp task
let network = network_task::new(self.clone(), udp_recv_tx.clone(), udp_send_rx).await?; let network = network_task::new(self.clone(), udp_recv_tx.clone(), udp_send_rx).await?;
// input capture
let capture = capture_task::new(self.clone(), capture_rx, udp_send_tx.clone()); let capture = capture_task::new(self.clone(), capture_rx, udp_send_tx.clone());
// input emulation
let emulation = let emulation =
emulation_task::new(self.clone(), emulation_rx, udp_recv_rx, udp_send_tx.clone()); emulation_task::new(self.clone(), emulation_rx, udp_recv_rx, udp_send_tx.clone());
// create dns resolver
let resolver = DnsResolver::new(dns_rx)?; let resolver = DnsResolver::new(dns_rx)?;
let dns_task = tokio::task::spawn_local(resolver.run(self.clone())); let dns_task = tokio::task::spawn_local(resolver.run(self.clone()));
@@ -150,22 +153,30 @@ impl Server {
); );
for handle in self.active_clients() { for handle in self.active_clients() {
dns_tx.send(handle).expect("channel closed"); self.request_dns(handle);
} }
log::info!("running service");
let mut join_handles = vec![];
loop { loop {
tokio::select! { tokio::select! {
request = frontend.next() => { stream = frontend.accept() => {
let request = match request { match stream {
Some(Ok(r)) => r, Ok(s) => join_handles.push(handle_frontend_stream(self.notifies.cancel.clone(), s, request_tx.clone())),
Some(Err(e)) => { Err(e) => log::warn!("error accepting frontend connection: {e}"),
log::error!("error receiving request: {e}");
continue;
}
None => break,
}; };
log::debug!("handle frontend request: {request:?}"); self.enumerate();
self.handle_request(&capture_tx.clone(), &emulation_tx.clone(), request, &dns_tx); self.notify_frontend(FrontendEvent::EmulationStatus(self.emulation_status.get()));
self.notify_frontend(FrontendEvent::CaptureStatus(self.capture_status.get()));
self.notify_frontend(FrontendEvent::PortChanged(self.port.get(), None));
}
request = request_rx.recv() => {
let request = request.expect("channel closed");
log::debug!("received frontend request: {request:?}");
self.handle_request(&capture_tx.clone(), &emulation_tx.clone(), request).await;
log::debug!("handled frontend request");
} }
_ = self.notifies.frontend_event_pending.notified() => { _ = self.notifies.frontend_event_pending.notified() => {
while let Some(event) = { while let Some(event) = {
@@ -176,6 +187,15 @@ impl Server {
frontend.broadcast(event).await; frontend.broadcast(event).await;
} }
}, },
_ = self.notifies.dns_request_pending.notified() => {
while let Some(request) = {
/* need to drop borrow before next iteration! */
let request = self.pending_dns_requests.borrow_mut().pop_front();
request
} {
dns_tx.send(request).expect("channel closed");
}
}
_ = self.cancelled() => break, _ = self.cancelled() => break,
r = signal::ctrl_c() => { r = signal::ctrl_c() => {
r.expect("failed to wait for CTRL+C"); r.expect("failed to wait for CTRL+C");
@@ -187,6 +207,7 @@ impl Server {
log::info!("terminating service"); log::info!("terminating service");
self.cancel(); self.cancel();
futures::future::join_all(join_handles).await;
let _ = join!(capture, dns_task, emulation, network, ping); let _ = join!(capture, dns_task, emulation, network, ping);
Ok(()) Ok(())
@@ -210,7 +231,6 @@ impl Server {
} }
fn notify_capture(&self) { fn notify_capture(&self) {
log::info!("received capture enable request");
self.notifies.capture.notify_waiters() self.notifies.capture.notify_waiters()
} }
@@ -219,7 +239,6 @@ impl Server {
} }
fn notify_emulation(&self) { fn notify_emulation(&self) {
log::info!("received emulation enable request");
self.notifies.emulation.notify_waiters() self.notifies.emulation.notify_waiters()
} }
@@ -246,7 +265,10 @@ impl Server {
} }
pub(crate) fn client_updated(&self, handle: ClientHandle) { pub(crate) fn client_updated(&self, handle: ClientHandle) {
self.notify_frontend(FrontendEvent::Changed(handle)); let state = self.client_manager.borrow().get(handle).cloned();
if let Some((config, state)) = state {
self.notify_frontend(FrontendEvent::State(handle, config, state));
}
} }
fn active_clients(&self) -> Vec<ClientHandle> { fn active_clients(&self) -> Vec<ClientHandle> {
@@ -258,49 +280,55 @@ impl Server {
.collect() .collect()
} }
fn handle_request( fn request_dns(&self, handle: ClientHandle) {
self.pending_dns_requests.borrow_mut().push_back(handle);
self.notifies.dns_request_pending.notify_one();
}
async fn handle_request(
&self, &self,
capture: &Sender<CaptureRequest>, capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>, emulate: &Sender<EmulationRequest>,
event: FrontendRequest, event: FrontendRequest,
dns: &Sender<ClientHandle>,
) -> bool { ) -> bool {
log::debug!("frontend: {event:?}"); log::debug!("frontend: {event:?}");
match event { match event {
FrontendRequest::EnableCapture => self.notify_capture(), FrontendRequest::EnableCapture => {
FrontendRequest::EnableEmulation => self.notify_emulation(), log::info!("received capture enable request");
self.notify_capture();
}
FrontendRequest::EnableEmulation => {
log::info!("received emulation enable request");
self.notify_emulation();
}
FrontendRequest::Create => { FrontendRequest::Create => {
self.add_client(); let handle = self.add_client().await;
self.request_dns(handle);
} }
FrontendRequest::Activate(handle, active) => { FrontendRequest::Activate(handle, active) => {
if active { if active {
self.activate_client(capture, emulate, handle); self.activate_client(capture, emulate, handle).await;
} else { } else {
self.deactivate_client(capture, emulate, handle); self.deactivate_client(capture, emulate, handle).await;
} }
} }
FrontendRequest::ChangePort(port) => self.request_port_change(port), FrontendRequest::ChangePort(port) => self.request_port_change(port),
FrontendRequest::Delete(handle) => { FrontendRequest::Delete(handle) => {
self.remove_client(capture, emulate, handle); self.remove_client(capture, emulate, handle).await;
self.notify_frontend(FrontendEvent::Deleted(handle)); self.notify_frontend(FrontendEvent::Deleted(handle));
} }
FrontendRequest::Enumerate() => self.enumerate(), FrontendRequest::Enumerate() => self.enumerate(),
FrontendRequest::GetState(handle) => self.broadcast_client(handle), FrontendRequest::GetState(handle) => self.broadcast_client(handle),
FrontendRequest::UpdateFixIps(handle, fix_ips) => self.update_fix_ips(handle, fix_ips), FrontendRequest::UpdateFixIps(handle, fix_ips) => {
FrontendRequest::UpdateHostname(handle, host) => { self.update_fix_ips(handle, fix_ips);
self.update_hostname(handle, host, dns) self.request_dns(handle);
} }
FrontendRequest::UpdateHostname(handle, host) => self.update_hostname(handle, host),
FrontendRequest::UpdatePort(handle, port) => self.update_port(handle, port), FrontendRequest::UpdatePort(handle, port) => self.update_port(handle, port),
FrontendRequest::UpdatePosition(handle, pos) => { FrontendRequest::UpdatePosition(handle, pos) => {
self.update_pos(handle, capture, emulate, pos) self.update_pos(handle, capture, emulate, pos).await;
}
FrontendRequest::ResolveDns(handle) => dns.send(handle).expect("channel closed"),
FrontendRequest::Sync => {
self.enumerate();
self.notify_frontend(FrontendEvent::EmulationStatus(self.emulation_status.get()));
self.notify_frontend(FrontendEvent::CaptureStatus(self.capture_status.get()));
self.notify_frontend(FrontendEvent::PortChanged(self.port.get(), None));
} }
FrontendRequest::ResolveDns(handle) => self.request_dns(handle),
}; };
false false
} }
@@ -315,7 +343,7 @@ impl Server {
self.notify_frontend(FrontendEvent::Enumerate(clients)); self.notify_frontend(FrontendEvent::Enumerate(clients));
} }
fn add_client(&self) -> ClientHandle { async fn add_client(&self) -> ClientHandle {
let handle = self.client_manager.borrow_mut().add_client(); let handle = self.client_manager.borrow_mut().add_client();
log::info!("added client {handle}"); log::info!("added client {handle}");
let (c, s) = self.client_manager.borrow().get(handle).unwrap().clone(); let (c, s) = self.client_manager.borrow().get(handle).unwrap().clone();
@@ -323,40 +351,41 @@ impl Server {
handle handle
} }
fn deactivate_client( async fn deactivate_client(
&self, &self,
capture: &Sender<CaptureRequest>, capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>, emulate: &Sender<EmulationRequest>,
handle: ClientHandle, handle: ClientHandle,
) { ) {
log::debug!("deactivating client {handle}");
match self.client_manager.borrow_mut().get_mut(handle) { match self.client_manager.borrow_mut().get_mut(handle) {
None => return,
Some((_, s)) if !s.active => return,
Some((_, s)) => s.active = false, Some((_, s)) => s.active = false,
None => return,
}; };
let _ = capture.send(CaptureRequest::Destroy(handle)); let _ = capture.send(CaptureRequest::Destroy(handle));
let _ = emulate.send(EmulationRequest::Destroy(handle)); let _ = emulate.send(EmulationRequest::Destroy(handle));
self.client_updated(handle); log::debug!("deactivating client {handle} done");
log::info!("deactivated client {handle}");
} }
fn activate_client( async fn activate_client(
&self, &self,
capture: &Sender<CaptureRequest>, capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>, emulate: &Sender<EmulationRequest>,
handle: ClientHandle, handle: ClientHandle,
) { ) {
log::debug!("activating client");
/* deactivate potential other client at this position */ /* deactivate potential other client at this position */
let pos = match self.client_manager.borrow().get(handle) { let pos = match self.client_manager.borrow().get(handle) {
None => return,
Some((_, s)) if s.active => return,
Some((client, _)) => client.pos, Some((client, _)) => client.pos,
None => return,
}; };
let other = self.client_manager.borrow_mut().find_client(pos); let other = self.client_manager.borrow_mut().find_client(pos);
if let Some(other) = other { if let Some(other) = other {
self.deactivate_client(capture, emulate, other); if other != handle {
self.deactivate_client(capture, emulate, other).await;
}
} }
/* activate the client */ /* activate the client */
@@ -367,15 +396,12 @@ impl Server {
}; };
/* notify emulation, capture and frontends */ /* notify emulation, capture and frontends */
let _ = capture.send(CaptureRequest::Create(handle, to_capture_pos(pos))); let _ = capture.send(CaptureRequest::Create(handle, pos.into()));
let _ = emulate.send(EmulationRequest::Create(handle)); let _ = emulate.send(EmulationRequest::Create(handle));
log::debug!("activating client {handle} done");
self.client_updated(handle);
log::info!("activated client {handle} ({pos})");
} }
fn remove_client( async fn remove_client(
&self, &self,
capture: &Sender<CaptureRequest>, capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>, emulate: &Sender<EmulationRequest>,
@@ -407,7 +433,6 @@ impl Server {
c.fix_ips = fix_ips; c.fix_ips = fix_ips;
}; };
self.update_ips(handle); self.update_ips(handle);
self.client_updated(handle);
} }
pub(crate) fn update_dns_ips(&self, handle: ClientHandle, dns_ips: Vec<IpAddr>) { pub(crate) fn update_dns_ips(&self, handle: ClientHandle, dns_ips: Vec<IpAddr>) {
@@ -415,7 +440,6 @@ impl Server {
s.dns_ips = dns_ips; s.dns_ips = dns_ips;
}; };
self.update_ips(handle); self.update_ips(handle);
self.client_updated(handle);
} }
fn update_ips(&self, handle: ClientHandle) { fn update_ips(&self, handle: ClientHandle) {
@@ -429,12 +453,7 @@ impl Server {
} }
} }
fn update_hostname( fn update_hostname(&self, handle: ClientHandle, hostname: Option<String>) {
&self,
handle: ClientHandle,
hostname: Option<String>,
dns: &Sender<ClientHandle>,
) {
let mut client_manager = self.client_manager.borrow_mut(); let mut client_manager = self.client_manager.borrow_mut();
let Some((c, s)) = client_manager.get_mut(handle) else { let Some((c, s)) = client_manager.get_mut(handle) else {
return; return;
@@ -443,13 +462,10 @@ impl Server {
// hostname changed // hostname changed
if c.hostname != hostname { if c.hostname != hostname {
c.hostname = hostname; c.hostname = hostname;
s.ips = HashSet::from_iter(c.fix_ips.iter().cloned());
s.active_addr = None; s.active_addr = None;
s.dns_ips.clear(); self.request_dns(handle);
drop(client_manager);
self.update_ips(handle);
dns.send(handle).expect("channel closed");
} }
self.client_updated(handle);
} }
fn update_port(&self, handle: ClientHandle, port: u16) { fn update_port(&self, handle: ClientHandle, port: u16) {
@@ -464,7 +480,7 @@ impl Server {
} }
} }
fn update_pos( async fn update_pos(
&self, &self,
handle: ClientHandle, handle: ClientHandle,
capture: &Sender<CaptureRequest>, capture: &Sender<CaptureRequest>,
@@ -478,19 +494,18 @@ impl Server {
}; };
let changed = c.pos != pos; let changed = c.pos != pos;
if changed {
log::info!("update pos {handle} {} -> {}", c.pos, pos);
}
c.pos = pos; c.pos = pos;
(changed, s.active) (changed, s.active)
}; };
// update state in event input emulator & input capture // update state in event input emulator & input capture
if changed { if changed {
self.deactivate_client(capture, emulate, handle);
if active { if active {
self.activate_client(capture, emulate, handle); let _ = capture.send(CaptureRequest::Destroy(handle));
let _ = emulate.send(EmulationRequest::Destroy(handle));
} }
let _ = capture.send(CaptureRequest::Create(handle, pos.into()));
let _ = emulate.send(EmulationRequest::Create(handle));
} }
} }
@@ -523,7 +538,7 @@ impl Server {
self.client_updated(handle); self.client_updated(handle);
} }
pub(crate) fn get_hostname(&self, handle: ClientHandle) -> Option<String> { pub(crate) fn get_hostname(&self, handle: u64) -> Option<String> {
self.client_manager self.client_manager
.borrow_mut() .borrow_mut()
.get_mut(handle) .get_mut(handle)
@@ -539,12 +554,12 @@ impl Server {
self.state.replace(state); self.state.replace(state);
} }
fn set_active(&self, handle: Option<ClientHandle>) { fn set_active(&self, handle: Option<u64>) {
log::debug!("active client => {handle:?}"); log::debug!("active client => {handle:?}");
self.active_client.replace(handle); self.active_client.replace(handle);
} }
fn active_addr(&self, handle: ClientHandle) -> Option<SocketAddr> { fn active_addr(&self, handle: u64) -> Option<SocketAddr> {
self.client_manager self.client_manager
.borrow() .borrow()
.get(handle) .get(handle)
@@ -552,11 +567,41 @@ impl Server {
} }
} }
fn to_capture_pos(pos: Position) -> input_capture::Position { async fn listen_frontend(
match pos { request_tx: Sender<FrontendRequest>,
Position::Left => input_capture::Position::Left, #[cfg(unix)] mut stream: ReadHalf<UnixStream>,
Position::Right => input_capture::Position::Right, #[cfg(windows)] mut stream: ReadHalf<TcpStream>,
Position::Top => input_capture::Position::Top, ) {
Position::Bottom => input_capture::Position::Bottom, use std::io;
loop {
let request = frontend::wait_for_request(&mut stream).await;
match request {
Ok(request) => {
let _ = request_tx.send(request);
}
Err(e) => {
if let Some(e) = e.downcast_ref::<io::Error>() {
if e.kind() == ErrorKind::UnexpectedEof {
return;
}
}
log::error!("error reading frontend event: {e}");
return;
}
}
} }
} }
fn handle_frontend_stream(
cancel: CancellationToken,
#[cfg(unix)] stream: ReadHalf<UnixStream>,
#[cfg(windows)] stream: ReadHalf<TcpStream>,
request_tx: Sender<FrontendRequest>,
) -> JoinHandle<()> {
tokio::task::spawn_local(async move {
tokio::select! {
_ = listen_frontend(request_tx, stream) => {},
_ = cancel.cancelled() => {},
}
})
}

View File

@@ -9,8 +9,7 @@ use input_capture::{
self, CaptureError, CaptureEvent, CaptureHandle, InputCapture, InputCaptureError, Position, self, CaptureError, CaptureEvent, CaptureHandle, InputCapture, InputCaptureError, Position,
}; };
use crate::server::State; use crate::{client::ClientHandle, frontend::Status, server::State};
use lan_mouse_ipc::{ClientHandle, Status};
use super::Server; use super::Server;
@@ -86,7 +85,7 @@ async fn do_capture(
) )
}); });
for (handle, pos) in clients { for (handle, pos) in clients {
capture.create(handle, to_capture_pos(pos)).await?; capture.create(handle, pos.into()).await?;
} }
loop { loop {
@@ -195,12 +194,3 @@ fn spawn_hook_command(server: &Server, handle: ClientHandle) {
} }
}); });
} }
fn to_capture_pos(pos: lan_mouse_ipc::Position) -> input_capture::Position {
match pos {
lan_mouse_ipc::Position::Left => input_capture::Position::Left,
lan_mouse_ipc::Position::Right => input_capture::Position::Right,
lan_mouse_ipc::Position::Top => input_capture::Position::Top,
lan_mouse_ipc::Position::Bottom => input_capture::Position::Bottom,
}
}

View File

@@ -4,11 +4,12 @@ use std::net::SocketAddr;
use lan_mouse_proto::ProtoEvent; use lan_mouse_proto::ProtoEvent;
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use lan_mouse_ipc::ClientHandle; use crate::{
client::{ClientHandle, ClientManager},
use crate::{client::ClientManager, server::State}; frontend::Status,
server::State,
};
use input_emulation::{self, EmulationError, EmulationHandle, InputEmulation, InputEmulationError}; use input_emulation::{self, EmulationError, EmulationHandle, InputEmulation, InputEmulationError};
use lan_mouse_ipc::Status;
use super::{network_task::NetworkError, Server}; use super::{network_task::NetworkError, Server};

View File

@@ -4,7 +4,7 @@ use lan_mouse_proto::ProtoEvent;
use local_channel::mpsc::Sender; use local_channel::mpsc::Sender;
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use lan_mouse_ipc::ClientHandle; use crate::client::ClientHandle;
use super::{capture_task::CaptureRequest, emulation_task::EmulationRequest, Server, State}; use super::{capture_task::CaptureRequest, emulation_task::EmulationRequest, Server, State};