Compare commits

..

19 Commits

Author SHA1 Message Date
Ferdinand Schober
d4d6f05802 chore: Release lan-mouse version 0.3.3 2023-10-11 14:32:18 +02:00
Ferdinand Schober
79fa42b74e Update README.md 2023-09-30 16:29:15 +02:00
Ferdinand Schober
851b6d60eb Avoid sending frame events (#29)
* Avoid sending frame events

Frame events are now implicit - each network event implies a frame event
TODO: Accumulate correctly

* remove trace logs from producer
2023-09-28 13:01:38 +02:00
Ferdinand Schober
06725f4b14 Frontend improvement (#27)
* removed redundant dns lookups
* frontend now correctly reflects the state of the backend
* config.toml is loaded when starting gtk frontend
2023-09-25 13:03:17 +02:00
Ferdinand Schober
603646c799 Add LM_DEBUG_LAYER_SHELL environment variable
setting LM_DEBUG_LAYER_SHELL to a value will
make the indicators visible
2023-09-21 18:23:01 +02:00
Ferdinand Schober
b2179e88de adjust window size 2023-09-21 13:59:18 +02:00
Ferdinand Schober
bae52eb9e7 chore: Release lan-mouse version 0.3.2 2023-09-21 13:23:45 +02:00
Ferdinand Schober
0fbd09b07f fix 1px gap 2023-09-21 13:22:23 +02:00
Ferdinand Schober
96dd9c05a1 fix interference with swaybar 2023-09-21 12:57:51 +02:00
Ferdinand Schober
15c02ac505 chore: Release lan-mouse version 0.3.1 2023-09-21 12:37:00 +02:00
Ferdinand Schober
08893a39be fix incorrect orientation of layer surfaces
top and bottom surfaces were not sized & oriented correctly
closes #3
2023-09-21 12:35:27 +02:00
Ferdinand Schober
48b701b726 remove an unused import 2023-09-21 00:13:53 +02:00
Ferdinand Schober
891e21d3e9 read all output globals 2023-09-21 00:12:11 +02:00
Ferdinand Schober
6a5de3f025 Update README.md (#25)
scale image
2023-09-20 15:40:19 +02:00
Ferdinand Schober
1eb12baf15 chore: Release lan-mouse version 0.3.0 2023-09-20 15:31:53 +02:00
Ferdinand Schober
65048abcfc Update README.md (#24) 2023-09-20 15:25:09 +02:00
Ferdinand Schober
d042c0aa4a Libadwaita gui (#19)
Major Update: Functional GUI Frontend!
2023-09-20 15:23:33 +02:00
Ferdinand Schober
c50b746816 fix 2023-09-19 21:13:17 +02:00
Ferdinand Schober
3b09abb532 unlink socket in case it's left over from a crash 2023-09-19 21:11:47 +02:00
31 changed files with 2188 additions and 498 deletions

View File

@@ -18,6 +18,7 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install libx11-dev libxtst-dev
sudo apt-get install libadwaita-1-dev libgtk-4-dev
- name: Release Build
run: cargo build --release
- name: Upload build artifact

View File

@@ -20,6 +20,7 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install libx11-dev libxtst-dev
sudo apt-get install libadwaita-1-dev libgtk-4-dev
- name: Build
run: cargo build --verbose
- name: Run tests

View File

@@ -14,6 +14,7 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install libx11-dev libxtst-dev
sudo apt-get install libadwaita-1-dev libgtk-4-dev
- name: Release Build
run: cargo build --release
- name: Upload build artifact

55
Cargo.lock generated
View File

@@ -155,14 +155,14 @@ checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650"
[[package]]
name = "enum-as-inner"
version = "0.5.1"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116"
checksum = "5ffccbb6966c05b32ef8fbac435df276c4ae4d3dc55a8cd0eb9745e6c12f546a"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 1.0.109",
"syn 2.0.37",
]
[[package]]
@@ -423,6 +423,12 @@ dependencies = [
"thiserror",
]
[[package]]
name = "glib-build-tools"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3431c56f463443cba9bc3600248bc6d680cb614c2ee1cdd39dab5415bd12ac5c"
[[package]]
name = "glib-macros"
version = "0.18.2"
@@ -601,17 +607,6 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "idna"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8"
dependencies = [
"matches",
"unicode-bidi",
"unicode-normalization",
]
[[package]]
name = "idna"
version = "0.4.0"
@@ -680,10 +675,11 @@ checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
[[package]]
name = "lan-mouse"
version = "0.2.1"
version = "0.3.3"
dependencies = [
"anyhow",
"env_logger",
"glib-build-tools",
"gtk4",
"libadwaita",
"libc",
@@ -705,12 +701,6 @@ dependencies = [
"x11",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libadwaita"
version = "0.5.2"
@@ -802,12 +792,6 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4"
[[package]]
name = "matches"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5"
[[package]]
name = "memchr"
version = "2.6.3"
@@ -1433,9 +1417,9 @@ dependencies = [
[[package]]
name = "trust-dns-proto"
version = "0.22.0"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f7f83d1e4a0e4358ac54c5c3681e5d7da5efc5a7a632c90bb6d6669ddd9bc26"
checksum = "0dc775440033cb114085f6f2437682b194fa7546466024b1037e82a48a052a69"
dependencies = [
"async-trait",
"cfg-if",
@@ -1444,9 +1428,9 @@ dependencies = [
"futures-channel",
"futures-io",
"futures-util",
"idna 0.2.3",
"idna",
"ipnet",
"lazy_static",
"once_cell",
"rand",
"smallvec",
"thiserror",
@@ -1458,16 +1442,17 @@ dependencies = [
[[package]]
name = "trust-dns-resolver"
version = "0.22.0"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aff21aa4dcefb0a1afbfac26deb0adc93888c7d295fb63ab273ef276ba2b7cfe"
checksum = "2dff7aed33ef3e8bf2c9966fccdfed93f93d46f432282ea875cd66faabc6ef2f"
dependencies = [
"cfg-if",
"futures-util",
"ipconfig",
"lazy_static",
"lru-cache",
"once_cell",
"parking_lot",
"rand",
"resolv-conf",
"smallvec",
"thiserror",
@@ -1504,7 +1489,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5"
dependencies = [
"form_urlencoded",
"idna 0.4.0",
"idna",
"percent-encoding",
]

View File

@@ -1,7 +1,7 @@
[package]
name = "lan-mouse"
description = "Software KVM Switch / mouse & keyboard sharing software for Local Area Networks"
version = "0.2.1"
version = "0.3.3"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/ferdinandschober/lan-mouse"
@@ -13,8 +13,8 @@ strip = true
lto = "fat"
[dependencies]
tempfile = "3.6"
trust-dns-resolver = "0.22"
tempfile = "3.8"
trust-dns-resolver = "0.23"
memmap = "0.7"
toml = "0.7"
serde = { version = "1.0", features = ["derive"] }
@@ -33,16 +33,30 @@ wayland-protocols-misc = { version="0.1.0", features=["client"], optional = true
wayland-protocols-plasma = { version="0.1.0", features=["client"], optional = true }
mio-signals = "0.2.0"
x11 = { version = "2.21.0", features = ["xlib", "xtest"], optional = true }
gtk = { package = "gtk4", version = "0.7.2", features = ["v4_8"], optional = true }
adw = { package = "libadwaita", version = "0.5.2", features = ["v1_3"], optional = true }
gtk = { package = "gtk4", version = "0.7.2", features = ["v4_6"], optional = true }
adw = { package = "libadwaita", version = "0.5.2", features = ["v1_1"], optional = true }
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3.9", features = ["winuser"] }
[target.'cfg(unix)'.build-dependencies]
glib-build-tools = "0.18.0"
[features]
default = ["wayland", "x11", "xdg_desktop_portal", "libei"]
wayland = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:wayland-protocols-misc", "dep:wayland-protocols-plasma"]
x11 = ["dep:x11"]
default = [
"wayland",
"x11",
"xdg_desktop_portal",
"libei",
"gtk",
]
wayland = [
"dep:wayland-client",
"dep:wayland-protocols",
"dep:wayland-protocols-wlr",
"dep:wayland-protocols-misc",
"dep:wayland-protocols-plasma" ]
x11 = [ "dep:x11" ]
xdg_desktop_portal = []
libei = []
gtk = ["dep:gtk", "dep:adw"]

View File

@@ -1,4 +1,8 @@
# Lan Mouse Share
# Lan Mouse
![image](https://github.com/ferdinandschober/lan-mouse/assets/40996949/ccb33815-4357-4c8d-a5d2-8897ab626a08)
Goal of this project is to be an open-source replacement for proprietary tools like [Synergy](https://symless.com/synergy), [Share Mouse](https://www.sharemouse.com/de/).
Focus lies on performance and a clean, manageable implementation that can easily be expanded to support additional backends like e.g. Android, iOS, ... .
@@ -7,41 +11,53 @@ Of course ***blazingly fast™*** and stable, because it's written in rust.
For an alternative (with slightly different goals) you may check out [Input Leap](https://github.com/input-leap).
_Now with a gtk frontend_
## Configuration
Configuration is done through the file `config.toml`,
which must be located in the current working directory when
executing lan-mouse.
### Example config
A minimal config file could look like this:
A config file could look like this:
```toml
# example configuration
# optional port (defaults to 4242)
port = 4242
# # optional frontend -> defaults to gtk if available
# # possible values are "cli" and "gtk"
# frontend = "gtk"
# define a client on the right side with host name "iridium"
[right]
# hostname
host_name = "iridium"
# optional list of (known) ip addresses
ips = ["192.168.178.156"]
# define a client on the left side with IP address 192.168.178.189
[left]
host_name = "my-laptop"
# The hostname is optional: When no hostname is specified,
# at least one ip address needs to be specified.
host_name = "thorium"
# ips for ethernet and wifi
ips = ["192.168.178.189", "192.168.178.172"]
# optional port
port = 4242
```
Where `left` can be either `left`, `right`, `top` or `bottom`.
### Additional options
Additionally
- a preferred backend
- a port override for the default port (4242)
can be specified.
Supported backends currently include "wlroots", "x11" and "windows".
These two options can also be specified via the commandline
options `--backend` and `--port` respectively.
## Build and Run
Build only
Build in release mode:
```sh
cargo build --release
```
Run
Run directly:
```sh
cargo run --release
```
@@ -133,12 +149,8 @@ This is to be looked into in the future.
(this works natively on sway versions >= 1.8)
## Windows support
Currently windows can receive mouse and keyboard events, however unlike
with the wlroots back-end,
the scancodes are not translated between keyboard layouts.
Event emitting is WIP.
Currently windows can receive mouse and keyboard events,
event producing on windows is WIP.
## TODOS
@@ -151,11 +163,11 @@ Event emitting is WIP.
- [x] Button support
- [ ] Latency measurement + logging
- [ ] Bandwidth usage approximation + logging
- [ ] Multiple IP addresses -> check which one is reachable
- [x] Multiple IP addresses -> check which one is reachable
- [x] Merge server and client -> Both client and server can send and receive events depending on what mouse is used where
- [ ] Liveness tracking (automatically ungrab mouse when client unreachable)
- [x] Liveness tracking (automatically ungrab mouse when client unreachable)
- [ ] Clipboard support
- [ ] Graphical frontend (gtk?)
- [x] Graphical frontend (gtk?)
- [ ] *Encrytion*
- [ ] Gnome Shell Extension (layer shell is not supported)
- [ ] respect xdg-config-home for config file location.

9
build.rs Normal file
View File

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

View File

@@ -2,19 +2,22 @@
# optional port (defaults to 4242)
port = 4242
# optional frontend -> defaults to gtk if available
# frontend = "gtk"
# define a client on the right side with host name "iridium"
[right]
# hostname
host_name = "iridium"
# optional list of (known) ip addresses
ips = ["192.168.178.141"]
# optional port (defaults to 4242)
port = 4242
ips = ["192.168.178.156"]
# define a client on the left side with IP address 192.168.178.189
[left]
# The hostname is optional: When no hostname is specified,
# at least one ip address needs to be specified.
host_name = "thorium"
ips = ["192.168.178.189"]
# ips for ethernet and wifi
ips = ["192.168.178.189", "192.168.178.172"]
# optional port
port = 4242

14
de.feschber.LanMouse.yml Normal file
View File

@@ -0,0 +1,14 @@
app-id: de.feschber.LanMouse
runtime: org.freedesktop.Platform
runtime-version: '22.08'
sdk: org.freedesktop.Sdk
command: target/release/lan-mouse
modules:
- name: hello
buildsystem: simple
build-commands:
- cargo build --release
- install -D lan-mouse /app/bin/lan-mouse
sources:
- type: file
path: target/release/lan-mouse

74
resources/client_row.ui Normal file
View File

@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<template class="ClientRow" parent="AdwExpanderRow">
<property name="title">hostname</property>
<!-- enabled -->
<child type="prefix">
<object class="GtkSwitch" id="enable_switch">
<signal name="state_set" handler="handle_client_set_state" swapped="true"/>
<property name="valign">center</property>
<property name="halign">end</property>
<property name="tooltip-text" translatable="yes">enable</property>
</object>
</child>
<!-- host -->
<child>
<object class="AdwActionRow">
<property name="title">hostname</property>
<property name="subtitle">port</property>
<!-- hostname -->
<child>
<object class="GtkEntry" id="hostname">
<!-- <property name="title" translatable="yes">hostname</property> -->
<property name="xalign">0.5</property>
<property name="valign">center</property>
<property name="placeholder-text">hostname</property>
<property name="width-chars">-1</property>
</object>
</child>
<!-- port -->
<child>
<object class="GtkEntry" id="port">
<!-- <property name="title" translatable="yes">port</property> -->
<property name="input_purpose">GTK_INPUT_PURPOSE_NUMBER</property>
<property name="xalign">0.5</property>
<property name="valign">center</property>
<property name="placeholder-text">4242</property>
<property name="width-chars">5</property>
</object>
</child>
</object>
</child>
<!-- position -->
<child>
<object class="AdwComboRow" id="position">
<property name="title" translatable="yes">position</property>
<property name="model">
<object class="GtkStringList">
<items>
<item>Left</item>
<item>Right</item>
<item>Top</item>
<item>Bottom</item>
</items>
</object>
</property>
</object>
</child>
<!-- delete button -->
<child>
<object class="AdwActionRow" id="delete_row">
<property name="title">delete this client</property>
<child>
<object class="GtkButton" id="delete_button">
<signal name="activate" handler="handle_client_delete" object="delete_row" swapped="true"/>
<property name="icon-name">user-trash-symbolic</property>
<property name="valign">center</property>
<property name="halign">center</property>
<property name="name">delete-button</property>
</object>
</child>
</object>
</child>
</template>
</interface>

171
resources/mouse-icon.svg Normal file
View File

@@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="48"
height="48"
viewBox="0 0 12.7 12.7"
version="1.1"
id="svg1"
inkscape:version="1.3 (0e150ed6c4, 2023-07-21)"
sodipodi:docname="mouse-icon.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview1"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="mm"
inkscape:zoom="22.737887"
inkscape:cx="19.54887"
inkscape:cy="26.167778"
inkscape:window-width="2560"
inkscape:window-height="1374"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="layer1" />
<defs
id="defs1" />
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<g
id="g20"
transform="translate(1.1586889,0.39019296)">
<g
id="g8"
transform="translate(-0.11519282,-3.9659242)">
<g
id="g6"
transform="translate(0.67275315,0.39959697)">
<g
id="g5">
<rect
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="rect4"
width="1.3032579"
height="1.3032579"
x="1.7199994"
y="7.5408325"
ry="0.3373504" />
<rect
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="rect4-2"
width="1.3032579"
height="1.3032579"
x="3.8428385"
y="7.5408325"
ry="0.3373504" />
</g>
<rect
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="rect4-3"
width="1.3032579"
height="1.3032579"
x="2.781419"
y="5.1382394"
ry="0.3373504" />
</g>
<path
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
d="M 1.1519282,7.3907619 H 7.059674"
id="path5" />
<path
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
d="M 4.1058009,6.8410941 V 7.3907617"
id="path6" />
<path
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
d="m 5.1672204,7.9404294 2e-7,-0.5496677"
id="path7" />
<path
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
d="M 3.0443815,7.9404294 V 7.3907617"
id="path8" />
</g>
<path
style="fill:none;stroke:#000000;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
d="M 6.9444811,3.4248375 Z"
id="path9" />
<path
style="color:#000000;fill:#000000;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
d="m 6.9840449,3.4464199 c -0.072714,-0.0035 -0.1209639,-0.2113583 -0.125,-0.1386718 -0.0035,0.072714 0.052314,0.1346357 0.125,0.1386718 0,0 0.6614057,0.034643 1.3535156,0.4765625 0.6921097,0.4419191 1.4111567,1.2803292 1.5136717,2.9433594 0.05132,0.832563 -0.07521,1.3855916 -0.279297,1.75 -0.20409,0.3644084 -0.482943,0.5482749 -0.777343,0.640625 -0.5888014,0.1847002 -1.2265629,-0.021484 -1.2265629,-0.021484 -0.069024,-0.023541 -0.144095,0.013122 -0.1679688,0.082031 -0.023366,0.069587 0.014295,0.1449093 0.083984,0.1679687 0,0 0.6961634,0.2406696 1.3886717,0.023437 C 9.2189712,9.4003039 9.5672292,9.1706004 9.8043572,8.7472012 10.041486,8.323802 10.170261,7.7150888 10.116858,6.8487637 10.009921,5.1140179 9.2320232,4.3532014 8.4801387,3.8731154 7.7282538,3.3930294 6.9840449,3.4464198 6.9840449,3.4464199 Z"
id="path18"
sodipodi:nodetypes="cccsssscccssssc" />
<g
id="g19"
transform="matrix(1.8148709,0,0,1.8148709,-4.1533763,-7.8818885)">
<g
id="g17"
transform="translate(0.01163623,0.23038484)">
<ellipse
style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="path10"
cx="3.9823804"
cy="8.17869"
rx="0.49368349"
ry="0.62533247" />
<ellipse
style="fill:#3d3d3d;fill-opacity:1;stroke:none;stroke-width:0.168876;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="ellipse17"
cx="3.9823804"
cy="8.17869"
rx="0.31096464"
ry="0.40317491" />
</g>
<path
id="path11"
style="stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round"
d="M 7.479305,9.4704944 C 7.4964603,9.9336885 6.9306558,9.9678313 5.3811502,10.087599 3.2109768,10.255341 2.4751992,9.6707727 2.4355055,9.5280908 2.3112754,9.0815374 3.8270232,8.4090748 5.3811502,8.4090748 c 1.5633309,0 2.0816988,0.6171052 2.0981548,1.0614196 z"
sodipodi:nodetypes="sssss" />
<circle
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="path12"
cx="3.5281858"
cy="9.0632057"
r="0.18513133" />
<g
id="g18"
transform="translate(0.01163623,0.23038484)">
<ellipse
style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="path10-2"
cx="4.6085634"
cy="8.17869"
rx="0.49368349"
ry="0.62533247" />
<ellipse
style="fill:#3d3d3d;fill-opacity:1;stroke:none;stroke-width:0.168876;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="ellipse16"
cx="4.6085634"
cy="8.17869"
rx="0.31096464"
ry="0.40317491" />
</g>
<ellipse
style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.112226;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"
id="circle18"
cx="3.5003331"
cy="9.0344076"
rx="0.078639306"
ry="0.07816644" />
<ellipse
style="fill:#4f4f4f;fill-opacity:1;stroke:none;stroke-width:0.264999;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:normal"
id="path19"
cx="2.4818404"
cy="9.4499254"
rx="0.05348238"
ry="0.11930636" />
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/de/feschber/LanMouse">
<file compressed="true" preprocess="xml-stripblanks">window.ui</file>
<file compressed="true" preprocess="xml-stripblanks">client_row.ui</file>
<file compressed="true">style.css</file>
<file compressed="true">style-dark.css</file>
</gresource>
<gresource prefix="/de/feschber/LanMouse/icons">
<file compressed="true" preprocess="xml-stripblanks">mouse-icon.svg</file>
</gresource>
</gresources>

3
resources/style-dark.css Normal file
View File

@@ -0,0 +1,3 @@
#delete-button {
color: @red_1;
}

3
resources/style.css Normal file
View File

@@ -0,0 +1,3 @@
#delete-button {
color: @red_3;
}

121
resources/window.ui Normal file
View File

@@ -0,0 +1,121 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk" version="4.0"/>
<requires lib="libadwaita" version="1.0"/>
<menu id="main-menu">
<item>
<attribute name="label" translatable="yes">_Close window</attribute>
<attribute name="action">window.close</attribute>
</item>
</menu>
<template class="LanMouseWindow" parent="GtkApplicationWindow">
<property name="width-request">600</property>
<property name="title" translatable="yes">Lan Mouse</property>
<property name="show-menubar">True</property>
<child type="titlebar">
<object class="GtkHeaderBar">
<child type ="end">
<object class="GtkMenuButton">
<property name="icon-name">open-menu-symbolic</property>
<property name="menu-model">main-menu</property>
</object>
</child>
<style>
<class name="flat"/>
</style>
</object>
</child>
<child>
<object class="AdwStatusPage">
<property name="title" translatable="yes">Lan Mouse</property>
<property name="description" translatable="yes">easily use your mouse and keyboard on multiple computers</property>
<property name="icon-name">mouse-icon</property>
<property name="child">
<object class="AdwClamp">
<property name="maximum-size">600</property>
<property name="tightening-threshold">0</property>
<property name="child">
<object class="GtkBox">
<property name="orientation">vertical</property>
<property name="spacing">12</property>
<child>
<object class="AdwPreferencesGroup">
<property name="title" translatable="yes">General</property>
<child>
<object class="AdwActionRow">
<property name="title" translatable="yes">enable</property>
<child type="suffix">
<object class="GtkSwitch">
<property name="valign">center</property>
<property name="tooltip-text" translatable="yes">enable</property>
</object>
</child>
</object>
</child>
<child>
<object class="AdwActionRow">
<property name="title">port</property>
<child>
<object class="GtkEntry">
<!-- <property name="title" translatable="yes">port</property> -->
<property name="placeholder-text">4242</property>
<property name="width-chars">5</property>
<property name="xalign">0.5</property>
<property name="valign">center</property>
<!-- <property name="show-apply-button">True</property> -->
<property name="input-purpose">GTK_INPUT_PURPOSE_DIGITS</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="AdwPreferencesGroup">
<property name="title" translatable="yes">Connections</property>
<child>
<object class="GtkListBox" id="client_list">
<property name="selection-mode">none</property>
<child type="placeholder">
<object class="AdwActionRow" id="client_placeholder">
<property name="title">No connections!</property>
<property name="subtitle">add a new client via the button below</property>
</object>
</child>
<style>
<class name="boxed-list" />
</style>
</object>
</child>
</object>
</child>
<child>
<object class="AdwPreferencesGroup">
<child>
<object class="GtkButton" id="add_client_button">
<property name="halign">center</property>
<property name="valign">center</property>
<property name="tooltip-text">connect a new computer</property>
<property name="child">
<object class="AdwButtonContent">
<property name="icon-name">list-add-symbolic</property>
<property name="label" translatable="yes">Add</property>
<property name="use-underline">True</property>
</object>
</property>
<!-- <signal name="clicked" handler="handle_add_client" swapped="true"/> -->
<style>
<class name="pill"/>
</style>
</object>
</child>
</object>
</child>
</object>
</property>
</object>
</property>
</object>
</child>
</template>
</interface>

View File

@@ -165,64 +165,73 @@ enum VirtualInput {
impl VirtualInput {
fn consume_event(&self, event: Event) -> Result<(),()> {
match event {
Event::Pointer(e) => match e {
PointerEvent::Motion {
time,
relative_x,
relative_y,
} => match self {
VirtualInput::Wlroots {
pointer,
keyboard: _,
} => {
pointer.motion(time, relative_x, relative_y);
}
VirtualInput::Kde { fake_input } => {
fake_input.pointer_motion(relative_y, relative_y);
}
},
PointerEvent::Button {
time,
button,
state,
} => {
let state: ButtonState = state.try_into()?;
match self {
Event::Pointer(e) => {
match e {
PointerEvent::Motion {
time,
relative_x,
relative_y,
} => match self {
VirtualInput::Wlroots {
pointer,
keyboard: _,
} => {
pointer.button(time, button, state);
pointer.motion(time, relative_x, relative_y);
}
VirtualInput::Kde { fake_input } => {
fake_input.button(button, state as u32);
fake_input.pointer_motion(relative_y, relative_y);
}
},
PointerEvent::Button {
time,
button,
state,
} => {
let state: ButtonState = state.try_into()?;
match self {
VirtualInput::Wlroots {
pointer,
keyboard: _,
} => {
pointer.button(time, button, state);
}
VirtualInput::Kde { fake_input } => {
fake_input.button(button, state as u32);
}
}
}
}
PointerEvent::Axis { time, axis, value } => {
let axis: Axis = (axis as u32).try_into()?;
match self {
PointerEvent::Axis { time, axis, value } => {
let axis: Axis = (axis as u32).try_into()?;
match self {
VirtualInput::Wlroots {
pointer,
keyboard: _,
} => {
pointer.axis(time, axis, value);
pointer.frame();
}
VirtualInput::Kde { fake_input } => {
fake_input.axis(axis as u32, value);
}
}
}
PointerEvent::Frame {} => match self {
VirtualInput::Wlroots {
pointer,
keyboard: _,
} => {
pointer.axis(time, axis, value);
pointer.frame();
}
VirtualInput::Kde { fake_input } => {
fake_input.axis(axis as u32, value);
}
}
VirtualInput::Kde { fake_input: _ } => {}
},
}
PointerEvent::Frame {} => match self {
VirtualInput::Wlroots {
pointer,
keyboard: _,
} => {
match self {
VirtualInput::Wlroots { pointer, .. } => {
// insert a frame event after each mouse event
pointer.frame();
}
VirtualInput::Kde { fake_input: _ } => {}
},
_ => {},
}
},
Event::Keyboard(e) => match e {
KeyboardEvent::Key { time, key, state } => match self {

View File

@@ -1,7 +1,7 @@
use crate::{client::{ClientHandle, Position, ClientEvent}, producer::EventProducer};
use mio::{event::Source, unix::SourceFd};
use std::{os::fd::RawFd, vec::Drain, io::ErrorKind};
use std::{os::fd::RawFd, vec::Drain, io::ErrorKind, env};
use memmap::MmapOptions;
use anyhow::{anyhow, Result};
@@ -12,7 +12,7 @@ use std::{
rc::Rc,
};
use wayland_protocols::wp::{
use wayland_protocols::{wp::{
keyboard_shortcuts_inhibit::zv1::client::{
zwp_keyboard_shortcuts_inhibit_manager_v1::ZwpKeyboardShortcutsInhibitManagerV1,
zwp_keyboard_shortcuts_inhibitor_v1::ZwpKeyboardShortcutsInhibitorV1,
@@ -25,7 +25,7 @@ use wayland_protocols::wp::{
zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1,
zwp_relative_pointer_v1::{self, ZwpRelativePointerV1},
},
};
}, xdg::xdg_output::zv1::client::{zxdg_output_manager_v1::ZxdgOutputManagerV1, zxdg_output_v1::{self, ZxdgOutputV1}}};
use wayland_protocols_wlr::layer_shell::v1::client::{
zwlr_layer_shell_v1::{Layer, ZwlrLayerShellV1},
@@ -38,7 +38,7 @@ use wayland_client::{
globals::{registry_queue_init, GlobalListContents},
protocol::{
wl_buffer, wl_compositor, wl_keyboard, wl_pointer, wl_region, wl_registry, wl_seat, wl_shm,
wl_shm_pool, wl_surface,
wl_shm_pool, wl_surface, wl_output::{self, WlOutput},
},
Connection, Dispatch, DispatchError, QueueHandle, WEnum, EventQueue,
};
@@ -55,6 +55,25 @@ struct Globals {
seat: wl_seat::WlSeat,
shm: wl_shm::WlShm,
layer_shell: ZwlrLayerShellV1,
outputs: Vec<wl_output::WlOutput>,
xdg_output_manager: ZxdgOutputManagerV1,
}
#[derive(Debug, Clone)]
struct OutputInfo {
name: String,
position: (i32, i32),
size: (i32, i32),
}
impl OutputInfo {
fn new() -> Self {
Self {
name: "".to_string(),
position: (0,0),
size: (0,0),
}
}
}
struct State {
@@ -68,6 +87,7 @@ struct State {
read_guard: Option<ReadEventsGuard>,
qh: QueueHandle<Self>,
pending_events: Vec<(ClientHandle, Event)>,
output_info: Vec<(WlOutput, OutputInfo)>,
}
pub struct WaylandEventProducer {
@@ -82,8 +102,13 @@ struct Window {
}
impl Window {
fn new(g: &Globals, qh: &QueueHandle<State>, pos: Position) -> Window {
let (width, height) = (1, 1440);
fn new(state: &State, qh: &QueueHandle<State>, output: &WlOutput, pos: Position, size: (i32, i32)) -> Window {
let g = &state.g;
let (width, height) = match pos {
Position::Left | Position::Right => (1, size.1 as u32),
Position::Top | Position::Bottom => (size.0 as u32, 1),
};
let mut file = tempfile::tempfile().unwrap();
draw(&mut file, (width, height));
let pool = g
@@ -102,8 +127,8 @@ impl Window {
let layer_surface = g.layer_shell.get_layer_surface(
&surface,
None,
Layer::Top,
Some(&output),
Layer::Overlay,
"LAN Mouse Sharing".into(),
qh,
(),
@@ -116,9 +141,9 @@ impl Window {
};
layer_surface.set_anchor(anchor);
layer_surface.set_size(1, 1440);
layer_surface.set_exclusive_zone(0);
layer_surface.set_margin(0, 0, 0, 0);
layer_surface.set_size(width, height);
layer_surface.set_exclusive_zone(-1);
layer_surface.set_margin(0,0,0,0);
surface.set_input_region(None);
surface.commit();
Window {
@@ -129,20 +154,71 @@ impl Window {
}
}
impl Drop for Window {
fn drop(&mut self) {
log::debug!("destroying window!");
self.layer_surface.destroy();
self.surface.destroy();
self.buffer.destroy();
}
}
fn get_edges(outputs: &[(WlOutput, OutputInfo)], pos: Position) -> Vec<(WlOutput, i32)> {
outputs.iter().map(|(o, i)| {
(o.clone(),
match pos {
Position::Left => i.position.0,
Position::Right => i.position.0 + i.size.0,
Position::Top => i.position.1,
Position::Bottom => i.position.1 + i.size.1,
})
}).collect()
}
fn get_output_configuration(state: &State, pos: Position) -> Vec<(WlOutput, OutputInfo)> {
// get all output edges corresponding to the position
let edges = get_edges(&state.output_info, pos);
let opposite_edges = get_edges(&state.output_info, pos.opposite());
// remove those edges that are at the same position
// as an opposite edge of a different output
let outputs: Vec<WlOutput> = edges.iter().filter(|(_,edge)| {
opposite_edges.iter().map(|(_,e)| *e).find(|e| e == edge).is_none()
}).map(|(o,_)| o.clone()).collect();
state.output_info
.iter()
.filter(|(o,_)| outputs.contains(o))
.map(|(o, i)| (o.clone(), i.clone()))
.collect()
}
fn draw(f: &mut File, (width, height): (u32, u32)) {
let mut buf = BufWriter::new(f);
for _ in 0..height {
for _ in 0..width {
buf.write_all(&0x44FbF1C7u32.to_ne_bytes()).unwrap();
if env::var("LM_DEBUG_LAYER_SHELL").ok().is_some() {
// AARRGGBB
buf.write_all(&0xFF11d116u32.to_ne_bytes()).unwrap();
} else {
// AARRGGBB
buf.write_all(&0x00000000u32.to_ne_bytes()).unwrap();
}
}
}
}
impl WaylandEventProducer {
pub fn new() -> Result<Self> {
let conn = Connection::connect_to_env().expect("could not connect to wayland compositor");
let (g, queue) =
registry_queue_init::<State>(&conn).expect("failed to initialize wl_registry");
let conn = match Connection::connect_to_env() {
Ok(c) => c,
Err(e) => return Err(anyhow!("could not connect to wayland compositor: {e:?}")),
};
let (g, mut queue) = match registry_queue_init::<State>(&conn) {
Ok(q) => q,
Err(e) => return Err(anyhow!("failed to initialize wl_registry: {e:?}")),
};
let qh = queue.handle();
let compositor: wl_compositor::WlCompositor = match g.bind(&qh, 4..=5, ()) {
@@ -150,6 +226,11 @@ impl WaylandEventProducer {
Err(_) => return Err(anyhow!("wl_compositor >= v4 not supported")),
};
let xdg_output_manager: ZxdgOutputManagerV1 = match g.bind(&qh, 1..=3, ()) {
Ok(xdg_output_manager) => xdg_output_manager,
Err(_) => return Err(anyhow!("xdg_output not supported!")),
};
let shm: wl_shm::WlShm = match g.bind(&qh, 1..=1, ()) {
Ok(wl_shm) => wl_shm,
Err(_) => return Err(anyhow!("wl_shm v1 not supported")),
@@ -180,6 +261,8 @@ impl WaylandEventProducer {
Err(_) => return Err(anyhow!("zwp_keyboard_shortcuts_inhibit_manager_v1 not supported")),
};
let outputs = vec![];
let g = Globals {
compositor,
shm,
@@ -188,6 +271,8 @@ impl WaylandEventProducer {
pointer_constraints,
relative_pointer_manager,
shortcut_inhibit_manager,
outputs,
xdg_output_manager,
};
// flush outgoing events
@@ -196,23 +281,47 @@ impl WaylandEventProducer {
// prepare reading wayland events
let read_guard = queue.prepare_read()?;
let wayland_fd = read_guard.connection_fd().as_raw_fd();
let read_guard = Some(read_guard);
std::mem::drop(read_guard);
Ok(WaylandEventProducer {
queue,
state: State {
g,
pointer_lock: None,
rel_pointer: None,
shortcut_inhibitor: None,
client_for_window: Vec::new(),
focused: None,
qh,
wayland_fd,
read_guard,
pending_events: vec![],
}
})
let mut state = State {
g,
pointer_lock: None,
rel_pointer: None,
shortcut_inhibitor: None,
client_for_window: Vec::new(),
focused: None,
qh,
wayland_fd,
read_guard: None,
pending_events: vec![],
output_info: vec![],
};
// dispatch registry to () again, in order to read all wl_outputs
conn.display().get_registry(&state.qh, ());
log::debug!("==============> requested registry");
// roundtrip to read wl_output globals
queue.roundtrip(&mut state)?;
log::debug!("==============> roundtrip 1 done");
// read outputs
for output in state.g.outputs.iter() {
state.g.xdg_output_manager.get_xdg_output(output, &state.qh, output.clone());
}
// roundtrip to read xdg_output events
queue.roundtrip(&mut state)?;
log::debug!("==============> roundtrip 2 done");
for i in &state.output_info {
log::debug!("{:#?}", i.1);
}
let read_guard = queue.prepare_read()?;
state.read_guard = Some(read_guard);
Ok(WaylandEventProducer { queue, state })
}
}
@@ -300,8 +409,15 @@ impl State {
}
fn add_client(&mut self, client: ClientHandle, pos: Position) {
let window = Rc::new(Window::new(&self.g, &self.qh, pos));
self.client_for_window.push((window, client));
let outputs = get_output_configuration(self, pos);
outputs.iter().for_each(|(o, i)| {
let window = Window::new(&self, &self.qh, &o, pos, i.size);
let window = Rc::new(window);
self.client_for_window.push((window, client));
});
}
}
@@ -412,10 +528,27 @@ impl EventProducer for WaylandEventProducer {
}
fn notify(&mut self, client_event: ClientEvent) {
if let ClientEvent::Create(handle, pos) = client_event {
self.state.add_client(handle, pos);
self.flush_events();
match client_event {
ClientEvent::Create(handle, pos) => {
self.state.add_client(handle, pos);
}
ClientEvent::Destroy(handle) => {
loop {
// remove all windows corresponding to this client
if let Some(i) = self
.state
.client_for_window
.iter()
.position(|(_,c)| *c == handle) {
self.state.client_for_window.remove(i);
self.state.focused = None;
} else {
break
}
}
}
}
self.flush_events();
}
fn release(&mut self) {
@@ -465,16 +598,16 @@ impl Dispatch<wl_pointer::WlPointer, ()> for State {
surface_y: _,
} => {
// get client corresponding to the focused surface
log::trace!("produce: enter()");
{
let (window, client) = app
if let Some((window, client)) = app
.client_for_window
.iter()
.find(|(w, _c)| w.surface == surface)
.unwrap();
app.focused = Some((window.clone(), *client));
app.grab(&surface, pointer, serial.clone(), qh);
.find(|(w, _c)| w.surface == surface) {
app.focused = Some((window.clone(), *client));
app.grab(&surface, pointer, serial.clone(), qh);
} else {
return;
}
}
let (_, client) = app
.client_for_window
@@ -484,7 +617,6 @@ impl Dispatch<wl_pointer::WlPointer, ()> for State {
app.pending_events.push((*client, Event::Release()));
}
wl_pointer::Event::Leave { .. } => {
log::trace!("produce: leave()");
app.ungrab();
}
wl_pointer::Event::Button {
@@ -493,7 +625,6 @@ impl Dispatch<wl_pointer::WlPointer, ()> for State {
button,
state,
} => {
log::trace!("produce: button()");
let (_, client) = app.focused.as_ref().unwrap();
app.pending_events.push((
*client,
@@ -505,7 +636,6 @@ impl Dispatch<wl_pointer::WlPointer, ()> for State {
));
}
wl_pointer::Event::Axis { time, axis, value } => {
log::trace!("produce: scroll()");
let (_, client) = app.focused.as_ref().unwrap();
app.pending_events.push((
*client,
@@ -517,12 +647,9 @@ impl Dispatch<wl_pointer::WlPointer, ()> for State {
));
}
wl_pointer::Event::Frame {} => {
log::trace!("produce: frame()");
let (_, client) = app.focused.as_ref().unwrap();
app.pending_events.push((
*client,
Event::Pointer(PointerEvent::Frame {}),
));
// TODO properly handle frame events
// we simply insert a frame event on the client side
// after each event for now
}
_ => {}
}
@@ -615,7 +742,6 @@ impl Dispatch<ZwpRelativePointerV1, ()> for State {
dy_unaccel: surface_y,
} = event
{
log::trace!("produce: motion()");
if let Some((_window, client)) = &app.focused {
let time = (((utime_hi as u64) << 32 | utime_lo as u64) / 1000) as u32;
app.pending_events.push((
@@ -641,23 +767,22 @@ impl Dispatch<ZwlrLayerSurfaceV1, ()> for State {
_: &QueueHandle<Self>,
) {
if let zwlr_layer_surface_v1::Event::Configure { serial, .. } = event {
let (window, _client) = app
if let Some((window, _client)) = app
.client_for_window
.iter()
.find(|(w, _c)| &w.layer_surface == layer_surface)
.unwrap();
// client corresponding to the layer_surface
let surface = &window.surface;
let buffer = &window.buffer;
surface.attach(Some(&buffer), 0, 0);
layer_surface.ack_configure(serial);
surface.commit();
.find(|(w, _c)| &w.layer_surface == layer_surface) {
// client corresponding to the layer_surface
let surface = &window.surface;
let buffer = &window.buffer;
surface.attach(Some(&buffer), 0, 0);
layer_surface.ack_configure(serial);
surface.commit();
}
}
}
}
// delegate wl_registry events to App itself
// delegate_dispatch!(App: [wl_registry::WlRegistry: GlobalListContents] => App);
impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for State {
fn event(
_state: &mut Self,
@@ -670,6 +795,70 @@ impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for State {
}
}
impl Dispatch<wl_registry::WlRegistry, ()> for State {
fn event(
state: &mut Self,
registry: &wl_registry::WlRegistry,
event: <wl_registry::WlRegistry as wayland_client::Proxy>::Event,
_: &(),
_: &Connection,
qh: &QueueHandle<Self>,
) {
match event {
wl_registry::Event::Global { name, interface, version: _ } => {
match interface.as_str() {
"wl_output" => {
log::debug!("wl_output global");
state.g.outputs.push(registry.bind::<wl_output::WlOutput, _, _>(name, 4, qh, ()))
}
_ => {}
}
},
wl_registry::Event::GlobalRemove { .. } => {},
_ => {},
}
}
}
impl Dispatch<ZxdgOutputV1, WlOutput> for State {
fn event(
state: &mut Self,
_: &ZxdgOutputV1,
event: <ZxdgOutputV1 as wayland_client::Proxy>::Event,
wl_output: &WlOutput,
_: &Connection,
_: &QueueHandle<Self>,
) {
log::debug!("xdg-output - {event:?}");
let output_info = match state
.output_info
.iter_mut()
.find(|(o, _)| o == wl_output) {
Some((_,c)) => c,
None => {
let output_info = OutputInfo::new();
state.output_info.push((wl_output.clone(), output_info));
&mut state.output_info.last_mut().unwrap().1
}
};
match event {
zxdg_output_v1::Event::LogicalPosition { x, y } => {
output_info.position = (x, y);
},
zxdg_output_v1::Event::LogicalSize { width, height } => {
output_info.size = (width, height);
},
zxdg_output_v1::Event::Done => {},
zxdg_output_v1::Event::Name { name } => {
output_info.name = name;
},
zxdg_output_v1::Event::Description { .. } => {},
_ => {},
}
}
}
// don't emit any events
delegate_noop!(State: wl_region::WlRegion);
delegate_noop!(State: wl_shm_pool::WlShmPool);
@@ -680,6 +869,8 @@ delegate_noop!(State: ZwpKeyboardShortcutsInhibitManagerV1);
delegate_noop!(State: ZwpPointerConstraintsV1);
// ignore events
delegate_noop!(State: ignore wl_output::WlOutput);
delegate_noop!(State: ignore ZxdgOutputManagerV1);
delegate_noop!(State: ignore wl_shm::WlShm);
delegate_noop!(State: ignore wl_buffer::WlBuffer);
delegate_noop!(State: ignore wl_surface::WlSurface);

View File

@@ -1,4 +1,4 @@
use std::{net::SocketAddr, collections::{HashSet, hash_set::Iter}, fmt::Display, time::{Instant, Duration}, iter::Cloned};
use std::{net::{SocketAddr, IpAddr}, collections::HashSet, fmt::Display, time::Instant};
use serde::{Serialize, Deserialize};
@@ -9,6 +9,24 @@ pub enum Position {
Top,
Bottom,
}
impl Default for Position {
fn default() -> Self {
Self::Left
}
}
impl Position {
pub fn opposite(&self) -> Self {
match self {
Position::Left => Self::Right,
Position::Right => Self::Left,
Position::Top => Self::Bottom,
Position::Bottom => Self::Top,
}
}
}
impl Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", match self {
@@ -22,7 +40,9 @@ impl Display for Position {
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct Client {
/// handle to refer to the client.
/// hostname of this client
pub hostname: Option<String>,
/// unique handle to refer to the client.
/// This way any event consumer / producer backend does not
/// need to know anything about a client other than its handle.
pub handle: ClientHandle,
@@ -34,6 +54,8 @@ pub struct Client {
/// e.g. Laptops usually have at least an ethernet and a wifi port
/// which have different ip addresses
pub addrs: HashSet<SocketAddr>,
/// 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,
}
@@ -41,150 +63,118 @@ pub struct Client {
pub enum ClientEvent {
Create(ClientHandle, Position),
Destroy(ClientHandle),
UpdatePos(ClientHandle, Position),
AddAddr(ClientHandle, SocketAddr),
RemoveAddr(ClientHandle, SocketAddr),
}
pub type ClientHandle = u32;
#[derive(Debug, Clone)]
pub struct ClientState {
pub client: Client,
pub active: bool,
pub last_ping: Option<Instant>,
pub last_seen: Option<Instant>,
pub last_replied: Option<Instant>,
}
pub struct ClientManager {
/// probably not beneficial to use a hashmap here
clients: Vec<Client>,
last_ping: Vec<(ClientHandle, Option<Instant>)>,
last_seen: Vec<(ClientHandle, Option<Instant>)>,
last_replied: Vec<(ClientHandle, Option<Instant>)>,
next_client_id: u32,
clients: Vec<Option<ClientState>>, // HashMap likely not beneficial
}
impl ClientManager {
pub fn new() -> Self {
Self {
clients: vec![],
next_client_id: 0,
last_ping: vec![],
last_seen: vec![],
last_replied: vec![],
}
}
/// add a new client to this manager
pub fn add_client(&mut self, addrs: HashSet<SocketAddr>, pos: Position) -> ClientHandle {
let handle = self.next_id();
pub fn add_client(
&mut self,
hostname: Option<String>,
addrs: HashSet<IpAddr>,
port: u16,
pos: Position,
) -> ClientHandle {
// get a new client_handle
let handle = self.free_id();
// we dont know, which IP is initially active
let active_addr = None;
// map ip addresses to socket addresses
let addrs = HashSet::from_iter(
addrs
.into_iter()
.map(|ip| SocketAddr::new(ip, port))
);
// store the client
let client = Client { handle, active_addr, addrs, pos };
self.clients.push(client);
self.last_ping.push((handle, None));
self.last_seen.push((handle, None));
self.last_replied.push((handle, None));
let client = Client { hostname, handle, active_addr, addrs, port, pos };
// client was never seen, nor pinged
let client_state = ClientState {
client,
last_ping: None,
last_seen: None,
last_replied: None,
active: false,
};
if handle as usize >= self.clients.len() {
assert_eq!(handle as usize, self.clients.len());
self.clients.push(Some(client_state));
} else {
self.clients[handle as usize] = Some(client_state);
}
handle
}
/// add a socket address to the given client
pub fn add_addr(&mut self, client: ClientHandle, addr: SocketAddr) {
if let Some(client) = self.get_mut(client) {
client.addrs.insert(addr);
}
}
/// remove socket address from the given client
pub fn remove_addr(&mut self, client: ClientHandle, addr: SocketAddr) {
if let Some(client) = self.get_mut(client) {
client.addrs.remove(&addr);
}
}
pub fn set_default_addr(&mut self, client: ClientHandle, addr: SocketAddr) {
if let Some(client) = self.get_mut(client) {
client.active_addr = Some(addr)
}
}
/// update the position of a client
pub fn update_pos(&mut self, client: ClientHandle, pos: Position) {
if let Some(client) = self.get_mut(client) {
client.pos = pos;
}
}
pub fn get_active_addr(&self, client: ClientHandle) -> Option<SocketAddr> {
self.get(client)?.active_addr
}
pub fn get_addrs(&self, client: ClientHandle) -> Option<Cloned<Iter<'_, SocketAddr>>> {
Some(self.get(client)?.addrs.iter().cloned())
}
pub fn last_ping(&self, client: ClientHandle) -> Option<Duration> {
let last_ping = self.last_ping
.iter()
.find(|(c,_)| *c == client)
.unwrap().1;
last_ping.map(|p| p.elapsed())
}
pub fn last_seen(&self, client: ClientHandle) -> Option<Duration> {
let last_seen = self.last_seen
.iter()
.find(|(c, _)| *c == client)
.unwrap().1;
last_seen.map(|t| t.elapsed())
}
pub fn last_replied(&self, client: ClientHandle) -> Option<Duration> {
let last_replied = self.last_replied
.iter()
.find(|(c, _)| *c == client)
.unwrap().1;
last_replied.map(|t| t.elapsed())
}
pub fn reset_last_ping(&mut self, client: ClientHandle) {
self.last_ping
.iter_mut()
.find(|(c, _)| *c == client)
.unwrap().1 = Some(Instant::now());
}
pub fn reset_last_seen(&mut self, client: ClientHandle) {
self.last_seen
.iter_mut()
.find(|(c, _)| *c == client)
.unwrap().1 = Some(Instant::now());
}
pub fn reset_last_replied(&mut self, client: ClientHandle) {
self.last_replied
.iter_mut()
.find(|(c, _)| *c == client)
.unwrap().1 = Some(Instant::now());
}
/// find a client by its address
pub fn get_client(&self, addr: SocketAddr) -> Option<ClientHandle> {
// since there shouldn't be more than a handful of clients at any given
// time this is likely faster than using a HashMap
self.clients
.iter()
.find(|c| c.addrs.contains(&addr))
.map(|c| c.handle)
.position(|c| if let Some(c) = c {
c.active && c.client.addrs.contains(&addr)
} else {
false
})
.map(|p| p as ClientHandle)
}
fn next_id(&mut self) -> ClientHandle {
let handle = self.next_client_id;
self.next_client_id += 1;
handle
/// remove a client from the list
pub fn remove_client(&mut self, client: ClientHandle) -> Option<ClientState> {
// remove id from occupied ids
self.clients.get_mut(client as usize)?.take()
}
fn get<'a>(&'a self, client: ClientHandle) -> Option<&'a Client> {
/// get a free slot in the client list
fn free_id(&mut self) -> ClientHandle {
for i in 0..u32::MAX {
if self.clients.get(i as usize).is_none()
|| self.clients.get(i as usize).unwrap().is_none() {
return i;
}
}
panic!("Out of client ids");
}
// returns an immutable reference to the client state corresponding to `client`
pub fn get<'a>(&'a self, client: ClientHandle) -> Option<&'a ClientState> {
self.clients.get(client as usize)?.as_ref()
}
/// returns a mutable reference to the client state corresponding to `client`
pub fn get_mut<'a>(&'a mut self, client: ClientHandle) -> Option<&'a mut ClientState> {
self.clients.get_mut(client as usize)?.as_mut()
}
pub fn enumerate(&self) -> Vec<(Client, bool)> {
self.clients
.iter()
.find(|c| c.handle == client)
}
fn get_mut<'a>(&'a mut self, client: ClientHandle) -> Option<&'a mut Client> {
self.clients
.iter_mut()
.find(|c| c.handle == client)
.filter_map(|s|s.as_ref())
.map(|s| (s.client.clone(), s.active))
.collect()
}
}

View File

@@ -1,14 +1,13 @@
use serde::{Deserialize, Serialize};
use core::fmt;
use std::collections::HashSet;
use std::net::{IpAddr, SocketAddr};
use std::net::IpAddr;
use std::{error::Error, fs};
use std::env;
use toml;
use crate::client::Position;
use crate::dns;
pub const DEFAULT_PORT: u16 = 4242;
@@ -64,6 +63,7 @@ fn find_arg(key: &'static str) -> Result<Option<String>, MissingParameter> {
Ok(None)
}
#[derive(PartialEq, Eq)]
pub enum Frontend {
Gtk,
Cli,
@@ -96,6 +96,9 @@ impl Config {
};
let frontend = match frontend {
#[cfg(all(unix, feature = "gtk"))]
None => Frontend::Gtk,
#[cfg(any(not(feature = "gtk"), not(unix)))]
None => Frontend::Cli,
Some(s) => match s.as_str() {
"cli" => Frontend::Cli,
@@ -132,40 +135,16 @@ impl Config {
Ok(Config { frontend, clients, port })
}
pub fn get_clients(&self) -> Vec<(HashSet<SocketAddr>, Option<String>, Position)> {
pub fn get_clients(&self) -> Vec<(HashSet<IpAddr>, Option<String>, u16, Position)> {
self.clients.iter().map(|(c,p)| {
let port = c.port.unwrap_or(DEFAULT_PORT);
// add ips from config
let config_ips: Vec<IpAddr> = if let Some(ips) = c.ips.as_ref() {
ips.iter().cloned().collect()
let ips: HashSet<IpAddr> = if let Some(ips) = c.ips.as_ref() {
HashSet::from_iter(ips.iter().cloned())
} else {
vec![]
HashSet::new()
};
let host_name = c.host_name.clone();
// add ips from dns lookup
let dns_ips = match host_name.as_ref() {
None => vec![],
Some(host_name) => match dns::resolve(host_name) {
Err(e) => {
log::warn!("{host_name}: could not resolve host: {e}");
vec![]
}
Ok(l) if l.is_empty() => {
log::warn!("{host_name}: could not resolve host");
vec![]
}
Ok(l) => l,
}
};
if config_ips.is_empty() && dns_ips.is_empty() {
log::error!("no ips found for client {p:?}, ignoring!");
log::error!("You can manually specify ip addresses via the `ips` config option");
}
let ips = config_ips.into_iter().chain(dns_ips.into_iter());
// map ip addresses to socket addresses
let addrs: HashSet<SocketAddr> = ips.map(|ip| SocketAddr::new(ip, port)).collect();
(addrs, host_name, *p)
}).filter(|(a, _, _)| !a.is_empty()).collect()
(ips, host_name, port, *p)
}).collect()
}
}

View File

@@ -1,9 +1,20 @@
use anyhow::Result;
use std::{error::Error, net::IpAddr};
use trust_dns_resolver::Resolver;
pub fn resolve(host: &str) -> Result<Vec<IpAddr>, Box<dyn Error>> {
log::info!("resolving {host} ...");
let response = Resolver::from_system_conf()?.lookup_ip(host)?;
Ok(response.iter().collect())
pub(crate) struct DnsResolver {
resolver: Resolver,
}
impl DnsResolver {
pub(crate) fn new() -> Result<Self> {
let resolver = Resolver::from_system_conf()?;
Ok(Self { resolver })
}
pub(crate) fn resolve(&self, host: &str) -> Result<Vec<IpAddr>, Box<dyn Error>> {
log::info!("resolving {host} ...");
let response = self.resolver.lookup_ip(host)?;
Ok(response.iter().collect())
}
}

View File

@@ -1,12 +1,12 @@
use std::{error::Error, io::Result, collections::HashSet, time::Duration};
use std::{error::Error, io::Result, collections::HashSet, time::{Duration, Instant}, net::IpAddr};
use log;
use mio::{Events, Poll, Interest, Token, net::UdpSocket};
use mio::{Events, Poll, Interest, Token, net::UdpSocket, event::Source};
#[cfg(not(windows))]
use mio_signals::{Signals, Signal, SignalSet};
use std::{net::SocketAddr, io::ErrorKind};
use crate::{client::{ClientEvent, ClientManager, Position}, consumer::EventConsumer, producer::EventProducer, frontend::{FrontendEvent, FrontendAdapter}};
use crate::{client::{ClientEvent, ClientManager, Position, ClientHandle}, consumer::EventConsumer, producer::EventProducer, frontend::{FrontendEvent, FrontendListener, FrontendNotify}, dns::{self, DnsResolver}};
use super::Event;
/// keeps track of state to prevent a feedback loop
@@ -22,11 +22,13 @@ pub struct Server {
socket: UdpSocket,
producer: Box<dyn EventProducer>,
consumer: Box<dyn EventConsumer>,
resolver: DnsResolver,
#[cfg(not(windows))]
signals: Signals,
frontend: FrontendAdapter,
frontend: FrontendListener,
client_manager: ClientManager,
state: State,
next_token: usize,
}
const UDP_RX: Token = Token(0);
@@ -35,17 +37,22 @@ const PRODUCER_RX: Token = Token(2);
#[cfg(not(windows))]
const SIGNAL: Token = Token(3);
const MAX_TOKEN: usize = 4;
impl Server {
pub fn new(
port: u16,
mut producer: Box<dyn EventProducer>,
consumer: Box<dyn EventConsumer>,
mut frontend: FrontendAdapter,
) -> Result<Self> {
mut frontend: FrontendListener,
) -> anyhow::Result<Self> {
// bind the udp socket
let listen_addr = SocketAddr::new("0.0.0.0".parse().unwrap(), port);
let mut socket = UdpSocket::bind(listen_addr)?;
// create dns resolver
let resolver = dns::DnsResolver::new()?;
// register event sources
let poll = Poll::new()?;
@@ -55,7 +62,7 @@ impl Server {
#[cfg(not(windows))]
poll.registry().register(&mut signals, SIGNAL, Interest::READABLE)?;
poll.registry().register(&mut socket, UDP_RX, Interest::READABLE | Interest::WRITABLE)?;
poll.registry().register(&mut socket, UDP_RX, Interest::READABLE)?;
poll.registry().register(&mut producer, PRODUCER_RX, Interest::READABLE)?;
poll.registry().register(&mut frontend, FRONTEND_RX, Interest::READABLE)?;
@@ -63,10 +70,12 @@ impl Server {
let client_manager = ClientManager::new();
Ok(Server {
poll, socket, consumer, producer,
resolver,
#[cfg(not(windows))]
signals, frontend,
client_manager,
state: State::Receiving,
next_token: MAX_TOKEN,
})
}
@@ -83,19 +92,105 @@ impl Server {
match event.token() {
UDP_RX => self.handle_udp_rx(),
PRODUCER_RX => self.handle_producer_rx(),
FRONTEND_RX => if self.handle_frontend_rx() { return Ok(()) },
FRONTEND_RX => self.handle_frontend_incoming(),
#[cfg(not(windows))]
SIGNAL => if self.handle_signal() { return Ok(()) },
_ => panic!("what happened here?")
_ => if self.handle_frontend_event(event.token()) { return Ok(()) },
}
}
}
}
pub fn add_client(&mut self, addr: HashSet<SocketAddr>, pos: Position) {
let client = self.client_manager.add_client(addr, pos);
self.producer.notify(ClientEvent::Create(client, pos));
self.consumer.notify(ClientEvent::Create(client, pos));
pub fn add_client(&mut self, hostname: Option<String>, mut addr: HashSet<IpAddr>, port: u16, pos: Position) -> ClientHandle {
let ips = if let Some(hostname) = hostname.as_ref() {
HashSet::from_iter(self.resolver.resolve(hostname.as_str()).ok().iter().flatten().cloned())
} else {
HashSet::new()
};
addr.extend(ips.iter());
log::info!("adding client [{}]{} @ {:?}", pos, hostname.as_deref().unwrap_or(""), &ips);
let client = self.client_manager.add_client(hostname.clone(), addr, port, pos);
log::debug!("add_client {client}");
let notify = FrontendNotify::NotifyClientCreate(client, hostname, port, pos);
if let Err(e) = self.frontend.notify_all(notify) {
log::error!("{e}");
};
client
}
pub fn activate_client(&mut self, client: ClientHandle, active: bool) {
if let Some(state) = self.client_manager.get_mut(client) {
state.active = active;
if state.active {
self.producer.notify(ClientEvent::Create(client, state.client.pos));
self.consumer.notify(ClientEvent::Create(client, state.client.pos));
} else {
self.producer.notify(ClientEvent::Destroy(client));
self.consumer.notify(ClientEvent::Destroy(client));
}
}
}
pub fn remove_client(&mut self, client: ClientHandle) -> Option<ClientHandle> {
self.producer.notify(ClientEvent::Destroy(client));
self.consumer.notify(ClientEvent::Destroy(client));
if let Some(client) = self.client_manager.remove_client(client).map(|s| s.client.handle) {
let notify = FrontendNotify::NotifyClientDelete(client);
log::debug!("{notify:?}");
if let Err(e) = self.frontend.notify_all(notify) {
log::error!("{e}");
}
Some(client)
} else {
None
}
}
pub fn update_client(
&mut self,
client: ClientHandle,
hostname: Option<String>,
port: u16,
pos: Position,
) {
// retrieve state
let Some(state) = self.client_manager.get_mut(client) else {
return
};
// update pos
state.client.pos = pos;
if state.active {
self.producer.notify(ClientEvent::Destroy(client));
self.consumer.notify(ClientEvent::Destroy(client));
self.producer.notify(ClientEvent::Create(client, pos));
self.consumer.notify(ClientEvent::Create(client, pos));
}
// update port
if state.client.port != port {
state.client.port = port;
state.client.addrs = state.client.addrs
.iter()
.cloned()
.map(|mut a| { a.set_port(port); a })
.collect();
state.client.active_addr.map(|a| { SocketAddr::new(a.ip(), port) });
}
// update hostname
if state.client.hostname != hostname {
state.client.addrs = HashSet::new();
state.client.active_addr = None;
state.client.hostname = hostname;
if let Some(hostname) = state.client.hostname.as_ref() {
if let Ok(ips) = self.resolver.resolve(hostname.as_str()) {
let addrs = ips.iter().map(|i| SocketAddr::new(*i, port));
state.client.addrs = HashSet::from_iter(addrs);
}
}
}
log::debug!("client updated: {:?}", state);
}
fn handle_udp_rx(&mut self) {
@@ -114,7 +209,6 @@ impl Server {
continue
}
};
log::trace!("{:20} <-<-<-<------ {addr}", event.to_string());
// get handle for addr
let handle = match self.client_manager.get_client(addr) {
@@ -124,43 +218,54 @@ impl Server {
continue
}
};
log::trace!("{:20} <-<-<-<------ {addr} ({handle})", event.to_string());
let state = match self.client_manager.get_mut(handle) {
Some(s) => s,
None => {
log::error!("unknown handle");
continue
}
};
// reset ttl for client and set addr as new default for this client
self.client_manager.reset_last_seen(handle);
self.client_manager.set_default_addr(handle, addr);
// reset ttl for client and
state.last_seen = Some(Instant::now());
// set addr as new default for this client
state.client.active_addr = Some(addr);
match (event, addr) {
(Event::Pong(), _) => {},
(Event::Ping(), addr) => {
if let Err(e) = Self::send_event(&self.socket, Event::Pong(), addr) {
log::error!("udp send: {}", e);
}
// we release the mouse here,
// since its very likely, that we wont get a release event
self.producer.release();
}
(event, addr) => {
match self.state {
State::Sending => {
// in sending state, we dont want to process
// any events to avoid feedback loops,
// therefore we tell the event producer
// to release the pointer and move on
// first event -> release pointer
if let Event::Release() = event {
log::debug!("releasing pointer ...");
self.producer.release();
self.state = State::Receiving;
}
(event, addr) => match self.state {
State::Sending => {
// in sending state, we dont want to process
// any events to avoid feedback loops,
// therefore we tell the event producer
// to release the pointer and move on
// first event -> release pointer
if let Event::Release() = event {
log::debug!("releasing pointer ...");
self.producer.release();
self.state = State::Receiving;
}
State::Receiving => {
// consume event
self.consumer.consume(event, handle);
}
State::Receiving => {
// consume event
self.consumer.consume(event, handle);
// let the server know we are still alive once every second
let last_replied = self.client_manager.last_replied(handle);
if last_replied.is_none()
|| last_replied.is_some() && last_replied.unwrap() > Duration::from_secs(1) {
self.client_manager.reset_last_replied(handle);
if let Err(e) = Self::send_event(&self.socket, Event::Pong(), addr) {
log::error!("udp send: {}", e);
}
// let the server know we are still alive once every second
let last_replied = state.last_replied;
if last_replied.is_none()
|| last_replied.is_some()
&& last_replied.unwrap().elapsed() > Duration::from_secs(1) {
state.last_replied = Some(Instant::now());
if let Err(e) = Self::send_event(&self.socket, Event::Pong(), addr) {
log::error!("udp send: {}", e);
}
}
}
@@ -171,16 +276,25 @@ impl Server {
fn handle_producer_rx(&mut self) {
let events = self.producer.read_events();
let mut should_release = false;
for (c, e) in events.into_iter() {
// in receiving state, only release events
// must be transmitted
if let Event::Release() = e {
self.state = State::Sending;
}
log::trace!("producer: ({c}) {e:?}");
let state = match self.client_manager.get_mut(c) {
Some(state) => state,
None => {
log::warn!("unknown client!");
continue
}
};
// otherwise we should have an address to send to
// transmit events to the corrensponding client
if let Some(addr) = self.client_manager.get_active_addr(c) {
log::trace!("{:20} ------>->->-> {addr}", e.to_string());
if let Some(addr) = state.client.active_addr {
if let Err(e) = Self::send_event(&self.socket, e, addr) {
log::error!("udp send: {}", e);
}
@@ -189,57 +303,113 @@ impl Server {
// if client last responded > 2 seconds ago
// and we have not sent a ping since 500 milliseconds,
// send a ping
let last_seen = self.client_manager.last_seen(c);
let last_ping = self.client_manager.last_ping(c);
if last_seen.is_some() && last_seen.unwrap() < Duration::from_secs(2) {
if state.last_seen.is_some()
&& state.last_seen.unwrap().elapsed() < Duration::from_secs(2) {
continue
}
// client last seen > 500ms ago
if last_ping.is_some() && last_ping.unwrap() < Duration::from_millis(500) {
if state.last_ping.is_some()
&& state.last_ping.unwrap().elapsed() < Duration::from_millis(500) {
continue
}
// release mouse if client didnt respond to the first ping
if state.last_ping.is_some()
&& state.last_ping.unwrap().elapsed() < Duration::from_secs(1) {
should_release = true;
}
// last ping > 500ms ago -> ping all interfaces
self.client_manager.reset_last_ping(c);
if let Some(iter) = self.client_manager.get_addrs(c) {
for addr in iter {
log::debug!("pinging {addr}");
if let Err(e) = Self::send_event(&self.socket, Event::Ping(), addr) {
if e.kind() != ErrorKind::WouldBlock {
log::error!("udp send: {}", e);
}
state.last_ping = Some(Instant::now());
for addr in state.client.addrs.iter() {
log::debug!("pinging {addr}");
if let Err(e) = Self::send_event(&self.socket, Event::Ping(), *addr) {
if e.kind() != ErrorKind::WouldBlock {
log::error!("udp send: {}", e);
}
}
// send additional release event, in case client is still in sending mode
if let Err(e) = Self::send_event(&self.socket, Event::Release(), *addr) {
if e.kind() != ErrorKind::WouldBlock {
log::error!("udp send: {}", e);
}
}
} else {
// TODO should repeat dns lookup
}
}
if should_release && self.state != State::Receiving {
log::info!("client not responding - releasing pointer");
self.producer.release();
self.state = State::Receiving;
}
}
fn handle_frontend_rx(&mut self) -> bool {
fn handle_frontend_incoming(&mut self) {
loop {
match self.frontend.read_event() {
Ok(event) => match event {
FrontendEvent::RequestPortChange(_) => todo!(),
FrontendEvent::RequestClientAdd(addr, pos) => {
self.add_client(HashSet::from_iter(&mut [addr].into_iter()), pos);
let token = self.fresh_token();
let poll = &mut self.poll;
match self.frontend.handle_incoming(|s, i| {
poll.registry().register(s, token, i)?;
Ok(token)
}) {
Err(e) if e.kind() == ErrorKind::WouldBlock => break,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
log::error!("{e}");
break
}
_ => continue,
}
}
// notify new frontend connections of current clients
self.enumerate();
}
fn handle_frontend_event(&mut self, token: Token) -> bool {
loop {
let event = match self.frontend.read_event(token) {
Ok(event) => event,
Err(e) if e.kind() == ErrorKind::WouldBlock => return false,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
log::error!("{e}");
return false;
}
};
if let Some(event) = event {
log::debug!("frontend: {event:?}");
match event {
FrontendEvent::AddClient(hostname, port, pos) => {
self.add_client(hostname, HashSet::new(), port, pos);
}
FrontendEvent::RequestClientDelete(_) => todo!(),
FrontendEvent::RequestClientUpdate(_) => todo!(),
FrontendEvent::RequestShutdown() => {
FrontendEvent::ActivateClient(client, active) => {
self.activate_client(client, active);
}
FrontendEvent::DelClient(client) => {
self.remove_client(client);
}
FrontendEvent::UpdateClient(client, hostname, port, pos) => {
self.update_client(client, hostname, port, pos);
}
FrontendEvent::Enumerate() => self.enumerate(),
FrontendEvent::Shutdown() => {
log::info!("terminating gracefully...");
return true;
},
}
Err(e) if e.kind() == ErrorKind::WouldBlock => return false,
Err(e) => {
log::error!("frontend: {e}");
}
}
}
}
fn enumerate(&mut self) {
let clients = self.client_manager.enumerate();
if let Err(e) = self.frontend.notify_all(FrontendNotify::Enumerate(clients)) {
log::error!("{e}");
}
}
#[cfg(not(windows))]
fn handle_signal(&mut self) -> bool {
#[cfg(windows)]
@@ -266,6 +436,7 @@ impl Server {
}
fn send_event(sock: &UdpSocket, e: Event, addr: SocketAddr) -> Result<usize> {
log::trace!("{:20} ------>->->-> {addr}", e.to_string());
let data: Vec<u8> = (&e).into();
// We are currently abusing a blocking send to get the lowest possible latency.
// It may be better to set the socket to non-blocking and only send when ready.
@@ -279,4 +450,16 @@ impl Server {
Err(e) => Err(Box::new(e)),
}
}
fn fresh_token(&mut self) -> Token {
let token = self.next_token as usize;
self.next_token += 1;
Token(token)
}
pub fn register_frontend(&mut self, source: &mut dyn Source, interests: Interest) -> Result<Token> {
let token = self.fresh_token();
self.poll.registry().register(source, token, interests)?;
Ok(token)
}
}

View File

@@ -1,19 +1,25 @@
use std::io::{Read, Result};
use std::{str, net::SocketAddr};
use std::collections::HashMap;
use std::io::{Read, Result, Write};
use std::str;
#[cfg(unix)]
use std::{env, path::{Path, PathBuf}};
use mio::Interest;
use mio::{Registry, Token, event::Source};
#[cfg(unix)]
use mio::net::UnixStream;
#[cfg(unix)]
use mio::net::UnixListener;
#[cfg(windows)]
use mio::net::TcpStream;
#[cfg(windows)]
use mio::net::TcpListener;
use serde::{Serialize, Deserialize};
use crate::client::{Client, Position};
use crate::client::{Position, ClientHandle, Client};
/// cli frontend
pub mod cli;
@@ -24,33 +30,50 @@ pub mod gtk;
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum FrontendEvent {
RequestPortChange(u16),
RequestClientAdd(SocketAddr, Position),
RequestClientDelete(Client),
RequestClientUpdate(Client),
RequestShutdown(),
/// add a new client
AddClient(Option<String>, u16, Position),
/// activate/deactivate client
ActivateClient(ClientHandle, bool),
/// update a client (hostname, port, position)
UpdateClient(ClientHandle, Option<String>, u16, Position),
/// remove a client
DelClient(ClientHandle),
/// request an enumertaion of all clients
Enumerate(),
/// service shutdown
Shutdown(),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FrontendNotify {
NotifyClientCreate(Client),
NotifyClientCreate(ClientHandle, Option<String>, u16, Position),
NotifyClientUpdate(ClientHandle, Option<String>, u16, Position),
NotifyClientDelete(ClientHandle),
Enumerate(Vec<(Client, bool)>),
NotifyError(String),
}
pub struct FrontendAdapter {
pub struct FrontendListener {
#[cfg(windows)]
listener: TcpListener,
#[cfg(unix)]
listener: UnixListener,
#[cfg(unix)]
socket_path: PathBuf,
frontend_connections: HashMap<Token, FrontendConnection>,
}
impl FrontendAdapter {
impl FrontendListener {
pub fn new() -> std::result::Result<Self, Box<dyn std::error::Error>> {
#[cfg(unix)]
let socket_path = Path::new(env::var("XDG_RUNTIME_DIR")?.as_str()).join("lan-mouse-socket.sock");
#[cfg(unix)]
log::debug!("remove socket: {:?}", socket_path);
#[cfg(unix)]
if socket_path.exists() {
std::fs::remove_file(&socket_path).unwrap();
}
#[cfg(unix)]
let listener = UnixListener::bind(&socket_path)?;
#[cfg(windows)]
@@ -60,27 +83,57 @@ impl FrontendAdapter {
listener,
#[cfg(unix)]
socket_path,
frontend_connections: HashMap::new(),
};
Ok(adapter)
}
pub fn read_event(&mut self) -> Result<FrontendEvent>{
#[cfg(unix)]
pub fn handle_incoming<F>(&mut self, register_frontend: F) -> Result<()>
where F: Fn(&mut UnixStream, Interest) -> Result<Token> {
let (mut stream, _) = self.listener.accept()?;
let mut buf = [0u8; 128]; // FIXME
stream.read(&mut buf)?;
let json = str::from_utf8(&buf)
.unwrap()
.trim_end_matches(char::from(0)); // remove trailing 0-bytes
let event = serde_json::from_str(json).unwrap();
log::debug!("{:?}", event);
Ok(event)
let token = register_frontend(&mut stream, Interest::READABLE)?;
let con = FrontendConnection::new(stream);
self.frontend_connections.insert(token, con);
Ok(())
}
pub fn notify(&self, _event: FrontendNotify) { }
#[cfg(windows)]
pub fn handle_incoming<F>(&mut self, register_frontend: F) -> Result<()>
where F: Fn(&mut TcpStream, Interest) -> Result<Token> {
let (mut stream, _) = self.listener.accept()?;
let token = register_frontend(&mut stream, Interest::READABLE)?;
let con = FrontendConnection::new(stream);
self.frontend_connections.insert(token, con);
Ok(())
}
pub fn read_event(&mut self, token: Token) -> Result<Option<FrontendEvent>> {
if let Some(con) = self.frontend_connections.get_mut(&token) {
con.handle_event()
} else {
panic!("unknown token");
}
}
pub(crate) fn notify_all(&mut self, notify: FrontendNotify) -> Result<()> {
// encode event
let json = serde_json::to_string(&notify).unwrap();
let payload = json.as_bytes();
let len = payload.len().to_ne_bytes();
log::debug!("json: {json}, len: {}", payload.len());
for con in self.frontend_connections.values_mut() {
// write len + payload
con.stream.write(&len)?;
con.stream.write(payload)?;
}
Ok(())
}
}
impl Source for FrontendAdapter {
impl Source for FrontendListener {
fn register(
&mut self,
registry: &Registry,
@@ -105,11 +158,79 @@ impl Source for FrontendAdapter {
}
#[cfg(unix)]
impl Drop for FrontendAdapter {
impl Drop for FrontendListener {
fn drop(&mut self) {
log::debug!("remove socket: {:?}", self.socket_path);
std::fs::remove_file(&self.socket_path).unwrap();
let _ = std::fs::remove_file(&self.socket_path);
}
}
pub trait Frontend { }
enum ReceiveState {
Len, Data,
}
pub struct FrontendConnection {
#[cfg(unix)]
stream: UnixStream,
#[cfg(windows)]
stream: TcpStream,
state: ReceiveState,
len: usize,
len_buf: [u8; std::mem::size_of::<usize>()],
recieve_buf: [u8; 256], // FIXME
pos: usize,
}
impl FrontendConnection {
#[cfg(unix)]
pub fn new(stream: UnixStream) -> Self {
Self {
stream,
state: ReceiveState::Len,
len: 0,
len_buf: [0u8; std::mem::size_of::<usize>()],
recieve_buf: [0u8; 256],
pos: 0,
}
}
#[cfg(windows)]
pub fn new(stream: TcpStream) -> Self {
Self {
stream,
state: ReceiveState::Len,
len: 0,
len_buf: [0u8; std::mem::size_of::<usize>()],
recieve_buf: [0u8; 256],
pos: 0,
}
}
pub fn handle_event(&mut self) -> Result<Option<FrontendEvent>> {
match self.state {
ReceiveState::Len => {
// we receive sizeof(usize) Bytes
let n = self.stream.read(&mut self.len_buf)?;
self.pos += n;
if self.pos == self.len_buf.len() {
self.state = ReceiveState::Data;
self.len = usize::from_ne_bytes(self.len_buf);
self.pos = 0;
}
Ok(None)
},
ReceiveState::Data => {
// read at most as many bytes as the length of the next event
let n = self.stream.read(&mut self.recieve_buf[..self.len])?;
self.pos += n;
if n == self.len {
self.state = ReceiveState::Len;
self.pos = 0;
Ok(Some(serde_json::from_slice(&self.recieve_buf[..self.len])?))
} else {
Ok(None)
}
}
}
}
}

View File

@@ -1,5 +1,5 @@
use anyhow::Result;
use std::{thread, io::Write, net::SocketAddr};
use anyhow::{anyhow, Result, Context};
use std::{thread::{self, JoinHandle}, io::{Write, Read, ErrorKind}, str::SplitWhitespace};
#[cfg(windows)]
use std::net::SocketAddrV4;
@@ -8,78 +8,190 @@ use std::{os::unix::net::UnixStream, path::Path, env};
#[cfg(windows)]
use std::net::TcpStream;
use crate::client::Position;
use crate::{client::Position, config::DEFAULT_PORT};
use super::{FrontendEvent, Frontend};
use super::{FrontendEvent, FrontendNotify};
pub struct CliFrontend;
pub fn start() -> Result<(JoinHandle<()>, JoinHandle<()>)> {
#[cfg(unix)]
let socket_path = Path::new(env::var("XDG_RUNTIME_DIR")?.as_str()).join("lan-mouse-socket.sock");
impl Frontend for CliFrontend {}
#[cfg(unix)]
let Ok(mut tx) = UnixStream::connect(&socket_path) else {
return Err(anyhow!("Could not connect to lan-mouse-socket"));
};
impl CliFrontend {
pub fn new() -> Result<CliFrontend> {
#[cfg(unix)]
let socket_path = Path::new(env::var("XDG_RUNTIME_DIR")?.as_str()).join("lan-mouse-socket.sock");
thread::Builder::new()
.name("cli-frontend".to_string())
.spawn(move || {
loop {
eprint!("lan-mouse > ");
std::io::stderr().flush().unwrap();
let mut buf = String::new();
match std::io::stdin().read_line(&mut buf) {
Ok(len) => {
if let Some(event) = parse_event(buf, len) {
#[cfg(unix)]
let Ok(mut stream) = UnixStream::connect(&socket_path) else {
log::error!("Could not connect to lan-mouse-socket");
continue;
};
#[cfg(windows)]
let Ok(mut stream) = TcpStream::connect("127.0.0.1:5252".parse::<SocketAddrV4>().unwrap()) else {
log::error!("Could not connect to lan-mouse-server");
continue;
};
#[cfg(windows)]
let Ok(mut tx) = TcpStream::connect("127.0.0.1:5252".parse::<SocketAddrV4>().unwrap()) else {
return Err(anyhow!("Could not connect to lan-mouse-socket"));
};
let mut rx = tx.try_clone()?;
let reader = thread::Builder::new()
.name("cli-frontend".to_string())
.spawn(move || {
// all further prompts
prompt();
loop {
let mut buf = String::new();
match std::io::stdin().read_line(&mut buf) {
Ok(0) => break,
Ok(len) => {
if let Some(events) = parse_cmd(buf, len) {
for event in events.iter() {
let json = serde_json::to_string(&event).unwrap();
if let Err(e) = stream.write(json.as_bytes()) {
let bytes = json.as_bytes();
let len = bytes.len().to_ne_bytes();
if let Err(e) = tx.write(&len) {
log::error!("error sending message: {e}");
};
if event == FrontendEvent::RequestShutdown() {
if let Err(e) = tx.write(bytes) {
log::error!("error sending message: {e}");
};
if *event == FrontendEvent::Shutdown() {
break;
}
}
}
Err(e) => {
log::error!("{e:?}");
break
// prompt is printed after the server response is received
} else {
prompt();
}
}
Err(e) => {
log::error!("error reading from stdin: {e}");
break
}
}
}).unwrap();
Ok(Self {})
}
}
})?;
let writer = thread::Builder::new()
.name("cli-frontend-notify".to_string())
.spawn(move || {
loop {
// read len
let mut len = [0u8; 8];
match rx.read_exact(&mut len) {
Ok(()) => (),
Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
Err(e) => break log::error!("{e}"),
};
let len = usize::from_ne_bytes(len);
// read payload
let mut buf: Vec<u8> = vec![0u8; len];
match rx.read_exact(&mut buf[..len]) {
Ok(()) => (),
Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
Err(e) => break log::error!("{e}"),
};
let notify: FrontendNotify = match serde_json::from_slice(&buf) {
Ok(n) => n,
Err(e) => break log::error!("{e}"),
};
match notify {
FrontendNotify::NotifyClientCreate(client, host, port, pos) => {
log::info!("new client ({client}): {}:{port} - {pos}", host.as_deref().unwrap_or(""));
},
FrontendNotify::NotifyClientUpdate(client, host, port, pos) => {
log::info!("client ({client}) updated: {}:{port} - {pos}", host.as_deref().unwrap_or(""));
},
FrontendNotify::NotifyClientDelete(client) => {
log::info!("client ({client}) deleted.");
},
FrontendNotify::NotifyError(e) => {
log::warn!("{e}");
},
FrontendNotify::Enumerate(clients) => {
for (client, active) in clients.into_iter() {
log::info!("client ({}) [{}]: active: {}, associated addresses: [{}]",
client.handle,
client.hostname.as_deref().unwrap_or(""),
if active { "yes" } else { "no" },
client.addrs.into_iter().map(|a| a.to_string())
.collect::<Vec<String>>()
.join(", ")
);
}
}
}
prompt();
}
})?;
Ok((reader, writer))
}
fn parse_event(s: String, len: usize) -> Option<FrontendEvent> {
fn prompt() {
eprint!("lan-mouse > ");
std::io::stderr().flush().unwrap();
}
fn parse_cmd(s: String, len: usize) -> Option<Vec<FrontendEvent>> {
if len == 0 {
return Some(FrontendEvent::RequestShutdown())
return Some(vec![FrontendEvent::Shutdown()])
}
let mut l = s.split_whitespace();
let cmd = l.next()?;
match cmd {
"connect" => {
let addr = match l.next()?.parse() {
Ok(addr) => SocketAddr::V4(addr),
Err(e) => {
log::error!("parse error: {e}");
return None;
}
};
Some(FrontendEvent::RequestClientAdd(addr, Position::Left ))
let res = match cmd {
"help" => {
log::info!("list list clients");
log::info!("connect <host> left|right|top|bottom [port] add a new client");
log::info!("disconnect <client> remove a client");
log::info!("activate <client> activate a client");
log::info!("deactivate <client> deactivate a client");
log::info!("exit exit lan-mouse");
None
}
"exit" => return Some(vec![FrontendEvent::Shutdown()]),
"list" => return Some(vec![FrontendEvent::Enumerate()]),
"connect" => Some(parse_connect(l)),
"disconnect" => Some(parse_disconnect(l)),
"activate" => Some(parse_activate(l)),
"deactivate" => Some(parse_deactivate(l)),
_ => {
log::error!("unknown command: {s}");
None
}
};
match res {
Some(Ok(e)) => Some(vec![e, FrontendEvent::Enumerate()]),
Some(Err(e)) => {
log::warn!("{e}");
None
}
_ => None
}
}
fn parse_connect(mut l: SplitWhitespace) -> Result<FrontendEvent> {
let usage = "usage: connect <host> left|right|top|bottom [port]";
let host = l.next().context(usage)?.to_owned();
let pos = match l.next().context(usage)? {
"right" => Position::Right,
"top" => Position::Top,
"bottom" => Position::Bottom,
_ => Position::Left,
};
let port = if let Some(p) = l.next() {
p.parse()?
} else {
DEFAULT_PORT
};
Ok(FrontendEvent::AddClient(Some(host), port, pos))
}
fn parse_disconnect(mut l: SplitWhitespace) -> Result<FrontendEvent> {
let client = l.next().context("usage: disconnect <client_id>")?.parse()?;
Ok(FrontendEvent::DelClient(client))
}
fn parse_activate(mut l: SplitWhitespace) -> Result<FrontendEvent> {
let client = l.next().context("usage: activate <client_id>")?.parse()?;
Ok(FrontendEvent::ActivateClient(client, true))
}
fn parse_deactivate(mut l: SplitWhitespace) -> Result<FrontendEvent> {
let client = l.next().context("usage: deactivate <client_id>")?.parse()?;
Ok(FrontendEvent::ActivateClient(client, false))
}

187
src/frontend/gtk.rs Normal file
View File

@@ -0,0 +1,187 @@
mod window;
mod client_object;
mod client_row;
use std::{io::{Result, Read, ErrorKind}, thread::{self, JoinHandle}, env, process, path::Path, os::unix::net::UnixStream, str};
use crate::{frontend::gtk::window::Window, config::DEFAULT_PORT};
use gtk::{prelude::*, IconTheme, gdk::Display, gio::{SimpleAction, SimpleActionGroup}, glib::{clone, MainContext, Priority}, CssProvider, subclass::prelude::ObjectSubclassIsExt};
use adw::Application;
use gtk::{gio, glib, prelude::ApplicationExt};
use self::client_object::ClientObject;
use super::FrontendNotify;
pub fn start() -> Result<JoinHandle<glib::ExitCode>> {
thread::Builder::new()
.name("gtk-thread".into())
.spawn(gtk_main)
}
fn gtk_main() -> glib::ExitCode {
gio::resources_register_include!("lan-mouse.gresource")
.expect("Failed to register resources.");
let app = Application::builder()
.application_id("de.feschber.lan-mouse")
.build();
app.connect_startup(|_| load_icons());
app.connect_startup(|_| load_css());
app.connect_activate(build_ui);
app.run()
}
fn load_css() {
let provider = CssProvider::new();
provider.load_from_resource("de/feschber/LanMouse/style.css");
gtk::style_context_add_provider_for_display(
&Display::default().expect("Could not connect to a display."),
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
fn load_icons() {
let icon_theme = IconTheme::for_display(&Display::default().expect("Could not connect to a display."));
icon_theme.add_resource_path("/de/feschber/LanMouse/icons");
}
fn build_ui(app: &Application) {
let xdg_runtime_dir = match env::var("XDG_RUNTIME_DIR") {
Ok(v) => v,
Err(e) => {
log::error!("{e}");
process::exit(1);
}
};
let socket_path = Path::new(xdg_runtime_dir.as_str())
.join("lan-mouse-socket.sock");
let Ok(mut rx) = UnixStream::connect(&socket_path) else {
log::error!("Could not connect to lan-mouse-socket @ {socket_path:?}");
process::exit(1);
};
let tx = match rx.try_clone() {
Ok(sock) => sock,
Err(e) => {
log::error!("{e}");
process::exit(1);
}
};
let (sender, receiver) = MainContext::channel::<FrontendNotify>(Priority::default());
gio::spawn_blocking(move || {
match loop {
// read length
let mut len = [0u8; 8];
match rx.read_exact(&mut len) {
Ok(_) => (),
Err(e) if e.kind() == ErrorKind::UnexpectedEof => break Ok(()),
Err(e) => break Err(e),
};
let len = usize::from_ne_bytes(len);
// read payload
let mut buf = vec![0u8; len];
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(notify).unwrap(),
Err(e) => log::error!("{e}"),
}
} {
Ok(()) => {},
Err(e) => log::error!("{e}"),
}
});
let window = Window::new(app);
window.imp().stream.borrow_mut().replace(tx);
receiver.attach(None, clone!(@weak window => @default-return glib::ControlFlow::Break,
move |notify| {
match notify {
FrontendNotify::NotifyClientCreate(client, hostname, port, position) => {
window.new_client(client, hostname, port, position, false);
},
FrontendNotify::NotifyClientUpdate(client, hostname, port, position) => {
log::info!("client updated: {client}, {}:{port}, {position}", hostname.unwrap_or("".to_string()));
}
FrontendNotify::NotifyError(e) => {
// TODO
log::error!("{e}");
},
FrontendNotify::NotifyClientDelete(client) => {
window.delete_client(client);
}
FrontendNotify::Enumerate(clients) => {
for (client, active) in clients {
if window.client_idx(client.handle).is_some() {
continue
}
window.new_client(
client.handle,
client.hostname,
client.addrs
.iter()
.next()
.map(|s| s.port())
.unwrap_or(DEFAULT_PORT),
client.pos,
active,
);
}
},
}
glib::ControlFlow::Continue
}
));
let action_request_client_update = SimpleAction::new(
"request-client-update",
Some(&u32::static_variant_type()),
);
// remove client
let action_client_delete = SimpleAction::new(
"request-client-delete",
Some(&u32::static_variant_type()),
);
// update client state
action_request_client_update.connect_activate(clone!(@weak window => move |_action, param| {
log::debug!("request-client-update");
let index = param.unwrap()
.get::<u32>()
.unwrap();
let Some(client) = window.clients().item(index as u32) else {
return;
};
let client = client.downcast_ref::<ClientObject>().unwrap();
window.request_client_update(client);
}));
action_client_delete.connect_activate(clone!(@weak window => move |_action, param| {
log::debug!("delete-client");
let idx = param.unwrap()
.get::<u32>()
.unwrap();
window.request_client_delete(idx);
}));
let actions = SimpleActionGroup::new();
window.insert_action_group("win", Some(&actions));
actions.add_action(&action_request_client_update);
actions.add_action(&action_client_delete);
window.present();
}

View File

@@ -0,0 +1,35 @@
mod imp;
use gtk::glib::{self, Object};
use adw::subclass::prelude::*;
use crate::client::ClientHandle;
glib::wrapper! {
pub struct ClientObject(ObjectSubclass<imp::ClientObject>);
}
impl ClientObject {
pub fn new(handle: ClientHandle, hostname: Option<String>, port: u32, position: String, active: bool) -> Self {
Object::builder()
.property("handle", handle)
.property("hostname", hostname)
.property("port", port)
.property("active", active)
.property("position", position)
.build()
}
pub fn get_data(&self) -> ClientData {
self.imp().data.borrow().clone()
}
}
#[derive(Default, Clone)]
pub struct ClientData {
pub handle: ClientHandle,
pub hostname: Option<String>,
pub port: u32,
pub active: bool,
pub position: String,
}

View File

@@ -0,0 +1,30 @@
use std::cell::RefCell;
use glib::Properties;
use gtk::glib;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use crate::client::ClientHandle;
use super::ClientData;
#[derive(Properties, Default)]
#[properties(wrapper_type = super::ClientObject)]
pub struct ClientObject {
#[property(name = "handle", get, set, type = ClientHandle, member = handle)]
#[property(name = "hostname", get, set, type = String, member = hostname)]
#[property(name = "port", get, set, type = u32, member = port, maximum = u16::MAX as u32)]
#[property(name = "active", get, set, type = bool, member = active)]
#[property(name = "position", get, set, type = String, member = position)]
pub data: RefCell<ClientData>,
}
#[glib::object_subclass]
impl ObjectSubclass for ClientObject {
const NAME: &'static str = "ClientObject";
type Type = super::ClientObject;
}
#[glib::derived_properties]
impl ObjectImpl for ClientObject {}

View File

@@ -0,0 +1,125 @@
mod imp;
use adw::prelude::*;
use adw::subclass::prelude::*;
use gtk::glib::{self, Object};
use crate::config::DEFAULT_PORT;
use super::ClientObject;
glib::wrapper! {
pub struct ClientRow(ObjectSubclass<imp::ClientRow>)
@extends gtk::ListBoxRow, gtk::Widget, adw::PreferencesRow, adw::ExpanderRow,
@implements gtk::Accessible, gtk::Actionable, gtk::Buildable, gtk::ConstraintTarget;
}
impl ClientRow {
pub fn new(_client_object: &ClientObject) -> Self {
Object::builder()
.build()
}
pub fn bind(&self, client_object: &ClientObject) {
let mut bindings = self.imp().bindings.borrow_mut();
let active_binding = client_object
.bind_property("active", &self.imp().enable_switch.get(), "state")
.bidirectional()
.sync_create()
.build();
let hostname_binding = client_object
.bind_property("hostname", &self.imp().hostname.get(), "text")
.transform_to(|_, v: Option<String>| {
if let Some(hostname) = v {
Some(hostname)
} else {
Some("".to_string())
}
})
.transform_from(|_, v: String| {
if v.as_str().trim() == "" {
Some(None)
} else {
Some(Some(v))
}
})
.bidirectional()
.sync_create()
.build();
let title_binding = client_object
.bind_property("hostname", self, "title")
.transform_to(|_, v: Option<String>| {
if let Some(hostname) = v {
Some(hostname)
} else {
Some("<span font_style=\"italic\" font_weight=\"light\" foreground=\"darkgrey\">no hostname!</span>".to_string())
}
})
.sync_create()
.build();
let port_binding = client_object
.bind_property("port", &self.imp().port.get(), "text")
.transform_from(|_, v: String| {
if v == "" {
Some(DEFAULT_PORT as u32)
} else {
Some(v.parse::<u16>().unwrap_or(DEFAULT_PORT) as u32)
}
})
.transform_to(|_, v: u32| {
if v == 4242 {
Some("".to_string())
} else {
Some(v.to_string())
}
})
.bidirectional()
.sync_create()
.build();
let subtitle_binding = client_object
.bind_property("port", self, "subtitle")
.sync_create()
.build();
let position_binding = client_object
.bind_property("position", &self.imp().position.get(), "selected")
.transform_from(|_, v: u32| {
match v {
1 => Some("right"),
2 => Some("top"),
3 => Some("bottom"),
_ => Some("left"),
}
})
.transform_to(|_, v: String| {
match v.as_str() {
"right" => Some(1),
"top" => Some(2u32),
"bottom" => Some(3u32),
_ => Some(0u32),
}
})
.bidirectional()
.sync_create()
.build();
bindings.push(active_binding);
bindings.push(hostname_binding);
bindings.push(title_binding);
bindings.push(port_binding);
bindings.push(subtitle_binding);
bindings.push(position_binding);
}
pub fn unbind(&self) {
for binding in self.imp().bindings.borrow_mut().drain(..) {
binding.unbind();
}
}
}

View File

@@ -0,0 +1,78 @@
use std::cell::RefCell;
use glib::{Binding, subclass::InitializingObject};
use adw::{prelude::*, ComboRow, ActionRow};
use adw::subclass::prelude::*;
use gtk::glib::clone;
use gtk::{glib, CompositeTemplate, Switch, Button};
#[derive(CompositeTemplate, Default)]
#[template(resource = "/de/feschber/LanMouse/client_row.ui")]
pub struct ClientRow {
#[template_child]
pub enable_switch: TemplateChild<gtk::Switch>,
#[template_child]
pub hostname: TemplateChild<gtk::Entry>,
#[template_child]
pub port: TemplateChild<gtk::Entry>,
#[template_child]
pub position: TemplateChild<ComboRow>,
#[template_child]
pub delete_row: TemplateChild<ActionRow>,
#[template_child]
pub delete_button: TemplateChild<gtk::Button>,
pub bindings: RefCell<Vec<Binding>>,
}
#[glib::object_subclass]
impl ObjectSubclass for ClientRow {
// `NAME` needs to match `class` attribute of template
const NAME: &'static str = "ClientRow";
type Type = super::ClientRow;
type ParentType = adw::ExpanderRow;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
klass.bind_template_callbacks();
}
fn instance_init(obj: &InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for ClientRow {
fn constructed(&self) {
self.parent_constructed();
self.delete_button.connect_clicked(clone!(@weak self as row => move |button| {
row.handle_client_delete(button);
}));
}
}
#[gtk::template_callbacks]
impl ClientRow {
#[template_callback]
fn handle_client_set_state(&self, state: bool, switch: &Switch) -> bool {
let idx = self.obj().index() as u32;
switch.activate_action("win.request-client-update", Some(&idx.to_variant())).unwrap();
switch.set_state(state);
true // dont run default handler
}
#[template_callback]
fn handle_client_delete(&self, button: &Button) {
log::debug!("delete button pressed");
let idx = self.obj().index() as u32;
button
.activate_action("win.request-client-delete", Some(&idx.to_variant()))
.unwrap();
}
}
impl WidgetImpl for ClientRow {}
impl BoxImpl for ClientRow {}
impl ListBoxRowImpl for ClientRow {}
impl PreferencesRowImpl for ClientRow {}
impl ExpanderRowImpl for ClientRow {}

160
src/frontend/gtk/window.rs Normal file
View File

@@ -0,0 +1,160 @@
mod imp;
use std::io::Write;
use adw::prelude::*;
use adw::subclass::prelude::*;
use gtk::{glib, gio, NoSelection};
use glib::{clone, Object};
use crate::{frontend::{gtk::client_object::ClientObject, FrontendEvent}, client::{Position, ClientHandle}, config::DEFAULT_PORT};
use super::client_row::ClientRow;
glib::wrapper! {
pub struct Window(ObjectSubclass<imp::Window>)
@extends adw::ApplicationWindow, gtk::Window, gtk::Widget,
@implements gio::ActionGroup, gio::ActionMap, gtk::Accessible, gtk::Buildable,
gtk::ConstraintTarget, gtk::Native, gtk::Root, gtk::ShortcutManager;
}
impl Window {
pub(crate) fn new(app: &adw::Application) -> Self {
Object::builder().property("application", app).build()
}
pub fn clients(&self) -> gio::ListStore {
self.imp()
.clients
.borrow()
.clone()
.expect("Could not get clients")
}
fn setup_clients(&self) {
let model = gio::ListStore::new::<ClientObject>();
self.imp().clients.replace(Some(model));
let selection_model = NoSelection::new(Some(self.clients()));
self.imp().client_list.bind_model(
Some(&selection_model),
clone!(@weak self as window => @default-panic, move |obj| {
let client_object = obj.downcast_ref().expect("Expected object of type `ClientObject`.");
let row = window.create_client_row(client_object);
row.upcast()
})
);
}
/// workaround for a bug in libadwaita that shows an ugly line beneath
/// the last element if a placeholder is set.
/// https://gitlab.gnome.org/GNOME/gtk/-/merge_requests/6308
pub fn set_placeholder_visible(&self, visible: bool) {
let placeholder = self.imp().client_placeholder.get();
self.imp().client_list.set_placeholder(match visible {
true => Some(&placeholder),
false => None,
});
}
fn setup_icon(&self) {
self.set_icon_name(Some("mouse-icon"));
}
fn create_client_row(&self, client_object: &ClientObject) -> ClientRow {
let row = ClientRow::new(client_object);
row.bind(client_object);
row
}
pub fn new_client(&self, handle: ClientHandle, hostname: Option<String>, port: u16, position: Position, active: bool) {
let client = ClientObject::new(handle, hostname, port as u32, position.to_string(), active);
self.clients().append(&client);
self.set_placeholder_visible(false);
}
pub fn client_idx(&self, handle: ClientHandle) -> Option<usize> {
self.clients()
.iter::<ClientObject>()
.position(|c| {
if let Ok(c) = c {
c.handle() == handle
} else {
false
}
})
.map(|p| p as usize)
}
pub fn delete_client(&self, handle: ClientHandle) {
let Some(idx) = self.client_idx(handle) else {
log::warn!("could not find client with handle {handle}");
return;
};
self.clients().remove(idx as u32);
if self.clients().n_items() == 0 {
self.set_placeholder_visible(true);
}
}
pub fn request_client_create(&self) {
let event = FrontendEvent::AddClient(None, DEFAULT_PORT, Position::default());
self.request(event);
}
pub fn request_client_update(&self, client: &ClientObject) {
let data = client.get_data();
let position = match data.position.as_str() {
"left" => Position::Left,
"right" => Position::Right,
"top" => Position::Top,
"bottom" => Position::Bottom,
_ => {
log::error!("invalid position: {}", data.position);
return
}
};
let hostname = data.hostname;
let port = data.port as u16;
let event = FrontendEvent::UpdateClient(client.handle(), hostname, port, position);
self.request(event);
let event = FrontendEvent::ActivateClient(client.handle(), !client.active());
self.request(event);
}
pub fn request_client_delete(&self, idx: u32) {
if let Some(obj) = self.clients().item(idx) {
let client_object: &ClientObject = obj
.downcast_ref()
.expect("Expected object of type `ClientObject`.");
let handle = client_object.handle();
let event = FrontendEvent::DelClient(handle);
self.request(event);
}
}
fn request(&self, event: FrontendEvent) {
let json = serde_json::to_string(&event).unwrap();
log::debug!("requesting {json}");
let mut stream = self.imp().stream.borrow_mut();
let stream = stream.as_mut().unwrap();
let bytes = json.as_bytes();
let len = bytes.len().to_ne_bytes();
if let Err(e) = stream.write(&len) {
log::error!("error sending message: {e}");
};
if let Err(e) = stream.write(bytes) {
log::error!("error sending message: {e}");
};
}
fn setup_callbacks(&self) {
self.imp()
.add_client_button
.connect_clicked(clone!(@weak self as window => move |_| {
window.request_client_create();
}));
}
}

View File

@@ -0,0 +1,62 @@
use std::{cell::{Cell, RefCell}, os::unix::net::UnixStream};
use glib::subclass::InitializingObject;
use adw::{prelude::*, ActionRow};
use adw::subclass::prelude::*;
use gtk::{glib, Button, CompositeTemplate, ListBox, gio};
#[derive(CompositeTemplate, Default)]
#[template(resource = "/de/feschber/LanMouse/window.ui")]
pub struct Window {
pub number: Cell<i32>,
#[template_child]
pub add_client_button: TemplateChild<Button>,
#[template_child]
pub client_list: TemplateChild<ListBox>,
#[template_child]
pub client_placeholder: TemplateChild<ActionRow>,
pub clients: RefCell<Option<gio::ListStore>>,
pub stream: RefCell<Option<UnixStream>>,
}
#[glib::object_subclass]
impl ObjectSubclass for Window {
// `NAME` needs to match `class` attribute of template
const NAME: &'static str = "LanMouseWindow";
type Type = super::Window;
type ParentType = gtk::ApplicationWindow;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
klass.bind_template_callbacks();
}
fn instance_init(obj: &InitializingObject<Self>) {
obj.init_template();
}
}
#[gtk::template_callbacks]
impl Window {
#[template_callback]
fn handle_button_clicked(&self, button: &Button) {
let number_increased = self.number.get() + 1;
self.number.set(number_increased);
button.set_label(&number_increased.to_string())
}
}
impl ObjectImpl for Window {
fn constructed(&self) {
self.parent_constructed();
let obj = self.obj();
obj.setup_icon();
obj.setup_clients();
obj.setup_callbacks();
}
}
impl WidgetImpl for Window {}
impl WindowImpl for Window {}
impl ApplicationWindowImpl for Window {}

View File

@@ -3,10 +3,13 @@ use std::{process, error::Error};
use env_logger::Env;
use lan_mouse::{
consumer, producer,
config::{Config, Frontend::{Gtk, Cli}}, event::server::Server,
frontend::{FrontendAdapter, cli::CliFrontend},
config::{Config, Frontend::{Cli, Gtk}}, event::server::Server,
frontend::{FrontendListener, cli},
};
#[cfg(all(unix, feature = "gtk"))]
use lan_mouse::frontend::gtk;
pub fn main() {
// init logging
@@ -28,35 +31,25 @@ pub fn run() -> Result<(), Box<dyn Error>> {
let consumer = consumer::create()?;
// create frontend communication adapter
let frontend_adapter = FrontendAdapter::new()?;
let frontend_adapter = FrontendListener::new()?;
// start sending and receiving events
let mut event_server = Server::new(config.port, producer, consumer, frontend_adapter)?;
// add clients form config
config.get_clients().into_iter().for_each(|(c, h, p)| {
let host_name = match h {
Some(h) => format!(" '{}'", h),
None => "".to_owned(),
};
if c.len() == 0 {
log::warn!("ignoring client{} with 0 assigned ips!", host_name);
}
log::info!("adding client [{}]{} @ {:?}", p, host_name, c);
event_server.add_client(c, p);
});
// any threads need to be started after event_server sets up signal handling
match config.frontend {
Gtk => {
#[cfg(all(unix, feature = "gtk"))]
frontend::gtk::create();
#[cfg(not(feature = "gtk"))]
panic!("gtk frontend requested but feature not enabled!");
},
Cli => Box::new(CliFrontend::new()?),
#[cfg(all(unix, feature = "gtk"))]
Gtk => { gtk::start()?; }
#[cfg(any(not(feature = "gtk"), not(unix)))]
Gtk => panic!("gtk frontend requested but feature not enabled!"),
Cli => { cli::start()?; }
};
// add clients from config
config.get_clients().into_iter().for_each(|(c, h, port, p)| {
event_server.add_client(h, c, port, p);
});
log::info!("Press Ctrl+Alt+Shift+Super to release the mouse");
// run event loop
event_server.run()?;