Compare commits

..

63 Commits

Author SHA1 Message Date
Ferdinand Schober
24948773fc ensure all keys are released when emulation ends 2024-07-16 20:39:38 +02:00
Ferdinand Schober
f3de36bc26 move capture/emulation errors into their creates 2024-07-15 21:10:30 +02:00
Ferdinand Schober
3d7163bf1f move channel creation out of dns 2024-07-15 20:32:57 +02:00
Ferdinand Schober
4a90d88420 add comment 2024-07-15 12:56:36 +02:00
Ferdinand Schober
824f5b52f5 panic if dropped without being terminated 2024-07-15 12:44:56 +02:00
Ferdinand Schober
102342ce36 fix input capture test 2024-07-15 12:37:34 +02:00
Ferdinand Schober
06c6b2ec2e simplify dns 2024-07-15 08:15:27 +02:00
Ferdinand Schober
0ffeaf7e91 simplify 2024-07-14 17:56:54 +02:00
Ferdinand Schober
bd09787f72 cleanup imports 2024-07-14 17:51:16 +02:00
Ferdinand Schober
4bac6d4bae simplify 2024-07-14 14:36:36 +02:00
Ferdinand Schober
a7e7941806 reduce visibility of some structs 2024-07-14 14:32:11 +02:00
Ferdinand Schober
8fa4ea530a remove duplicate log 2024-07-14 14:18:57 +02:00
Ferdinand Schober
970575de8d simplify 2024-07-14 14:03:36 +02:00
Ferdinand Schober
151ff34383 remove debug log 2024-07-14 12:04:39 +02:00
Ferdinand Schober
8e94a64570 ignore requests with capture / emulation disabled
otherwise the server would hang when trying to enable clients
2024-07-14 12:02:14 +02:00
Ferdinand Schober
bba9400ab1 add FIXME 2024-07-12 21:01:49 +02:00
Ferdinand Schober
303a8294b9 fix unused import in windows 2024-07-12 18:30:24 +02:00
Ferdinand Schober
a60a1c7095 fix emulation client creation 2024-07-12 18:27:49 +02:00
Ferdinand Schober
f74b7f98fe fix conditional compilation 2024-07-12 18:18:46 +02:00
Ferdinand Schober
7e77e0c3f5 sync port 2024-07-12 18:09:23 +02:00
Ferdinand Schober
aea4d0f3fb fix edge case where cancellation is not possible 2024-07-12 18:07:28 +02:00
Ferdinand Schober
69afbe1674 simplify 2024-07-12 18:02:32 +02:00
Ferdinand Schober
d02d8d5ab9 move assert to correct location 2024-07-12 17:55:12 +02:00
Ferdinand Schober
54943d9057 fix possible panic because channels are dropped 2024-07-12 17:53:20 +02:00
Ferdinand Schober
9227bde6bf sync capture + emulation status 2024-07-12 17:44:24 +02:00
Ferdinand Schober
f052efe086 add missing dns request notify 2024-07-12 17:18:18 +02:00
Ferdinand Schober
740272e9a5 fix clippy warnings 2024-07-12 17:13:10 +02:00
Ferdinand Schober
e063f4ffb4 restructure server 2024-07-12 17:09:45 +02:00
Ferdinand Schober
592cc01faf unused import 2024-07-12 12:54:01 +02:00
Ferdinand Schober
d84c572a4e allow deny capture / emulation 2024-07-12 12:46:57 +02:00
Ferdinand Schober
fa57b4ea34 allow cancelling session creation 2024-07-12 12:31:39 +02:00
Ferdinand Schober
8908c33603 move libei event conversion to event crate 2024-07-12 12:07:30 +02:00
Ferdinand Schober
7328958dde fix session not actually closed 2024-07-12 11:41:32 +02:00
Ferdinand Schober
8de738e597 impl session close 2024-07-12 11:35:21 +02:00
Ferdinand Schober
621d9eac59 fix termination of libei emulation on error 2024-07-12 02:45:47 +02:00
Ferdinand Schober
b4afbbec45 fix duplicate barriers 2024-07-12 01:36:47 +02:00
Ferdinand Schober
d25c6d4ec2 fix remnants from testing stuff 2024-07-12 01:32:52 +02:00
Ferdinand Schober
73a57ee892 cleanup 2024-07-12 01:29:03 +02:00
Ferdinand Schober
39d6a3cace clippy 2024-07-12 01:04:44 +02:00
Ferdinand Schober
335a1fc3e2 simplify 2024-07-12 01:01:09 +02:00
Ferdinand Schober
3014e404c3 asdf 2024-07-11 22:43:43 +02:00
Ferdinand Schober
d54e472498 fix emulation notify 2024-07-11 22:20:40 +02:00
Ferdinand Schober
b0407148bf add some log messages 2024-07-11 19:27:40 +02:00
Ferdinand Schober
2a2cbce17d cleanup 2024-07-11 17:18:31 +02:00
Ferdinand Schober
f1dc3a5708 clean 2024-07-11 17:07:29 +02:00
Ferdinand Schober
a4094b2ce7 remove termination request 2024-07-11 17:01:56 +02:00
Ferdinand Schober
69a5eec944 cleanup 2024-07-11 16:59:09 +02:00
Ferdinand Schober
4c30f032f4 cleanup 2024-07-11 16:47:36 +02:00
Ferdinand Schober
2d26bd6a0b improve cancellation 2024-07-11 16:34:41 +02:00
Ferdinand Schober
f0c9290579 fix duplicate barriers + use Notify 2024-07-11 15:35:37 +02:00
Ferdinand Schober
d73ced7b16 wire frontend 2024-07-11 15:12:59 +02:00
Ferdinand Schober
9990e5b578 move to own preferences group 2024-07-11 12:37:39 +02:00
Ferdinand Schober
fcdf80de00 improve ui mockup 2024-07-11 10:20:33 +02:00
Ferdinand Schober
252547dfdb solve clippy except tomanyargs 2024-07-11 01:14:35 +02:00
Ferdinand Schober
3f7dae65a2 fmt 2024-07-11 00:51:49 +02:00
Ferdinand Schober
c58f5dbdd5 fix missing Arc import 2024-07-11 00:44:17 +02:00
Ferdinand Schober
8ba178dce0 simplify cancellation of service 2024-07-11 00:42:32 +02:00
Ferdinand Schober
ae3ea2c497 fix windows/mac + rename async_drop to terminate 2024-07-10 22:33:37 +02:00
Ferdinand Schober
ebf7897caa create capture session only if clients are active 2024-07-10 22:24:38 +02:00
Ferdinand Schober
9c0a40563e prefer CancellationToken / Notify to channel 2024-07-10 22:03:56 +02:00
Ferdinand Schober
8ba92ede34 its getting cleaner 2024-07-10 20:31:02 +02:00
Ferdinand Schober
89ca9c3c0b improve libei error handling 2024-07-10 09:32:21 +02:00
Ferdinand Schober
110b37e26e improve capture error handling 2024-07-10 09:00:43 +02:00
44 changed files with 1248 additions and 1985 deletions

260
Cargo.lock generated
View File

