Compare commits

..

1 Commits

Author SHA1 Message Date
Ferdinand Schober
cba4cc6150 cleanup main 2024-09-04 23:53:59 +02:00
7 changed files with 105 additions and 183 deletions

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.
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]

View File

@@ -1,9 +1,6 @@
use super::{error::EmulationError, Emulation, EmulationHandle};
use async_trait::async_trait;
use core_graphics::base::CGFloat;
use core_graphics::display::{
CGDirectDisplayID, CGDisplayBounds, CGGetDisplaysWithRect, CGPoint, CGRect, CGSize,
};
use core_graphics::display::{CGDisplayBounds, CGMainDisplayID, CGPoint};
use core_graphics::event::{
CGEvent, CGEventTapLocation, CGEventType, CGKeyCode, CGMouseButton, EventField, ScrollEventUnit,
};
@@ -11,9 +8,8 @@ use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
use input_event::{Event, KeyboardEvent, PointerEvent};
use keycode::{KeyMap, KeyMapping};
use std::ops::{Index, IndexMut};
use std::sync::Arc;
use std::time::Duration;
use tokio::{sync::Notify, task::JoinHandle};
use tokio::task::AbortHandle;
use super::error::MacOSEmulationCreationError;
@@ -22,9 +18,8 @@ const DEFAULT_REPEAT_INTERVAL: Duration = Duration::from_millis(32);
pub(crate) struct MacOSEmulation {
event_source: CGEventSource,
repeat_task: Option<JoinHandle<()>>,
repeat_task: Option<AbortHandle>,
button_state: ButtonState,
notify_repeat_task: Arc<Notify>,
}
struct ButtonState {
@@ -70,7 +65,6 @@ impl MacOSEmulation {
event_source,
button_state,
repeat_task: None,
notify_repeat_task: Arc::new(Notify::new()),
})
}
@@ -82,33 +76,20 @@ impl MacOSEmulation {
async fn spawn_repeat_task(&mut self, key: u16) {
// there can only be one repeating key and it's
// always the last to be pressed
self.cancel_repeat_task().await;
self.kill_repeat_task();
let event_source = self.event_source.clone();
let notify = self.notify_repeat_task.clone();
let repeat_task = tokio::task::spawn_local(async move {
let stop = tokio::select! {
_ = tokio::time::sleep(DEFAULT_REPEAT_DELAY) => false,
_ = notify.notified() => true,
};
if !stop {
loop {
key_event(event_source.clone(), key, 1);
tokio::select! {
_ = tokio::time::sleep(DEFAULT_REPEAT_INTERVAL) => {},
_ = notify.notified() => break,
}
}
tokio::time::sleep(DEFAULT_REPEAT_DELAY).await;
loop {
key_event(event_source.clone(), key, 1);
tokio::time::sleep(DEFAULT_REPEAT_INTERVAL).await;
}
// release key when cancelled
key_event(event_source.clone(), key, 0);
});
self.repeat_task = Some(repeat_task);
self.repeat_task = Some(repeat_task.abort_handle());
}
async fn cancel_repeat_task(&mut self) {
fn kill_repeat_task(&mut self) {
if let Some(task) = self.repeat_task.take() {
self.notify_repeat_task.notify_waiters();
let _ = task.await;
task.abort();
}
}
}
@@ -124,77 +105,6 @@ fn key_event(event_source: CGEventSource, key: u16, state: u8) {
event.post(CGEventTapLocation::HID);
}
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]
impl Emulation for MacOSEmulation {
async fn consume(
@@ -205,6 +115,16 @@ impl Emulation for MacOSEmulation {
match event {
Event::Pointer(pointer_event) => match pointer_event {
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() {
Some(l) => l,
None => {
@@ -213,11 +133,8 @@ impl Emulation for MacOSEmulation {
}
};
let (new_mouse_x, new_mouse_y) =
clamp_to_screen_space(mouse_location.x, mouse_location.y, dx, dy);
mouse_location.x = new_mouse_x;
mouse_location.y = new_mouse_y;
mouse_location.x = (mouse_location.x + dx).clamp(min_x, max_x - 1.);
mouse_location.y = (mouse_location.y + dy).clamp(min_y, max_y - 1.);
let mut event_type = CGEventType::MouseMoved;
if self.button_state.left {
@@ -362,7 +279,7 @@ impl Emulation for MacOSEmulation {
match state {
// pressed
1 => self.spawn_repeat_task(code).await,
_ => self.cancel_repeat_task().await,
_ => self.kill_repeat_task(),
}
key_event(self.event_source.clone(), code, state)
}

View File

@@ -30,7 +30,6 @@ pub fn run() -> Result<(), IpcError> {
struct Cli {
clients: Vec<(ClientHandle, ClientConfig, ClientState)>,
changed: Option<ClientHandle>,
rx: AsyncFrontendEventReader,
tx: AsyncFrontendRequestWriter,
}
@@ -39,7 +38,6 @@ impl Cli {
fn new(rx: AsyncFrontendEventReader, tx: AsyncFrontendRequestWriter) -> Cli {
Self {
clients: vec![],
changed: None,
rx,
tx,
}
@@ -82,14 +80,9 @@ impl Cli {
event = self.rx.next() => {
if let Some(event) = event {
self.handle_event(event?);
} else {
break Ok(());
}
}
}
if let Some(handle) = self.changed.take() {
self.update_client(handle).await?;
}
}
}
@@ -209,7 +202,6 @@ impl Cli {
fn handle_event(&mut self, event: FrontendEvent) {
match event {
FrontendEvent::Changed(h) => self.changed = Some(h),
FrontendEvent::Created(h, c, s) => {
eprint!("client added ({h}): ");
print_config(&c);

View File

@@ -6,7 +6,7 @@ use std::{env, process, str};
use window::Window;
use lan_mouse_ipc::{FrontendEvent, FrontendRequest};
use lan_mouse_ipc::FrontendEvent;
use adw::Application;
use gtk::{
@@ -92,9 +92,6 @@ fn build_ui(app: &Application) {
loop {
let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1));
match notify {
FrontendEvent::Changed(handle) => {
window.request(FrontendRequest::GetState(handle));
}
FrontendEvent::Created(handle, client, state) => {
window.new_client(handle, client, state);
}

View File

@@ -247,11 +247,7 @@ impl Window {
}
pub fn request_client_state(&self, client: &ClientObject) {
self.request_client_state_for(client.handle());
}
pub fn request_client_state_for(&self, handle: ClientHandle) {
self.request(FrontendRequest::GetState(handle));
self.request(FrontendRequest::GetState(client.handle()));
}
pub fn request_client_create(&self) {

View File

@@ -166,8 +166,6 @@ pub struct ClientState {
#[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

View File

@@ -58,6 +58,7 @@ pub struct Server {
notifies: Rc<Notifies>,
config: Rc<Config>,
pending_frontend_events: Rc<RefCell<VecDeque<FrontendEvent>>>,
pending_dns_requests: Rc<RefCell<VecDeque<ClientHandle>>>,
capture_status: Rc<Cell<Status>>,
emulation_status: Rc<Cell<Status>>,
}
@@ -69,6 +70,7 @@ struct Notifies {
ping: Notify,
port_changed: Notify,
frontend_event_pending: Notify,
dns_request_pending: Notify,
cancel: CancellationToken,
}
@@ -112,6 +114,7 @@ impl Server {
release_bind,
notifies,
pending_frontend_events: Rc::new(RefCell::new(VecDeque::new())),
pending_dns_requests: Rc::new(RefCell::new(VecDeque::new())),
capture_status: Default::default(),
emulation_status: Default::default(),
}
@@ -134,10 +137,17 @@ impl Server {
let (udp_send_tx, udp_send_rx) = channel(); /* udp sender */
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?;
// input capture
let capture = capture_task::new(self.clone(), capture_rx, udp_send_tx.clone());
// input emulation
let emulation =
emulation_task::new(self.clone(), emulation_rx, udp_recv_rx, udp_send_tx.clone());
// create dns resolver
let resolver = DnsResolver::new(dns_rx)?;
let dns_task = tokio::task::spawn_local(resolver.run(self.clone()));
@@ -150,9 +160,11 @@ impl Server {
);
for handle in self.active_clients() {
dns_tx.send(handle).expect("channel closed");
self.request_dns(handle);
}
log::info!("running service");
loop {
tokio::select! {
request = frontend.next() => {
@@ -164,8 +176,9 @@ impl Server {
}
None => break,
};
log::debug!("handle frontend request: {request:?}");
self.handle_request(&capture_tx.clone(), &emulation_tx.clone(), request, &dns_tx);
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() => {
while let Some(event) = {
@@ -176,6 +189,15 @@ impl Server {
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,
r = signal::ctrl_c() => {
r.expect("failed to wait for CTRL+C");
@@ -210,7 +232,6 @@ impl Server {
}
fn notify_capture(&self) {
log::info!("received capture enable request");
self.notifies.capture.notify_waiters()
}
@@ -219,7 +240,6 @@ impl Server {
}
fn notify_emulation(&self) {
log::info!("received emulation enable request");
self.notifies.emulation.notify_waiters()
}
@@ -246,7 +266,10 @@ impl Server {
}
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> {
@@ -258,43 +281,55 @@ impl Server {
.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,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
event: FrontendRequest,
dns: &Sender<ClientHandle>,
) -> bool {
log::debug!("frontend: {event:?}");
match event {
FrontendRequest::EnableCapture => self.notify_capture(),
FrontendRequest::EnableEmulation => self.notify_emulation(),
FrontendRequest::EnableCapture => {
log::info!("received capture enable request");
self.notify_capture();
}
FrontendRequest::EnableEmulation => {
log::info!("received emulation enable request");
self.notify_emulation();
}
FrontendRequest::Create => {
self.add_client();
let handle = self.add_client().await;
self.request_dns(handle);
}
FrontendRequest::Activate(handle, active) => {
if active {
self.activate_client(capture, emulate, handle);
self.activate_client(capture, emulate, handle).await;
} else {
self.deactivate_client(capture, emulate, handle);
self.deactivate_client(capture, emulate, handle).await;
}
}
FrontendRequest::ChangePort(port) => self.request_port_change(port),
FrontendRequest::Delete(handle) => {
self.remove_client(capture, emulate, handle);
self.remove_client(capture, emulate, handle).await;
self.notify_frontend(FrontendEvent::Deleted(handle));
}
FrontendRequest::Enumerate() => self.enumerate(),
FrontendRequest::GetState(handle) => self.broadcast_client(handle),
FrontendRequest::UpdateFixIps(handle, fix_ips) => self.update_fix_ips(handle, fix_ips),
FrontendRequest::UpdateHostname(handle, host) => {
self.update_hostname(handle, host, dns)
FrontendRequest::UpdateFixIps(handle, fix_ips) => {
self.update_fix_ips(handle, fix_ips);
self.request_dns(handle);
}
FrontendRequest::UpdateHostname(handle, host) => self.update_hostname(handle, host),
FrontendRequest::UpdatePort(handle, port) => self.update_port(handle, port),
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::ResolveDns(handle) => self.request_dns(handle),
FrontendRequest::Sync => {
self.enumerate();
self.notify_frontend(FrontendEvent::EmulationStatus(self.emulation_status.get()));
@@ -315,7 +350,7 @@ impl Server {
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();
log::info!("added client {handle}");
let (c, s) = self.client_manager.borrow().get(handle).unwrap().clone();
@@ -323,40 +358,41 @@ impl Server {
handle
}
fn deactivate_client(
async fn deactivate_client(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
handle: ClientHandle,
) {
log::debug!("deactivating client {handle}");
match self.client_manager.borrow_mut().get_mut(handle) {
None => return,
Some((_, s)) if !s.active => return,
Some((_, s)) => s.active = false,
None => return,
};
let _ = capture.send(CaptureRequest::Destroy(handle));
let _ = emulate.send(EmulationRequest::Destroy(handle));
self.client_updated(handle);
log::info!("deactivated client {handle}");
log::debug!("deactivating client {handle} done");
}
fn activate_client(
async fn activate_client(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
handle: ClientHandle,
) {
log::debug!("activating client");
/* deactivate potential other client at this position */
let pos = match self.client_manager.borrow().get(handle) {
None => return,
Some((_, s)) if s.active => return,
Some((client, _)) => client.pos,
None => return,
};
let other = self.client_manager.borrow_mut().find_client(pos);
if let Some(other) = other {
self.deactivate_client(capture, emulate, other);
if other != handle {
self.deactivate_client(capture, emulate, other).await;
}
}
/* activate the client */
@@ -369,13 +405,10 @@ impl Server {
/* notify emulation, capture and frontends */
let _ = capture.send(CaptureRequest::Create(handle, to_capture_pos(pos)));
let _ = emulate.send(EmulationRequest::Create(handle));
self.client_updated(handle);
log::info!("activated client {handle} ({pos})");
log::debug!("activating client {handle} done");
}
fn remove_client(
async fn remove_client(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
@@ -407,7 +440,6 @@ impl Server {
c.fix_ips = fix_ips;
};
self.update_ips(handle);
self.client_updated(handle);
}
pub(crate) fn update_dns_ips(&self, handle: ClientHandle, dns_ips: Vec<IpAddr>) {
@@ -415,7 +447,6 @@ impl Server {
s.dns_ips = dns_ips;
};
self.update_ips(handle);
self.client_updated(handle);
}
fn update_ips(&self, handle: ClientHandle) {
@@ -429,12 +460,7 @@ impl Server {
}
}
fn update_hostname(
&self,
handle: ClientHandle,
hostname: Option<String>,
dns: &Sender<ClientHandle>,
) {
fn update_hostname(&self, handle: ClientHandle, hostname: Option<String>) {
let mut client_manager = self.client_manager.borrow_mut();
let Some((c, s)) = client_manager.get_mut(handle) else {
return;
@@ -443,13 +469,10 @@ impl Server {
// hostname changed
if c.hostname != hostname {
c.hostname = hostname;
s.ips = HashSet::from_iter(c.fix_ips.iter().cloned());
s.active_addr = None;
s.dns_ips.clear();
drop(client_manager);
self.update_ips(handle);
dns.send(handle).expect("channel closed");
self.request_dns(handle);
}
self.client_updated(handle);
}
fn update_port(&self, handle: ClientHandle, port: u16) {
@@ -464,7 +487,7 @@ impl Server {
}
}
fn update_pos(
async fn update_pos(
&self,
handle: ClientHandle,
capture: &Sender<CaptureRequest>,
@@ -478,19 +501,18 @@ impl Server {
};
let changed = c.pos != pos;
if changed {
log::info!("update pos {handle} {} -> {}", c.pos, pos);
}
c.pos = pos;
(changed, s.active)
};
// update state in event input emulator & input capture
if changed {
self.deactivate_client(capture, emulate, handle);
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, to_capture_pos(pos)));
let _ = emulate.send(EmulationRequest::Create(handle));
}
}
@@ -523,7 +545,7 @@ impl Server {
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
.borrow_mut()
.get_mut(handle)
@@ -539,12 +561,12 @@ impl Server {
self.state.replace(state);
}
fn set_active(&self, handle: Option<ClientHandle>) {
fn set_active(&self, handle: Option<u64>) {
log::debug!("active client => {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
.borrow()
.get(handle)