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 {
pub hostname: Option<String>,
pub fix_ips: Vec<IpAddr>,
pub port: u16,
pub pos: Position,
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 {
pub active: bool,
pub active_addr: Option<SocketAddr>,
pub alive: bool,
pub dns_ips: Vec<IpAddr>,
pub ips: HashSet<IpAddr>,
pub has_pressed_keys: bool,
pub resolving: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FrontendEvent {
Changed(ClientHandle),
Created(ClientHandle, ClientConfig, ClientState),
NoSuchClient(ClientHandle),
State(ClientHandle, ClientConfig, ClientState),
Deleted(ClientHandle),
PortChanged(u16, Option<String>),
Enumerate(Vec<(ClientHandle, ClientConfig, ClientState)>),
Error(String),
CaptureStatus(Status),
EmulationStatus(Status),
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum FrontendRequest {
Activate(ClientHandle, bool),
Create,
ChangePort(u16),
Delete(ClientHandle),
Enumerate(),
ResolveDns(ClientHandle),
UpdateHostname(ClientHandle, Option<String>),
UpdatePort(ClientHandle, u16),
UpdatePosition(ClientHandle, Position),
UpdateFixIps(ClientHandle, Vec<IpAddr>),
GetState(ClientHandle),
EnableCapture,
EnableEmulation,
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))
}