@@ -98,9 +98,9 @@ dependencies = [
[[package]]
name = "ashpd"
version = "0.9.1"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfe7e0dd0ac5a401dc116ed9f9119cf9decc625600474cb41f0fc0a0050abc9a"
checksum = "dd884d7c72877a94102c3715f3b1cd09ff4fac28221add3e57cfbe25c236d093"
dependencies = [
"enumflags2",
"futures-channel",
@@ -200,9 +200,9 @@ dependencies = [
[[package]]
name = "async-signal"
version = "0.2.9"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfb3634b73397aa844481f814fad23bbf07fdb0eabec10f2eb95e58944b1ec32"
checksum = "794f185324c2f00e771cd9f1ae8b5ac68be2ca7abb129a87afd6e86d228bc54d"
dependencies = [
"async-io",
"async-lock",
@@ -296,15 +296,15 @@ dependencies = [
[[package]]
name = "bytes"
version = "1.6.1"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952"
checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cairo-rs"
version = "0.20.0"
version = "0.19.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "797fd5a634dcb0ad0d7d583df794deb0a236d88e759cd34b7da20198c6c9d145"
checksum = "b2ac2a4d0e69036cf0062976f6efcba1aaee3e448594e6514bb2ddf87acce562"
dependencies = [
"bitflags 2.6.0",
"cairo-sys-rs",
@@ -315,9 +315,9 @@ dependencies = [
[[package]]
name = "cairo-sys-rs"
version = "0.20.0"
version = "0.19.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "428290f914b9b86089f60f5d8a9f6e440508e1bcff23b25afd51502b0a2da88f"
checksum = "fd3bb3119664efbd78b5e6c93957447944f16bdbced84c17a9f41c7829b81e64"
dependencies = [
"glib-sys",
"libc",
@@ -326,9 +326,9 @@ dependencies = [
[[package]]
name = "cc"
version = "1.1.6"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f"
checksum = "eaff6f8ce506b9773fa786672d63fc7a191ffea1be33f72bbd4aeacefca9ffc8"
[[package]]
name = "cfg-expr"
@@ -758,9 +758,9 @@ dependencies = [
[[package]]
name = "gdk-pixbuf"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28bb53ecb56857c683c9ec859908e076dd3969c7d67598bd8b1ce095d211304a"
checksum = "624eaba126021103c7339b2e179ae4ee8cdab842daab419040710f38ed9f8699"
dependencies = [
"gdk-pixbuf-sys",
"gio",
@@ -770,9 +770,9 @@ dependencies = [
[[package]]
name = "gdk-pixbuf-sys"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f6681a0c1330d1d3968bec1529f7172d62819ef0bdbb0d18022320654158b03"
checksum = "4efa05a4f83c8cc50eb4d883787b919b85e5f1d8dd10b5a1df53bf5689782379"
dependencies = [
"gio-sys",
"glib-sys",
@@ -783,9 +783,9 @@ dependencies = [
[[package]]
name = "gdk4"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b7d7237c1487ed4b300aac7744efcbf1319e12d60d7afcd6f505414bd5b5dea"
checksum = "db265c9dd42d6a371e09e52deab3a84808427198b86ac792d75fd35c07990a07"
dependencies = [
"cairo-rs",
"gdk-pixbuf",
@@ -798,9 +798,9 @@ dependencies = [
[[package]]
name = "gdk4-sys"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a67576c8ec012156d7f680e201a807b4432a77babb3157e0555e990ab6bcd878"
checksum = "c9418fb4e8a67074919fe7604429c45aa74eb9df82e7ca529767c6d4e9dc66dd"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
@@ -842,9 +842,9 @@ checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd"
[[package]]
name = "gio"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "398e3da68749fdc32783cbf7521ec3f65c9cf946db8c7774f8460af49e52c6e2"
checksum = "4c49f117d373ffcc98a35d114db5478bc223341cff53e39a5d6feced9e2ddffe"
dependencies = [
"futures-channel",
"futures-core",
@@ -860,9 +860,9 @@ dependencies = [
[[package]]
name = "gio-sys"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4feb96b31c32730ea3e1e89aecd2e4e37ecb1c473ad8f685e3430a159419f63"
checksum = "2cd743ba4714d671ad6b6234e8ab2a13b42304d0e13ab7eba1dcdd78a7d6d4ef"
dependencies = [
"glib-sys",
"gobject-sys",
@@ -873,9 +873,9 @@ dependencies = [
[[package]]
name = "glib"
version = "0.20.0"
version = "0.19.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fee90a615ce05be7a32932cfb8adf2c4bbb4700e80d37713c981fb24c0c56238"
checksum = "39650279f135469465018daae0ba53357942a5212137515777d5fdca74984a44"
dependencies = [
"bitflags 2.6.0",
"futures-channel",
@@ -895,18 +895,18 @@ dependencies = [
[[package]]
name = "glib-build-tools"
version = "0.20.0"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7029c2651d9b5d5a3eea93ec8a1995665c6d3a69ce9bf6042ad9064d134736d8"
checksum = "108f374fff60efd14b0d70d8916e7213aed18d7dd071ba3e9334ed2dac1dc86a"
dependencies = [
"gio",
]
[[package]]
name = "glib-macros"
version = "0.20.0"
version = "0.19.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4da558d8177c0c8c54368818b508a4244e1286fce2858cef4e547023f0cfa5ef"
checksum = "4429b0277a14ae9751350ad9b658b1be0abb5b54faa5bcdf6e74a3372582fad7"
dependencies = [
"heck 0.5.0",
"proc-macro-crate",
@@ -917,9 +917,9 @@ dependencies = [
[[package]]
name = "glib-sys"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4958c26e5a01c9af00dea669a97369eccbec29a8e6d125c24ea2d85ee7467b60"
checksum = "5c2dc18d3a82b0006d470b13304fbbb3e0a9bd4884cf985a60a7ed733ac2c4a5"
dependencies = [
"libc",
"system-deps",
@@ -927,9 +927,9 @@ dependencies = [
[[package]]
name = "gobject-sys"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6908864f5ffff15b56df7e90346863904f49b949337ed0456b9287af61903b8"
checksum = "2e697e252d6e0416fd1d9e169bda51c0f1c926026c39ca21fbe8b1bb5c3b8b9e"
dependencies = [
"glib-sys",
"libc",
@@ -938,9 +938,9 @@ dependencies = [
[[package]]
name = "graphene-rs"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "630e940ad5824f90221d6579043a9cd1f8bec86b4a17faaf7827d58eb16e8c1f"
checksum = "f5fb86031d24d9ec0a2a15978fc7a65d545a2549642cf1eb7c3dda358da42bcf"
dependencies = [
"glib",
"graphene-sys",
@@ -949,9 +949,9 @@ dependencies = [
[[package]]
name = "graphene-sys"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fb8fade7b754982f47ebbed241fd2680816fdd4598321784da10b9e1168836a"
checksum = "2f530e0944bccba4b55065e9c69f4975ad691609191ebac16e13ab8e1f27af05"
dependencies = [
"glib-sys",
"libc",
@@ -961,9 +961,9 @@ dependencies = [
[[package]]
name = "gsk4"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3cf2091e1af185b347b3450817d93dea6fe435df7abd4c2cd7fb5bcb4cfda8"
checksum = "7563884bf6939f4468e5d94654945bdd9afcaf8c3ba4c5dd17b5342b747221be"
dependencies = [
"cairo-rs",
"gdk4",
@@ -976,9 +976,9 @@ dependencies = [
[[package]]
name = "gsk4-sys"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6aa69614a26d8760c186c3690f1b0fbb917572ca23ef83137445770ceddf8cde"
checksum = "23024bf2636c38bbd1f822f58acc9d1c25b28da896ff0f291a1a232d4272b3dc"
dependencies = [
"cairo-sys-rs",
"gdk4-sys",
@@ -992,9 +992,9 @@ dependencies = [
[[package]]
name = "gtk4"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaffc6c743c9160514cc9b67eace364e5dc5798369fa809cdb04e035c21c5c5d"
checksum = "b04e11319b08af11358ab543105a9e49b0c491faca35e2b8e7e36bfba8b671ab"
dependencies = [
"cairo-rs",
"field-offset",
@@ -1013,9 +1013,9 @@ dependencies = [
[[package]]
name = "gtk4-macros"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "188211f546ce5801f6d0245c37b6249143a2cb4fa040e54829ca1e76796e9f09"
checksum = "ec655a7ef88d8ce9592899deb8b2d0fa50bab1e6dd69182deb764e643c522408"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -1025,9 +1025,9 @@ dependencies = [
[[package]]
name = "gtk4-sys"
version = "0.9.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1114a207af8ada02cf4658a76692f4190f06f093380d5be07e3ca8b43aa7c666"
checksum = "8c8aa86b7f85ea71d66ea88c1d4bae1cfacf51ca4856274565133838d77e57b5"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
@@ -1192,19 +1192,14 @@ dependencies = [
[[package]]
name = "input-capture"
version = "0.2.0"
version = "0.1.0"
dependencies = [
"ashpd",
"async-trait",
"bitflags 2.6.0",
"core-foundation",
"core-foundation-sys",
"core-graphics",
"futures",
"futures-core",
"input-event",
"keycode",
"libc",
"log",
"memmap",
"once_cell",
@@ -1216,13 +1211,13 @@ dependencies = [
"wayland-client",
"wayland-protocols",
"wayland-protocols-wlr",
"windows 0.58.0",
"windows 0.57.0",
"x11",
]
[[package]]
name = "input-emulation"
version = "0.2.1"
version = "0.1.0"
dependencies = [
"ashpd",
"async-trait",
@@ -1239,13 +1234,13 @@ dependencies = [
"wayland-protocols",
"wayland-protocols-misc",
"wayland-protocols-wlr",
"windows 0.58.0",
"windows 0.57.0",
"x11",
]
[[package]]
name = "input-event"
version = "0.2.1"
version = "0.1.0"
dependencies = [
"futures-core",
"log",
@@ -1311,7 +1306,7 @@ dependencies = [
[[package]]
name = "lan-mouse"
version = "0.9.1"
version = "0.8.0"
dependencies = [
"anyhow",
"async-channel",
@@ -1326,10 +1321,8 @@ dependencies = [
"input-capture",
"input-emulation",
"input-event",
"lan-mouse-proto",
"libadwaita",
"libc",
"local-channel",
"log",
"serde",
"serde_json",
@@ -1340,22 +1333,13 @@ dependencies = [
"toml",
]
[[package]]
name = "lan-mouse-proto"
version = "0.1.0"
dependencies = [
"input-event",
"num_enum",
"paste",
"thiserror",
]
[[package]]
name = "libadwaita"
version = "0.7.0"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ff9c222b5c783729de45185f07b2fec2d43a7f9c63961e777d3667e20443878"
checksum = "91b4990248b9e1ec5e72094a2ccaea70ec3809f88f6fd52192f2af306b87c5d9"
dependencies = [
"gdk-pixbuf",
"gdk4",
"gio",
"glib",
@@ -1367,9 +1351,9 @@ dependencies = [
[[package]]
name = "libadwaita-sys"
version = "0.7.0"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c44d8bdbad31d6639e1f20cc9c1424f1a8e02d751fc28d44659bf743fb9eca6"
checksum = "23a748e4e92be1265cd9e93d569c0b5dfc7814107985aa6743d670ab281ea1a8"
dependencies = [
"gdk4-sys",
"gio-sys",
@@ -1409,23 +1393,6 @@ version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]]
name = "local-channel"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6cbc85e69b8df4b8bb8b89ec634e7189099cea8927a276b7384ce5488e53ec8"
dependencies = [
"futures-core",
"futures-sink",
"local-waker",
]
[[package]]
name = "local-waker"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d873d7c67ce09b42110d801813efbc9364414e356be9935700d368351657487"
[[package]]
name = "lock_api"
version = "0.4.12"
@@ -1579,9 +1546,9 @@ dependencies = [
[[package]]
name = "pango"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54768854025df6903061d0084fd9702a253ddfd60db7d9b751d43b76689a7f0a"
checksum = "3f0d328648058085cfd6897c9ae4272884098a926f3a833cd50c8c73e6eccecd"
dependencies = [
"gio",
"glib",
@@ -1591,9 +1558,9 @@ dependencies = [
[[package]]
name = "pango-sys"
version = "0.20.0"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b07cc57d10cee4ec661f718a6902cee18c2f4cfae08e87e5a390525946913390"
checksum = "ff03da4fa086c0b244d4a4587d3e20622a3ecdb21daea9edf66597224c634ba0"
dependencies = [
"glib-sys",
"gobject-sys",
@@ -1630,12 +1597,6 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "percent-encoding"
version = "2.3.1"
@@ -1766,9 +1727,9 @@ dependencies = [
[[package]]
name = "redox_syscall"
version = "0.5.3"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4"
checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd"
dependencies = [
"bitflags 2.6.0",
]
@@ -1985,9 +1946,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.71"
version = "2.0.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462"
checksum = "2f0209b68b3613b093e0ec905354eccaedcfe83b8cb37cbdeae64026c3064c16"
dependencies = [
"proc-macro2",
"quote",
@@ -1996,9 +1957,9 @@ dependencies = [
[[package]]
name = "system-deps"
version = "7.0.1"
version = "6.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c81f13d9a334a6c242465140bd262fae382b752ff2011c4f7419919a9c97922"
checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
dependencies = [
"cfg-expr",
"heck 0.5.0",
@@ -2027,18 +1988,18 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.63"
version = "1.0.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724"
checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.63"
version = "1.0.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261"
checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
dependencies = [
"proc-macro2",
"quote",
@@ -2062,9 +2023,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.38.1"
version = "1.38.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb2caba9f80616f438e09748d5acda951967e1ea58508ef53d9c6402485a46df"
checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a"
dependencies = [
"backtrace",
"bytes",
@@ -2105,14 +2066,14 @@ dependencies = [
[[package]]
name = "toml"
version = "0.8.15"
version = "0.8.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac2caab0bf757388c6c0ae23b3293fdb463fee59434529014f85e3263b995c28"
checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime",
"toml_edit 0.22.16",
"toml_edit 0.22.15",
]
[[package]]
@@ -2137,9 +2098,9 @@ dependencies = [
[[package]]
name = "toml_edit"
version = "0.22.16"
version = "0.22.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "278f3d518e152219c994ce877758516bca5e118eaed6996192a774fb9fbf0788"
checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1"
dependencies = [
"indexmap",
"serde",
@@ -2261,9 +2222,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wayland-backend"
version = "0.3.6"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90e11ce2ca99c97b940ee83edbae9da2d56a08f9ea8158550fd77fa31722993"
checksum = "269c04f203640d0da2092d1b8d89a2d081714ae3ac2f1b53e99f205740517198"
dependencies = [
"cc",
"downcast-rs",
@@ -2275,9 +2236,9 @@ dependencies = [
[[package]]
name = "wayland-client"
version = "0.31.5"
version = "0.31.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e321577a0a165911bdcfb39cf029302479d7527b517ee58ab0f6ad09edf0943"
checksum = "08bd0f46c069d3382a36c8666c1b9ccef32b8b04f41667ca1fef06a1adcc2982"
dependencies = [
"bitflags 2.6.0",
"rustix",
@@ -2287,9 +2248,9 @@ dependencies = [
[[package]]
name = "wayland-protocols"
version = "0.32.3"
version = "0.32.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62989625a776e827cc0f15d41444a3cea5205b963c3a25be48ae1b52d6b4daaa"
checksum = "1794d82d869f38439d15c24b26f06f6c8603d27d47b4f786d5197c99044de415"
dependencies = [
"bitflags 2.6.0",
"wayland-backend",
@@ -2299,9 +2260,9 @@ dependencies = [
[[package]]
name = "wayland-protocols-misc"
version = "0.3.3"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfe44d48a0e51909c89da297f6b43bb814b881c78b69e254a4558a5fa8752887"
checksum = "28b497d7edd777ca365f2cce3837046b7832365b2a0b32f9c913b4e6f8d99839"
dependencies = [
"bitflags 2.6.0",
"wayland-backend",
@@ -2312,9 +2273,9 @@ dependencies = [
[[package]]
name = "wayland-protocols-wlr"
version = "0.3.3"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd993de54a40a40fbe5601d9f1fbcaef0aebcc5fda447d7dc8f6dcbaae4f8953"
checksum = "fa43c961473aed713d44c1f616f775186249dfca657f256d8841ca0690366aba"
dependencies = [
"bitflags 2.6.0",
"wayland-backend",
@@ -2325,9 +2286,9 @@ dependencies = [
[[package]]
name = "wayland-scanner"
version = "0.31.4"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7b56f89937f1cf2ee1f1259cf2936a17a1f45d8f0aa1019fae6d470d304cfa6"
checksum = "edf466fc49a4feb65a511ca403fec3601494d0dee85dbf37fff6fa0dd4eec3b6"
dependencies = [
"proc-macro2",
"quick-xml",
@@ -2336,9 +2297,9 @@ dependencies = [
[[package]]
name = "wayland-sys"
version = "0.31.4"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43676fe2daf68754ecf1d72026e4e6c15483198b5d24e888b74d3f22f887a148"
checksum = "4a6754825230fa5b27bafaa28c30b3c9e72c55530581220cef401fa422c0fae7"
dependencies = [
"dlib",
"log",
@@ -2385,11 +2346,11 @@ dependencies = [
[[package]]
name = "windows"
version = "0.58.0"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
dependencies = [
"windows-core 0.58.0",
"windows-core 0.57.0",
"windows-targets 0.52.6",
]
@@ -2404,22 +2365,21 @@ dependencies = [
[[package]]
name = "windows-core"
version = "0.58.0"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d"
dependencies = [
"windows-implement",
"windows-interface",
"windows-result",
"windows-strings",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"
dependencies = [
"proc-macro2",
"quote",
@@ -2428,9 +2388,9 @@ dependencies = [
[[package]]
name = "windows-interface"
version = "0.58.0"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"
dependencies = [
"proc-macro2",
"quote",
@@ -2439,23 +2399,13 @@ dependencies = [
[[package]]
name = "windows-result"
version = "0.2.0"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.48.0"

View File

@@ -1,23 +1,22 @@
[workspace]
members = ["input-capture", "input-emulation", "input-event", "lan-mouse-proto"]
members = ["input-capture", "input-emulation", "input-event"]
[package]
name = "lan-mouse"
description = "Software KVM Switch / mouse & keyboard sharing software for Local Area Networks"
version = "0.9.1"
version = "0.8.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
repository = "https://github.com/ferdinandschober/lan-mouse"
[profile.release]
strip = true
lto = "fat"
[dependencies]
input-event = { path = "input-event", version = "0.2.1" }
input-emulation = { path = "input-emulation", version = "0.2.1", default-features = false }
input-capture = { path = "input-capture", version = "0.2.0", default-features = false }
lan-mouse-proto = { path = "lan-mouse-proto", version = "0.1.0" }
input-event = { path = "input-event", version = "0.1.0" }
input-emulation = { path = "input-emulation", version = "0.1.0", default-features = false }
input-capture = { path = "input-capture", version = "0.1.0", default-features = false }
hickory-resolver = "0.24.1"
toml = "0.8"
@@ -38,10 +37,10 @@ tokio = { version = "1.32.0", features = [
] }
futures = "0.3.28"
clap = { version = "4.4.11", features = ["derive"] }
gtk = { package = "gtk4", version = "0.9.0", features = [
gtk = { package = "gtk4", version = "0.8.1", features = [
"v4_2",
], optional = true }
adw = { package = "libadwaita", version = "0.7.0", features = [
adw = { package = "libadwaita", version = "0.6.0", features = [
"v1_1",
], optional = true }
async-channel = { version = "2.1.1", optional = true }
@@ -50,13 +49,12 @@ slab = "0.4.9"
endi = "1.1.0"
thiserror = "1.0.61"
tokio-util = "0.7.11"
local-channel = "0.1.5"
[target.'cfg(unix)'.dependencies]
libc = "0.2.148"
[build-dependencies]
glib-build-tools = { version = "0.20.0", optional = true }
glib-build-tools = { version = "0.19.0", optional = true }
[features]
default = ["wayland", "x11", "xdg_desktop_portal", "libei", "gtk"]

View File

@@ -57,10 +57,6 @@ input capture (to send events *to* other clients) on different operating systems
> If you are using [Wayfire](https://github.com/WayfireWM/wayfire), make sure to use a recent version (must be newer than October 23rd) and **add `shortcuts-inhibit` to the list of plugins in your wayfire config!**
> Otherwise input capture will not work.
> [!Important]
> The mouse cursor will be invisible when sending input to a Windows system if
> there is no real mouse connected to the machine.
## Installation
### Install via cargo
```sh

View File

@@ -16,7 +16,6 @@
inherit (nixpkgs) lib;
genSystems = lib.genAttrs [
"aarch64-darwin"
"aarch64-linux"
"x86_64-darwin"
"x86_64-linux"
];
@@ -51,13 +50,10 @@
xorg.libX11
gtk4
libadwaita
librsvg
xorg.libXtst
] ++ lib.optionals stdenv.isDarwin
(with darwin.apple_sdk_11_0.frameworks; [
CoreGraphics
ApplicationServices
]);
] ++ lib.optionals stdenv.isDarwin [
darwin.apple_sdk_11_0.frameworks.CoreGraphics
];
RUST_SRC_PATH = "${rust}/lib/rustlib/src/rust/library";
};

View File

@@ -1,16 +1,16 @@
[package]
name = "input-capture"
description = "cross-platform input-capture library used by lan-mouse"
version = "0.2.0"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
repository = "https://github.com/ferdinandschober/lan-mouse"
[dependencies]
futures = "0.3.28"
futures-core = "0.3.30"
log = "0.4.22"
input-event = { path = "../input-event", version = "0.2.1" }
input-event = { path = "../input-event", version = "0.1.0" }
memmap = "0.7"
tempfile = "3.8"
thiserror = "1.0.61"
@@ -40,21 +40,16 @@ wayland-protocols-wlr = { version = "0.3.1", features = [
"client",
], optional = true }
x11 = { version = "2.21.0", features = ["xlib", "xtest"], optional = true }
ashpd = { version = "0.9", default-features = false, features = [
ashpd = { version = "0.8", default-features = false, features = [
"tokio",
], optional = true }
reis = { version = "0.2", features = ["tokio"], optional = true }
[target.'cfg(target_os="macos")'.dependencies]
core-graphics = { version = "0.23", features = ["highsierra"] }
core-foundation = "0.9.4"
core-foundation-sys = "0.8.6"
libc = "0.2.155"
keycode = "0.4.0"
bitflags = "2.5.0"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58.0", features = [
windows = { version = "0.57.0", features = [
"Win32_System_LibraryLoader",
"Win32_System_Threading",
"Win32_Foundation",

View File

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

View File

@@ -22,9 +22,6 @@ use ashpd::desktop::ResponseError;
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
use reis::tokio::{EiConvertEventStreamError, HandshakeError};
#[cfg(target_os = "macos")]
use core_graphics::base::CGError;
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
#[derive(Debug, Error)]
#[error("error in libei stream: {inner:?}")]
@@ -59,21 +56,6 @@ pub enum CaptureError {
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
#[error("libei disconnected - reason: `{0}`")]
Disconnected(String),
#[cfg(target_os = "macos")]
#[error("failed to warp mouse cursor: `{0}`")]
WarpCursor(CGError),
#[cfg(target_os = "macos")]
#[error("reset_mouse_position called without a connected client")]
ResetMouseWithoutClient,
#[cfg(target_os = "macos")]
#[error("core-graphics error: {0}")]
CoreGraphics(CGError),
#[cfg(target_os = "macos")]
#[error("unable to map key event: {0}")]
KeyMapError(i64),
#[cfg(target_os = "macos")]
#[error("Event tap disabled")]
EventTapDisabled,
}
#[derive(Debug, Error)]
@@ -89,12 +71,12 @@ pub enum CaptureCreationError {
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
#[error("error creating x11 capture backend: `{0}`")]
X11(#[from] X11InputCaptureCreationError),
#[cfg(target_os = "macos")]
#[error("error creating macos capture backend: `{0}`")]
Macos(#[from] MacOSInputCaptureCreationError),
#[cfg(windows)]
#[error("error creating windows capture backend")]
Windows,
#[cfg(target_os = "macos")]
#[error("error creating macos capture backend")]
MacOS(#[from] MacosCaptureCreationError),
}
impl CaptureCreationError {
@@ -162,12 +144,7 @@ pub enum X11InputCaptureCreationError {
#[cfg(target_os = "macos")]
#[derive(Debug, Error)]
pub enum MacosCaptureCreationError {
#[error("event source creation failed!")]
EventSourceCreation,
#[error("failed to set CG Cursor property")]
CGCursorProperty,
#[cfg(target_os = "macos")]
#[error("failed to get display ids: {0}")]
ActiveDisplays(CGError),
pub enum MacOSInputCaptureCreationError {
#[error("MacOS input capture is not yet implemented :(")]
NotImplemented,
}

View File

@@ -1,52 +1,34 @@
use std::{collections::HashSet, fmt::Display, task::Poll};
use std::fmt::Display;
use async_trait::async_trait;
use futures::StreamExt;
use futures_core::Stream;
use input_event::{scancode, Event, KeyboardEvent};
use input_event::Event;
pub use error::{CaptureCreationError, CaptureError, InputCaptureError};
pub mod error;
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
mod libei;
pub mod libei;
#[cfg(target_os = "macos")]
mod macos;
pub mod macos;
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
mod wayland;
pub mod wayland;
#[cfg(windows)]
mod windows;
pub mod windows;
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
mod x11;
pub mod x11;
/// fallback input capture (does not produce events)
mod dummy;
pub mod dummy;
pub type CaptureHandle = u64;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum CaptureEvent {
/// capture on this capture handle is now active
Begin,
/// input event coming from capture handle
Input(Event),
}
impl Display for CaptureEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CaptureEvent::Begin => write!(f, "begin capture"),
CaptureEvent::Input(e) => write!(f, "{e}"),
}
}
}
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum Position {
Left,
@@ -111,83 +93,10 @@ impl Display for Backend {
}
}
pub struct InputCapture {
capture: Box<dyn Capture>,
pressed_keys: HashSet<scancode::Linux>,
}
impl InputCapture {
/// create a new client with the given id
pub async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
self.capture.create(id, pos).await
}
/// destroy the client with the given id, if it exists
pub async fn destroy(&mut self, id: CaptureHandle) -> Result<(), CaptureError> {
self.capture.destroy(id).await
}
/// release mouse
pub async fn release(&mut self) -> Result<(), CaptureError> {
self.pressed_keys.clear();
self.capture.release().await
}
/// destroy the input capture
pub async fn terminate(&mut self) -> Result<(), CaptureError> {
self.capture.terminate().await
}
/// creates a new [`InputCapture`]
pub async fn new(backend: Option<Backend>) -> Result<Self, CaptureCreationError> {
let capture = create(backend).await?;
Ok(Self {
capture,
pressed_keys: HashSet::new(),
})
}
/// check whether the given keys are pressed
pub fn keys_pressed(&self, keys: &[scancode::Linux]) -> bool {
keys.iter().all(|k| self.pressed_keys.contains(k))
}
fn update_pressed_keys(&mut self, key: u32, state: u8) {
if let Ok(scancode) = scancode::Linux::try_from(key) {
log::debug!("key: {key}, state: {state}, scancode: {scancode:?}");
match state {
1 => self.pressed_keys.insert(scancode),
_ => self.pressed_keys.remove(&scancode),
};
}
}
}
impl Stream for InputCapture {
type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
match self.capture.poll_next_unpin(cx) {
Poll::Ready(e) => {
if let Some(Ok((
_,
CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { key, state, .. })),
))) = e
{
self.update_pressed_keys(key, state);
}
Poll::Ready(e)
}
Poll::Pending => Poll::Pending,
}
}
}
#[async_trait]
trait Capture: Stream<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>> + Unpin {
pub trait InputCapture:
Stream<Item = Result<(CaptureHandle, Event), CaptureError>> + Unpin
{
/// create a new client with the given id
async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError>;
@@ -201,10 +110,10 @@ trait Capture: Stream<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>
async fn terminate(&mut self) -> Result<(), CaptureError>;
}
async fn create_backend(
pub async fn create_backend(
backend: Backend,
) -> Result<
Box<dyn Capture<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>>>,
Box<dyn InputCapture<Item = Result<(CaptureHandle, Event), CaptureError>>>,
CaptureCreationError,
> {
match backend {
@@ -217,15 +126,15 @@ async fn create_backend(
#[cfg(windows)]
Backend::Windows => Ok(Box::new(windows::WindowsInputCapture::new())),
#[cfg(target_os = "macos")]
Backend::MacOs => Ok(Box::new(macos::MacOSInputCapture::new().await?)),
Backend::MacOs => Ok(Box::new(macos::MacOSInputCapture::new()?)),
Backend::Dummy => Ok(Box::new(dummy::DummyInputCapture::new())),
}
}
async fn create(
pub async fn create(
backend: Option<Backend>,
) -> Result<
Box<dyn Capture<Item = Result<(CaptureHandle, CaptureEvent), CaptureError>>>,
Box<dyn InputCapture<Item = Result<(CaptureHandle, Event), CaptureError>>>,
CaptureCreationError,
> {
if let Some(backend) = backend {

View File

@@ -36,11 +36,9 @@ use once_cell::sync::Lazy;
use input_event::Event;
use crate::CaptureEvent;
use super::{
error::{CaptureError, LibeiCaptureCreationError, ReisConvertEventStreamError},
Capture as LanMouseInputCapture, CaptureHandle, Position,
CaptureHandle, InputCapture as LanMouseInputCapture, Position,
};
/* there is a bug in xdg-remote-desktop-portal-gnome / mutter that
@@ -58,7 +56,7 @@ enum LibeiNotifyEvent {
pub struct LibeiInputCapture<'a> {
input_capture: Pin<Box<InputCapture<'a>>>,
capture_task: JoinHandle<Result<(), CaptureError>>,
event_rx: Receiver<(CaptureHandle, CaptureEvent)>,
event_rx: Receiver<(CaptureHandle, Event)>,
notify_capture: Sender<LibeiNotifyEvent>,
notify_release: Arc<Notify>,
cancellation_token: CancellationToken,
@@ -93,35 +91,13 @@ fn pos_to_barrier(r: &Region, pos: Position) -> (i32, i32, i32, i32) {
}
}
/// Ashpd does not expose fields
#[derive(Clone, Copy, Debug)]
struct ICBarrier {
barrier_id: BarrierID,
position: (i32, i32, i32, i32),
}
impl ICBarrier {
fn new(barrier_id: BarrierID, position: (i32, i32, i32, i32)) -> Self {
Self {
barrier_id,
position,
}
}
}
impl From<ICBarrier> for Barrier {
fn from(barrier: ICBarrier) -> Self {
Barrier::new(barrier.barrier_id, barrier.position)
}
}
fn select_barriers(
zones: &Zones,
clients: &[(CaptureHandle, Position)],
clients: &Vec<(CaptureHandle, Position)>,
next_barrier_id: &mut u32,
) -> (Vec<ICBarrier>, HashMap<BarrierID, CaptureHandle>) {
) -> (Vec<Barrier>, HashMap<BarrierID, CaptureHandle>) {
let mut client_for_barrier = HashMap::new();
let mut barriers: Vec<ICBarrier> = vec![];
let mut barriers: Vec<Barrier> = vec![];
for (handle, pos) in clients {
let mut client_barriers = zones
@@ -132,7 +108,7 @@ fn select_barriers(
*next_barrier_id = id + 1;
let position = pos_to_barrier(r, *pos);
client_for_barrier.insert(id, *handle);
ICBarrier::new(id, position)
Barrier::new(id, position)
})
.collect();
barriers.append(&mut client_barriers);
@@ -142,10 +118,10 @@ fn select_barriers(
async fn update_barriers(
input_capture: &InputCapture<'_>,
session: &Session<'_, InputCapture<'_>>,
active_clients: &[(CaptureHandle, Position)],
session: &Session<'_>,
active_clients: &Vec<(CaptureHandle, Position)>,
next_barrier_id: &mut u32,
) -> Result<(Vec<ICBarrier>, HashMap<BarrierID, CaptureHandle>), ashpd::Error> {
) -> Result<HashMap<BarrierID, CaptureHandle>, ashpd::Error> {
let zones = input_capture.zones(session).await?.response()?;
log::debug!("zones: {zones:?}");
@@ -153,18 +129,17 @@ async fn update_barriers(
log::debug!("barriers: {barriers:?}");
log::debug!("client for barrier id: {id_map:?}");
let ashpd_barriers: Vec<Barrier> = barriers.iter().copied().map(|b| b.into()).collect();
let response = input_capture
.set_pointer_barriers(session, &ashpd_barriers, zones.zone_set())
.set_pointer_barriers(session, &barriers, zones.zone_set())
.await?;
let response = response.response()?;
log::debug!("{response:?}");
Ok((barriers, id_map))
Ok(id_map)
}
async fn create_session<'a>(
input_capture: &'a InputCapture<'a>,
) -> std::result::Result<(Session<'_, InputCapture<'_>>, BitFlags<Capabilities>), ashpd::Error> {
) -> std::result::Result<(Session<'a>, BitFlags<Capabilities>), ashpd::Error> {
log::debug!("creating input capture session");
input_capture
.create_session(
@@ -176,7 +151,7 @@ async fn create_session<'a>(
async fn connect_to_eis(
input_capture: &InputCapture<'_>,
session: &Session<'_, InputCapture<'_>>,
session: &Session<'_>,
) -> Result<(ei::Context, EiConvertEventStream), CaptureError> {
log::debug!("connect_to_eis");
let fd = input_capture.connect_to_eis(session).await?;
@@ -203,7 +178,7 @@ async fn connect_to_eis(
async fn libei_event_handler(
mut ei_event_stream: EiConvertEventStream,
context: ei::Context,
event_tx: Sender<(CaptureHandle, CaptureEvent)>,
event_tx: Sender<(CaptureHandle, Event)>,
release_session: Arc<Notify>,
current_client: Rc<Cell<Option<CaptureHandle>>>,
) -> Result<(), CaptureError> {
@@ -255,12 +230,12 @@ impl<'a> LibeiInputCapture<'a> {
}
}
async fn do_capture(
input_capture: *const InputCapture<'static>,
async fn do_capture<'a>(
input_capture: *const InputCapture<'a>,
mut capture_event: Receiver<LibeiNotifyEvent>,
notify_release: Arc<Notify>,
session: Option<(Session<'_, InputCapture<'_>>, BitFlags<Capabilities>)>,
event_tx: Sender<(CaptureHandle, CaptureEvent)>,
session: Option<(Session<'a>, BitFlags<Capabilities>)>,
event_tx: Sender<(CaptureHandle, Event)>,
cancellation_token: CancellationToken,
) -> Result<(), CaptureError> {
let mut session = session.map(|s| s.0);
@@ -314,7 +289,7 @@ async fn do_capture(
input_capture,
&mut session,
&event_tx,
&active_clients,
&mut active_clients,
&mut next_barrier_id,
&notify_release,
(cancel_session.clone(), cancel_update.clone()),
@@ -355,9 +330,9 @@ async fn do_capture(
async fn do_capture_session(
input_capture: &InputCapture<'_>,
session: &mut Session<'_, InputCapture<'_>>,
event_tx: &Sender<(CaptureHandle, CaptureEvent)>,
active_clients: &[(CaptureHandle, Position)],
session: &mut Session<'_>,
event_tx: &Sender<(CaptureHandle, Event)>,
active_clients: &mut Vec<(CaptureHandle, Position)>,
next_barrier_id: &mut u32,
notify_release: &Notify,
cancel: (CancellationToken, CancellationToken),
@@ -370,7 +345,7 @@ async fn do_capture_session(
let (context, ei_event_stream) = connect_to_eis(input_capture, session).await?;
// set barriers
let (barriers, client_for_barrier_id) =
let client_for_barrier_id =
update_barriers(input_capture, session, active_clients, next_barrier_id).await?;
log::debug!("enabling session");
@@ -413,19 +388,13 @@ async fn do_capture_session(
let activated = activated.ok_or(CaptureError::ActivationClosed)?;
log::debug!("activated: {activated:?}");
// get barrier id from activation
let barrier_id = match activated.barrier_id() {
Some(bid) => bid,
// workaround for KDE plasma not reporting barrier ids
None => find_corresponding_client(&barriers, activated.cursor_position().expect("no cursor position reported by compositor")),
};
// find client corresponding to barrier
let client = *client_for_barrier_id.get(&barrier_id).expect("invalid barrier id");
let client = *client_for_barrier_id
.get(&activated.barrier_id())
.expect("invalid barrier id");
current_client.replace(Some(client));
// client entered => send event
event_tx.send((client, CaptureEvent::Begin)).await.expect("no channel");
event_tx.send((client, Event::Enter())).await.expect("no channel");
tokio::select! {
_ = notify_release.notified() => { /* capture release */
@@ -480,20 +449,15 @@ async fn do_capture_session(
Ok(())
}
async fn release_capture<'a>(
input_capture: &InputCapture<'a>,
session: &Session<'a, InputCapture<'a>>,
async fn release_capture(
input_capture: &InputCapture<'_>,
session: &Session<'_>,
activated: Activated,
current_client: CaptureHandle,
active_clients: &[(CaptureHandle, Position)],
) -> Result<(), CaptureError> {
if let Some(activation_id) = activated.activation_id() {
log::debug!("releasing input capture {activation_id}");
}
let (x, y) = activated
.cursor_position()
.expect("compositor did not report cursor position!");
log::debug!("client entered @ ({x}, {y})");
log::debug!("releasing input capture {}", activated.activation_id());
let (x, y) = activated.cursor_position();
let pos = active_clients
.iter()
.filter(|(c, _)| *c == current_client)
@@ -510,39 +474,11 @@ async fn release_capture<'a>(
// release 1px to the right of the entered zone
let cursor_position = (x as f64 + dx, y as f64 + dy);
input_capture
.release(session, activated.activation_id(), Some(cursor_position))
.release(session, activated.activation_id(), cursor_position)
.await?;
Ok(())
}
fn find_corresponding_client(barriers: &[ICBarrier], pos: (f32, f32)) -> BarrierID {
barriers
.iter()
.copied()
.min_by_key(|b| {
let (x1, y1, x2, y2) = b.position;
let (x1, y1, x2, y2) = (x1 as f32, y1 as f32, x2 as f32, y2 as f32);
distance_to_line(((x1, y1), (x2, y2)), pos) as i32
})
.expect("could not find barrier corresponding to client")
.barrier_id
}
fn distance_to_line(line: ((f32, f32), (f32, f32)), p: (f32, f32)) -> f32 {
let ((x1, y1), (x2, y2)) = line;
let (x0, y0) = p;
/*
* we use the fact that for the triangle spanned by the line and p,
* the height of the triangle is the desired distance and can be calculated by
* h = 2A / b with b being the line_length and
*/
let double_triangle_area = ((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1).abs();
let line_length = ((y2 - y1).powf(2.0) + (x2 - x1).powf(2.0)).sqrt();
let distance = double_triangle_area / line_length;
log::debug!("distance to line({line:?}, {p:?}) = {distance}");
distance
}
static ALL_CAPABILITIES: &[DeviceCapability] = &[
DeviceCapability::Pointer,
DeviceCapability::PointerAbsolute,
@@ -556,7 +492,7 @@ async fn handle_ei_event(
ei_event: EiEvent,
current_client: Option<CaptureHandle>,
context: &ei::Context,
event_tx: &Sender<(CaptureHandle, CaptureEvent)>,
event_tx: &Sender<(CaptureHandle, Event)>,
release_session: &Notify,
) -> Result<(), CaptureError> {
match ei_event {
@@ -577,7 +513,7 @@ async fn handle_ei_event(
_ => {
if let Some(handle) = current_client {
for event in Event::from_ei_event(ei_event) {
event_tx.send((handle, CaptureEvent::Input(event))).await.expect("no channel");
event_tx.send((handle, event)).await.expect("no channel");
}
}
}
@@ -629,7 +565,7 @@ impl<'a> Drop for LibeiInputCapture<'a> {
}
impl<'a> Stream for LibeiInputCapture<'a> {
type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
type Item = Result<(CaptureHandle, Event), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.capture_task.poll_unpin(cx) {

View File

@@ -1,522 +1,39 @@
use super::{
error::MacosCaptureCreationError, Capture, CaptureError, CaptureEvent, CaptureHandle, Position,
use crate::{
error::MacOSInputCaptureCreationError, CaptureError, CaptureHandle, InputCapture, Position,
};
use async_trait::async_trait;
use bitflags::bitflags;
use core_foundation::base::{kCFAllocatorDefault, CFRelease};
use core_foundation::date::CFTimeInterval;
use core_foundation::number::{kCFBooleanTrue, CFBooleanRef};
use core_foundation::runloop::{kCFRunLoopCommonModes, CFRunLoop, CFRunLoopSource};
use core_foundation::string::{kCFStringEncodingUTF8, CFStringCreateWithCString, CFStringRef};
use core_graphics::base::{kCGErrorSuccess, CGError};
use core_graphics::display::{CGDisplay, CGPoint};
use core_graphics::event::{
CGEvent, CGEventFlags, CGEventTap, CGEventTapLocation, CGEventTapOptions, CGEventTapPlacement,
CGEventTapProxy, CGEventType, EventField,
};
use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
use futures_core::Stream;
use input_event::{Event, KeyboardEvent, PointerEvent, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT};
use keycode::{KeyMap, KeyMapping};
use libc::c_void;
use once_cell::unsync::Lazy;
use std::collections::HashMap;
use std::ffi::{c_char, CString};
use input_event::Event;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{ready, Context, Poll};
use std::thread::{self};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::sync::Mutex;
use std::task::{Context, Poll};
#[derive(Debug, Default)]
struct Bounds {
xmin: f64,
xmax: f64,
ymin: f64,
ymax: f64,
}
#[derive(Debug)]
struct InputCaptureState {
client_for_pos: Lazy<HashMap<Position, CaptureHandle>>,
current_client: Option<(CaptureHandle, Position)>,
bounds: Bounds,
}
#[derive(Debug)]
enum ProducerEvent {
Release,
Create(CaptureHandle, Position),
Destroy(CaptureHandle),
Grab((CaptureHandle, Position)),
EventTapDisabled,
}
impl InputCaptureState {
fn new() -> Result<Self, MacosCaptureCreationError> {
let mut res = Self {
client_for_pos: Lazy::new(HashMap::new),
current_client: None,
bounds: Bounds::default(),
};
res.update_bounds()?;
Ok(res)
}
fn crossed(&mut self, event: &CGEvent) -> Option<(CaptureHandle, Position)> {
let location = event.location();
let relative_x = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_X);
let relative_y = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_Y);
for (position, client) in self.client_for_pos.iter() {
if (position == &Position::Left && (location.x + relative_x) <= self.bounds.xmin)
|| (position == &Position::Right && (location.x + relative_x) >= self.bounds.xmax)
|| (position == &Position::Top && (location.y + relative_y) <= self.bounds.ymin)
|| (position == &Position::Bottom && (location.y + relative_y) >= self.bounds.ymax)
{
log::debug!("Crossed barrier into client: {client}, {position:?}");
return Some((*client, *position));
}
}
None
}
// Get the max bounds of all displays
fn update_bounds(&mut self) -> Result<(), MacosCaptureCreationError> {
let active_ids =
CGDisplay::active_displays().map_err(MacosCaptureCreationError::ActiveDisplays)?;
active_ids.iter().for_each(|d| {
let bounds = CGDisplay::new(*d).bounds();
self.bounds.xmin = self.bounds.xmin.min(bounds.origin.x);
self.bounds.xmax = self.bounds.xmax.max(bounds.origin.x + bounds.size.width);
self.bounds.ymin = self.bounds.ymin.min(bounds.origin.y);
self.bounds.ymax = self.bounds.ymax.max(bounds.origin.y + bounds.size.height);
});
log::debug!("Updated displays bounds: {0:?}", self.bounds);
Ok(())
}
// We can't disable mouse movement when in a client so we need to reset the cursor position
// to the edge of the screen, the cursor will be hidden but we dont want it to appear in a
// random location when we exit the client
fn reset_mouse_position(&self, event: &CGEvent) -> Result<(), CaptureError> {
if let Some((_, pos)) = self.current_client {
let location = event.location();
let edge_offset = 1.0;
// After the cursor is warped no event is produced but the next event
// will carry the delta from the warp so only half the delta is needed to move the cursor
let delta_y = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_Y) / 2.0;
let delta_x = event.get_double_value_field(EventField::MOUSE_EVENT_DELTA_X) / 2.0;
let mut new_x = location.x + delta_x;
let mut new_y = location.y + delta_y;
match pos {
Position::Left => {
new_x = self.bounds.xmin + edge_offset;
}
Position::Right => {
new_x = self.bounds.xmax - edge_offset;
}
Position::Top => {
new_y = self.bounds.ymin + edge_offset;
}
Position::Bottom => {
new_y = self.bounds.ymax - edge_offset;
}
}
let new_pos = CGPoint::new(new_x, new_y);
log::trace!("Resetting cursor position to: {new_x}, {new_y}");
return CGDisplay::warp_mouse_cursor_position(new_pos)
.map_err(CaptureError::WarpCursor);
}
Err(CaptureError::ResetMouseWithoutClient)
}
async fn handle_producer_event(
&mut self,
producer_event: ProducerEvent,
) -> Result<(), CaptureError> {
log::debug!("handling event: {producer_event:?}");
match producer_event {
ProducerEvent::Release => {
if self.current_client.is_some() {
CGDisplay::show_cursor(&CGDisplay::main())
.map_err(CaptureError::CoreGraphics)?;
self.current_client = None;
}
}
ProducerEvent::Grab(client) => {
if self.current_client.is_none() {
CGDisplay::hide_cursor(&CGDisplay::main())
.map_err(CaptureError::CoreGraphics)?;
self.current_client = Some(client);
}
}
ProducerEvent::Create(c, p) => {
self.client_for_pos.insert(p, c);
}
ProducerEvent::Destroy(c) => {
for pos in [
Position::Left,
Position::Right,
Position::Top,
Position::Bottom,
] {
if let Some((current_c, _)) = self.current_client {
if current_c == c {
CGDisplay::show_cursor(&CGDisplay::main())
.map_err(CaptureError::CoreGraphics)?;
self.current_client = None;
};
}
if self.client_for_pos.get(&pos).copied() == Some(c) {
self.client_for_pos.remove(&pos);
}
}
}
ProducerEvent::EventTapDisabled => return Err(CaptureError::EventTapDisabled),
};
Ok(())
}
}
fn get_events(
ev_type: &CGEventType,
ev: &CGEvent,
result: &mut Vec<CaptureEvent>,
) -> Result<(), CaptureError> {
fn map_pointer_event(ev: &CGEvent) -> PointerEvent {
PointerEvent::Motion {
time: 0,
dx: ev.get_double_value_field(EventField::MOUSE_EVENT_DELTA_X),
dy: ev.get_double_value_field(EventField::MOUSE_EVENT_DELTA_Y),
}
}
fn map_key(ev: &CGEvent) -> Result<u32, CaptureError> {
let code = ev.get_integer_value_field(EventField::KEYBOARD_EVENT_KEYCODE);
match KeyMap::from_key_mapping(KeyMapping::Mac(code as u16)) {
Ok(k) => Ok(k.evdev as u32),
Err(()) => Err(CaptureError::KeyMapError(code)),
}
}
match ev_type {
CGEventType::KeyDown => {
let k = map_key(ev)?;
result.push(CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key {
time: 0,
key: k,
state: 1,
})));
}
CGEventType::KeyUp => {
let k = map_key(ev)?;
result.push(CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key {
time: 0,
key: k,
state: 0,
})));
}
CGEventType::FlagsChanged => {
let mut mods = XMods::empty();
let mut mods_locked = XMods::empty();
let cg_flags = ev.get_flags();
if cg_flags.contains(CGEventFlags::CGEventFlagShift) {
mods |= XMods::ShiftMask;
}
if cg_flags.contains(CGEventFlags::CGEventFlagControl) {
mods |= XMods::ControlMask;
}
if cg_flags.contains(CGEventFlags::CGEventFlagAlternate) {
mods |= XMods::Mod1Mask;
}
if cg_flags.contains(CGEventFlags::CGEventFlagCommand) {
mods |= XMods::Mod4Mask;
}
if cg_flags.contains(CGEventFlags::CGEventFlagAlphaShift) {
mods |= XMods::LockMask;
mods_locked |= XMods::LockMask;
}
let modifier_event = KeyboardEvent::Modifiers {
depressed: mods.bits(),
latched: 0,
locked: mods_locked.bits(),
group: 0,
};
result.push(CaptureEvent::Input(Event::Keyboard(modifier_event)));
}
CGEventType::MouseMoved => {
result.push(CaptureEvent::Input(Event::Pointer(map_pointer_event(ev))))
}
CGEventType::LeftMouseDragged => {
result.push(CaptureEvent::Input(Event::Pointer(map_pointer_event(ev))))
}
CGEventType::RightMouseDragged => {
result.push(CaptureEvent::Input(Event::Pointer(map_pointer_event(ev))))
}
CGEventType::OtherMouseDragged => {
result.push(CaptureEvent::Input(Event::Pointer(map_pointer_event(ev))))
}
CGEventType::LeftMouseDown => {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time: 0,
button: BTN_LEFT,
state: 1,
})))
}
CGEventType::LeftMouseUp => {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time: 0,
button: BTN_LEFT,
state: 0,
})))
}
CGEventType::RightMouseDown => {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time: 0,
button: BTN_RIGHT,
state: 1,
})))
}
CGEventType::RightMouseUp => {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time: 0,
button: BTN_RIGHT,
state: 0,
})))
}
CGEventType::OtherMouseDown => {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time: 0,
button: BTN_MIDDLE,
state: 1,
})))
}
CGEventType::OtherMouseUp => {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
time: 0,
button: BTN_MIDDLE,
state: 0,
})))
}
CGEventType::ScrollWheel => {
let v = ev.get_integer_value_field(EventField::SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_1);
let h = ev.get_integer_value_field(EventField::SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_2);
if v != 0 {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Axis {
time: 0,
axis: 0, // Vertical
value: v as f64,
})));
}
if h != 0 {
result.push(CaptureEvent::Input(Event::Pointer(PointerEvent::Axis {
time: 0,
axis: 1, // Horizontal
value: h as f64,
})));
}
}
_ => (),
}
Ok(())
}
fn event_tap_thread(
client_state: Arc<Mutex<InputCaptureState>>,
event_tx: Sender<(CaptureHandle, CaptureEvent)>,
notify_tx: Sender<ProducerEvent>,
exit: tokio::sync::oneshot::Sender<Result<(), &'static str>>,
) {
let cg_events_of_interest: Vec<CGEventType> = vec![
CGEventType::LeftMouseDown,
CGEventType::LeftMouseUp,
CGEventType::RightMouseDown,
CGEventType::RightMouseUp,
CGEventType::OtherMouseDown,
CGEventType::OtherMouseUp,
CGEventType::MouseMoved,
CGEventType::LeftMouseDragged,
CGEventType::RightMouseDragged,
CGEventType::OtherMouseDragged,
CGEventType::ScrollWheel,
CGEventType::KeyDown,
CGEventType::KeyUp,
CGEventType::FlagsChanged,
];
let tap = CGEventTap::new(
CGEventTapLocation::Session,
CGEventTapPlacement::HeadInsertEventTap,
CGEventTapOptions::Default,
cg_events_of_interest,
|_proxy: CGEventTapProxy, event_type: CGEventType, cg_ev: &CGEvent| {
log::trace!("Got event from tap: {event_type:?}");
let mut state = client_state.blocking_lock();
let mut client = None;
let mut res_events = vec![];
if matches!(
event_type,
CGEventType::TapDisabledByTimeout | CGEventType::TapDisabledByUserInput
) {
log::error!("CGEventTap disabled");
notify_tx
.blocking_send(ProducerEvent::EventTapDisabled)
.unwrap_or_else(|e| {
log::error!("Failed to send notification: {e}");
});
}
// Are we in a client?
if let Some((current_client, _)) = state.current_client {
client = Some(current_client);
get_events(&event_type, cg_ev, &mut res_events).unwrap_or_else(|e| {
log::error!("Failed to get events: {e}");
});
// Keep (hidden) cursor at the edge of the screen
if matches!(event_type, CGEventType::MouseMoved) {
state.reset_mouse_position(cg_ev).unwrap_or_else(|e| {
log::error!("Failed to reset mouse position: {e}");
})
}
}
// Did we cross a barrier?
else if matches!(event_type, CGEventType::MouseMoved) {
if let Some((new_client, pos)) = state.crossed(cg_ev) {
client = Some(new_client);
res_events.push(CaptureEvent::Begin);
notify_tx
.blocking_send(ProducerEvent::Grab((new_client, pos)))
.expect("Failed to send notification");
}
}
if let Some(client) = client {
res_events.iter().for_each(|e| {
event_tx
.blocking_send((client, *e))
.expect("Failed to send event");
});
// Returning None should stop the event from being processed
// but core fundation still returns the event
cg_ev.set_type(CGEventType::Null);
}
Some(cg_ev.to_owned())
},
)
.expect("Failed creating tap");
let tap_source: CFRunLoopSource = tap
.mach_port
.create_runloop_source(0)
.expect("Failed creating loop source");
unsafe {
CFRunLoop::get_current().add_source(&tap_source, kCFRunLoopCommonModes);
}
CFRunLoop::run_current();
let _ = exit.send(Err("tap thread exited"));
}
pub struct MacOSInputCapture {
event_rx: Receiver<(CaptureHandle, CaptureEvent)>,
notify_tx: Sender<ProducerEvent>,
}
pub struct MacOSInputCapture;
impl MacOSInputCapture {
pub async fn new() -> Result<Self, MacosCaptureCreationError> {
let state = Arc::new(Mutex::new(InputCaptureState::new()?));
let (event_tx, event_rx) = tokio::sync::mpsc::channel(32);
let (notify_tx, mut notify_rx) = tokio::sync::mpsc::channel(32);
let (tap_exit_tx, mut tap_exit_rx) = tokio::sync::oneshot::channel();
pub fn new() -> std::result::Result<Self, MacOSInputCaptureCreationError> {
Err(MacOSInputCaptureCreationError::NotImplemented)
}
}
unsafe {
configure_cf_settings()?;
}
impl Stream for MacOSInputCapture {
type Item = Result<(CaptureHandle, Event), CaptureError>;
log::info!("Enabling CGEvent tap");
let event_tap_thread_state = state.clone();
let event_tap_notify = notify_tx.clone();
thread::spawn(move || {
event_tap_thread(
event_tap_thread_state,
event_tx,
event_tap_notify,
tap_exit_tx,
)
});
let _tap_task: tokio::task::JoinHandle<()> = tokio::task::spawn_local(async move {
loop {
tokio::select! {
producer_event = notify_rx.recv() => {
let producer_event = producer_event.expect("channel closed");
let mut state = state.lock().await;
state.handle_producer_event(producer_event).await.unwrap_or_else(|e| {
log::error!("Failed to handle producer event: {e}");
})
}
res = &mut tap_exit_rx => {
if let Err(e) = res.expect("channel closed") {
log::error!("Tap thread failed: {:?}", e);
break;
}
}
}
}
});
Ok(Self {
event_rx,
notify_tx,
})
fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Poll::Pending
}
}
#[async_trait]
impl Capture for MacOSInputCapture {
async fn create(&mut self, id: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
let notify_tx = self.notify_tx.clone();
tokio::task::spawn_local(async move {
log::debug!("creating client {id}, {pos}");
let _ = notify_tx.send(ProducerEvent::Create(id, pos)).await;
log::debug!("done !");
});
impl InputCapture for MacOSInputCapture {
async fn create(&mut self, _id: CaptureHandle, _pos: Position) -> Result<(), CaptureError> {
Ok(())
}
async fn destroy(&mut self, id: CaptureHandle) -> Result<(), CaptureError> {
let notify_tx = self.notify_tx.clone();
tokio::task::spawn_local(async move {
log::debug!("destroying client {id}");
let _ = notify_tx.send(ProducerEvent::Destroy(id)).await;
log::debug!("done !");
});
async fn destroy(&mut self, _id: CaptureHandle) -> Result<(), CaptureError> {
Ok(())
}
async fn release(&mut self) -> Result<(), CaptureError> {
let notify_tx = self.notify_tx.clone();
tokio::task::spawn_local(async move {
log::debug!("notifying Release");
let _ = notify_tx.send(ProducerEvent::Release).await;
});
Ok(())
}
@@ -524,79 +41,3 @@ impl Capture for MacOSInputCapture {
Ok(())
}
}
impl Stream for MacOSInputCapture {
type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match ready!(self.event_rx.poll_recv(cx)) {
None => Poll::Ready(None),
Some(e) => Poll::Ready(Some(Ok(e))),
}
}
}
type CGSConnectionID = u32;
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
fn CGSSetConnectionProperty(
cid: CGSConnectionID,
targetCID: CGSConnectionID,
key: CFStringRef,
value: CFBooleanRef,
) -> CGError;
fn _CGSDefaultConnection() -> CGSConnectionID;
}
extern "C" {
fn CGEventSourceSetLocalEventsSuppressionInterval(
event_source: CGEventSource,
seconds: CFTimeInterval,
);
}
unsafe fn configure_cf_settings() -> Result<(), MacosCaptureCreationError> {
// When we warp the cursor using CGWarpMouseCursorPosition local events are suppressed for a short time
// this leeds to the cursor not flowing when crossing back from a clinet, set this to to 0 stops the warp
// from working, set a low value by trial and error, 0.05s seems good. 0.25s is the default
let event_source = CGEventSource::new(CGEventSourceStateID::CombinedSessionState)
.map_err(|_| MacosCaptureCreationError::EventSourceCreation)?;
CGEventSourceSetLocalEventsSuppressionInterval(event_source, 0.05);
// This is a private settings that allows the cursor to be hidden while in the background.
// It is used by Barrier and other apps.
let key = CString::new("SetsCursorInBackground").unwrap();
let cf_key = CFStringCreateWithCString(
kCFAllocatorDefault,
key.as_ptr() as *const c_char,
kCFStringEncodingUTF8,
);
if CGSSetConnectionProperty(
_CGSDefaultConnection(),
_CGSDefaultConnection(),
cf_key,
kCFBooleanTrue,
) != kCGErrorSuccess
{
return Err(MacosCaptureCreationError::CGCursorProperty);
}
CFRelease(cf_key as *const c_void);
Ok(())
}
// From X11/X.h
bitflags! {
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct XMods: u32 {
const ShiftMask = (1<<0);
const LockMask = (1<<1);
const ControlMask = (1<<2);
const Mod1Mask = (1<<3);
const Mod2Mask = (1<<4);
const Mod3Mask = (1<<5);
const Mod4Mask = (1<<6);
const Mod5Mask = (1<<7);
}
}

View File

@@ -1,10 +1,11 @@
use async_trait::async_trait;
use futures_core::Stream;
use memmap::MmapOptions;
use std::{
collections::VecDeque,
env,
io::{self, ErrorKind},
os::fd::{AsFd, RawFd},
os::fd::{AsFd, OwnedFd, RawFd},
pin::Pin,
task::{ready, Context, Poll},
};
@@ -13,7 +14,7 @@ use tokio::io::unix::AsyncFd;
use std::{
fs::File,
io::{BufWriter, Write},
os::unix::prelude::AsRawFd,
os::unix::prelude::{AsRawFd, FromRawFd},
sync::Arc,
};
@@ -58,13 +59,15 @@ use wayland_client::{
Connection, Dispatch, DispatchError, EventQueue, QueueHandle, WEnum,
};
use tempfile;
use input_event::{Event, KeyboardEvent, PointerEvent};
use crate::{CaptureError, CaptureEvent};
use crate::CaptureError;
use super::{
error::{LayerShellCaptureCreationError, WaylandBindError},
Capture, CaptureHandle, Position,
CaptureHandle, InputCapture, Position,
};
struct Globals {
@@ -105,10 +108,10 @@ struct State {
client_for_window: Vec<(Arc<Window>, CaptureHandle)>,
focused: Option<(Arc<Window>, CaptureHandle)>,
g: Globals,
wayland_fd: RawFd,
wayland_fd: OwnedFd,
read_guard: Option<ReadEventsGuard>,
qh: QueueHandle<Self>,
pending_events: VecDeque<(CaptureHandle, CaptureEvent)>,
pending_events: VecDeque<(CaptureHandle, Event)>,
output_info: Vec<(WlOutput, OutputInfo)>,
scroll_discrete_pending: bool,
}
@@ -120,7 +123,7 @@ struct Inner {
impl AsRawFd for Inner {
fn as_raw_fd(&self) -> RawFd {
self.state.wayland_fd
self.state.wayland_fd.as_raw_fd()
}
}
@@ -305,7 +308,10 @@ impl WaylandInputCapture {
// flush outgoing events
queue.flush()?;
let wayland_fd = queue.as_fd().as_raw_fd();
// prepare reading wayland events
let read_guard = queue.prepare_read().unwrap(); // there can not yet be events to dispatch
let wayland_fd = read_guard.connection_fd().try_clone_to_owned().unwrap();
std::mem::drop(read_guard);
let mut state = State {
pointer: None,
@@ -559,7 +565,7 @@ impl Inner {
}
#[async_trait]
impl Capture for WaylandInputCapture {
impl InputCapture for WaylandInputCapture {
async fn create(&mut self, handle: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
self.add_client(handle, pos);
let inner = self.0.get_mut();
@@ -585,7 +591,7 @@ impl Capture for WaylandInputCapture {
}
impl Stream for WaylandInputCapture {
type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
type Item = Result<(CaptureHandle, Event), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Some(event) = self.0.get_mut().state.pending_events.pop_front() {
@@ -694,7 +700,7 @@ impl Dispatch<WlPointer, ()> for State {
.iter()
.find(|(w, _c)| w.surface == surface)
.unwrap();
app.pending_events.push_back((*client, CaptureEvent::Begin));
app.pending_events.push_back((*client, Event::Enter()));
}
wl_pointer::Event::Leave { .. } => {
/* There are rare cases, where when a window is opened in
@@ -718,11 +724,11 @@ impl Dispatch<WlPointer, ()> for State {
let (_, client) = app.focused.as_ref().unwrap();
app.pending_events.push_back((
*client,
CaptureEvent::Input(Event::Pointer(PointerEvent::Button {
Event::Pointer(PointerEvent::Button {
time,
button,
state: u32::from(state),
})),
}),
));
}
wl_pointer::Event::Axis { time, axis, value } => {
@@ -735,11 +741,11 @@ impl Dispatch<WlPointer, ()> for State {
} else {
app.pending_events.push_back((
*client,
CaptureEvent::Input(Event::Pointer(PointerEvent::Axis {
Event::Pointer(PointerEvent::Axis {
time,
axis: u32::from(axis) as u8,
value,
})),
}),
));
}
}
@@ -748,10 +754,10 @@ impl Dispatch<WlPointer, ()> for State {
app.scroll_discrete_pending = true;
app.pending_events.push_back((
*client,
CaptureEvent::Input(Event::Pointer(PointerEvent::AxisDiscrete120 {
Event::Pointer(PointerEvent::AxisDiscrete120 {
axis: u32::from(axis) as u8,
value: value120,
})),
}),
));
}
wl_pointer::Event::Frame {} => {
@@ -787,11 +793,11 @@ impl Dispatch<WlKeyboard, ()> for State {
if let Some(client) = client {
app.pending_events.push_back((
*client,
CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key {
Event::Keyboard(KeyboardEvent::Key {
time,
key,
state: u32::from(state) as u8,
})),
}),
));
}
}
@@ -805,15 +811,24 @@ impl Dispatch<WlKeyboard, ()> for State {
if let Some(client) = client {
app.pending_events.push_back((
*client,
CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Modifiers {
depressed: mods_depressed,
latched: mods_latched,
locked: mods_locked,
Event::Keyboard(KeyboardEvent::Modifiers {
mods_depressed,
mods_latched,
mods_locked,
group,
})),
}),
));
}
}
wl_keyboard::Event::Keymap {
format: _,
fd,
size: _,
} => {
let fd = unsafe { &File::from_raw_fd(fd.as_raw_fd()) };
let _mmap = unsafe { MmapOptions::new().map_copy(fd).unwrap() };
// TODO keymap
}
_ => (),
}
}
@@ -840,7 +855,7 @@ impl Dispatch<ZwpRelativePointerV1, ()> for State {
let time = (((utime_hi as u64) << 32 | utime_lo as u64) / 1000) as u32;
app.pending_events.push_back((
*client,
CaptureEvent::Input(Event::Pointer(PointerEvent::Motion { time, dx, dy })),
Event::Pointer(PointerEvent::Motion { time, dx, dy }),
));
}
}

View File

@@ -37,7 +37,7 @@ use input_event::{
Event, KeyboardEvent, PointerEvent, BTN_BACK, BTN_FORWARD, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT,
};
use super::{Capture, CaptureError, CaptureEvent, CaptureHandle, Position};
use super::{CaptureError, CaptureHandle, InputCapture, Position};
enum Request {
Create(CaptureHandle, Position),
@@ -45,7 +45,7 @@ enum Request {
}
pub struct WindowsInputCapture {
event_rx: Receiver<(CaptureHandle, CaptureEvent)>,
event_rx: Receiver<(CaptureHandle, Event)>,
msg_thread: Option<std::thread::JoinHandle<()>>,
}
@@ -64,7 +64,7 @@ unsafe fn signal_message_thread(event_type: EventType) {
}
#[async_trait]
impl Capture for WindowsInputCapture {
impl InputCapture for WindowsInputCapture {
async fn create(&mut self, handle: CaptureHandle, pos: Position) -> Result<(), CaptureError> {
unsafe {
{
@@ -100,7 +100,7 @@ impl Capture for WindowsInputCapture {
static mut REQUEST_BUFFER: Mutex<Vec<Request>> = Mutex::new(Vec::new());
static mut ACTIVE_CLIENT: Option<CaptureHandle> = None;
static mut CLIENT_FOR_POS: Lazy<HashMap<Position, CaptureHandle>> = Lazy::new(HashMap::new);
static mut EVENT_TX: Option<Sender<(CaptureHandle, CaptureEvent)>> = None;
static mut EVENT_TX: Option<Sender<(CaptureHandle, Event)>> = None;
static mut EVENT_THREAD_ID: AtomicU32 = AtomicU32::new(0);
unsafe fn set_event_tid(tid: u32) {
EVENT_THREAD_ID.store(tid, Ordering::SeqCst);
@@ -249,7 +249,7 @@ fn clamp_to_display_bounds(prev_point: (i32, i32), point: (i32, i32)) -> (i32, i
(x.clamp(min_x, max_x), y.clamp(min_y, max_y))
}
unsafe fn send_blocking(event: CaptureEvent) {
unsafe fn send_blocking(event: Event) {
if let Some(active) = ACTIVE_CLIENT {
block_on(async move {
let _ = EVENT_TX.as_ref().unwrap().send((active, event)).await;
@@ -291,7 +291,7 @@ unsafe fn check_client_activation(wparam: WPARAM, lparam: LPARAM) -> bool {
/* notify main thread */
log::debug!("ENTERED @ {prev_pos:?} -> {curr_pos:?}");
send_blocking(CaptureEvent::Begin);
send_blocking(Event::Enter());
ret
}
@@ -313,7 +313,7 @@ unsafe extern "system" fn mouse_proc(ncode: i32, wparam: WPARAM, lparam: LPARAM)
let Some(pointer_event) = to_mouse_event(wparam, lparam) else {
return LRESULT(1);
};
let event = (client, CaptureEvent::Input(Event::Pointer(pointer_event)));
let event = (client, Event::Pointer(pointer_event));
/* notify mainthread (drop events if sending too fast) */
if let Err(e) = EVENT_TX.as_ref().unwrap().try_send(event) {
@@ -334,7 +334,7 @@ unsafe extern "system" fn kybrd_proc(ncode: i32, wparam: WPARAM, lparam: LPARAM)
let Some(key_event) = to_key_event(wparam, lparam) else {
return LRESULT(1);
};
let event = (client, CaptureEvent::Input(Event::Keyboard(key_event)));
let event = (client, Event::Keyboard(key_event));
if let Err(e) = EVENT_TX.as_ref().unwrap().try_send(event) {
log::warn!("e: {e}");
@@ -519,7 +519,7 @@ fn message_thread(ready_tx: mpsc::Sender<()>) {
}
/* window is used ro receive WM_DISPLAYCHANGE messages */
CreateWindowExW(
let ret = CreateWindowExW(
Default::default(),
w!("lan-mouse-message-window-class"),
w!("lan-mouse-msg-window"),
@@ -532,8 +532,10 @@ fn message_thread(ready_tx: mpsc::Sender<()>) {
HMENU::default(),
instance,
None,
)
.expect("CreateWindowExW");
);
if ret.0 == 0 {
panic!("CreateWindowExW");
}
/* run message loop */
loop {
@@ -541,7 +543,7 @@ fn message_thread(ready_tx: mpsc::Sender<()>) {
let Some(msg) = get_msg() else {
break;
};
if msg.hwnd.0.is_null() {
if msg.hwnd.0 == 0 {
/* messages sent via PostThreadMessage */
match msg.wParam.0 {
x if x == EventType::Exit as usize => break,
@@ -614,7 +616,7 @@ impl WindowsInputCapture {
}
impl Stream for WindowsInputCapture {
type Item = Result<(CaptureHandle, CaptureEvent), CaptureError>;
type Item = Result<(CaptureHandle, Event), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match ready!(self.event_rx.poll_recv(cx)) {
None => Poll::Ready(None),

View File

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

View File

@@ -1,54 +1,35 @@
[package]
name = "input-emulation"
description = "cross-platform input emulation library used by lan-mouse"
version = "0.2.1"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
repository = "https://github.com/ferdinandschober/lan-mouse"
[dependencies]
async-trait = "0.1.80"
futures = "0.3.28"
log = "0.4.22"
input-event = { path = "../input-event", version = "0.2.1" }
input-event = { path = "../input-event", version = "0.1.0" }
thiserror = "1.0.61"
tokio = { version = "1.32.0", features = [
"io-util",
"io-std",
"macros",
"net",
"process",
"rt",
"sync",
"signal",
] }
tokio = { version = "1.32.0", features = ["io-util", "io-std", "macros", "net", "process", "rt", "sync", "signal"] }
once_cell = "1.19.0"
[target.'cfg(all(unix, not(target_os="macos")))'.dependencies]
wayland-client = { version = "0.31.1", optional = true }
wayland-protocols = { version = "0.32.1", features = [
"client",
"staging",
"unstable",
], optional = true }
wayland-protocols-wlr = { version = "0.3.1", features = [
"client",
], optional = true }
wayland-protocols-misc = { version = "0.3.1", features = [
"client",
], optional = true }
wayland-client = { version="0.31.1", optional = true }
wayland-protocols = { version="0.32.1", features=["client", "staging", "unstable"], optional = true }
wayland-protocols-wlr = { version="0.3.1", features=["client"], optional = true }
wayland-protocols-misc = { version="0.3.1", features=["client"], optional = true }
x11 = { version = "2.21.0", features = ["xlib", "xtest"], optional = true }
ashpd = { version = "0.9", default-features = false, features = [
"tokio",
], optional = true }
reis = { version = "0.2", features = ["tokio"], optional = true }
ashpd = { version = "0.8", default-features = false, features = ["tokio"], optional = true }
reis = { version = "0.2", features = [ "tokio" ], optional = true }
[target.'cfg(target_os="macos")'.dependencies]
core-graphics = { version = "0.23", features = ["highsierra"] }
keycode = "0.4.0"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58.0", features = [
windows = { version = "0.57.0", features = [
"Win32_System_LibraryLoader",
"Win32_System_Threading",
"Win32_Foundation",
@@ -60,12 +41,7 @@ windows = { version = "0.58.0", features = [
[features]
default = ["wayland", "x11", "xdg_desktop_portal", "libei"]
wayland = [
"dep:wayland-client",
"dep:wayland-protocols",
"dep:wayland-protocols-wlr",
"dep:wayland-protocols-misc",
]
wayland = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:wayland-protocols-misc" ]
x11 = ["dep:x11"]
xdg_desktop_portal = ["dep:ashpd"]
libei = ["dep:reis", "dep:ashpd"]

View File

@@ -3,19 +3,19 @@ use input_event::Event;
use crate::error::EmulationError;
use super::{Emulation, EmulationHandle};
use super::{EmulationHandle, InputEmulation};
#[derive(Default)]
pub(crate) struct DummyEmulation;
pub struct DummyEmulation;
impl DummyEmulation {
pub(crate) fn new() -> Self {
pub fn new() -> Self {
Self {}
}
}
#[async_trait]
impl Emulation for DummyEmulation {
impl InputEmulation for DummyEmulation {
async fn consume(
&mut self,
event: Event,

View File

@@ -87,25 +87,19 @@ pub enum EmulationCreationError {
impl EmulationCreationError {
/// request was intentionally denied by the user
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
pub(crate) fn cancelled_by_user(&self) -> bool {
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
if matches!(
matches!(
self,
EmulationCreationError::Libei(LibeiEmulationCreationError::Ashpd(Response(
ResponseError::Cancelled,
)))
) {
return true;
}
#[cfg(all(unix, feature = "xdg_desktop_portal", not(target_os = "macos")))]
if matches!(
self,
EmulationCreationError::Xdp(XdpEmulationCreationError::Ashpd(Response(
))) | EmulationCreationError::Xdp(XdpEmulationCreationError::Ashpd(Response(
ResponseError::Cancelled,
)))
) {
return true;
}
)
}
#[cfg(not(all(unix, feature = "libei", not(target_os = "macos"))))]
pub(crate) fn cancelled_by_user(&self) -> bool {
false
}
}

View File

@@ -1,34 +1,31 @@
use async_trait::async_trait;
use std::{
collections::{HashMap, HashSet},
fmt::Display,
};
use std::fmt::Display;
use input_event::{Event, KeyboardEvent};
use input_event::Event;
pub use self::error::{EmulationCreationError, EmulationError, InputEmulationError};
#[cfg(windows)]
mod windows;
pub mod windows;
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
mod x11;
pub mod x11;
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
mod wlroots;
pub mod wlroots;
#[cfg(all(unix, feature = "xdg_desktop_portal", not(target_os = "macos")))]
mod xdg_desktop_portal;
pub mod xdg_desktop_portal;
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
mod libei;
pub mod libei;
#[cfg(target_os = "macos")]
mod macos;
pub mod macos;
/// fallback input emulation (logs events)
mod dummy;
mod error;
pub mod dummy;
pub mod error;
pub type EmulationHandle = u64;
@@ -69,166 +66,8 @@ impl Display for Backend {
}
}
pub struct InputEmulation {
emulation: Box<dyn Emulation>,
handles: HashSet<EmulationHandle>,
pressed_keys: HashMap<EmulationHandle, HashSet<u32>>,
}
impl InputEmulation {
async fn with_backend(backend: Backend) -> Result<InputEmulation, EmulationCreationError> {
let emulation: Box<dyn Emulation> = match backend {
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
Backend::Wlroots => Box::new(wlroots::WlrootsEmulation::new()?),
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
Backend::Libei => Box::new(libei::LibeiEmulation::new().await?),
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
Backend::X11 => Box::new(x11::X11Emulation::new()?),
#[cfg(all(unix, feature = "xdg_desktop_portal", not(target_os = "macos")))]
Backend::Xdp => Box::new(xdg_desktop_portal::DesktopPortalEmulation::new().await?),
#[cfg(windows)]
Backend::Windows => Box::new(windows::WindowsEmulation::new()?),
#[cfg(target_os = "macos")]
Backend::MacOs => Box::new(macos::MacOSEmulation::new()?),
Backend::Dummy => Box::new(dummy::DummyEmulation::new()),
};
Ok(Self {
emulation,
handles: HashSet::new(),
pressed_keys: HashMap::new(),
})
}
pub async fn new(backend: Option<Backend>) -> Result<InputEmulation, EmulationCreationError> {
if let Some(backend) = backend {
let b = Self::with_backend(backend).await;
if b.is_ok() {
log::info!("using emulation backend: {backend}");
}
return b;
}
for backend in [
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
Backend::Wlroots,
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
Backend::Libei,
#[cfg(all(unix, feature = "xdg_desktop_portal", not(target_os = "macos")))]
Backend::Xdp,
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
Backend::X11,
#[cfg(windows)]
Backend::Windows,
#[cfg(target_os = "macos")]
Backend::MacOs,
Backend::Dummy,
] {
match Self::with_backend(backend).await {
Ok(b) => {
log::info!("using emulation backend: {backend}");
return Ok(b);
}
Err(e) if e.cancelled_by_user() => return Err(e),
Err(e) => log::warn!("{e}"),
}
}
Err(EmulationCreationError::NoAvailableBackend)
}
pub async fn consume(
&mut self,
event: Event,
handle: EmulationHandle,
) -> Result<(), EmulationError> {
match event {
Event::Keyboard(KeyboardEvent::Key { key, state, .. }) => {
// prevent double pressed / released keys
if self.update_pressed_keys(handle, key, state) {
self.emulation.consume(event, handle).await?;
}
Ok(())
}
_ => self.emulation.consume(event, handle).await,
}
}
pub async fn create(&mut self, handle: EmulationHandle) -> bool {
if self.handles.insert(handle) {
self.pressed_keys.insert(handle, HashSet::new());
self.emulation.create(handle).await;
true
} else {
false
}
}
pub async fn destroy(&mut self, handle: EmulationHandle) {
let _ = self.release_keys(handle).await;
if self.handles.remove(&handle) {
self.pressed_keys.remove(&handle);
self.emulation.destroy(handle).await
}
}
pub async fn terminate(&mut self) {
for handle in self.handles.iter().cloned().collect::<Vec<_>>() {
self.destroy(handle).await
}
self.emulation.terminate().await
}
pub async fn release_keys(&mut self, handle: EmulationHandle) -> Result<(), EmulationError> {
if let Some(keys) = self.pressed_keys.get_mut(&handle) {
let keys = keys.drain().collect::<Vec<_>>();
for key in keys {
let event = Event::Keyboard(KeyboardEvent::Key {
time: 0,
key,
state: 0,
});
self.emulation.consume(event, handle).await?;
if let Ok(key) = input_event::scancode::Linux::try_from(key) {
log::warn!("releasing stuck key: {key:?}");
}
}
}
let event = Event::Keyboard(KeyboardEvent::Modifiers {
depressed: 0,
latched: 0,
locked: 0,
group: 0,
});
self.emulation.consume(event, handle).await?;
Ok(())
}
pub fn has_pressed_keys(&self, handle: EmulationHandle) -> bool {
self.pressed_keys
.get(&handle)
.is_some_and(|p| !p.is_empty())
}
/// update the pressed_keys for the given handle
/// returns whether the event should be processed
fn update_pressed_keys(&mut self, handle: EmulationHandle, key: u32, state: u8) -> bool {
let Some(pressed_keys) = self.pressed_keys.get_mut(&handle) else {
return false;
};
if state == 0 {
// currently pressed => can release
pressed_keys.remove(&key)
} else {
// currently not pressed => can press
pressed_keys.insert(key)
}
}
}
#[async_trait]
trait Emulation: Send {
pub trait InputEmulation: Send {
async fn consume(
&mut self,
event: Event,
@@ -238,3 +77,64 @@ trait Emulation: Send {
async fn destroy(&mut self, handle: EmulationHandle);
async fn terminate(&mut self);
}
pub async fn create_backend(
backend: Backend,
) -> Result<Box<dyn InputEmulation>, EmulationCreationError> {
match backend {
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
Backend::Wlroots => Ok(Box::new(wlroots::WlrootsEmulation::new()?)),
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
Backend::Libei => Ok(Box::new(libei::LibeiEmulation::new().await?)),
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
Backend::X11 => Ok(Box::new(x11::X11Emulation::new()?)),
#[cfg(all(unix, feature = "xdg_desktop_portal", not(target_os = "macos")))]
Backend::Xdp => Ok(Box::new(
xdg_desktop_portal::DesktopPortalEmulation::new().await?,
)),
#[cfg(windows)]
Backend::Windows => Ok(Box::new(windows::WindowsEmulation::new()?)),
#[cfg(target_os = "macos")]
Backend::MacOs => Ok(Box::new(macos::MacOSEmulation::new()?)),
Backend::Dummy => Ok(Box::new(dummy::DummyEmulation::new())),
}
}
pub async fn create(
backend: Option<Backend>,
) -> Result<Box<dyn InputEmulation>, EmulationCreationError> {
if let Some(backend) = backend {
let b = create_backend(backend).await;
if b.is_ok() {
log::info!("using emulation backend: {backend}");
}
return b;
}
for backend in [
#[cfg(all(unix, feature = "wayland", not(target_os = "macos")))]
Backend::Wlroots,
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
Backend::Libei,
#[cfg(all(unix, feature = "xdg_desktop_portal", not(target_os = "macos")))]
Backend::Xdp,
#[cfg(all(unix, feature = "x11", not(target_os = "macos")))]
Backend::X11,
#[cfg(windows)]
Backend::Windows,
#[cfg(target_os = "macos")]
Backend::MacOs,
Backend::Dummy,
] {
match create_backend(backend).await {
Ok(b) => {
log::info!("using emulation backend: {backend}");
return Ok(b);
}
Err(e) if e.cancelled_by_user() => return Err(e),
Err(e) => log::warn!("{e}"),
}
}
Err(EmulationCreationError::NoAvailableBackend)
}

View File

@@ -15,7 +15,7 @@ use tokio::task::JoinHandle;
use ashpd::{
desktop::{
remote_desktop::{DeviceType, RemoteDesktop},
PersistMode, Session,
Session,
},
WindowIdentifier,
};
@@ -34,7 +34,7 @@ use input_event::{Event, KeyboardEvent, PointerEvent};
use crate::error::{EmulationError, ReisConvertStreamError};
use super::{error::LibeiEmulationCreationError, Emulation, EmulationHandle};
use super::{error::LibeiEmulationCreationError, EmulationHandle, InputEmulation};
static INTERFACES: Lazy<HashMap<&'static str, u32>> = Lazy::new(|| {
let mut m = HashMap::new();
@@ -60,7 +60,7 @@ struct Devices {
keyboard: Arc<RwLock<Option<(ei::Device, ei::Keyboard)>>>,
}
pub(crate) struct LibeiEmulation<'a> {
pub struct LibeiEmulation<'a> {
context: ei::Context,
devices: Devices,
ei_task: JoinHandle<()>,
@@ -68,11 +68,10 @@ pub(crate) struct LibeiEmulation<'a> {
libei_error: Arc<AtomicBool>,
serial: AtomicU32,
_remote_desktop: RemoteDesktop<'a>,
session: Session<'a, RemoteDesktop<'a>>,
session: Session<'a>,
}
async fn get_ei_fd<'a>(
) -> Result<(RemoteDesktop<'a>, Session<'a, RemoteDesktop<'a>>, OwnedFd), ashpd::Error> {
async fn get_ei_fd<'a>() -> Result<(RemoteDesktop<'a>, Session<'a>, OwnedFd), ashpd::Error> {
let remote_desktop = RemoteDesktop::new().await?;
log::debug!("creating session ...");
@@ -80,12 +79,7 @@ async fn get_ei_fd<'a>(
log::debug!("selecting devices ...");
remote_desktop
.select_devices(
&session,
DeviceType::Keyboard | DeviceType::Pointer,
None,
PersistMode::ExplicitlyRevoked,
)
.select_devices(&session, DeviceType::Keyboard | DeviceType::Pointer)
.await?;
log::info!("requesting permission for input emulation");
@@ -99,7 +93,7 @@ async fn get_ei_fd<'a>(
}
impl<'a> LibeiEmulation<'a> {
pub(crate) async fn new() -> Result<Self, LibeiEmulationCreationError> {
pub async fn new() -> Result<Self, LibeiEmulationCreationError> {
let (_remote_desktop, session, eifd) = get_ei_fd().await?;
let stream = UnixStream::from(eifd);
stream.set_nonblocking(true)?;
@@ -147,7 +141,7 @@ impl<'a> Drop for LibeiEmulation<'a> {
}
#[async_trait]
impl<'a> Emulation for LibeiEmulation<'a> {
impl<'a> InputEmulation for LibeiEmulation<'a> {
async fn consume(
&mut self,
event: Event,
@@ -213,6 +207,7 @@ impl<'a> Emulation for LibeiEmulation<'a> {
d.frame(self.serial.load(Ordering::SeqCst), now);
}
}
PointerEvent::Frame {} => {}
},
Event::Keyboard(k) => match k {
KeyboardEvent::Key {
@@ -234,6 +229,7 @@ impl<'a> Emulation for LibeiEmulation<'a> {
}
KeyboardEvent::Modifiers { .. } => {}
},
_ => {}
}
self.context
.flush()

View File

@@ -1,4 +1,4 @@
use super::{error::EmulationError, Emulation, EmulationHandle};
use super::{error::EmulationError, EmulationHandle, InputEmulation};
use async_trait::async_trait;
use core_graphics::display::{CGDisplayBounds, CGMainDisplayID, CGPoint};
use core_graphics::event::{
@@ -16,8 +16,8 @@ use super::error::MacOSEmulationCreationError;
const DEFAULT_REPEAT_DELAY: Duration = Duration::from_millis(500);
const DEFAULT_REPEAT_INTERVAL: Duration = Duration::from_millis(32);
pub(crate) struct MacOSEmulation {
event_source: CGEventSource,
pub struct MacOSEmulation {
pub event_source: CGEventSource,
repeat_task: Option<AbortHandle>,
button_state: ButtonState,
}
@@ -53,7 +53,7 @@ impl IndexMut<CGMouseButton> for ButtonState {
unsafe impl Send for MacOSEmulation {}
impl MacOSEmulation {
pub(crate) fn new() -> Result<Self, MacOSEmulationCreationError> {
pub fn new() -> Result<Self, MacOSEmulationCreationError> {
let event_source = CGEventSource::new(CGEventSourceStateID::CombinedSessionState)
.map_err(|_| MacOSEmulationCreationError::EventSourceCreation)?;
let button_state = ButtonState {
@@ -106,7 +106,7 @@ fn key_event(event_source: CGEventSource, key: u16, state: u8) {
}
#[async_trait]
impl Emulation for MacOSEmulation {
impl InputEmulation for MacOSEmulation {
async fn consume(
&mut self,
event: Event,
@@ -262,6 +262,7 @@ impl Emulation for MacOSEmulation {
};
event.post(CGEventTapLocation::HID);
}
PointerEvent::Frame { .. } => {}
},
Event::Keyboard(keyboard_event) => match keyboard_event {
KeyboardEvent::Key {
@@ -285,6 +286,7 @@ impl Emulation for MacOSEmulation {
}
KeyboardEvent::Modifiers { .. } => {}
},
_ => (),
}
// FIXME
Ok(())

View File

@@ -19,23 +19,23 @@ use windows::Win32::UI::Input::KeyboardAndMouse::{
};
use windows::Win32::UI::WindowsAndMessaging::{XBUTTON1, XBUTTON2};
use super::{Emulation, EmulationHandle};
use super::{EmulationHandle, InputEmulation};
const DEFAULT_REPEAT_DELAY: Duration = Duration::from_millis(500);
const DEFAULT_REPEAT_INTERVAL: Duration = Duration::from_millis(32);
pub(crate) struct WindowsEmulation {
pub struct WindowsEmulation {
repeat_task: Option<AbortHandle>,
}
impl WindowsEmulation {
pub(crate) fn new() -> Result<Self, WindowsEmulationCreationError> {
pub fn new() -> Result<Self, WindowsEmulationCreationError> {
Ok(Self { repeat_task: None })
}
}
#[async_trait]
impl Emulation for WindowsEmulation {
impl InputEmulation for WindowsEmulation {
async fn consume(&mut self, event: Event, _: EmulationHandle) -> Result<(), EmulationError> {
match event {
Event::Pointer(pointer_event) => match pointer_event {
@@ -53,6 +53,7 @@ impl Emulation for WindowsEmulation {
value,
} => scroll(axis, value as i32),
PointerEvent::AxisDiscrete120 { axis, value } => scroll(axis, value),
PointerEvent::Frame {} => {}
},
Event::Keyboard(keyboard_event) => match keyboard_event {
KeyboardEvent::Key {
@@ -70,6 +71,7 @@ impl Emulation for WindowsEmulation {
}
KeyboardEvent::Modifiers { .. } => {}
},
_ => {}
}
// FIXME
Ok(())

View File

@@ -1,6 +1,6 @@
use crate::error::EmulationError;
use super::{error::WlrootsEmulationCreationError, Emulation};
use super::{error::WlrootsEmulationCreationError, InputEmulation};
use async_trait::async_trait;
use std::collections::HashMap;
use std::io;
@@ -50,7 +50,7 @@ pub(crate) struct WlrootsEmulation {
}
impl WlrootsEmulation {
pub(crate) fn new() -> Result<Self, WlrootsEmulationCreationError> {
pub fn new() -> Result<Self, WlrootsEmulationCreationError> {
let conn = Connection::connect_to_env()?;
let (globals, queue) = registry_queue_init::<State>(&conn)?;
let qh = queue.handle();
@@ -116,7 +116,7 @@ impl State {
}
#[async_trait]
impl Emulation for WlrootsEmulation {
impl InputEmulation for WlrootsEmulation {
async fn consume(
&mut self,
event: Event,
@@ -200,6 +200,7 @@ impl VirtualInput {
.axis_discrete(0, axis, value as f64 / 6., value / 120);
self.pointer.frame();
}
PointerEvent::Frame {} => self.pointer.frame(),
}
self.pointer.frame();
}
@@ -208,15 +209,16 @@ impl VirtualInput {
self.keyboard.key(time, key, state as u32);
}
KeyboardEvent::Modifiers {
depressed: mods_depressed,
latched: mods_latched,
locked: mods_locked,
mods_depressed,
mods_latched,
mods_locked,
group,
} => {
self.keyboard
.modifiers(mods_depressed, mods_latched, mods_locked, group);
}
},
_ => {}
}
Ok(())
}

View File

@@ -11,16 +11,16 @@ use input_event::{
use crate::error::EmulationError;
use super::{error::X11EmulationCreationError, Emulation, EmulationHandle};
use super::{error::X11EmulationCreationError, EmulationHandle, InputEmulation};
pub(crate) struct X11Emulation {
pub struct X11Emulation {
display: *mut xlib::Display,
}
unsafe impl Send for X11Emulation {}
impl X11Emulation {
pub(crate) fn new() -> Result<Self, X11EmulationCreationError> {
pub fn new() -> Result<Self, X11EmulationCreationError> {
let display = unsafe {
match xlib::XOpenDisplay(ptr::null()) {
d if d == ptr::null::<xlib::Display>() as *mut xlib::Display => {
@@ -99,7 +99,7 @@ impl Drop for X11Emulation {
}
#[async_trait]
impl Emulation for X11Emulation {
impl InputEmulation for X11Emulation {
async fn consume(&mut self, event: Event, _: EmulationHandle) -> Result<(), EmulationError> {
match event {
Event::Pointer(pointer_event) => match pointer_event {
@@ -123,6 +123,7 @@ impl Emulation for X11Emulation {
PointerEvent::AxisDiscrete120 { axis, value } => {
self.emulate_scroll(axis, value as f64);
}
PointerEvent::Frame {} => {}
},
Event::Keyboard(KeyboardEvent::Key {
time: _,

View File

@@ -1,7 +1,7 @@
use ashpd::{
desktop::{
remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop},
PersistMode, Session,
Session,
},
zbus::AsyncDrop,
WindowIdentifier,
@@ -16,15 +16,15 @@ use input_event::{
use crate::error::EmulationError;
use super::{error::XdpEmulationCreationError, Emulation, EmulationHandle};
use super::{error::XdpEmulationCreationError, EmulationHandle, InputEmulation};
pub(crate) struct DesktopPortalEmulation<'a> {
pub struct DesktopPortalEmulation<'a> {
proxy: RemoteDesktop<'a>,
session: Session<'a, RemoteDesktop<'a>>,
session: Session<'a>,
}
impl<'a> DesktopPortalEmulation<'a> {
pub(crate) async fn new() -> Result<DesktopPortalEmulation<'a>, XdpEmulationCreationError> {
pub async fn new() -> Result<DesktopPortalEmulation<'a>, XdpEmulationCreationError> {
log::debug!("connecting to org.freedesktop.portal.RemoteDesktop portal ...");
let proxy = RemoteDesktop::new().await?;
@@ -34,12 +34,7 @@ impl<'a> DesktopPortalEmulation<'a> {
log::debug!("selecting devices ...");
proxy
.select_devices(
&session,
DeviceType::Keyboard | DeviceType::Pointer,
None,
PersistMode::ExplicitlyRevoked,
)
.select_devices(&session, DeviceType::Keyboard | DeviceType::Pointer)
.await?;
log::info!("requesting permission for input emulation");
@@ -56,7 +51,7 @@ impl<'a> DesktopPortalEmulation<'a> {
}
#[async_trait]
impl<'a> Emulation for DesktopPortalEmulation<'a> {
impl<'a> InputEmulation for DesktopPortalEmulation<'a> {
async fn consume(
&mut self,
event: input_event::Event,
@@ -88,7 +83,7 @@ impl<'a> Emulation for DesktopPortalEmulation<'a> {
_ => Axis::Horizontal,
};
self.proxy
.notify_pointer_axis_discrete(&self.session, axis, value / 120)
.notify_pointer_axis_discrete(&self.session, axis, value)
.await?;
}
PointerEvent::Axis {
@@ -108,6 +103,7 @@ impl<'a> Emulation for DesktopPortalEmulation<'a> {
.notify_pointer_axis(&self.session, dx, dy, true)
.await?;
}
PointerEvent::Frame {} => {}
},
Keyboard(k) => {
match k {
@@ -129,6 +125,7 @@ impl<'a> Emulation for DesktopPortalEmulation<'a> {
}
}
}
_ => {}
}
Ok(())
}

View File

@@ -1,10 +1,10 @@
[package]
name = "input-event"
description = "cross-platform input-event types for input-capture / input-emulation"
version = "0.2.1"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
repository = "https://github.com/ferdinandschober/lan-mouse"
[dependencies]
futures-core = "0.3.30"

View File

@@ -1 +1,17 @@
use std::array::TryFromSliceError;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ProtocolError {
#[error(transparent)]
MissingData(#[from] TryFromSliceError),
#[error("invalid event id: `{0}`")]
InvalidEventId(u8),
#[error("invalid pointer event type: `{0}`")]
InvalidPointerEventId(u8),
#[error("invalid keyboard event type: `{0}`")]
InvalidKeyboardEventId(u8),
#[error("expected data at idx `{0:?}`")]
Data(String),
}

View File

@@ -1,6 +1,8 @@
pub use error::ProtocolError;
use std::fmt::{self, Display};
pub mod error;
pub mod proto;
pub mod scancode;
#[cfg(all(unix, feature = "libei", not(target_os = "macos")))]
@@ -23,6 +25,8 @@ pub enum PointerEvent {
Axis { time: u32, axis: u8, value: f64 },
/// discrete axis event, scroll event for mice - 120 = one scroll tick
AxisDiscrete120 { axis: u8, value: i32 },
/// frame event
Frame {},
}
#[derive(Debug, PartialEq, Clone, Copy)]
@@ -31,9 +35,9 @@ pub enum KeyboardEvent {
Key { time: u32, key: u32, state: u8 },
/// modifiers changed state
Modifiers {
depressed: u32,
latched: u32,
locked: u32,
mods_depressed: u32,
mods_latched: u32,
mods_locked: u32,
group: u32,
},
}
@@ -44,6 +48,23 @@ pub enum Event {
Pointer(PointerEvent),
/// keyboard events (key / modifiers)
Keyboard(KeyboardEvent),
/// enter event: request to enter a client.
/// The client must release the pointer if it is grabbed
/// and reply with a leave event, as soon as its ready to
/// receive events
Enter(),
/// leave event: this client is now ready to receive events and will
/// not send any events after until it sends an enter event
Leave(),
/// ping a client, to see if it is still alive. A client that does
/// not respond with a pong event will be assumed to be offline.
Ping(),
/// response to a ping event: this event signals that a client
/// is still alive but must otherwise be ignored
Pong(),
/// explicit disconnect request. The client will no longer
/// send events until the next Enter event. All of its keys should be released.
Disconnect(),
}
impl Display for PointerEvent {
@@ -77,6 +98,7 @@ impl Display for PointerEvent {
PointerEvent::AxisDiscrete120 { axis, value } => {
write!(f, "scroll-120 ({axis}, {value})")
}
PointerEvent::Frame {} => write!(f, "frame()"),
}
}
}
@@ -97,9 +119,9 @@ impl Display for KeyboardEvent {
}
}
KeyboardEvent::Modifiers {
depressed: mods_depressed,
latched: mods_latched,
locked: mods_locked,
mods_depressed,
mods_latched,
mods_locked,
group,
} => write!(
f,
@@ -114,6 +136,11 @@ impl Display for Event {
match self {
Event::Pointer(p) => write!(f, "{}", p),
Event::Keyboard(k) => write!(f, "{}", k),
Event::Enter() => write!(f, "enter"),
Event::Leave() => write!(f, "leave"),
Event::Ping() => write!(f, "ping"),
Event::Pong() => write!(f, "pong"),
Event::Disconnect() => write!(f, "disconnect"),
}
}
}

View File

@@ -57,9 +57,9 @@ fn to_input_events(ei_event: EiEvent) -> Events {
match ei_event {
EiEvent::KeyboardModifiers(mods) => {
let modifier_event = KeyboardEvent::Modifiers {
depressed: mods.depressed,
latched: mods.latched,
locked: mods.locked,
mods_depressed: mods.depressed,
mods_latched: mods.latched,
mods_locked: mods.locked,
group: mods.group,
};
Events::One(Event::Keyboard(modifier_event))

307
input-event/src/proto.rs Normal file
View File

@@ -0,0 +1,307 @@
use std::{fmt::Debug, slice::SliceIndex};
use crate::ProtocolError;
use super::{Event, KeyboardEvent, PointerEvent};
enum PointerEventType {
Motion,
Button,
Axis,
AxisDiscrete120,
Frame,
}
enum KeyboardEventType {
Key,
Modifiers,
}
enum EventType {
Pointer,
Keyboard,
Enter,
Leave,
Ping,
Pong,
Disconnect,
}
impl Event {
fn event_type(&self) -> EventType {
match self {
Self::Pointer(_) => EventType::Pointer,
Self::Keyboard(_) => EventType::Keyboard,
Self::Enter() => EventType::Enter,
Self::Leave() => EventType::Leave,
Self::Ping() => EventType::Ping,
Self::Pong() => EventType::Pong,
Self::Disconnect() => EventType::Disconnect,
}
}
}
impl PointerEvent {
fn event_type(&self) -> PointerEventType {
match self {
Self::Motion { .. } => PointerEventType::Motion,
Self::Button { .. } => PointerEventType::Button,
Self::Axis { .. } => PointerEventType::Axis,
Self::AxisDiscrete120 { .. } => PointerEventType::AxisDiscrete120,
Self::Frame { .. } => PointerEventType::Frame,
}
}
}
impl KeyboardEvent {
fn event_type(&self) -> KeyboardEventType {
match self {
KeyboardEvent::Key { .. } => KeyboardEventType::Key,
KeyboardEvent::Modifiers { .. } => KeyboardEventType::Modifiers,
}
}
}
impl TryFrom<u8> for PointerEventType {
type Error = ProtocolError;
fn try_from(value: u8) -> Result<Self, ProtocolError> {
match value {
x if x == Self::Motion as u8 => Ok(Self::Motion),
x if x == Self::Button as u8 => Ok(Self::Button),
x if x == Self::Axis as u8 => Ok(Self::Axis),
x if x == Self::AxisDiscrete120 as u8 => Ok(Self::AxisDiscrete120),
x if x == Self::Frame as u8 => Ok(Self::Frame),
_ => Err(ProtocolError::InvalidPointerEventId(value)),
}
}
}
impl TryFrom<u8> for KeyboardEventType {
type Error = ProtocolError;
fn try_from(value: u8) -> Result<Self, ProtocolError> {
match value {
x if x == Self::Key as u8 => Ok(Self::Key),
x if x == Self::Modifiers as u8 => Ok(Self::Modifiers),
_ => Err(ProtocolError::InvalidKeyboardEventId(value)),
}
}
}
impl From<&Event> for Vec<u8> {
fn from(event: &Event) -> Self {
let event_id = vec![event.event_type() as u8];
let event_data = match event {
Event::Pointer(p) => p.into(),
Event::Keyboard(k) => k.into(),
Event::Enter() => vec![],
Event::Leave() => vec![],
Event::Ping() => vec![],
Event::Pong() => vec![],
Event::Disconnect() => vec![],
};
[event_id, event_data].concat()
}
}
impl TryFrom<Vec<u8>> for Event {
type Error = ProtocolError;
fn try_from(value: Vec<u8>) -> Result<Self, ProtocolError> {
let event_id = u8::from_be_bytes(value[..1].try_into()?);
match event_id {
i if i == (EventType::Pointer as u8) => Ok(Event::Pointer(value.try_into()?)),
i if i == (EventType::Keyboard as u8) => Ok(Event::Keyboard(value.try_into()?)),
i if i == (EventType::Enter as u8) => Ok(Event::Enter()),
i if i == (EventType::Leave as u8) => Ok(Event::Leave()),
i if i == (EventType::Ping as u8) => Ok(Event::Ping()),
i if i == (EventType::Pong as u8) => Ok(Event::Pong()),
i if i == (EventType::Disconnect as u8) => Ok(Event::Disconnect()),
_ => Err(ProtocolError::InvalidEventId(event_id)),
}
}
}
impl From<&PointerEvent> for Vec<u8> {
fn from(event: &PointerEvent) -> Self {
let id = vec![event.event_type() as u8];
let data = match event {
PointerEvent::Motion { time, dx, dy } => {
let time = time.to_be_bytes();
let dx = dx.to_be_bytes();
let dy = dy.to_be_bytes();
[&time[..], &dx[..], &dy[..]].concat()
}
PointerEvent::Button {
time,
button,
state,
} => {
let time = time.to_be_bytes();
let button = button.to_be_bytes();
let state = state.to_be_bytes();
[&time[..], &button[..], &state[..]].concat()
}
PointerEvent::Axis { time, axis, value } => {
let time = time.to_be_bytes();
let axis = axis.to_be_bytes();
let value = value.to_be_bytes();
[&time[..], &axis[..], &value[..]].concat()
}
PointerEvent::AxisDiscrete120 { axis, value } => {
let axis = axis.to_be_bytes();
let value = value.to_be_bytes();
[&axis[..], &value[..]].concat()
}
PointerEvent::Frame {} => {
vec![]
}
};
[id, data].concat()
}
}
fn decode_u8<I>(data: &[u8], idx: I) -> Result<u8, ProtocolError>
where
I: SliceIndex<[u8], Output = [u8]> + Debug + Clone,
{
let data = data
.get(idx.clone())
.ok_or(ProtocolError::Data(format!("{:?}", idx)))?;
Ok(u8::from_be_bytes(data.try_into()?))
}
fn decode_u32<I>(data: &[u8], idx: I) -> Result<u32, ProtocolError>
where
I: SliceIndex<[u8], Output = [u8]> + Debug + Clone,
{
let data = data
.get(idx.clone())
.ok_or(ProtocolError::Data(format!("{:?}", idx)))?;
Ok(u32::from_be_bytes(data.try_into()?))
}
fn decode_i32<I>(data: &[u8], idx: I) -> Result<i32, ProtocolError>
where
I: SliceIndex<[u8], Output = [u8]> + Debug + Clone,
{
let data = data
.get(idx.clone())
.ok_or(ProtocolError::Data(format!("{:?}", idx)))?;
Ok(i32::from_be_bytes(data.try_into()?))
}
fn decode_f64<I>(data: &[u8], idx: I) -> Result<f64, ProtocolError>
where
I: SliceIndex<[u8], Output = [u8]> + Debug + Clone,
{
let data = data
.get(idx.clone())
.ok_or(ProtocolError::Data(format!("{:?}", idx)))?;
Ok(f64::from_be_bytes(data.try_into()?))
}
impl TryFrom<Vec<u8>> for PointerEvent {
type Error = ProtocolError;
fn try_from(data: Vec<u8>) -> Result<Self, ProtocolError> {
match data.get(1) {
Some(id) => match id.to_owned().try_into()? {
PointerEventType::Motion => {
let time = decode_u32(&data, 2..6)?;
let dx = decode_f64(&data, 6..14)?;
let dy = decode_f64(&data, 14..22)?;
Ok(Self::Motion { time, dx, dy })
}
PointerEventType::Button => {
let time = decode_u32(&data, 2..6)?;
let button = decode_u32(&data, 6..10)?;
let state = decode_u32(&data, 10..14)?;
Ok(Self::Button {
time,
button,
state,
})
}
PointerEventType::Axis => {
let time = decode_u32(&data, 2..6)?;
let axis = decode_u8(&data, 6..7)?;
let value = decode_f64(&data, 7..15)?;
Ok(Self::Axis { time, axis, value })
}
PointerEventType::AxisDiscrete120 => {
let axis = decode_u8(&data, 2..3)?;
let value = decode_i32(&data, 3..7)?;
Ok(Self::AxisDiscrete120 { axis, value })
}
PointerEventType::Frame => Ok(Self::Frame {}),
},
None => Err(ProtocolError::Data("0".to_string())),
}
}
}
impl From<&KeyboardEvent> for Vec<u8> {
fn from(event: &KeyboardEvent) -> Self {
let id = vec![event.event_type() as u8];
let data = match event {
KeyboardEvent::Key { time, key, state } => {
let time = time.to_be_bytes();
let key = key.to_be_bytes();
let state = state.to_be_bytes();
[&time[..], &key[..], &state[..]].concat()
}
KeyboardEvent::Modifiers {
mods_depressed,
mods_latched,
mods_locked,
group,
} => {
let mods_depressed = mods_depressed.to_be_bytes();
let mods_latched = mods_latched.to_be_bytes();
let mods_locked = mods_locked.to_be_bytes();
let group = group.to_be_bytes();
[
&mods_depressed[..],
&mods_latched[..],
&mods_locked[..],
&group[..],
]
.concat()
}
};
[id, data].concat()
}
}
impl TryFrom<Vec<u8>> for KeyboardEvent {
type Error = ProtocolError;
fn try_from(data: Vec<u8>) -> Result<Self, ProtocolError> {
match data.get(1) {
Some(id) => match id.to_owned().try_into()? {
KeyboardEventType::Key => {
let time = decode_u32(&data, 2..6)?;
let key = decode_u32(&data, 6..10)?;
let state = decode_u8(&data, 10..11)?;
Ok(KeyboardEvent::Key { time, key, state })
}
KeyboardEventType::Modifiers => {
let mods_depressed = decode_u32(&data, 2..6)?;
let mods_latched = decode_u32(&data, 6..10)?;
let mods_locked = decode_u32(&data, 10..14)?;
let group = decode_u32(&data, 14..18)?;
Ok(KeyboardEvent::Modifiers {
mods_depressed,
mods_latched,
mods_locked,
group,
})
}
},
None => Err(ProtocolError::Data("0".to_string())),
}
}
}

View File

@@ -1,13 +0,0 @@
[package]
name = "lan-mouse-proto"
description = "network protocol for lan-mouse"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
repository = "https://github.com/feschber/lan-mouse"
[dependencies]
num_enum = "0.7.2"
thiserror = "1.0.61"
input-event = { path = "../input-event", version = "0.2.1" }
paste = "1.0"

View File

@@ -1,251 +0,0 @@
use input_event::{Event as InputEvent, KeyboardEvent, PointerEvent};
use num_enum::{IntoPrimitive, TryFromPrimitive, TryFromPrimitiveError};
use paste::paste;
use std::{
fmt::{Debug, Display},
mem::size_of,
};
use thiserror::Error;
/// defines the maximum size an encoded event can take up
/// this is currently the pointer motion event
/// type: u8, time: u32, dx: f64, dy: f64
pub const MAX_EVENT_SIZE: usize = size_of::<u8>() + size_of::<u32>() + 2 * size_of::<f64>();
/// error type for protocol violations
#[derive(Debug, Error)]
pub enum ProtocolError {
/// event type does not exist
#[error("invalid event id: `{0}`")]
InvalidEventId(#[from] TryFromPrimitiveError<EventType>),
}
/// main lan-mouse protocol event type
#[derive(Clone, Copy, Debug)]
pub enum ProtoEvent {
/// notify a client that the cursor entered its region
/// [`ProtoEvent::Ack`] with the same serial is used for synchronization between devices
Enter(u32),
/// notify a client that the cursor left its region
/// [`ProtoEvent::Ack`] with the same serial is used for synchronization between devices
Leave(u32),
/// acknowledge of an [`ProtoEvent::Enter`] or [`ProtoEvent::Leave`] event
Ack(u32),
/// Input event
Input(InputEvent),
/// Ping event for tracking unresponsive clients.
/// A client has to respond with [`ProtoEvent::Pong`].
Ping,
/// Response to [`ProtoEvent::Ping`]
Pong,
}
impl Display for ProtoEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ProtoEvent::Enter(s) => write!(f, "Enter({s})"),
ProtoEvent::Leave(s) => write!(f, "Leave({s})"),
ProtoEvent::Ack(s) => write!(f, "Ack({s})"),
ProtoEvent::Input(e) => write!(f, "{e}"),
ProtoEvent::Ping => write!(f, "ping"),
ProtoEvent::Pong => write!(f, "pong"),
}
}
}
#[derive(TryFromPrimitive, IntoPrimitive)]
#[repr(u8)]
pub enum EventType {
PointerMotion,
PointerButton,
PointerAxis,
PointerAxisValue120,
KeyboardKey,
KeyboardModifiers,
Ping,
Pong,
Enter,
Leave,
Ack,
}
impl ProtoEvent {
fn event_type(&self) -> EventType {
match self {
ProtoEvent::Input(e) => match e {
InputEvent::Pointer(p) => match p {
PointerEvent::Motion { .. } => EventType::PointerMotion,
PointerEvent::Button { .. } => EventType::PointerButton,
PointerEvent::Axis { .. } => EventType::PointerAxis,
PointerEvent::AxisDiscrete120 { .. } => EventType::PointerAxisValue120,
},
InputEvent::Keyboard(k) => match k {
KeyboardEvent::Key { .. } => EventType::KeyboardKey,
KeyboardEvent::Modifiers { .. } => EventType::KeyboardModifiers,
},
},
ProtoEvent::Ping => EventType::Ping,
ProtoEvent::Pong => EventType::Pong,
ProtoEvent::Enter(_) => EventType::Enter,
ProtoEvent::Leave(_) => EventType::Leave,
ProtoEvent::Ack(_) => EventType::Ack,
}
}
}
impl TryFrom<[u8; MAX_EVENT_SIZE]> for ProtoEvent {
type Error = ProtocolError;
fn try_from(buf: [u8; MAX_EVENT_SIZE]) -> Result<Self, Self::Error> {
let mut buf = &buf[..];
let event_type = decode_u8(&mut buf)?;
match EventType::try_from(event_type)? {
EventType::PointerMotion => {
Ok(Self::Input(InputEvent::Pointer(PointerEvent::Motion {
time: decode_u32(&mut buf)?,
dx: decode_f64(&mut buf)?,
dy: decode_f64(&mut buf)?,
})))
}
EventType::PointerButton => {
Ok(Self::Input(InputEvent::Pointer(PointerEvent::Button {
time: decode_u32(&mut buf)?,
button: decode_u32(&mut buf)?,
state: decode_u32(&mut buf)?,
})))
}
EventType::PointerAxis => Ok(Self::Input(InputEvent::Pointer(PointerEvent::Axis {
time: decode_u32(&mut buf)?,
axis: decode_u8(&mut buf)?,
value: decode_f64(&mut buf)?,
}))),
EventType::PointerAxisValue120 => Ok(Self::Input(InputEvent::Pointer(
PointerEvent::AxisDiscrete120 {
axis: decode_u8(&mut buf)?,
value: decode_i32(&mut buf)?,
},
))),
EventType::KeyboardKey => Ok(Self::Input(InputEvent::Keyboard(KeyboardEvent::Key {
time: decode_u32(&mut buf)?,
key: decode_u32(&mut buf)?,
state: decode_u8(&mut buf)?,
}))),
EventType::KeyboardModifiers => Ok(Self::Input(InputEvent::Keyboard(
KeyboardEvent::Modifiers {
depressed: decode_u32(&mut buf)?,
latched: decode_u32(&mut buf)?,
locked: decode_u32(&mut buf)?,
group: decode_u32(&mut buf)?,
},
))),
EventType::Ping => Ok(Self::Ping),
EventType::Pong => Ok(Self::Pong),
EventType::Enter => Ok(Self::Enter(decode_u32(&mut buf)?)),
EventType::Leave => Ok(Self::Leave(decode_u32(&mut buf)?)),
EventType::Ack => Ok(Self::Ack(decode_u32(&mut buf)?)),
}
}
}
impl From<ProtoEvent> for ([u8; MAX_EVENT_SIZE], usize) {
fn from(event: ProtoEvent) -> Self {
let mut buf = [0u8; MAX_EVENT_SIZE];
let mut len = 0usize;
{
let mut buf = &mut buf[..];
let buf = &mut buf;
let len = &mut len;
encode_u8(buf, len, event.event_type() as u8);
match event {
ProtoEvent::Input(event) => match event {
InputEvent::Pointer(p) => match p {
PointerEvent::Motion { time, dx, dy } => {
encode_u32(buf, len, time);
encode_f64(buf, len, dx);
encode_f64(buf, len, dy);
}
PointerEvent::Button {
time,
button,
state,
} => {
encode_u32(buf, len, time);
encode_u32(buf, len, button);
encode_u32(buf, len, state);
}
PointerEvent::Axis { time, axis, value } => {
encode_u32(buf, len, time);
encode_u8(buf, len, axis);
encode_f64(buf, len, value);
}
PointerEvent::AxisDiscrete120 { axis, value } => {
encode_u8(buf, len, axis);
encode_i32(buf, len, value);
}
},
InputEvent::Keyboard(k) => match k {
KeyboardEvent::Key { time, key, state } => {
encode_u32(buf, len, time);
encode_u32(buf, len, key);
encode_u8(buf, len, state);
}
KeyboardEvent::Modifiers {
depressed,
latched,
locked,
group,
} => {
encode_u32(buf, len, depressed);
encode_u32(buf, len, latched);
encode_u32(buf, len, locked);
encode_u32(buf, len, group);
}
},
},
ProtoEvent::Ping => {}
ProtoEvent::Pong => {}
ProtoEvent::Enter(serial) => encode_u32(buf, len, serial),
ProtoEvent::Leave(serial) => encode_u32(buf, len, serial),
ProtoEvent::Ack(serial) => encode_u32(buf, len, serial),
}
}
(buf, len)
}
}
macro_rules! decode_impl {
($t:ty) => {
paste! {
fn [<decode_ $t>](data: &mut &[u8]) -> Result<$t, ProtocolError> {
let (int_bytes, rest) = data.split_at(size_of::<$t>());
*data = rest;
Ok($t::from_be_bytes(int_bytes.try_into().unwrap()))
}
}
};
}
decode_impl!(u8);
decode_impl!(u32);
decode_impl!(i32);
decode_impl!(f64);
macro_rules! encode_impl {
($t:ty) => {
paste! {
fn [<encode_ $t>](buf: &mut &mut [u8], amt: &mut usize, n: $t) {
let src = n.to_be_bytes();
let data = std::mem::take(buf);
let (int_bytes, rest) = data.split_at_mut(size_of::<$t>());
int_bytes.copy_from_slice(&src);
*amt += size_of::<$t>();
*buf = rest
}
}
};
}
encode_impl!(u8);
encode_impl!(u32);
encode_impl!(i32);
encode_impl!(f64);

View File

@@ -14,7 +14,6 @@ rustPlatform.buildRustPackage {
nativeBuildInputs = with pkgs; [
pkg-config
cmake
makeWrapper
buildPackages.gtk4
];
@@ -23,11 +22,9 @@ rustPlatform.buildRustPackage {
gtk4
libadwaita
xorg.libXtst
] ++ lib.optionals stdenv.isDarwin
(with darwin.apple_sdk_11_0.frameworks; [
CoreGraphics
ApplicationServices
]);
] ++ lib.optionals stdenv.isDarwin [
darwin.apple_sdk_11_0.frameworks.CoreGraphics
];
src = builtins.path {
name = pname;
@@ -39,12 +36,6 @@ rustPlatform.buildRustPackage {
# Set Environment Variables
RUST_BACKTRACE = "full";
# Needed to enable support for SVG icons in GTK
postInstall = ''
wrapProgram "$out/bin/lan-mouse" \
--set GDK_PIXBUF_MODULE_FILE ${pkgs.librsvg.out}/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache
'';
meta = with lib; {
description = "Lan Mouse is a mouse and keyboard sharing software";
longDescription = ''

View File

@@ -1,6 +1,6 @@
use crate::config::Config;
use futures::StreamExt;
use input_capture::{self, CaptureError, CaptureEvent, InputCapture, InputCaptureError, Position};
use input_capture::{self, CaptureError, InputCapture, InputCaptureError, Position};
use input_event::{Event, KeyboardEvent};
use tokio::task::LocalSet;
@@ -20,7 +20,7 @@ async fn input_capture_test(config: Config) -> Result<(), InputCaptureError> {
log::info!("creating input capture");
let backend = config.capture_backend.map(|b| b.into());
loop {
let mut input_capture = InputCapture::new(backend).await?;
let mut input_capture = input_capture::create(backend).await?;
log::info!("creating clients");
input_capture.create(0, Position::Left).await?;
input_capture.create(1, Position::Right).await?;
@@ -33,7 +33,7 @@ async fn input_capture_test(config: Config) -> Result<(), InputCaptureError> {
}
}
async fn do_capture(input_capture: &mut InputCapture) -> Result<(), CaptureError> {
async fn do_capture(input_capture: &mut Box<dyn InputCapture>) -> Result<(), CaptureError> {
loop {
let (client, event) = input_capture
.next()
@@ -46,7 +46,7 @@ async fn do_capture(input_capture: &mut InputCapture) -> Result<(), CaptureError
_ => Position::Bottom,
};
log::info!("position: {pos}, event: {event}");
if let CaptureEvent::Input(Event::Keyboard(KeyboardEvent::Key { key: 1, .. })) = event {
if let Event::Keyboard(KeyboardEvent::Key { key: 1, .. }) = event {
input_capture.release().await?;
break Ok(());
}

View File

@@ -125,8 +125,8 @@ pub struct ClientState {
/// e.g. Laptops usually have at least an ethernet and a wifi port
/// which have different ip addresses
pub ips: HashSet<IpAddr>,
/// client has pressed keys
pub has_pressed_keys: bool,
/// keys currently pressed by this client
pub pressed_keys: HashSet<u32>,
/// dns resolving in progress
pub resolving: bool,
}

View File

@@ -1,5 +1,5 @@
use local_channel::mpsc::Receiver;
use std::net::IpAddr;
use tokio::sync::mpsc::Receiver;
use hickory_resolver::{error::ResolveError, TokioAsyncResolver};

View File

@@ -1,6 +1,5 @@
use crate::config::Config;
use anyhow::Result;
use input_emulation::InputEmulation;
use input_event::{Event, PointerEvent};
use std::f64::consts::PI;
use std::time::{Duration, Instant};
@@ -23,7 +22,7 @@ const RADIUS: f64 = 100.0;
async fn input_emulation_test(config: Config) -> Result<()> {
let backend = config.emulation_backend.map(|b| b.into());
let mut emulation = InputEmulation::new(backend).await?;
let mut emulation = input_emulation::create(backend).await?;
emulation.create(0).await;
let start = Instant::now();
let mut offset = (0, 0);

View File

@@ -114,54 +114,50 @@ fn build_ui(app: &Application) {
let window = Window::new(app, tx);
glib::spawn_future_local(clone!(
#[weak]
window,
async move {
loop {
let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1));
match notify {
FrontendEvent::Created(handle, client, state) => {
window.new_client(handle, client, state);
}
FrontendEvent::Deleted(client) => {
window.delete_client(client);
}
FrontendEvent::State(handle, config, state) => {
window.update_client_config(handle, config);
window.update_client_state(handle, state);
}
FrontendEvent::NoSuchClient(_) => {}
FrontendEvent::Error(e) => {
window.show_toast(e.as_str());
}
FrontendEvent::Enumerate(clients) => {
for (handle, client, state) in clients {
if window.client_idx(handle).is_some() {
window.update_client_config(handle, client);
window.update_client_state(handle, state);
} else {
window.new_client(handle, client, state);
}
glib::spawn_future_local(clone!(@weak window => async move {
loop {
let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1));
match notify {
FrontendEvent::Created(handle, client, state) => {
window.new_client(handle, client, state);
},
FrontendEvent::Deleted(client) => {
window.delete_client(client);
}
FrontendEvent::State(handle, config, state) => {
window.update_client_config(handle, config);
window.update_client_state(handle, state);
}
FrontendEvent::NoSuchClient(_) => { }
FrontendEvent::Error(e) => {
window.show_toast(e.as_str());
},
FrontendEvent::Enumerate(clients) => {
for (handle, client, state) in clients {
if window.client_idx(handle).is_some() {
window.update_client_config(handle, client);
window.update_client_state(handle, state);
} else {
window.new_client(handle, client, state);
}
}
FrontendEvent::PortChanged(port, msg) => {
match msg {
None => window.show_toast(format!("port changed: {port}").as_str()),
Some(msg) => window.show_toast(msg.as_str()),
}
window.imp().set_port(port);
}
FrontendEvent::CaptureStatus(s) => {
window.set_capture(s.into());
}
FrontendEvent::EmulationStatus(s) => {
window.set_emulation(s.into());
},
FrontendEvent::PortChanged(port, msg) => {
match msg {
None => window.show_toast(format!("port changed: {port}").as_str()),
Some(msg) => window.show_toast(msg.as_str()),
}
window.imp().set_port(port);
}
FrontendEvent::CaptureStatus(s) => {
window.set_capture(s.into());
}
FrontendEvent::EmulationStatus(s) => {
window.set_emulation(s.into());
}
}
}
));
}));
window.present();
}

View File

@@ -52,13 +52,10 @@ impl ObjectSubclass for ClientRow {
impl ObjectImpl for ClientRow {
fn constructed(&self) {
self.parent_constructed();
self.delete_button.connect_clicked(clone!(
#[weak(rename_to = row)]
self,
move |button| {
self.delete_button
.connect_clicked(clone!(@weak self as row => move |button| {
row.handle_client_delete(button);
}
));
}));
}
fn signals() -> &'static [glib::subclass::Signal] {

View File

@@ -63,61 +63,31 @@ impl Window {
let selection_model = NoSelection::new(Some(self.clients()));
self.imp().client_list.bind_model(
Some(&selection_model),
clone!(
#[weak(rename_to = window)]
self,
#[upgrade_or_panic]
move |obj| {
let client_object = obj
.downcast_ref()
.expect("Expected object of type `ClientObject`.");
let row = window.create_client_row(client_object);
row.connect_closure(
"request-update",
false,
closure_local!(
#[strong]
window,
move |row: ClientRow, active: bool| {
if let Some(client) = window.client_by_idx(row.index() as u32) {
window.request_client_activate(&client, active);
window.request_client_update(&client);
window.request_client_state(&client);
}
}
),
);
row.connect_closure(
"request-delete",
false,
closure_local!(
#[strong]
window,
move |row: ClientRow| {
if let Some(client) = window.client_by_idx(row.index() as u32) {
window.request_client_delete(&client);
}
}
),
);
row.connect_closure(
"request-dns",
false,
closure_local!(
#[strong]
window,
move |row: ClientRow| {
if let Some(client) = window.client_by_idx(row.index() as u32) {
window.request_client_update(&client);
window.request_dns(&client);
window.request_client_state(&client);
}
}
),
);
row.upcast()
}
),
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.connect_closure("request-update", false, closure_local!(@strong window => move |row: ClientRow, active: bool| {
if let Some(client) = window.client_by_idx(row.index() as u32) {
window.request_client_activate(&client, active);
window.request_client_update(&client);
window.request_client_state(&client);
}
}));
row.connect_closure("request-delete", false, closure_local!(@strong window => move |row: ClientRow| {
if let Some(client) = window.client_by_idx(row.index() as u32) {
window.request_client_delete(&client);
}
}));
row.connect_closure("request-dns", false, closure_local!(@strong window => move
|row: ClientRow| {
if let Some(client) = window.client_by_idx(row.index() as u32) {
window.request_client_update(&client);
window.request_dns(&client);
window.request_client_state(&client);
}
}));
row.upcast()
})
);
}

View File

@@ -84,15 +84,11 @@ impl Window {
clipboard.set_text(hostname.to_str().expect("hostname: invalid utf8"));
button.set_icon_name("emblem-ok-symbolic");
button.set_css_classes(&["success"]);
glib::spawn_future_local(clone!(
#[weak]
button,
async move {
glib::timeout_future_seconds(1).await;
button.set_icon_name("edit-copy-symbolic");
button.set_css_classes(&[]);
}
));
glib::spawn_future_local(clone!(@weak button => async move {
glib::timeout_future_seconds(1).await;
button.set_icon_name("edit-copy-symbolic");
button.set_css_classes(&[]);
}));
}
}

View File

@@ -1,6 +1,5 @@
use capture_task::CaptureRequest;
use emulation_task::EmulationRequest;
use local_channel::mpsc::{channel, Sender};
use capture_task::CaptureEvent;
use emulation_task::EmulationEvent;
use log;
use std::{
cell::{Cell, RefCell},
@@ -9,7 +8,15 @@ use std::{
net::{IpAddr, SocketAddr},
rc::Rc,
};
use tokio::{io::ReadHalf, join, signal, sync::Notify, task::JoinHandle};
use tokio::{
io::ReadHalf,
join, signal,
sync::{
mpsc::{channel, Sender},
Notify,
},
task::JoinHandle,
};
use tokio_util::sync::CancellationToken;
use crate::{
@@ -38,7 +45,7 @@ enum State {
Receiving,
/// Entered the deadzone of another device but waiting
/// for acknowledgement (Leave event) from the device
AwaitAck,
AwaitingLeave,
}
#[derive(Clone)]
@@ -123,12 +130,12 @@ impl Server {
}
};
let (capture_tx, capture_rx) = channel(); /* requests for input capture */
let (emulation_tx, emulation_rx) = channel(); /* emulation requests */
let (udp_recv_tx, udp_recv_rx) = channel(); /* udp receiver */
let (udp_send_tx, udp_send_rx) = channel(); /* udp sender */
let (request_tx, mut request_rx) = channel(); /* frontend requests */
let (dns_tx, dns_rx) = channel(); /* dns requests */
let (capture_tx, capture_rx) = channel(1); /* requests for input capture */
let (emulation_tx, emulation_rx) = channel(1); /* emulation requests */
let (udp_recv_tx, udp_recv_rx) = channel(1); /* udp receiver */
let (udp_send_tx, udp_send_rx) = channel(1); /* udp sender */
let (request_tx, mut request_rx) = channel(1); /* frontend requests */
let (dns_tx, dns_rx) = channel(1); /* dns requests */
// udp task
let network = network_task::new(self.clone(), udp_recv_tx.clone(), udp_send_rx).await?;
@@ -137,8 +144,13 @@ impl Server {
let capture = capture_task::new(self.clone(), capture_rx, udp_send_tx.clone());
// input emulation
let emulation =
emulation_task::new(self.clone(), emulation_rx, udp_recv_rx, udp_send_tx.clone());
let emulation = emulation_task::new(
self.clone(),
emulation_rx,
udp_recv_rx,
udp_send_tx.clone(),
capture_tx.clone(),
);
// create dns resolver
let resolver = DnsResolver::new(dns_rx)?;
@@ -193,7 +205,7 @@ impl Server {
let request = self.pending_dns_requests.borrow_mut().pop_front();
request
} {
dns_tx.send(request).expect("channel closed");
dns_tx.send(request).await.expect("channel closed");
}
}
_ = self.cancelled() => break,
@@ -206,6 +218,13 @@ impl Server {
log::info!("terminating service");
assert!(!capture_tx.is_closed());
assert!(!emulation_tx.is_closed());
assert!(!udp_recv_tx.is_closed());
assert!(!udp_send_tx.is_closed());
assert!(!request_tx.is_closed());
assert!(!dns_tx.is_closed());
self.cancel();
futures::future::join_all(join_handles).await;
let _ = join!(capture, dns_task, emulation, network, ping);
@@ -234,7 +253,7 @@ impl Server {
self.notifies.capture.notify_waiters()
}
async fn capture_enabled(&self) {
async fn capture_notified(&self) {
self.notifies.capture.notified().await
}
@@ -287,8 +306,8 @@ impl Server {
async fn handle_request(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
capture: &Sender<CaptureEvent>,
emulate: &Sender<EmulationEvent>,
event: FrontendRequest,
) -> bool {
log::debug!("frontend: {event:?}");
@@ -353,8 +372,8 @@ impl Server {
async fn deactivate_client(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
capture: &Sender<CaptureEvent>,
emulate: &Sender<EmulationEvent>,
handle: ClientHandle,
) {
log::debug!("deactivating client {handle}");
@@ -363,15 +382,15 @@ impl Server {
None => return,
};
let _ = capture.send(CaptureRequest::Destroy(handle));
let _ = emulate.send(EmulationRequest::Destroy(handle));
let _ = capture.send(CaptureEvent::Destroy(handle)).await;
let _ = emulate.send(EmulationEvent::Destroy(handle)).await;
log::debug!("deactivating client {handle} done");
}
async fn activate_client(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
capture: &Sender<CaptureEvent>,
emulate: &Sender<EmulationEvent>,
handle: ClientHandle,
) {
log::debug!("activating client");
@@ -396,15 +415,15 @@ impl Server {
};
/* notify emulation, capture and frontends */
let _ = capture.send(CaptureRequest::Create(handle, pos.into()));
let _ = emulate.send(EmulationRequest::Create(handle));
let _ = capture.send(CaptureEvent::Create(handle, pos.into())).await;
let _ = emulate.send(EmulationEvent::Create(handle)).await;
log::debug!("activating client {handle} done");
}
async fn remove_client(
&self,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
capture: &Sender<CaptureEvent>,
emulate: &Sender<EmulationEvent>,
handle: ClientHandle,
) {
let Some(active) = self
@@ -417,14 +436,8 @@ impl Server {
};
if active {
let _ = capture.send(CaptureRequest::Destroy(handle));
let _ = emulate.send(EmulationRequest::Destroy(handle));
}
}
fn update_pressed_keys(&self, handle: ClientHandle, has_pressed_keys: bool) {
if let Some((_, s)) = self.client_manager.borrow_mut().get_mut(handle) {
s.has_pressed_keys = has_pressed_keys;
let _ = capture.send(CaptureEvent::Destroy(handle)).await;
let _ = emulate.send(EmulationEvent::Destroy(handle)).await;
}
}
@@ -483,8 +496,8 @@ impl Server {
async fn update_pos(
&self,
handle: ClientHandle,
capture: &Sender<CaptureRequest>,
emulate: &Sender<EmulationRequest>,
capture: &Sender<CaptureEvent>,
emulate: &Sender<EmulationEvent>,
pos: Position,
) {
let (changed, active) = {
@@ -501,11 +514,11 @@ impl Server {
// update state in event input emulator & input capture
if changed {
if active {
let _ = capture.send(CaptureRequest::Destroy(handle));
let _ = emulate.send(EmulationRequest::Destroy(handle));
let _ = capture.send(CaptureEvent::Destroy(handle)).await;
let _ = emulate.send(EmulationEvent::Destroy(handle)).await;
}
let _ = capture.send(CaptureRequest::Create(handle, pos.into()));
let _ = emulate.send(EmulationRequest::Create(handle));
let _ = capture.send(CaptureEvent::Create(handle, pos.into())).await;
let _ = emulate.send(EmulationEvent::Create(handle)).await;
}
}
@@ -544,27 +557,6 @@ impl Server {
.get_mut(handle)
.and_then(|(c, _)| c.hostname.clone())
}
fn get_state(&self) -> State {
self.state.get()
}
fn set_state(&self, state: State) {
log::debug!("state => {state:?}");
self.state.replace(state);
}
fn set_active(&self, handle: Option<u64>) {
log::debug!("active client => {handle:?}");
self.active_client.replace(handle);
}
fn active_addr(&self, handle: u64) -> Option<SocketAddr> {
self.client_manager
.borrow()
.get(handle)
.and_then(|(_, s)| s.active_addr)
}
}
async fn listen_frontend(
@@ -577,7 +569,7 @@ async fn listen_frontend(
let request = frontend::wait_for_request(&mut stream).await;
match request {
Ok(request) => {
let _ = request_tx.send(request);
let _ = request_tx.send(request).await;
}
Err(e) => {
if let Some(e) = e.downcast_ref::<io::Error>() {

View File

@@ -1,20 +1,22 @@
use futures::StreamExt;
use lan_mouse_proto::ProtoEvent;
use local_channel::mpsc::{Receiver, Sender};
use std::net::SocketAddr;
use std::{collections::HashSet, net::SocketAddr};
use tokio::{process::Command, task::JoinHandle};
use input_capture::{
self, CaptureError, CaptureEvent, CaptureHandle, InputCapture, InputCaptureError, Position,
use tokio::{
process::Command,
sync::mpsc::{Receiver, Sender},
task::JoinHandle,
};
use input_capture::{self, CaptureError, CaptureHandle, InputCapture, InputCaptureError, Position};
use input_event::{scancode, Event, KeyboardEvent};
use crate::{client::ClientHandle, frontend::Status, server::State};
use super::Server;
#[derive(Clone, Copy, Debug)]
pub(crate) enum CaptureRequest {
pub(crate) enum CaptureEvent {
/// capture must release the mouse
Release,
/// add a capture client
@@ -25,8 +27,8 @@ pub(crate) enum CaptureRequest {
pub(crate) fn new(
server: Server,
capture_rx: Receiver<CaptureRequest>,
udp_send: Sender<(ProtoEvent, SocketAddr)>,
capture_rx: Receiver<CaptureEvent>,
udp_send: Sender<(Event, SocketAddr)>,
) -> JoinHandle<()> {
let backend = server.config.capture_backend.map(|b| b.into());
tokio::task::spawn_local(capture_task(server, backend, udp_send, capture_rx))
@@ -35,8 +37,8 @@ pub(crate) fn new(
async fn capture_task(
server: Server,
backend: Option<input_capture::Backend>,
sender_tx: Sender<(ProtoEvent, SocketAddr)>,
mut notify_rx: Receiver<CaptureRequest>,
sender_tx: Sender<(Event, SocketAddr)>,
mut notify_rx: Receiver<CaptureEvent>,
) {
loop {
if let Err(e) = do_capture(backend, &server, &sender_tx, &mut notify_rx).await {
@@ -51,7 +53,7 @@ async fn capture_task(
loop {
tokio::select! {
_ = notify_rx.recv() => continue, /* need to ignore requests here! */
_ = server.capture_enabled() => break,
_ = server.capture_notified() => break,
_ = server.cancelled() => return,
}
}
@@ -61,49 +63,51 @@ async fn capture_task(
async fn do_capture(
backend: Option<input_capture::Backend>,
server: &Server,
sender_tx: &Sender<(ProtoEvent, SocketAddr)>,
notify_rx: &mut Receiver<CaptureRequest>,
sender_tx: &Sender<(Event, SocketAddr)>,
notify_rx: &mut Receiver<CaptureEvent>,
) -> Result<(), InputCaptureError> {
/* allow cancelling capture request */
let mut capture = tokio::select! {
r = InputCapture::new(backend) => r?,
r = input_capture::create(backend) => {
r?
},
_ = server.cancelled() => return Ok(()),
};
server.set_capture_status(Status::Enabled);
let clients = server.active_clients();
let clients = clients.iter().copied().map(|handle| {
(
handle,
server
.client_manager
.borrow()
.get(handle)
.map(|(c, _)| c.pos)
.expect("no such client"),
)
});
for (handle, pos) in clients {
capture.create(handle, pos.into()).await?;
// FIXME DUPLICATES
let clients = server
.client_manager
.borrow()
.get_client_states()
.map(|(h, s)| (h, s.clone()))
.collect::<Vec<_>>();
log::info!("{clients:?}");
for (handle, (config, _state)) in clients {
capture.create(handle, config.pos.into()).await?;
}
let mut pressed_keys = HashSet::new();
loop {
tokio::select! {
event = capture.next() => match event {
Some(event) => handle_capture_event(server, &mut capture, sender_tx, event?).await?,
None => return Ok(()),
},
event = capture.next() => {
match event {
Some(Ok(event)) => handle_capture_event(server, &mut capture, sender_tx, event, &mut pressed_keys).await?,
Some(Err(e)) => return Err(e.into()),
None => return Ok(()),
}
}
e = notify_rx.recv() => {
log::debug!("input capture notify rx: {e:?}");
match e {
Some(e) => match e {
CaptureRequest::Release => {
CaptureEvent::Release => {
capture.release().await?;
server.state.replace(State::Receiving);
}
CaptureRequest::Create(h, p) => capture.create(h, p).await?,
CaptureRequest::Destroy(h) => capture.destroy(h).await?,
CaptureEvent::Create(h, p) => capture.create(h, p).await?,
CaptureEvent::Destroy(h) => capture.destroy(h).await?,
},
None => break,
}
@@ -115,52 +119,93 @@ async fn do_capture(
Ok(())
}
fn update_pressed_keys(pressed_keys: &mut HashSet<scancode::Linux>, key: u32, state: u8) {
if let Ok(scancode) = scancode::Linux::try_from(key) {
log::debug!("key: {key}, state: {state}, scancode: {scancode:?}");
match state {
1 => pressed_keys.insert(scancode),
_ => pressed_keys.remove(&scancode),
};
}
}
async fn handle_capture_event(
server: &Server,
capture: &mut InputCapture,
sender_tx: &Sender<(ProtoEvent, SocketAddr)>,
event: (CaptureHandle, CaptureEvent),
capture: &mut Box<dyn InputCapture>,
sender_tx: &Sender<(Event, SocketAddr)>,
event: (CaptureHandle, Event),
pressed_keys: &mut HashSet<scancode::Linux>,
) -> Result<(), CaptureError> {
let (handle, event) = event;
log::trace!("({handle}) {event:?}");
let (handle, mut e) = event;
log::trace!("({handle}) {e:?}");
// capture started
if event == CaptureEvent::Begin {
// wait for remote to acknowlegde enter
server.set_state(State::AwaitAck);
server.set_active(Some(handle));
// restart ping timer to release capture if unreachable
server.restart_ping_timer();
// spawn enter hook cmd
spawn_hook_command(server, handle);
if let Event::Keyboard(KeyboardEvent::Key { key, state, .. }) = e {
update_pressed_keys(pressed_keys, key, state);
log::debug!("{pressed_keys:?}");
if server.release_bind.iter().all(|k| pressed_keys.contains(k)) {
pressed_keys.clear();
log::info!("releasing pointer");
capture.release().await?;
server.state.replace(State::Receiving);
log::trace!("STATE ===> Receiving");
// send an event to release all the modifiers
e = Event::Disconnect();
}
}
// release capture if emulation set state to Receiveing
if server.get_state() == State::Receiving {
capture.release().await?;
return Ok(());
}
let info = {
let mut enter = false;
let mut start_timer = false;
// check release bind
if capture.keys_pressed(&server.release_bind) {
capture.release().await?;
server.set_state(State::Receiving);
}
if let Some(addr) = server.active_addr(handle) {
let event = match server.get_state() {
State::Sending => match event {
CaptureEvent::Begin => ProtoEvent::Enter(0),
CaptureEvent::Input(e) => ProtoEvent::Input(e),
},
/* send additional enter events until acknowleged */
State::AwaitAck => ProtoEvent::Enter(0),
/* released capture */
State::Receiving => ProtoEvent::Leave(0),
};
sender_tx.send((event, addr)).expect("sender closed");
// get client state for handle
let mut client_manager = server.client_manager.borrow_mut();
let client_state = client_manager.get_mut(handle).map(|(_, s)| s);
if let Some(client_state) = client_state {
// if we just entered the client we want to send additional enter events until
// we get a leave event
if let Event::Enter() = e {
server.state.replace(State::AwaitingLeave);
server.active_client.replace(Some(handle));
log::trace!("Active client => {}", handle);
start_timer = true;
log::trace!("STATE ===> AwaitingLeave");
enter = true;
} else {
// ignore any potential events in receiving mode
if server.state.get() == State::Receiving && e != Event::Disconnect() {
return Ok(());
}
}
Some((client_state.active_addr, enter, start_timer))
} else {
None
}
};
let (addr, enter, start_timer) = match info {
Some(i) => i,
None => {
// should not happen
log::warn!("unknown client!");
capture.release().await?;
server.state.replace(State::Receiving);
log::trace!("STATE ===> Receiving");
return Ok(());
}
};
if start_timer {
server.restart_ping_timer();
}
if enter {
spawn_hook_command(server, handle);
}
if let Some(addr) = addr {
if enter {
let _ = sender_tx.send((Event::Enter(), addr)).await;
}
let _ = sender_tx.send((e, addr)).await;
}
Ok(())
}

View File

@@ -1,8 +1,9 @@
use local_channel::mpsc::{Receiver, Sender};
use std::net::SocketAddr;
use lan_mouse_proto::ProtoEvent;
use tokio::task::JoinHandle;
use tokio::{
sync::mpsc::{Receiver, Sender},
task::JoinHandle,
};
use crate::{
client::{ClientHandle, ClientManager},
@@ -10,11 +11,12 @@ use crate::{
server::State,
};
use input_emulation::{self, EmulationError, EmulationHandle, InputEmulation, InputEmulationError};
use input_event::{Event, KeyboardEvent};
use super::{network_task::NetworkError, Server};
use super::{network_task::NetworkError, CaptureEvent, Server};
#[derive(Clone, Debug)]
pub(crate) enum EmulationRequest {
pub(crate) enum EmulationEvent {
/// create a new client
Create(EmulationHandle),
/// destroy a client
@@ -25,22 +27,24 @@ pub(crate) enum EmulationRequest {
pub(crate) fn new(
server: Server,
emulation_rx: Receiver<EmulationRequest>,
udp_rx: Receiver<Result<(ProtoEvent, SocketAddr), NetworkError>>,
sender_tx: Sender<(ProtoEvent, SocketAddr)>,
emulation_rx: Receiver<EmulationEvent>,
udp_rx: Receiver<Result<(Event, SocketAddr), NetworkError>>,
sender_tx: Sender<(Event, SocketAddr)>,
capture_tx: Sender<CaptureEvent>,
) -> JoinHandle<()> {
let emulation_task = emulation_task(server, emulation_rx, udp_rx, sender_tx);
let emulation_task = emulation_task(server, emulation_rx, udp_rx, sender_tx, capture_tx);
tokio::task::spawn_local(emulation_task)
}
async fn emulation_task(
server: Server,
mut rx: Receiver<EmulationRequest>,
mut udp_rx: Receiver<Result<(ProtoEvent, SocketAddr), NetworkError>>,
sender_tx: Sender<(ProtoEvent, SocketAddr)>,
mut rx: Receiver<EmulationEvent>,
mut udp_rx: Receiver<Result<(Event, SocketAddr), NetworkError>>,
sender_tx: Sender<(Event, SocketAddr)>,
capture_tx: Sender<CaptureEvent>,
) {
loop {
if let Err(e) = do_emulation(&server, &mut rx, &mut udp_rx, &sender_tx).await {
if let Err(e) = do_emulation(&server, &mut rx, &mut udp_rx, &sender_tx, &capture_tx).await {
log::warn!("input emulation exited: {e}");
}
server.set_emulation_status(Status::Disabled);
@@ -61,14 +65,17 @@ async fn emulation_task(
async fn do_emulation(
server: &Server,
rx: &mut Receiver<EmulationRequest>,
udp_rx: &mut Receiver<Result<(ProtoEvent, SocketAddr), NetworkError>>,
sender_tx: &Sender<(ProtoEvent, SocketAddr)>,
rx: &mut Receiver<EmulationEvent>,
udp_rx: &mut Receiver<Result<(Event, SocketAddr), NetworkError>>,
sender_tx: &Sender<(Event, SocketAddr)>,
capture_tx: &Sender<CaptureEvent>,
) -> Result<(), InputEmulationError> {
let backend = server.config.emulation_backend.map(|b| b.into());
log::info!("creating input emulation...");
let mut emulation = tokio::select! {
r = InputEmulation::new(backend) => r?,
r = input_emulation::create(backend) => {
r?
}
_ = server.cancelled() => return Ok(()),
};
@@ -79,17 +86,24 @@ async fn do_emulation(
emulation.create(handle).await;
}
let res = do_emulation_session(server, &mut emulation, rx, udp_rx, sender_tx).await;
emulation.terminate().await; // manual drop
res
let res = do_emulation_session(server, &mut emulation, rx, udp_rx, sender_tx, capture_tx).await;
// release potentially still pressed keys
release_all_keys(server, &mut emulation).await?;
emulation.terminate().await;
res?;
Ok(())
}
async fn do_emulation_session(
server: &Server,
emulation: &mut InputEmulation,
rx: &mut Receiver<EmulationRequest>,
udp_rx: &mut Receiver<Result<(ProtoEvent, SocketAddr), NetworkError>>,
sender_tx: &Sender<(ProtoEvent, SocketAddr)>,
emulation: &mut Box<dyn InputEmulation>,
rx: &mut Receiver<EmulationEvent>,
udp_rx: &mut Receiver<Result<(Event, SocketAddr), NetworkError>>,
sender_tx: &Sender<(Event, SocketAddr)>,
capture_tx: &Sender<CaptureEvent>,
) -> Result<(), InputEmulationError> {
let mut last_ignored = None;
@@ -103,13 +117,13 @@ async fn do_emulation_session(
continue;
}
};
handle_incoming_event(server, emulation, sender_tx, &mut last_ignored, udp_event).await?;
handle_udp_rx(server, capture_tx, emulation, sender_tx, &mut last_ignored, udp_event).await?;
}
emulate_event = rx.recv() => {
match emulate_event.expect("channel closed") {
EmulationRequest::Create(h) => { let _ = emulation.create(h).await; },
EmulationRequest::Destroy(h) => emulation.destroy(h).await,
EmulationRequest::ReleaseKeys(c) => emulation.release_keys(c).await?,
EmulationEvent::Create(h) => emulation.create(h).await,
EmulationEvent::Destroy(h) => emulation.destroy(h).await,
EmulationEvent::ReleaseKeys(c) => release_keys(server, emulation, c).await?,
}
}
_ = server.notifies.cancel.cancelled() => break Ok(()),
@@ -117,12 +131,13 @@ async fn do_emulation_session(
}
}
async fn handle_incoming_event(
async fn handle_udp_rx(
server: &Server,
emulate: &mut InputEmulation,
sender_tx: &Sender<(ProtoEvent, SocketAddr)>,
capture_tx: &Sender<CaptureEvent>,
emulate: &mut Box<dyn InputEmulation>,
sender_tx: &Sender<(Event, SocketAddr)>,
last_ignored: &mut Option<SocketAddr>,
event: (ProtoEvent, SocketAddr),
event: (Event, SocketAddr),
) -> Result<(), EmulationError> {
let (event, addr) = event;
@@ -136,26 +151,72 @@ async fn handle_incoming_event(
};
match (event, addr) {
(ProtoEvent::Pong, _) => { /* ignore pong events */ }
(ProtoEvent::Ping, addr) => {
let _ = sender_tx.send((ProtoEvent::Pong, addr));
(Event::Pong(), _) => { /* ignore pong events */ }
(Event::Ping(), addr) => {
let _ = sender_tx.send((Event::Pong(), addr)).await;
}
(ProtoEvent::Leave(_), _) => emulate.release_keys(handle).await?,
(ProtoEvent::Ack(_), _) => server.set_state(State::Sending),
(ProtoEvent::Enter(_), _) => {
server.set_state(State::Receiving);
sender_tx
.send((ProtoEvent::Ack(0), addr))
.expect("no channel")
(Event::Disconnect(), _) => {
release_keys(server, emulate, handle).await?;
}
(ProtoEvent::Input(e), _) => {
if let State::Receiving = server.get_state() {
log::trace!("{event} => emulate");
emulate.consume(e, handle).await?;
let has_pressed_keys = emulate.has_pressed_keys(handle);
server.update_pressed_keys(handle, has_pressed_keys);
if has_pressed_keys {
server.restart_ping_timer();
(event, addr) => {
// tell clients that we are ready to receive events
if let Event::Enter() = event {
let _ = sender_tx.send((Event::Leave(), addr)).await;
}
match server.state.get() {
State::Sending => {
if let Event::Leave() = event {
// ignore additional leave events that may
// have been sent for redundancy
} else {
// upon receiving any event, we go back to receiving mode
server.state.replace(State::Receiving);
let _ = capture_tx.send(CaptureEvent::Release).await;
log::trace!("STATE ===> Receiving");
}
}
State::Receiving => {
let ignore_event =
if let Event::Keyboard(KeyboardEvent::Key { key, state, .. }) = event {
let (ignore_event, restart_timer) = update_client_keys(
&mut server.client_manager.borrow_mut(),
handle,
key,
state,
);
// restart timer if necessary
if restart_timer {
server.restart_ping_timer();
}
ignore_event
} else {
false
};
// workaround buggy rdp backend.
if !ignore_event {
// consume event
emulate.consume(event, handle).await?;
log::trace!("{event} => emulate");
}
}
State::AwaitingLeave => {
// we just entered the deadzone of a client, so
// we need to ignore events that may still
// be on the way until a leave event occurs
// telling us the client registered the enter
if let Event::Leave() = event {
server.state.replace(State::Sending);
log::trace!("STATE ===> Sending");
}
// entering a client that is waiting for a leave
// event should still be possible
if let Event::Enter() = event {
server.state.replace(State::Receiving);
let _ = capture_tx.send(CaptureEvent::Release).await;
log::trace!("STATE ===> Receiving");
}
}
}
}
@@ -163,6 +224,57 @@ async fn handle_incoming_event(
Ok(())
}
async fn release_all_keys(
server: &Server,
emulation: &mut Box<dyn InputEmulation>,
) -> Result<(), EmulationError> {
let clients = server
.client_manager
.borrow()
.get_client_states()
.map(|(h, _)| h)
.collect::<Vec<_>>();
for client in clients {
release_keys(server, emulation, client).await?;
}
Ok(())
}
async fn release_keys(
server: &Server,
emulate: &mut Box<dyn InputEmulation>,
client: ClientHandle,
) -> Result<(), EmulationError> {
let keys = server
.client_manager
.borrow_mut()
.get_mut(client)
.iter_mut()
.flat_map(|(_, s)| s.pressed_keys.drain())
.collect::<Vec<_>>();
for key in keys {
let event = Event::Keyboard(KeyboardEvent::Key {
time: 0,
key,
state: 0,
});
emulate.consume(event, client).await?;
if let Ok(key) = input_event::scancode::Linux::try_from(key) {
log::warn!("releasing stuck key: {key:?}");
}
}
let event = Event::Keyboard(KeyboardEvent::Modifiers {
mods_depressed: 0,
mods_latched: 0,
mods_locked: 0,
group: 0,
});
emulate.consume(event, client).await?;
Ok(())
}
fn activate_client_if_exists(
client_manager: &mut ClientManager,
addr: SocketAddr,
@@ -187,3 +299,25 @@ fn activate_client_if_exists(
client_state.active_addr = Some(addr);
Some(handle)
}
fn update_client_keys(
client_manager: &mut ClientManager,
handle: ClientHandle,
key: u32,
state: u8,
) -> (bool, bool) {
let Some(client_state) = client_manager.get_mut(handle).map(|(_, s)| s) else {
return (true, false);
};
// ignore double press / release events
let ignore_event = if state == 0 {
// ignore release event if key not pressed
!client_state.pressed_keys.remove(&key)
} else {
// ignore press event if key not released
!client_state.pressed_keys.insert(key)
};
let restart_timer = !client_state.pressed_keys.is_empty();
(ignore_event, restart_timer)
}

View File

@@ -1,16 +1,20 @@
use local_channel::mpsc::{Receiver, Sender};
use std::{io, net::SocketAddr};
use thiserror::Error;
use tokio::{net::UdpSocket, task::JoinHandle};
use tokio::{
net::UdpSocket,
sync::mpsc::{Receiver, Sender},
task::JoinHandle,
};
use input_event::{Event, ProtocolError};
use super::Server;
use lan_mouse_proto::{ProtoEvent, ProtocolError};
pub(crate) async fn new(
server: Server,
udp_recv_tx: Sender<Result<(ProtoEvent, SocketAddr), NetworkError>>,
udp_send_rx: Receiver<(ProtoEvent, SocketAddr)>,
udp_recv_tx: Sender<Result<(Event, SocketAddr), NetworkError>>,
udp_send_rx: Receiver<(Event, SocketAddr)>,
) -> io::Result<JoinHandle<()>> {
// bind the udp socket
let listen_addr = SocketAddr::new("0.0.0.0".parse().unwrap(), server.port.get());
@@ -58,15 +62,15 @@ async fn update_port(server: &Server, socket: &mut UdpSocket) {
async fn udp_receiver(
socket: &UdpSocket,
receiver_tx: &Sender<Result<(ProtoEvent, SocketAddr), NetworkError>>,
receiver_tx: &Sender<Result<(Event, SocketAddr), NetworkError>>,
) {
loop {
let event = receive_event(socket).await;
receiver_tx.send(event).expect("channel closed");
receiver_tx.send(event).await.expect("channel closed");
}
}
async fn udp_sender(socket: &UdpSocket, rx: &mut Receiver<(ProtoEvent, SocketAddr)>) {
async fn udp_sender(socket: &UdpSocket, rx: &mut Receiver<(Event, SocketAddr)>) {
loop {
let (event, addr) = rx.recv().await.expect("channel closed");
if let Err(e) = send_event(socket, event, addr) {
@@ -83,17 +87,16 @@ pub(crate) enum NetworkError {
Io(#[from] io::Error),
}
async fn receive_event(socket: &UdpSocket) -> Result<(ProtoEvent, SocketAddr), NetworkError> {
let mut buf = [0u8; lan_mouse_proto::MAX_EVENT_SIZE];
let (_len, src) = socket.recv_from(&mut buf).await?;
let event = ProtoEvent::try_from(buf)?;
Ok((event, src))
async fn receive_event(socket: &UdpSocket) -> Result<(Event, SocketAddr), NetworkError> {
let mut buf = vec![0u8; 22];
let (_amt, src) = socket.recv_from(&mut buf).await?;
Ok((Event::try_from(buf)?, src))
}
fn send_event(sock: &UdpSocket, e: ProtoEvent, addr: SocketAddr) -> Result<usize, NetworkError> {
fn send_event(sock: &UdpSocket, e: Event, addr: SocketAddr) -> Result<usize, NetworkError> {
log::trace!("{:20} ------>->->-> {addr}", e.to_string());
let (data, len): ([u8; lan_mouse_proto::MAX_EVENT_SIZE], usize) = e.into();
let data: Vec<u8> = (&e).into();
// When udp blocks, we dont want to block the event loop.
// Dropping events is better than potentially crashing the input capture.
Ok(sock.try_send_to(&data[..len], addr)?)
Ok(sock.try_send_to(&data, addr)?)
}

View File

@@ -1,20 +1,20 @@
use std::{net::SocketAddr, time::Duration};
use lan_mouse_proto::ProtoEvent;
use local_channel::mpsc::Sender;
use tokio::task::JoinHandle;
use tokio::{sync::mpsc::Sender, task::JoinHandle};
use input_event::Event;
use crate::client::ClientHandle;
use super::{capture_task::CaptureRequest, emulation_task::EmulationRequest, Server, State};
use super::{capture_task::CaptureEvent, emulation_task::EmulationEvent, Server, State};
const MAX_RESPONSE_TIME: Duration = Duration::from_millis(500);
pub(crate) fn new(
server: Server,
sender_ch: Sender<(ProtoEvent, SocketAddr)>,
emulate_notify: Sender<EmulationRequest>,
capture_notify: Sender<CaptureRequest>,
sender_ch: Sender<(Event, SocketAddr)>,
emulate_notify: Sender<EmulationEvent>,
capture_notify: Sender<CaptureEvent>,
) -> JoinHandle<()> {
// timer task
tokio::task::spawn_local(async move {
@@ -27,9 +27,9 @@ pub(crate) fn new(
async fn ping_task(
server: &Server,
sender_ch: Sender<(ProtoEvent, SocketAddr)>,
emulate_notify: Sender<EmulationRequest>,
capture_notify: Sender<CaptureRequest>,
sender_ch: Sender<(Event, SocketAddr)>,
emulate_notify: Sender<EmulationEvent>,
capture_notify: Sender<CaptureEvent>,
) {
loop {
// wait for wake up signal
@@ -42,8 +42,8 @@ async fn ping_task(
let ping_clients: Vec<ClientHandle> = if receiving {
// if receiving we care about clients with pressed keys
client_manager
.get_client_states()
.filter(|(_, (_, s))| s.has_pressed_keys)
.get_client_states_mut()
.filter(|(_, (_, s))| !s.pressed_keys.is_empty())
.map(|(h, _)| h)
.collect()
} else {
@@ -86,7 +86,7 @@ async fn ping_task(
// ping clients
for addr in ping_addrs {
if sender_ch.send((ProtoEvent::Ping, addr)).is_err() {
if sender_ch.send((Event::Ping(), addr)).await.is_err() {
break;
}
}
@@ -123,14 +123,14 @@ async fn ping_task(
if receiving {
for h in unresponsive_clients {
log::warn!("device not responding, releasing keys!");
let _ = emulate_notify.send(EmulationRequest::ReleaseKeys(h));
let _ = emulate_notify.send(EmulationEvent::ReleaseKeys(h)).await;
}
} else {
// release pointer if the active client has not responded
if !unresponsive_clients.is_empty() {
log::warn!("client not responding, releasing pointer!");
server.state.replace(State::Receiving);
let _ = capture_notify.send(CaptureRequest::Release);
let _ = capture_notify.send(CaptureEvent::Release).await;
}
}
}