Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
799bc03a81 | ||
|
|
67090d3aa1 | ||
|
|
001b0e9617 | ||
|
|
0bc2473ffe | ||
|
|
3f4bfe535e | ||
|
|
9b9e5f113a | ||
|
|
1d4abd0258 | ||
|
|
6da7977a94 | ||
|
|
25d2c6db55 | ||
|
|
f0bd880fe7 |
Generated
+13
-18
@@ -4163,16 +4163,6 @@ version = "2.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
|
||||
|
||||
[[package]]
|
||||
name = "iri-string"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"serde 1.0.228",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-terminal"
|
||||
version = "0.4.16"
|
||||
@@ -6772,7 +6762,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rdev"
|
||||
version = "0.5.0-2"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
|
||||
dependencies = [
|
||||
"cocoa 0.24.1",
|
||||
"core-foundation 0.9.4",
|
||||
@@ -6901,11 +6891,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.24"
|
||||
version = "0.12.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
@@ -6934,7 +6923,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
@@ -7187,6 +7175,7 @@ dependencies = [
|
||||
"uuid",
|
||||
"virtual_display",
|
||||
"wallpaper",
|
||||
"wayland-client",
|
||||
"winapi 0.3.9",
|
||||
"windows 0.61.1",
|
||||
"windows-service",
|
||||
@@ -7196,6 +7185,7 @@ dependencies = [
|
||||
"wol-rs",
|
||||
"x11-clipboard 0.8.1",
|
||||
"x11rb 0.12.0",
|
||||
"xkbcommon-dl",
|
||||
"xxhash-rust",
|
||||
"zstd",
|
||||
]
|
||||
@@ -8744,20 +8734,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.6.6"
|
||||
version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"bitflags 2.9.1",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"iri-string",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -202,6 +202,8 @@ gtk = "0.18"
|
||||
termios = "0.3"
|
||||
terminfo = "0.8"
|
||||
winit = "0.30"
|
||||
wayland-client = "0.31"
|
||||
xkbcommon-dl = { version = "0.4", features = ["x11"] }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
|
||||
openssl = { version = "0.10", features = ["vendored"] }
|
||||
|
||||
@@ -62,12 +62,15 @@ class _InstallPageBody extends StatefulWidget {
|
||||
|
||||
class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
with WindowListener {
|
||||
static const _printerStatusTimeout = Duration(seconds: 5);
|
||||
|
||||
late final TextEditingController controller;
|
||||
final RxBool startmenu = true.obs;
|
||||
final RxBool desktopicon = true.obs;
|
||||
final RxBool printer = false.obs;
|
||||
final RxBool showProgress = false.obs;
|
||||
final RxBool btnEnabled = true.obs;
|
||||
final RxBool cancelEnabled = true.obs;
|
||||
|
||||
// todo move to theme.
|
||||
final buttonStyle = OutlinedButton.styleFrom(
|
||||
@@ -83,10 +86,33 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
printer.value = installOptions['PRINTER'] == '1';
|
||||
}
|
||||
|
||||
Future<void> _loadPrinterStatus() async {
|
||||
btnEnabled.value = false;
|
||||
showProgress.value = true;
|
||||
try {
|
||||
final status = await bind
|
||||
.mainGetCommon(key: 'is-printer-installed')
|
||||
.timeout(_printerStatusTimeout);
|
||||
printer.value = status == 'true';
|
||||
if (status != 'true' && status != 'false') {
|
||||
debugPrint('Failed to check printer installation status: $status');
|
||||
}
|
||||
} catch (e) {
|
||||
printer.value = false;
|
||||
debugPrint('Failed to check printer installation status: $e');
|
||||
} finally {
|
||||
showProgress.value = false;
|
||||
btnEnabled.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
windowManager.addListener(this);
|
||||
super.initState();
|
||||
if (printer.value) {
|
||||
_loadPrinterStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -217,8 +243,9 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
() => OutlinedButton.icon(
|
||||
icon: Icon(Icons.close_rounded, size: 16),
|
||||
label: Text(translate('Cancel')),
|
||||
onPressed:
|
||||
btnEnabled.value ? () => windowManager.close() : null,
|
||||
onPressed: cancelEnabled.value
|
||||
? () => windowManager.close()
|
||||
: null,
|
||||
style: buttonStyle,
|
||||
).marginOnly(right: 10),
|
||||
),
|
||||
@@ -253,6 +280,7 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
void install() {
|
||||
do_install() {
|
||||
btnEnabled.value = false;
|
||||
cancelEnabled.value = false;
|
||||
showProgress.value = true;
|
||||
String args = '';
|
||||
if (startmenu.value) args += ' startmenu';
|
||||
|
||||
@@ -335,6 +335,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
||||
// clipboard
|
||||
oldValue = '';
|
||||
}
|
||||
// This length-only diff assumes the IME appends at the end. If an IME
|
||||
// leaves the caret inside paired punctuation, later insertions can replay
|
||||
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
|
||||
// client text-diff issue, independent of the host keyboard layout.
|
||||
if (newValue.length == oldValue.length) {
|
||||
// ?
|
||||
} else if (newValue.length < oldValue.length) {
|
||||
|
||||
@@ -36,6 +36,7 @@ const kUCKeyActionDisplay: u16 = 3;
|
||||
#[allow(non_upper_case_globals)]
|
||||
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
|
||||
const BUF_LEN: usize = 4;
|
||||
const KEYBOARD_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
const MOUSE_EVENT_BUTTON_NUMBER_BACK: i64 = 3;
|
||||
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
|
||||
@@ -428,7 +429,19 @@ impl KeyboardControllable for Enigo {
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
|
||||
event.set_string(cluster);
|
||||
self.post(event, None);
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-sequence: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-sequence: event source is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,17 +449,40 @@ impl KeyboardControllable for Enigo {
|
||||
fn key_click(&mut self, key: Key) {
|
||||
let keycode = self.key_to_keycode(key);
|
||||
if keycode == u16::MAX {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-click: keycode mapping is unavailable"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(src) = self.event_source.as_ref() {
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
|
||||
self.post(event, Some(keycode));
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-down in key-click: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
|
||||
self.post(event, Some(keycode));
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-up in key-click: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-click: event source is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,10 +501,29 @@ impl KeyboardControllable for Enigo {
|
||||
|
||||
fn key_up(&mut self, key: Key) {
|
||||
let code = self.key_to_keycode(key);
|
||||
if code == u16::MAX {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Cannot map macOS Enigo key-up to a keycode"
|
||||
);
|
||||
}
|
||||
if let Some(src) = self.event_source.as_ref() {
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
|
||||
self.post(event, Some(code));
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-up: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-up: event source is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use winapi::{
|
||||
shared::{
|
||||
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
|
||||
ntdef::HANDLE,
|
||||
winerror::ERROR_INVALID_PRINTER_NAME,
|
||||
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
|
||||
},
|
||||
um::winspool::{
|
||||
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
|
||||
@@ -42,20 +42,49 @@ fn enum_local_printer(
|
||||
|
||||
#[inline]
|
||||
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
|
||||
let r = common_enum(
|
||||
"EnumPrintersW",
|
||||
enum_local_printer,
|
||||
1,
|
||||
|info: &PRINTER_INFO_1W| {
|
||||
if is_name_equal(name, info.pName) {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
},
|
||||
|| None,
|
||||
)?;
|
||||
Ok(r.unwrap_or(false))
|
||||
const PRINTER_INFO_LEVEL: DWORD = 1;
|
||||
let mut needed = 0;
|
||||
let mut returned = 0;
|
||||
if enum_local_printer(
|
||||
PRINTER_INFO_LEVEL,
|
||||
null_mut(),
|
||||
0,
|
||||
&mut needed,
|
||||
&mut returned,
|
||||
) == FALSE
|
||||
{
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
|
||||
bail!("Failed to query EnumPrintersW buffer size: {error}");
|
||||
}
|
||||
}
|
||||
if needed == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u8; needed as usize];
|
||||
if enum_local_printer(
|
||||
PRINTER_INFO_LEVEL,
|
||||
buffer.as_mut_ptr(),
|
||||
needed,
|
||||
&mut needed,
|
||||
&mut returned,
|
||||
) == FALSE
|
||||
{
|
||||
bail!(
|
||||
"Failed to call EnumPrintersW, error: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
|
||||
let printers = buffer.as_ptr() as *const PRINTER_INFO_1W;
|
||||
for index in 0..returned {
|
||||
let printer = unsafe { &*printers.add(index as usize) };
|
||||
if is_name_equal(name, printer.pName) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
// Only return the first matched printer
|
||||
|
||||
@@ -553,6 +553,12 @@ impl DrmReader {
|
||||
plane_rotation_answer(rc, rotation)
|
||||
}
|
||||
|
||||
/// The primary plane's rotation read NOW, for a caller that has not grabbed (enumeration):
|
||||
/// `plane_rotation()` only reflects the last grab.
|
||||
pub fn query_plane_rotation(&mut self) -> Option<u32> {
|
||||
self.read_plane_rotation()
|
||||
}
|
||||
|
||||
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
|
||||
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
|
||||
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
|
||||
|
||||
@@ -23,7 +23,7 @@ use gstreamer_app::AppSink;
|
||||
use lazy_static::lazy_static;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use base::platform::linux::CMD_SH;
|
||||
use base::platform::linux::{WaylandDisplayInfo, CMD_SH};
|
||||
use hbb_common::{anyhow::anyhow, bail, config, serde_json, tokio, ResultType};
|
||||
|
||||
use super::capturable::PixelProvider;
|
||||
@@ -157,6 +157,9 @@ pub struct PipeWireCapturable {
|
||||
pub position: (i32, i32),
|
||||
pub logical_size: (usize, usize),
|
||||
pub physical_size: (usize, usize),
|
||||
// False when `physical_size` is the portal size standing in for a resolution get_res() could
|
||||
// not read.
|
||||
physical_size_measured: bool,
|
||||
}
|
||||
|
||||
impl PipeWireCapturable {
|
||||
@@ -168,7 +171,7 @@ impl PipeWireCapturable {
|
||||
) -> Self {
|
||||
// alternative to get screen resolution as stream.size is not always correct ex: on fractional scaling
|
||||
// https://github.com/rustdesk/rustdesk/issues/6116#issuecomment-1817724244
|
||||
let physical_size = get_res(Self {
|
||||
let measured = get_res(Self {
|
||||
dbus_conn: conn.clone(),
|
||||
fd: fd.clone(),
|
||||
path: stream.path,
|
||||
@@ -177,8 +180,10 @@ impl PipeWireCapturable {
|
||||
position: stream.position,
|
||||
logical_size: stream.size,
|
||||
physical_size: (0, 0),
|
||||
})
|
||||
.unwrap_or(stream.size);
|
||||
physical_size_measured: false,
|
||||
});
|
||||
let physical_size_measured = measured.is_ok();
|
||||
let physical_size = measured.unwrap_or(stream.size);
|
||||
*resolution.lock().unwrap() = Some(physical_size);
|
||||
Self {
|
||||
dbus_conn: conn,
|
||||
@@ -189,6 +194,7 @@ impl PipeWireCapturable {
|
||||
position: stream.position,
|
||||
logical_size: stream.size,
|
||||
physical_size,
|
||||
physical_size_measured,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1291,6 +1297,26 @@ pub fn fill_displays(
|
||||
}
|
||||
|
||||
if all_displays.displays.len() > 1 {
|
||||
for (i, sd) in shared_displays.iter_mut().enumerate() {
|
||||
if let crate::Display::WAYLAND(d) = sd {
|
||||
let capturable = &mut d.0;
|
||||
if let Some(origin) = reconciled_origin(
|
||||
capturable.position,
|
||||
capturable.physical_size,
|
||||
capturable.physical_size_measured,
|
||||
&all_displays.displays,
|
||||
) {
|
||||
warn!(
|
||||
"Position {:?} names no output of size {:?}, using {:?}.",
|
||||
capturable.position, capturable.physical_size, origin
|
||||
);
|
||||
capturable.position = origin;
|
||||
if let Some(pw_stream) = rdp_info.streams.get_mut(i) {
|
||||
pw_stream.position = origin;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sort_streams(&all_displays, shared_displays, &mut rdp_info.streams);
|
||||
}
|
||||
|
||||
@@ -1303,6 +1329,50 @@ pub fn fill_displays(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The origin a stream takes when its position names no output of its size. Only a measured size
|
||||
// moves a position: when get_res() failed, the size is the portal size, which can be the mode of
|
||||
// another output and says less than the position does, whether the portal sent that position or
|
||||
// try_fill_positions restored it from its cache.
|
||||
fn reconciled_origin(
|
||||
position: (i32, i32),
|
||||
size: (usize, usize),
|
||||
size_measured: bool,
|
||||
outputs: &[WaylandDisplayInfo],
|
||||
) -> Option<(i32, i32)> {
|
||||
if !size_measured {
|
||||
return None;
|
||||
}
|
||||
corrected_origin(position, size, outputs)
|
||||
}
|
||||
|
||||
// The origin for a stream whose position names no output of the stream's size (a rotated output
|
||||
// counts in either orientation), when exactly one output has that size. xdg-desktop-portal-hyprland reports every stream at (0, 0):
|
||||
// with no output there `sort_streams` dropped the stream, and with another output there the
|
||||
// stream took its origin and missed `try_fix_logical_size`, so the pointer landed on the wrong
|
||||
// output (#15731). With several outputs of that size the position is kept.
|
||||
fn corrected_origin(
|
||||
position: (i32, i32),
|
||||
size: (usize, usize),
|
||||
outputs: &[WaylandDisplayInfo],
|
||||
) -> Option<(i32, i32)> {
|
||||
let has_size = |o: &&WaylandDisplayInfo| {
|
||||
let mode = (o.width as usize, o.height as usize);
|
||||
mode == size || (o.transform % 180 != 0 && (mode.1, mode.0) == size)
|
||||
};
|
||||
if outputs
|
||||
.iter()
|
||||
.filter(has_size)
|
||||
.any(|o| (o.x, o.y) == position)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut same_size = outputs.iter().filter(has_size);
|
||||
match (same_size.next(), same_size.next()) {
|
||||
(Some(o), None) => Some((o.x, o.y)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn try_fill_positions(
|
||||
mouse_move_to: impl Fn(i32, i32),
|
||||
get_cursor_pos: fn() -> Option<(i32, i32)>,
|
||||
@@ -1605,6 +1675,7 @@ fn fill_multi_matched_positions_cursor(
|
||||
position: pw_stream_with_cursor.position,
|
||||
logical_size: pw_stream_with_cursor.size,
|
||||
physical_size: (0, 0),
|
||||
physical_size_measured: false,
|
||||
})?;
|
||||
// Take first frame and copy owned buffer to avoid borrow across second capture
|
||||
let (is_bgr, w, first_buf): (bool, usize, Vec<u8>) =
|
||||
@@ -1731,7 +1802,89 @@ fn sort_streams(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::stage_err;
|
||||
use super::{corrected_origin, reconciled_origin, stage_err, WaylandDisplayInfo};
|
||||
|
||||
fn output(x: i32, y: i32, mode: (i32, i32)) -> WaylandDisplayInfo {
|
||||
WaylandDisplayInfo {
|
||||
name: String::new(),
|
||||
x,
|
||||
y,
|
||||
width: mode.0,
|
||||
height: mode.1,
|
||||
logical_size: None,
|
||||
refresh_rate: 60,
|
||||
transform: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_portal_position_naming_no_output_of_its_size_moves_to_the_only_one() {
|
||||
// 1920x1080 at the origin, 2880x1800 to its right: xdph puts the right one at (0, 0).
|
||||
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
|
||||
assert_eq!(
|
||||
corrected_origin((0, 0), (2880, 1800), &pair),
|
||||
Some((1920, 0))
|
||||
);
|
||||
// A real origin is kept.
|
||||
assert_eq!(corrected_origin((1920, 0), (2880, 1800), &pair), None);
|
||||
// Nothing starts at the origin (the hyprland layout in #15731).
|
||||
let three = [
|
||||
output(0, 120, (1920, 1200)),
|
||||
output(1920, 0, (3440, 1440)),
|
||||
output(5360, 180, (1920, 1080)),
|
||||
];
|
||||
assert_eq!(
|
||||
corrected_origin((0, 0), (3440, 1440), &three),
|
||||
Some((1920, 0))
|
||||
);
|
||||
// Two outputs of that size cannot be told apart: the position is kept.
|
||||
let twins = [
|
||||
output(0, 0, (2560, 1600)),
|
||||
output(2560, 0, (1920, 1080)),
|
||||
output(4480, 0, (1920, 1080)),
|
||||
];
|
||||
assert_eq!(corrected_origin((0, 0), (1920, 1080), &twins), None);
|
||||
// A portrait panel turned to landscape keeps its position next to a 1920x1080 output.
|
||||
let turned = [
|
||||
WaylandDisplayInfo {
|
||||
transform: 90,
|
||||
..output(0, 0, (1080, 1920))
|
||||
},
|
||||
output(1920, 0, (1920, 1080)),
|
||||
];
|
||||
assert_eq!(corrected_origin((0, 0), (1920, 1080), &turned), None);
|
||||
// A rotated output that try_fill_positions could not match by its mode is found in its
|
||||
// delivered orientation.
|
||||
let turned_right = [
|
||||
output(0, 0, (2560, 1440)),
|
||||
WaylandDisplayInfo {
|
||||
transform: 90,
|
||||
..output(2560, 0, (1080, 1920))
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
corrected_origin((0, 0), (1920, 1080), &turned_right),
|
||||
Some((2560, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cached_position_is_not_overridden_by_an_unmeasured_size() {
|
||||
let outputs = [output(0, 0, (1440, 900)), output(1920, 0, (2880, 1800))];
|
||||
// Restored from the cache, or sent by the portal: get_res() failed, so the size is the
|
||||
// portal size, here the mode of the other output, and it moves nothing.
|
||||
assert_eq!(
|
||||
reconciled_origin((1920, 0), (1440, 900), false, &outputs),
|
||||
None
|
||||
);
|
||||
// A measured size still moves a position that names no output of that size: xdph sends
|
||||
// (0, 0) for every stream.
|
||||
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
|
||||
assert_eq!(
|
||||
reconciled_origin((0, 0), (2880, 1800), true, &pair),
|
||||
Some((1920, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_err_keeps_the_detail_safe_for_a_placeholder() {
|
||||
|
||||
@@ -14,3 +14,4 @@ EXPORTS
|
||||
RemoveAmyuniIdd
|
||||
InstallPrinter
|
||||
UninstallPrinter
|
||||
SetPrinterInstallDefault
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <Windows.h>
|
||||
#include <winspool.h>
|
||||
#include <setupapi.h>
|
||||
#include <strutil.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
@@ -356,6 +357,42 @@ namespace RemotePrinter
|
||||
return EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, level, pPrinterInfo, cbBuf, pcbNeeded, pcReturned);
|
||||
}
|
||||
|
||||
static HRESULT queryPrinterPresence(LPCWSTR name)
|
||||
{
|
||||
constexpr DWORD printerInfoLevel = 1;
|
||||
DWORD needed = 0;
|
||||
DWORD returned = 0;
|
||||
if (!enumLocalPrinter(printerInfoLevel, NULL, 0, &needed, &returned))
|
||||
{
|
||||
const DWORD error = GetLastError();
|
||||
if (error != ERROR_INSUFFICIENT_BUFFER || needed == 0)
|
||||
{
|
||||
return error == ERROR_SUCCESS ? E_FAIL : HRESULT_FROM_WIN32(error);
|
||||
}
|
||||
}
|
||||
if (needed == 0)
|
||||
{
|
||||
return S_FALSE;
|
||||
}
|
||||
|
||||
std::vector<BYTE> buffer(needed);
|
||||
if (!enumLocalPrinter(printerInfoLevel, buffer.data(), needed, &needed, &returned))
|
||||
{
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SUCCESS ? E_FAIL : HRESULT_FROM_WIN32(error);
|
||||
}
|
||||
|
||||
const auto printers = reinterpret_cast<const PRINTER_INFO_1W *>(buffer.data());
|
||||
for (DWORD i = 0; i < returned; i++)
|
||||
{
|
||||
if (isNameEqual(name, printers[i].pName))
|
||||
{
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return S_FALSE;
|
||||
}
|
||||
|
||||
BOOL isPrinterAdded(LPCWSTR name)
|
||||
{
|
||||
auto onData = [name](const PRINTER_INFO_1W &info)
|
||||
@@ -528,3 +565,32 @@ namespace RemotePrinter
|
||||
WcaLog(LOGMSG_STANDARD, "Deleted the local port\n");
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" UINT __stdcall SetPrinterInstallDefault(__in MSIHANDLE hInstall)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
LPWSTR appName = NULL;
|
||||
|
||||
hr = WcaInitialize(hInstall, "SetPrinterInstallDefault");
|
||||
ExitOnFailure(hr, "Failed to initialize printer detection");
|
||||
|
||||
hr = WcaGetProperty(L"ProductName", &appName);
|
||||
ExitOnFailure(hr, "Failed to get the printer's application name");
|
||||
|
||||
hr = RemotePrinter::queryPrinterPresence(RemotePrinter::printerNameOf(appName).c_str());
|
||||
if (FAILED(hr))
|
||||
{
|
||||
WcaLog(LOGMSG_STANDARD, "Failed to detect the existing printer (0x%08X); skipping printer installation.", static_cast<UINT>(hr));
|
||||
}
|
||||
|
||||
if (hr != S_OK)
|
||||
{
|
||||
hr = WcaSetProperty(L"INSTALLPRINTER", L"0");
|
||||
ExitOnFailure(hr, "Failed to disable printer installation");
|
||||
WcaLog(LOGMSG_STANDARD, "The application's printer was not confirmed present; leaving printer installation disabled by default.");
|
||||
}
|
||||
|
||||
LExit:
|
||||
ReleaseStr(appName);
|
||||
return WcaFinalize(SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE);
|
||||
}
|
||||
|
||||
@@ -74,13 +74,22 @@
|
||||
<SetProperty Action="RestoreSavedDesktopShortcutsValue" Id="CREATEDESKTOPSHORTCUTS" Value="[SavedDesktopShortcutsCmdLineValue]" After="AppSearch" Sequence="first" Condition="SavedDesktopShortcutsCmdLineValue" />
|
||||
<SetProperty Action="RestoreSavedPrinterValue" Id="INSTALLPRINTER" Value="[SavedPrinterCmdLineValue]" After="AppSearch" Sequence="first" Condition="SavedPrinterCmdLineValue" />
|
||||
|
||||
<!-- Check before the old product removes its printer. firstSequence preserves later UI choices. -->
|
||||
<CustomAction Id="SetPrinterInstallDefault" DllEntry="SetPrinterInstallDefault" Execute="firstSequence" Return="check" BinaryRef="Custom_Actions_Dll" />
|
||||
<InstallUISequence>
|
||||
<Custom Action="SetPrinterInstallDefault" After="RestoreSavedPrinterValue" Condition="WIX_UPGRADE_DETECTED AND NOT SavedPrinterCmdLineValue AND (INSTALLPRINTER = 1 OR INSTALLPRINTER = "Y" OR INSTALLPRINTER = "y")" />
|
||||
</InstallUISequence>
|
||||
<InstallExecuteSequence>
|
||||
<Custom Action="SetPrinterInstallDefault" After="RestoreSavedPrinterValue" Condition="WIX_UPGRADE_DETECTED AND NOT SavedPrinterCmdLineValue AND (INSTALLPRINTER = 1 OR INSTALLPRINTER = "Y" OR INSTALLPRINTER = "y")" />
|
||||
</InstallExecuteSequence>
|
||||
|
||||
<!-- If a command line value or registry value was set, update the main properties with the value -->
|
||||
<SetProperty Id="STARTMENUSHORTCUTS" Value="" After="RestoreSavedStartMenuShortcutsValue" Sequence="first" Condition="CREATESTARTMENUSHORTCUTS AND NOT (CREATESTARTMENUSHORTCUTS = 1 OR CREATESTARTMENUSHORTCUTS = "Y" OR CREATESTARTMENUSHORTCUTS = "y")" />
|
||||
<SetProperty Id="DESKTOPSHORTCUTS" Value="" After="RestoreSavedDesktopShortcutsValue" Sequence="first" Condition="CREATEDESKTOPSHORTCUTS AND NOT (CREATEDESKTOPSHORTCUTS = 1 OR CREATEDESKTOPSHORTCUTS = "Y" OR CREATEDESKTOPSHORTCUTS = "y")" />
|
||||
<!-- PRINTER defaults to empty now, so a saved or command-line INSTALLPRINTER=1
|
||||
must explicitly enable the main PRINTER property. Non-truthy INSTALLPRINTER
|
||||
values still clear PRINTER so upgrades preserve an explicit disabled choice. -->
|
||||
<SetProperty Action="SetPrinterValueEnabled" Id="PRINTER" Value="1" After="RestoreSavedPrinterValue" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = "Y" OR INSTALLPRINTER = "y"" />
|
||||
<SetProperty Action="SetPrinterValueEnabled" Id="PRINTER" Value="1" After="SetPrinterInstallDefault" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = "Y" OR INSTALLPRINTER = "y"" />
|
||||
<SetProperty Action="SetPrinterValueDisabled" Id="PRINTER" Value="" After="SetPrinterValueEnabled" Sequence="first" Condition="INSTALLPRINTER AND NOT (INSTALLPRINTER = 1 OR INSTALLPRINTER = "Y" OR INSTALLPRINTER = "y")" />
|
||||
|
||||
</Fragment>
|
||||
|
||||
@@ -267,6 +267,8 @@ pub enum DataKeyboard {
|
||||
#[serde(tag = "t", content = "c")]
|
||||
pub enum DataKeyboardResponse {
|
||||
GetKeyState(bool),
|
||||
#[cfg(target_os = "linux")]
|
||||
GetKeyStateError(String),
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
|
||||
@@ -23,6 +23,10 @@ pub struct DrmDisplayInfo {
|
||||
/// alone is ambiguous across cards. Empty = the single auto-detected device.
|
||||
#[serde(default)]
|
||||
pub device: String,
|
||||
/// The primary plane rotates its framebuffer by 90/270 in hardware, so every frame is this
|
||||
/// mode TRANSPOSED whatever the compositor reports (gamescope's wl_output has no transform).
|
||||
#[serde(default)]
|
||||
pub plane_transposed: bool,
|
||||
}
|
||||
|
||||
/// Mirrors `scrap::drm_reader::drmtap_dmabuf_desc` except `dma_buf_fd` (never serializes — it rides
|
||||
@@ -280,6 +284,7 @@ fn drm_displays_from_reader(
|
||||
true
|
||||
})
|
||||
.map(|d| DrmDisplayInfo {
|
||||
plane_transposed: plane_transposed(device, d.crtc_id),
|
||||
name: d.name,
|
||||
crtc_id: d.crtc_id,
|
||||
x: d.x,
|
||||
@@ -294,6 +299,33 @@ fn drm_displays_from_reader(
|
||||
(displays, undriven)
|
||||
}
|
||||
|
||||
const DRM_MODE_ROTATE_90: u32 = 0x2;
|
||||
const DRM_MODE_ROTATE_270: u32 = 0x8;
|
||||
|
||||
/// Through a reader bound to `crtc_id`: the enumerating reader is bound to whichever crtc
|
||||
/// auto-select picked.
|
||||
fn plane_transposed(device: &str, crtc_id: u32) -> bool {
|
||||
let dev = (!device.is_empty()).then_some(device);
|
||||
let Some(mut r) = scrap::drm_reader::DrmReader::open(dev, crtc_id) else {
|
||||
return false;
|
||||
};
|
||||
let transposed = match r.query_plane_rotation() {
|
||||
Some(m) => m & (DRM_MODE_ROTATE_90 | DRM_MODE_ROTATE_270) != 0,
|
||||
None => {
|
||||
hbb_common::throttled_log!(
|
||||
std::time::Duration::from_secs(600),
|
||||
debug,
|
||||
"drm: crtc {crtc_id} ({device:?}): plane rotation unreadable; sized as unrotated"
|
||||
);
|
||||
false
|
||||
}
|
||||
};
|
||||
if transposed {
|
||||
log::trace!("drm: crtc {crtc_id} ({device:?}) is rotated 90/270 by its plane");
|
||||
}
|
||||
transposed
|
||||
}
|
||||
|
||||
/// Active displays of every DRM device + the connected-but-undriven identities, from ONE look.
|
||||
fn drm_enumerate_all_displays() -> (Vec<DrmDisplayInfo>, Vec<String>) {
|
||||
if let Some(devices) = scrap::drm_reader::list_devices() {
|
||||
@@ -1673,6 +1705,7 @@ mod drm_conn_tests {
|
||||
active: true,
|
||||
render_node: "/dev/dri/renderD129".to_owned(),
|
||||
device: "/dev/dri/card2".to_owned(),
|
||||
plane_transposed: false,
|
||||
};
|
||||
let wire = serde_json::to_vec(¤t).unwrap();
|
||||
let back: DrmDisplayInfo = serde_json::from_slice(&wire).unwrap();
|
||||
|
||||
+24
-24
@@ -7,11 +7,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Password", "Wachtwoord"),
|
||||
("Ready", "Gereed"),
|
||||
("Established", "Opgezet"),
|
||||
("connecting_status", "Verbinding maken met het RustDesk-netwerk..."),
|
||||
("connecting_status", "Verbinding maken met het RustDesk-netwerk…"),
|
||||
("Enable service", "Service inschakelen"),
|
||||
("Start service", "Service starten"),
|
||||
("Service is running", "De service loopt."),
|
||||
("Service is not running", "De service loopt niet"),
|
||||
("Service is running", "Service loopt."),
|
||||
("Service is not running", "Service loopt niet"),
|
||||
("not_ready_status", "Niet verbonden met de server, controleer de netwerkverbinding"),
|
||||
("Control Remote Desktop", "Extern Bureaublad beheren"),
|
||||
("Transfer file", "Bestand overzetten"),
|
||||
@@ -76,12 +76,12 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Connection Error", "Fout bij verbinding"),
|
||||
("Error", "Fout"),
|
||||
("Reset by the peer", "Door de peer gereset"),
|
||||
("Connecting...", "Verbinding maken..."),
|
||||
("Connecting...", "Verbinding maken…"),
|
||||
("Connection in progress. Please wait.", "Verbinding wordt gemaakt. Even geduld."),
|
||||
("Please try 1 minute later", "Probeer opnieuw over 1 minuut"),
|
||||
("Login Error", "Loginfout"),
|
||||
("Successful", "Geslaagd"),
|
||||
("Connected, waiting for image...", "Verbonden, wachten op beeld..."),
|
||||
("Connected, waiting for image...", "Verbonden, wachten op beeld…"),
|
||||
("Name", "Naam"),
|
||||
("Type", "Type"),
|
||||
("Modified", "Gewijzigd"),
|
||||
@@ -94,7 +94,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Remote", "Op afstand"),
|
||||
("Remote Computer", "Externe computer"),
|
||||
("Local Computer", "Lokale computer"),
|
||||
("Confirm Delete", "Verwijderen bevestigen"),
|
||||
("Confirm Delete", "Verwijdering bevestigen"),
|
||||
("Delete", "Verwijderen"),
|
||||
("Properties", "Eigenschappen"),
|
||||
("Multi Select", "Meervoudige selectie"),
|
||||
@@ -127,7 +127,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Optimize reaction time", "Responstijd optimaliseren"),
|
||||
("Custom", "Aangepast"),
|
||||
("Show remote cursor", "Cursor van extern bureaublad weergeven"),
|
||||
("Show quality monitor", "Kwaliteitsmonitor tonen"),
|
||||
("Show quality monitor", "Kwaliteitsmonitor weergeven"),
|
||||
("Disable clipboard", "Klembord uitschakelen"),
|
||||
("Lock after session end", "Vergrendelen na einde sessie"),
|
||||
("Insert Ctrl + Alt + Del", "Ctrl + Alt + Del invoeren"),
|
||||
@@ -150,7 +150,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Configure", "Configureren"),
|
||||
("config_acc", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Toegankelijkheid."),
|
||||
("config_screen", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Schermopname."),
|
||||
("Installing ...", "Installeren ..."),
|
||||
("Installing ...", "Installeren…"),
|
||||
("Install", "Installeren"),
|
||||
("Installation", "Installatie"),
|
||||
("Installation Path", "Locatie"),
|
||||
@@ -159,10 +159,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("agreement_tip", "Het starten van de installatie betekent het accepteren van de licentieovereenkomst."),
|
||||
("Accept and Install", "Accepteren en installeren"),
|
||||
("End-user license agreement", "Eindgebruikerslicentieovereenkomst"),
|
||||
("Generating ...", "Genereren ..."),
|
||||
("Generating ...", "Genereren…"),
|
||||
("Your installation is lower version.", "Uw installatie is een lagere versie."),
|
||||
("not_close_tcp_tip", "Sluit dit venster niet zolang u de tunnel gebruikt"),
|
||||
("Listening ...", "Luisteren ..."),
|
||||
("Listening ...", "Luisteren…"),
|
||||
("Remote Host", "Externe host"),
|
||||
("Remote Port", "Externe poort"),
|
||||
("Action", "Actie"),
|
||||
@@ -185,7 +185,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Relayed and unencrypted connection", "Doorgeschakelde en niet-versleutelde verbinding"),
|
||||
("Enter Remote ID", "Extern ID invoeren"),
|
||||
("Enter your password", "Wachtwoord invoeren"),
|
||||
("Logging in...", "Aanmelden..."),
|
||||
("Logging in...", "Aanmelden…"),
|
||||
("Enable RDP session sharing", "Delen van RDP-sessie inschakelen"),
|
||||
("Auto Login", "Automatisch aanmelden"),
|
||||
("Enable direct IP access", "Directe IP-toegang inschakelen"),
|
||||
@@ -368,11 +368,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Deny LAN discovery", "LAN-detectie weigeren"),
|
||||
("Write a message", "Schrijf een bericht"),
|
||||
("Prompt", "Melding"),
|
||||
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging..."),
|
||||
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging…"),
|
||||
("elevated_foreground_window_tip", "Het momenteel geopende venster van de op afstand bediende computer vereist hogere rechten. Daarom is het momenteel niet mogelijk de muis en het toetsenbord te gebruiken. Vraag de gebruiker wiens computer u op afstand bedient om het venster te minimaliseren of de rechten te verhogen. Om dit probleem in de toekomst te voorkomen, wordt aanbevolen de software te installeren op de op afstand bediende computer."),
|
||||
("Disconnected", "Afgesloten"),
|
||||
("Other", "Andere"),
|
||||
("Confirm before closing multiple tabs", "Bevestig voordat u meerdere tabbladen sluit"),
|
||||
("Confirm before closing multiple tabs", "Bevestiging geven bij sluiten van meerdere tabbladen"),
|
||||
("Keyboard Settings", "Toetsenbordinstellingen"),
|
||||
("Full Access", "Volledige toegang"),
|
||||
("Screen Share", "Scherm delen"),
|
||||
@@ -381,7 +381,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("xdp-portal-unavailable", "Wayland schermopname is mislukt. De XDG Desktop Portal kan gecrashed zijn of is onbeschikbaar. Probeer het opnieuw te starten met `systemctl --user restart xdg-desktop-portal`."),
|
||||
("JumpLink", "JumpLink"),
|
||||
("Please Select the screen to be shared(Operate on the peer side).", "Selecteer het scherm dat moet worden gedeeld (Bediening aan de kant van de peer)."),
|
||||
("Show RustDesk", "Toon RustDesk"),
|
||||
("Show RustDesk", "RustDesk weergeven"),
|
||||
("This PC", "Deze PC"),
|
||||
("or", "of"),
|
||||
("Elevate", "Verhogen"),
|
||||
@@ -389,7 +389,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Accept sessions via password", "Sessies accepteren via wachtwoord"),
|
||||
("Accept sessions via click", "Sessies accepteren via klik"),
|
||||
("Accept sessions via both", "Accepteer sessies via klik of wachtwoord"),
|
||||
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert..."),
|
||||
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert…"),
|
||||
("One-time Password", "Eenmalig wachtwoord"),
|
||||
("Use one-time password", "Eenmalig wachtwoord gebruiken"),
|
||||
("One-time password length", "Lengte eenmalig wachtwoord"),
|
||||
@@ -428,7 +428,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Medium", "Middelmatig"),
|
||||
("Strong", "Sterk"),
|
||||
("Switch Sides", "Van kant wisselen"),
|
||||
("Please confirm if you want to share your desktop?", "Bevestig dat u uw bureaublad wilt delen?"),
|
||||
("Please confirm if you want to share your desktop?", "Weet u zeker dat u uw bureaublad wilt delen?"),
|
||||
("Display", "Weergave"),
|
||||
("Default View Style", "Standaard Weergavestijl"),
|
||||
("Default Scroll Style", "Standaard Scrollstijl"),
|
||||
@@ -649,13 +649,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("use-the-default-printer-tip", "Standaard printer gebruiken"),
|
||||
("use-the-selected-printer-tip", "Geselecteerde printer gebruiken"),
|
||||
("auto-print-tip", "Automatisch afdrukken op de geselecteerde printer."),
|
||||
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet ik deze lokaal afdrukken?"),
|
||||
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is verboden"),
|
||||
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet deze lokaal worden afgedrukt?"),
|
||||
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is niet toegestaan"),
|
||||
("remote-printing-disallowed-text-tip", "Machtigingsinstellingen aan beheerde zijde verhinderen afdrukken op afstand."),
|
||||
("save-settings-tip", "Instellingen opslaan"),
|
||||
("dont-show-again-tip", "Dit bericht wordt niet meer weergegeven"),
|
||||
("Take screenshot", "Schermopname maken"),
|
||||
("Taking screenshot", "Schermopname maken..."),
|
||||
("Taking screenshot", "Schermopname maken…"),
|
||||
("screenshot-merged-screen-not-supported-tip", "Schermopnames van meerdere schermen samenvoegen wordt momenteel niet ondersteund. Schakel over naar een enkel scherm en herhaal de actie."),
|
||||
("screenshot-action-tip", "Kies wat je met de gemaakte schermopname wilt doen."),
|
||||
("Save as", "Opslaan als"),
|
||||
@@ -693,7 +693,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Failed to check if the user is an administrator.", "Fout bij het controleren of de gebruiker een beheerder is."),
|
||||
("Supported only in the installed version.", "Alleen ondersteund in de geïnstalleerde versie."),
|
||||
("elevation_username_tip", "Voer je gebruikersnaam of domeinnaam in"),
|
||||
("Preparing for installation ...", "Installatie voorbereiden ..."),
|
||||
("Preparing for installation ...", "Installatie voorbereiden…"),
|
||||
("Show my cursor", "Mijn cursor weergeven"),
|
||||
("Scale custom", "Aangepaste schaal"),
|
||||
("Custom scale slider", "Aangepaste schuifregelaar voor schaal"),
|
||||
@@ -713,8 +713,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("disable-udp-tip", "Controleert of alleen TCP moet worden gebruikt. Als deze optie is ingeschakeld, gebruikt RustDesk niet langer UDP 21116, maar TCP 21116."),
|
||||
("server-oss-not-support-tip", "Opmerking: Deze functie is niet beschikbaar in de open-sourceversie van de RustDesk-server."),
|
||||
("input note here", "voeg hier een opmerking toe"),
|
||||
("note-at-conn-end-tip", "Vraag om een opmerking aan het einde van de verbinding"),
|
||||
("Show terminal extra keys", "Toon extra toetsen voor terminal"),
|
||||
("note-at-conn-end-tip", "Om een opmerking vragen aan het einde van de verbinding"),
|
||||
("Show terminal extra keys", "Extra toetsen voor terminal weergeven"),
|
||||
("Relative mouse mode", "Relatieve muismodus"),
|
||||
("rel-mouse-not-supported-peer-tip", "De relatieve muismodus wordt niet ondersteund door het externe apparaat."),
|
||||
("rel-mouse-not-ready-tip", "De relatieve muismodus was nog niet klaar, probeer het later opnieuw."),
|
||||
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Lock canvas", "Canvas vergrendelen"),
|
||||
("Sync clipboard between sessions", "Klembord synchroniseren tussen sessies"),
|
||||
("sync-clipboard-between-sessions-tip", "Tekst of afbeeldingen die in één externe sessie worden gekopieerd, worden ook naar het klembord van uw andere verbonden sessies gestuurd."),
|
||||
("terminal-clipboard-write-tip", ""),
|
||||
("Allow terminal apps to copy to clipboard", ""),
|
||||
("terminal-clipboard-write-tip", "Een app in de terminal wil tekst naar het klembord van dit apparaat kopiëren. Indien verleend, is deze toestemming van toepassing op terminal-apps in alle verbindingen totdat u deze uitschakelt in Instellingen. Handmatig kopiëren en plakken wordt niet beïnvloed."),
|
||||
("Allow terminal apps to copy to clipboard", "Terminal-apps toestaan om naar klembord te kopiëren"),
|
||||
("Enable", "Inschakelen"),
|
||||
("Reuse one connection for port forwarding", "Eén verbinding hergebruiken voor poortdoorschakeling"),
|
||||
("port-forward-mux-tip", "Alle verbindingen van een poortdoorschakeling via één enkele verbinding met de andere computer laten lopen, in plaats van voor elke verbinding opnieuw verbinding te maken en in te loggen."),
|
||||
|
||||
@@ -1302,6 +1302,11 @@ fn _get_display_manager() -> String {
|
||||
/// Returns the cached active username when available.
|
||||
/// Callers that require a fresh seat0 lookup should call `get_values_of_seat0` directly.
|
||||
pub fn get_active_username() -> String {
|
||||
// Flatpak runs only inside the logged-in user's session, and Flathub builds
|
||||
// cannot reach the host's loginctl.
|
||||
if is_flatpak() {
|
||||
return crate::username();
|
||||
}
|
||||
if let Some((_, username)) = get_active_user_id_name_from_cache() {
|
||||
return username;
|
||||
}
|
||||
|
||||
+35
-4
@@ -1354,6 +1354,10 @@ pub fn get_install_options() -> String {
|
||||
}
|
||||
|
||||
pub fn get_silent_install_options(printer_override: Option<bool>) -> &'static str {
|
||||
if !is_win_10_or_greater() {
|
||||
return "desktopicon startmenu";
|
||||
}
|
||||
|
||||
let install_printer = match printer_override {
|
||||
Some(override_value) => override_value,
|
||||
None => {
|
||||
@@ -1361,9 +1365,13 @@ pub fn get_silent_install_options(printer_override: Option<bool>) -> &'static st
|
||||
let subkey = format!(".{}", app_name.to_lowercase());
|
||||
let printer = get_reg_of_hkcr(&subkey, REG_NAME_INSTALL_PRINTER);
|
||||
printer.as_deref() == Some("1")
|
||||
&& remote_printer::is_rd_printer_installed(&app_name).unwrap_or_else(|err| {
|
||||
log::warn!("Failed to check printer installation status: {err}; skipping printer installation");
|
||||
false
|
||||
})
|
||||
}
|
||||
};
|
||||
if install_printer && is_win_10_or_greater() {
|
||||
if install_printer {
|
||||
"desktopicon startmenu printer"
|
||||
} else {
|
||||
"desktopicon startmenu"
|
||||
@@ -3911,8 +3919,22 @@ pub fn update_to(file: &str) -> ResultType<()> {
|
||||
// We need also to handle the command line parsing to find the tray processes.
|
||||
pub fn update_me_msi(msi: &str, quiet: bool) -> ResultType<()> {
|
||||
let quiet_args = if quiet { " /qn LAUNCH_TRAY_APP=N" } else { "" };
|
||||
let cmds =
|
||||
format!("chcp 65001 && msiexec /i \"{msi}\"{quiet_args} REBOOT=ReallySuppress /norestart");
|
||||
let app_name = crate::get_app_name();
|
||||
let subkey = format!(".{}", app_name.to_lowercase());
|
||||
let printer_installed = get_reg_of_hkcr(&subkey, REG_NAME_INSTALL_PRINTER).as_deref()
|
||||
!= Some("0")
|
||||
&& remote_printer::is_rd_printer_installed(&app_name).unwrap_or_else(|err| {
|
||||
log::warn!(
|
||||
"Failed to check printer installation status: {err}; skipping printer installation"
|
||||
);
|
||||
false
|
||||
});
|
||||
let printer_args = if printer_installed {
|
||||
""
|
||||
} else {
|
||||
" INSTALLPRINTER=0"
|
||||
};
|
||||
let cmds = format!("chcp 65001 && msiexec /i \"{msi}\"{quiet_args}{printer_args} REBOOT=ReallySuppress /norestart");
|
||||
run_cmds(cmds, false, "update-msi")?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -4846,7 +4868,16 @@ mod tests {
|
||||
#[test]
|
||||
fn install_app_names_enforce_ascii_command_safety() {
|
||||
assert!(validate_install_app_name("RustDesk-Admin1").is_ok());
|
||||
for app_name in ["", "RustDesk_Admin", "RustDesk&whoami", "RustDesk应用"] {
|
||||
for app_name in [
|
||||
"",
|
||||
"RustDesk_Admin",
|
||||
"RustDesk&whoami",
|
||||
"RustDesk应用",
|
||||
"RustDesk앱",
|
||||
"RustDeskBüro",
|
||||
"RustDeskFrançais",
|
||||
"RustDeskアプリ",
|
||||
] {
|
||||
assert!(
|
||||
validate_install_app_name(app_name).is_err(),
|
||||
"unsafe application name was accepted: {app_name}"
|
||||
|
||||
@@ -75,6 +75,11 @@ pub trait PrivacyMode: Sync + Send {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// `INVALID_PRIVACY_MODE_CONN_ID` deliberately bypasses the ownership check, meaning
|
||||
/// "turn it off whoever owns it": shutdown (`ipc::Data::Close`), `reset_all`, and
|
||||
/// `TurnOnGuard`, which undoes a half-finished turn-on however far it got. A caller
|
||||
/// acting for one connection must pass that connection's own id, or it can turn off
|
||||
/// privacy mode belonging to another.
|
||||
#[inline]
|
||||
fn check_off_conn_id(&self, conn_id: i32) -> ResultType<()> {
|
||||
let pre_conn_id = self.pre_conn_id();
|
||||
@@ -289,6 +294,29 @@ fn turn_on_privacy_sync(impl_key: &str, conn_id: i32) -> Option<ResultType<bool>
|
||||
Some(privacy_mode_lock.as_mut()?.turn_on_privacy(conn_id))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
pub(crate) fn close_other_remote_connections_for_privacy(owner_id: i32) {
|
||||
use crate::server::{AuthConnType, AUTHED_CONNS};
|
||||
|
||||
let privacy_mode_lock = PRIVACY_MODE.lock().unwrap();
|
||||
// Ownership can change while the caller validates the capturer.
|
||||
if privacy_mode_lock.as_ref().map(|mode| mode.pre_conn_id()) != Some(owner_id) {
|
||||
return;
|
||||
}
|
||||
for connection in AUTHED_CONNS.lock().unwrap().iter() {
|
||||
if connection.conn_type != AuthConnType::Remote || connection.conn_id == owner_id {
|
||||
continue;
|
||||
}
|
||||
if let Err(err) = connection.sender.send(crate::ipc::Data::Close) {
|
||||
hbb_common::log::debug!(
|
||||
"Failed to close connection {} for privacy mode: {}",
|
||||
connection.conn_id,
|
||||
err
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn turn_off_privacy(conn_id: i32, state: Option<PrivacyModeState>) -> Option<ResultType<()>> {
|
||||
Some(
|
||||
|
||||
@@ -1145,6 +1145,14 @@ impl Connection {
|
||||
},
|
||||
Some(data) = rx_from_authed.recv() => {
|
||||
match data {
|
||||
ipc::Data::Close => {
|
||||
conn.send(crate::common::make_privacy_mode_msg(
|
||||
back_notification::PrivacyModeState::PrvOnByOther,
|
||||
String::new(),
|
||||
)).await;
|
||||
conn.on_close("privacy mode", false).await;
|
||||
break;
|
||||
}
|
||||
#[cfg(all(target_os = "windows", feature = "flutter"))]
|
||||
ipc::Data::PrinterData(data) => {
|
||||
if Self::permission(keys::OPTION_ENABLE_REMOTE_PRINTER, &conn.control_permissions) {
|
||||
@@ -5142,6 +5150,7 @@ impl Connection {
|
||||
5_000,
|
||||
);
|
||||
if err_msg.is_empty() {
|
||||
privacy_mode::close_other_remote_connections_for_privacy(self.inner.id);
|
||||
crate::common::make_privacy_mode_msg(
|
||||
back_notification::PrivacyModeState::PrvOnSucceeded,
|
||||
impl_key,
|
||||
@@ -5168,10 +5177,10 @@ impl Connection {
|
||||
Some(Err(e)) => {
|
||||
log::error!("Failed to turn on privacy mode. {}", e);
|
||||
if privacy_mode::is_in_privacy_mode() {
|
||||
let _ = Self::turn_off_privacy_to_msg(
|
||||
privacy_mode::INVALID_PRIVACY_MODE_CONN_ID,
|
||||
String::new(),
|
||||
);
|
||||
// Use this connection's ID so a failed request cannot disable another
|
||||
// connection's privacy mode: INVALID_PRIVACY_MODE_CONN_ID would bypass
|
||||
// the ownership check (see `check_off_conn_id`).
|
||||
let _ = Self::turn_off_privacy_to_msg(self.inner.id, String::new());
|
||||
}
|
||||
crate::common::make_privacy_mode_msg_with_details(
|
||||
back_notification::PrivacyModeState::PrvOnFailed,
|
||||
|
||||
@@ -110,6 +110,17 @@ fn connector_key(d: &DrmDisplayInfo) -> String {
|
||||
format!("{}:{}", d.device, d.name)
|
||||
}
|
||||
|
||||
/// The transform whose dimensions the delivered frames have: a plane rotated 90/270 in hardware
|
||||
/// already hands over the transposed scanout (and `frame_transform` then turns nothing), whatever
|
||||
/// the output transform says; otherwise the output transform is undone in software.
|
||||
fn delivered_transform(d: &DrmDisplayInfo, wl_transform: i32) -> i32 {
|
||||
if d.plane_transposed {
|
||||
90
|
||||
} else {
|
||||
wl_transform
|
||||
}
|
||||
}
|
||||
|
||||
/// Frame dimensions after undoing `transform` degrees of output rotation.
|
||||
fn rotated_dims(transform: i32, w: usize, h: usize) -> (usize, usize) {
|
||||
if transform == 90 || transform == 270 {
|
||||
@@ -416,9 +427,13 @@ impl IpcDrmCapturer {
|
||||
stop,
|
||||
display,
|
||||
connector: displays.get(wire_idx).map(connector_key),
|
||||
session_size: displays
|
||||
.get(wire_idx)
|
||||
.map(|d| rotated_dims(wl_transform, d.width as usize, d.height as usize)),
|
||||
session_size: displays.get(wire_idx).map(|d| {
|
||||
rotated_dims(
|
||||
delivered_transform(d, wl_transform),
|
||||
d.width as usize,
|
||||
d.height as usize,
|
||||
)
|
||||
}),
|
||||
transform: wl_transform,
|
||||
snapshot_gen,
|
||||
cur: Vec::new(),
|
||||
@@ -2122,7 +2137,8 @@ fn augment_with_wayland_geometry_from(
|
||||
// Identity matches ONLY, the same rule the capturer's transform follows: swapping on a
|
||||
// layout-order guess advertises dimensions the capturer will not deliver.
|
||||
let is_identity = identity[i].is_some() && identity[i] == matched[i];
|
||||
if is_identity && (w.transform == 90 || w.transform == 270) {
|
||||
// A plane-transposed display was already swapped by `display_info_from_drm`.
|
||||
if is_identity && !drm[i].plane_transposed && (w.transform == 90 || w.transform == 270) {
|
||||
std::mem::swap(&mut info.width, &mut info.height);
|
||||
info.original_resolution = super::display_service::get_original_resolution(
|
||||
&drm[i].name,
|
||||
@@ -2259,13 +2275,18 @@ fn swap_available_displays(list: Vec<DrmDisplayInfo>) {
|
||||
}
|
||||
|
||||
fn display_info_from_drm(d: &DrmDisplayInfo) -> DisplayInfo {
|
||||
let (width, height) = rotated_dims(
|
||||
delivered_transform(d, 0),
|
||||
d.width as usize,
|
||||
d.height as usize,
|
||||
);
|
||||
let original_resolution =
|
||||
super::display_service::get_original_resolution(&d.name, d.width as usize, d.height as usize);
|
||||
super::display_service::get_original_resolution(&d.name, width, height);
|
||||
DisplayInfo {
|
||||
x: d.x,
|
||||
y: d.y,
|
||||
width: d.width as i32,
|
||||
height: d.height as i32,
|
||||
width: width as i32,
|
||||
height: height as i32,
|
||||
name: d.name.clone(),
|
||||
online: d.active,
|
||||
cursor_embedded: false,
|
||||
@@ -2330,7 +2351,11 @@ pub(super) fn get_capturer_info(
|
||||
// Origin and transform come from the ONE snapshot new() resolved, so both reflect the
|
||||
// same output assignment; dimensions stay PHYSICAL, rotated to frame orientation.
|
||||
let origin = origin.unwrap_or((d.x, d.y));
|
||||
let (cap_w, cap_h) = rotated_dims(capturer.transform, d.width as usize, d.height as usize);
|
||||
let (cap_w, cap_h) = rotated_dims(
|
||||
delivered_transform(&d, capturer.transform),
|
||||
d.width as usize,
|
||||
d.height as usize,
|
||||
);
|
||||
Ok(super::video_service::CapturerInfo {
|
||||
origin,
|
||||
width: cap_w,
|
||||
@@ -3792,6 +3817,7 @@ mod drm_capturer_tests {
|
||||
active: true,
|
||||
render_node: String::new(),
|
||||
device: String::new(),
|
||||
plane_transposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3814,6 +3840,51 @@ mod drm_capturer_tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn plane_transposed_display(name: &str, w: u32, h: u32) -> DrmDisplayInfo {
|
||||
DrmDisplayInfo {
|
||||
plane_transposed: true,
|
||||
..drm_display(name, w, h)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plane_transposed_display_advertises_its_scanout() {
|
||||
// Steam Deck under gamescope: 800x1280 panel mode, 1280x800 framebuffer on a rotate-270
|
||||
// plane, and no wayland output that matches the connector.
|
||||
let drm = [plane_transposed_display("eDP-1", 800, 1280)];
|
||||
let wl = scrap::wayland::display::Displays {
|
||||
primary: 0,
|
||||
displays: vec![],
|
||||
};
|
||||
let assignment = assign_wayland_outputs(&drm, &wl.displays);
|
||||
let infos = augment_with_wayland_geometry_from(&drm, &wl, &assignment);
|
||||
assert_eq!((infos[0].width, infos[0].height), (1280, 800));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plane_transposed_scanout_is_delivered_at_the_advertised_size() {
|
||||
let d = plane_transposed_display("eDP-1", 800, 1280);
|
||||
let session = rotated_dims(delivered_transform(&d, 0), d.width as usize, d.height as usize);
|
||||
let mut c = capturer_named(Some(session), Some("test:plane-transposed-session"));
|
||||
put_frame_rot(&c, 1280, 800, Some(0x8));
|
||||
assert!(matches!(c.frame(Duration::from_millis(50)), Ok(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_output_over_a_rotated_plane_is_swapped_once() {
|
||||
// mutter rotates the output and programs the plane from it: one quarter turn, as before.
|
||||
let drm = [plane_transposed_display("HDMI-A-1", 1920, 1080)];
|
||||
let mut out = wl_display("HDMI-1", 0, 0, 1920, 1080);
|
||||
out.transform = 90;
|
||||
let wl = scrap::wayland::display::Displays {
|
||||
primary: 0,
|
||||
displays: vec![out],
|
||||
};
|
||||
let assignment = assign_wayland_outputs(&drm, &wl.displays);
|
||||
let infos = augment_with_wayland_geometry_from(&drm, &wl, &assignment);
|
||||
assert_eq!((infos[0].width, infos[0].height), (1080, 1920));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_rotated_output_advertises_delivered_dimensions() {
|
||||
// Fix for the origin-only cut: one connector, one rotated output. The capturer will
|
||||
|
||||
@@ -710,6 +710,8 @@ struct VirtualInputState {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl VirtualInputState {
|
||||
const KEY_UP_ERROR_LOG_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
fn new() -> Option<Self> {
|
||||
VirtualInput::new(
|
||||
CGEventSourceStateID::CombinedSessionState,
|
||||
@@ -1657,6 +1659,12 @@ fn simulate_(event_type: &EventType) {
|
||||
let _lock = VIRTUAL_INPUT_MTX.lock();
|
||||
if let Some(input) = VIRTUAL_INPUT_STATE.as_ref() {
|
||||
let _ = input.simulate(&event_type);
|
||||
} else if matches!(event_type, EventType::KeyRelease(_)) {
|
||||
hbb_common::throttled_log!(
|
||||
VirtualInputState::KEY_UP_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS key-up: virtual input is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2481,6 +2489,9 @@ pub fn handle_key_(evt: &KeyEvent) {
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
super::uinput::prepare_layout(evt);
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
let mut _lock_mode_handler = None;
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
|
||||
+213
-10
@@ -10,6 +10,12 @@ use hbb_common::{
|
||||
ResultType,
|
||||
};
|
||||
|
||||
mod layout;
|
||||
|
||||
pub(super) fn prepare_layout(event: &base::message_proto::KeyEvent) {
|
||||
layout::prepare_layout(event);
|
||||
}
|
||||
|
||||
static IPC_CONN_TIMEOUT: u64 = 1000;
|
||||
static IPC_REQUEST_TIMEOUT: u64 = 1000;
|
||||
static IPC_POSTFIX_KEYBOARD: &str = "_uinput_keyboard";
|
||||
@@ -17,24 +23,182 @@ static IPC_POSTFIX_MOUSE: &str = "_uinput_mouse";
|
||||
static IPC_POSTFIX_CONTROL: &str = "_uinput_control";
|
||||
|
||||
pub mod client {
|
||||
use super::*;
|
||||
use super::{layout::LayoutKey, *};
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
const LAYOUT_ERROR_LOG_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
struct LayoutContext {
|
||||
locks: (bool, bool),
|
||||
// None for ordinary input; otherwise whether the shortcut holds Shift.
|
||||
shortcut_shift: Option<bool>,
|
||||
}
|
||||
|
||||
impl LayoutContext {
|
||||
fn resolve(&self, chr: char) -> ResultType<LayoutKey> {
|
||||
layout::resolve(chr, self.locks, self.shortcut_shift)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UInputKeyboard {
|
||||
conn: Connection,
|
||||
rt: Runtime,
|
||||
// Ownership is per character. The Linux connection turns character
|
||||
// downs into clicks; overlapping direct-backend holds can release a
|
||||
// generated modifier still needed by another character.
|
||||
layout_keys: HashMap<char, LayoutKey>,
|
||||
}
|
||||
|
||||
impl UInputKeyboard {
|
||||
pub async fn new() -> ResultType<Self> {
|
||||
let conn = ipc::connect(IPC_CONN_TIMEOUT, IPC_POSTFIX_KEYBOARD).await?;
|
||||
let rt = Runtime::new()?;
|
||||
Ok(Self { conn, rt })
|
||||
layout::prewarm_layout();
|
||||
Ok(Self {
|
||||
conn,
|
||||
rt,
|
||||
layout_keys: HashMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn send(&mut self, data: Data) -> ResultType<()> {
|
||||
self.rt.block_on(self.conn.send(&data))
|
||||
}
|
||||
|
||||
fn send_raw_key(&mut self, keycode: u16, down: bool) -> ResultType<()> {
|
||||
let key = Key::Raw(keycode);
|
||||
let event = if down {
|
||||
DataKeyboard::KeyDown(key)
|
||||
} else {
|
||||
DataKeyboard::KeyUp(key)
|
||||
};
|
||||
self.send(Data::Keyboard(event))
|
||||
}
|
||||
|
||||
fn press_layout_key(&mut self, chr: char, mapping: LayoutKey) -> ResultType<()> {
|
||||
if let Some(pressed) = self.layout_keys.get(&chr).cloned() {
|
||||
return self.send_layout_key_down(&pressed);
|
||||
}
|
||||
let mut pressed = LayoutKey {
|
||||
key: mapping.key,
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
for keycode in mapping.modifiers {
|
||||
let query = Data::Keyboard(DataKeyboard::GetKeyState(Key::Raw(keycode)));
|
||||
if !self.send_get_key_state(query)? {
|
||||
pressed.modifiers.push(keycode);
|
||||
}
|
||||
}
|
||||
let result = self.send_layout_key_down(&pressed);
|
||||
if let Err(error) = result {
|
||||
if let Err(release_error) = self.release_layout_key(&pressed) {
|
||||
bail!(
|
||||
"{}; failed to release uinput modifiers: {}",
|
||||
error,
|
||||
release_error
|
||||
);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
self.layout_keys.insert(chr, pressed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_layout_key_down(&mut self, pressed: &LayoutKey) -> ResultType<()> {
|
||||
// Character dispatch can release Shift before a repeated key-down.
|
||||
for keycode in &pressed.modifiers {
|
||||
self.send_raw_key(*keycode, true)?;
|
||||
}
|
||||
self.send(Data::Keyboard(DataKeyboard::KeyDown(pressed.key)))
|
||||
}
|
||||
|
||||
fn release_layout_key(&mut self, pressed: &LayoutKey) -> ResultType<()> {
|
||||
let mut result = self.send(Data::Keyboard(DataKeyboard::KeyUp(pressed.key)));
|
||||
for keycode in pressed.modifiers.iter().rev() {
|
||||
// Attempt every release even if an earlier send failed.
|
||||
result = result.and(self.send_raw_key(*keycode, false));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn layout_key_down(&mut self, chr: char) -> ResultType<()> {
|
||||
if let Some(pressed) = self.layout_keys.get(&chr).cloned() {
|
||||
return self.send_layout_key_down(&pressed);
|
||||
}
|
||||
let mapping = if layout::is_available() {
|
||||
self.layout_context()?.resolve(chr)?
|
||||
} else {
|
||||
// Discovery may finish before key-up; retain the legacy key for release.
|
||||
LayoutKey {
|
||||
key: Key::Layout(chr),
|
||||
modifiers: Vec::new(),
|
||||
}
|
||||
};
|
||||
self.press_layout_key(chr, mapping)
|
||||
}
|
||||
|
||||
fn layout_key_up(&mut self, chr: char) -> ResultType<()> {
|
||||
if let Some(pressed) = self.layout_keys.remove(&chr) {
|
||||
self.release_layout_key(&pressed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn layout_key_sequence(&mut self, sequence: &str) -> ResultType<()> {
|
||||
if sequence.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let context = self.layout_context()?;
|
||||
// Keep supported text after a mapping failure and report the first error.
|
||||
// Modifier and IPC failures must still stop the sequence immediately.
|
||||
let mut result = Ok(());
|
||||
for chr in sequence.chars() {
|
||||
let mapping = match context.resolve(chr) {
|
||||
Ok(mapping) => mapping,
|
||||
Err(error) => {
|
||||
result = result.and(Err(error));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
self.press_layout_key(chr, mapping)?;
|
||||
self.layout_key_up(chr)?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn layout_context(&mut self) -> ResultType<LayoutContext> {
|
||||
let caps_lock =
|
||||
self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::CapsLock)))?;
|
||||
let num_lock =
|
||||
self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::NumLock)))?;
|
||||
let shortcut = self
|
||||
.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Control)))?
|
||||
|| self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Alt)))?
|
||||
|| self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Meta)))?;
|
||||
let shortcut_shift = if shortcut {
|
||||
Some(
|
||||
self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Shift)))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(LayoutContext {
|
||||
locks: (caps_lock, num_lock),
|
||||
shortcut_shift,
|
||||
})
|
||||
}
|
||||
|
||||
fn log_layout_error(result: &ResultType<()>) {
|
||||
if let Err(error) = result {
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Uinput layout-aware keyboard input failed: {}",
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_get_key_state(&mut self, data: Data) -> ResultType<bool> {
|
||||
self.rt.block_on(self.conn.send(&data))?;
|
||||
|
||||
@@ -45,6 +209,9 @@ pub mod client {
|
||||
Ok(Some(Data::KeyboardResponse(ipc::DataKeyboardResponse::GetKeyState(state)))) => {
|
||||
Ok(state)
|
||||
}
|
||||
Ok(Some(Data::KeyboardResponse(ipc::DataKeyboardResponse::GetKeyStateError(
|
||||
error,
|
||||
)))) => bail!("Failed to query uinput key state: {}", error),
|
||||
Ok(Some(resp)) => {
|
||||
// FATAL error!!!
|
||||
bail!(
|
||||
@@ -90,25 +257,39 @@ pub mod client {
|
||||
}
|
||||
|
||||
fn key_sequence(&mut self, sequence: &str) {
|
||||
// Sequence events are normally handled in the --server process before reaching here.
|
||||
// Forward via IPC as a fallback — input_text_wayland can still handle ASCII chars
|
||||
// via keysym/uinput, though non-ASCII will be skipped (no clipboard in --service).
|
||||
log::debug!(
|
||||
"UInputKeyboard::key_sequence called (len={})",
|
||||
sequence.len()
|
||||
);
|
||||
allow_err!(self.send(Data::Keyboard(DataKeyboard::Sequence(sequence.to_string()))));
|
||||
if !layout::is_available() {
|
||||
Self::log_layout_error(
|
||||
&self.send(Data::Keyboard(DataKeyboard::Sequence(sequence.to_string()))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
Self::log_layout_error(&self.layout_key_sequence(sequence));
|
||||
}
|
||||
|
||||
// TODO: handle error???
|
||||
fn key_down(&mut self, key: Key) -> enigo::ResultType {
|
||||
if let Key::Layout(chr) = key {
|
||||
let result = self.layout_key_down(chr);
|
||||
Self::log_layout_error(&result);
|
||||
return result.map_err(Into::into);
|
||||
}
|
||||
allow_err!(self.send(Data::Keyboard(DataKeyboard::KeyDown(key))));
|
||||
Ok(())
|
||||
}
|
||||
fn key_up(&mut self, key: Key) {
|
||||
if let Key::Layout(chr) = key {
|
||||
Self::log_layout_error(&self.layout_key_up(chr));
|
||||
return;
|
||||
}
|
||||
allow_err!(self.send(Data::Keyboard(DataKeyboard::KeyUp(key))));
|
||||
}
|
||||
fn key_click(&mut self, key: Key) {
|
||||
if let Key::Layout(chr) = key {
|
||||
if layout::is_available() {
|
||||
Self::log_layout_error(&self.layout_key_sequence(&chr.to_string()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
allow_err!(self.send(Data::Keyboard(DataKeyboard::KeyClick(key))));
|
||||
}
|
||||
}
|
||||
@@ -203,6 +384,8 @@ pub mod service {
|
||||
use std::os::unix::io::AsRawFd;
|
||||
use std::{collections::HashMap, sync::Mutex};
|
||||
|
||||
const RAW_KEY_STATE_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref KEY_MAP: HashMap<enigo::Key, evdev::Key> = HashMap::from(
|
||||
[
|
||||
@@ -686,6 +869,9 @@ pub mod service {
|
||||
} else {
|
||||
match keyboard.get_key_state() {
|
||||
Ok(keys) => match key {
|
||||
enigo::Key::Raw(code) if *code >= layout::XKB_KEYCODE_OFFSET => {
|
||||
keys.contains(evdev::Key::new(*code - layout::XKB_KEYCODE_OFFSET))
|
||||
}
|
||||
enigo::Key::Shift => {
|
||||
keys.contains(evdev::Key::KEY_LEFTSHIFT)
|
||||
|| keys.contains(evdev::Key::KEY_RIGHTSHIFT)
|
||||
@@ -704,6 +890,23 @@ pub mod service {
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Err(error) if matches!(key, enigo::Key::Raw(_)) => {
|
||||
hbb_common::throttled_log!(
|
||||
RAW_KEY_STATE_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to query uinput layout modifier state: {}",
|
||||
error
|
||||
);
|
||||
// Unknown modifier state must not be treated as released.
|
||||
ipc_send_data(
|
||||
stream,
|
||||
&Data::KeyboardResponse(
|
||||
ipc::DataKeyboardResponse::GetKeyStateError(error.to_string()),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
Err(_e) => {
|
||||
// log::debug!("Failed to get key state: {}", &_e);
|
||||
false
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
use hbb_common::{anyhow::anyhow, bail, ResultType};
|
||||
use std::{collections::HashMap, ops::RangeInclusive, ptr::NonNull};
|
||||
use xkbcommon_dl::{self as xkb, keysyms};
|
||||
|
||||
mod cache;
|
||||
mod source;
|
||||
mod wayland;
|
||||
mod xwayland;
|
||||
|
||||
pub(super) use cache::{is_available, prepare_layout, prewarm_layout, resolve};
|
||||
|
||||
pub(super) const XKB_KEYCODE_OFFSET: u16 = 8;
|
||||
const CAPS_LOCK_BIT: usize = 1;
|
||||
const NUM_LOCK_BIT: usize = 2;
|
||||
const SHIFT_BIT: usize = 4;
|
||||
const LAYOUT_STATE_COUNT: usize = 8;
|
||||
const DEFAULT_GROUP: u32 = 0;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct LayoutKey {
|
||||
pub key: enigo::Key,
|
||||
pub modifiers: Vec<u16>,
|
||||
}
|
||||
|
||||
struct Keymap {
|
||||
maps: [HashMap<char, LayoutKey>; LAYOUT_STATE_COUNT],
|
||||
}
|
||||
|
||||
impl Keymap {
|
||||
fn load(source: &source::Source) -> ResultType<Self> {
|
||||
let keymap = XkbKeymap::open(source)?;
|
||||
let mut state = State::new(&keymap)?;
|
||||
let caps = state.locked_mask(keysyms::Caps_Lock);
|
||||
let num = state.locked_mask(keysyms::Num_Lock);
|
||||
let shift = state.modifier(&[keysyms::Shift_L, keysyms::Shift_R]);
|
||||
let level3 = state.modifier(&[keysyms::ISO_Level3_Shift]);
|
||||
let modifiers = [shift, level3];
|
||||
let maps = std::array::from_fn(|index| {
|
||||
let locked = if index & CAPS_LOCK_BIT != 0 { caps } else { 0 }
|
||||
| if index & NUM_LOCK_BIT != 0 { num } else { 0 };
|
||||
let held_shift = if index & SHIFT_BIT != 0 { shift } else { None };
|
||||
let modifiers = if held_shift.is_some() {
|
||||
std::slice::from_ref(&level3)
|
||||
} else {
|
||||
&modifiers
|
||||
};
|
||||
state.mappings(locked, modifiers, held_shift)
|
||||
});
|
||||
Ok(Self { maps })
|
||||
}
|
||||
}
|
||||
|
||||
struct XkbKeymap {
|
||||
api: &'static xkb::XkbCommon,
|
||||
map: NonNull<xkb::xkb_keymap>,
|
||||
group: u32,
|
||||
}
|
||||
|
||||
impl XkbKeymap {
|
||||
fn open(source: &source::Source) -> ResultType<Self> {
|
||||
let api = xkb::xkbcommon_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon"))?;
|
||||
let mut keymap = Self {
|
||||
api,
|
||||
map: compile(api, source)?,
|
||||
group: DEFAULT_GROUP,
|
||||
};
|
||||
let groups = unsafe { (api.xkb_keymap_num_layouts)(keymap.map.as_ptr()) };
|
||||
if let source::Source::Wayland { group, .. } | source::Source::Xwayland { group, .. } =
|
||||
source
|
||||
{
|
||||
if groups > 1 {
|
||||
keymap.group =
|
||||
group.ok_or_else(|| anyhow!("Cannot determine the active XKB group"))?;
|
||||
}
|
||||
}
|
||||
if keymap.group >= groups {
|
||||
bail!("The detected keyboard layout group is absent from the keymap");
|
||||
}
|
||||
Ok(keymap)
|
||||
}
|
||||
|
||||
fn keycodes(&self) -> RangeInclusive<u32> {
|
||||
unsafe {
|
||||
(self.api.xkb_keymap_min_keycode)(self.map.as_ptr())
|
||||
..=(self.api.xkb_keymap_max_keycode)(self.map.as_ptr())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbKeymap {
|
||||
fn drop(&mut self) {
|
||||
unsafe { (self.api.xkb_keymap_unref)(self.map.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
fn compile(api: &xkb::XkbCommon, source: &source::Source) -> ResultType<NonNull<xkb::xkb_keymap>> {
|
||||
let context =
|
||||
unsafe { (api.xkb_context_new)(xkb::xkb_context_flags::XKB_CONTEXT_NO_ENVIRONMENT_NAMES) };
|
||||
let context = NonNull::new(context).ok_or_else(|| anyhow!("Cannot create XKB context"))?;
|
||||
let flags = xkb::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS;
|
||||
let map = unsafe {
|
||||
match source {
|
||||
source::Source::Gnome(names) => {
|
||||
let names = xkb::xkb_rule_names {
|
||||
rules: std::ptr::null(),
|
||||
model: names.model.as_ptr(),
|
||||
layout: names.layout.as_ptr(),
|
||||
variant: names.variant.as_ptr(),
|
||||
options: names.options.as_ptr(),
|
||||
};
|
||||
(api.xkb_keymap_new_from_names)(context.as_ptr(), &names, flags)
|
||||
}
|
||||
source::Source::Wayland { keymap: bytes, .. }
|
||||
| source::Source::Xwayland { keymap: bytes, .. } => (api.xkb_keymap_new_from_string)(
|
||||
context.as_ptr(),
|
||||
bytes.as_ptr().cast(),
|
||||
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||
flags,
|
||||
),
|
||||
}
|
||||
};
|
||||
unsafe { (api.xkb_context_unref)(context.as_ptr()) };
|
||||
NonNull::new(map).ok_or_else(|| anyhow!("Cannot compile the detected XKB keyboard map"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Modifier {
|
||||
keycode: u16,
|
||||
mask: u32,
|
||||
}
|
||||
|
||||
struct State<'a> {
|
||||
keymap: &'a XkbKeymap,
|
||||
state: NonNull<xkb::xkb_state>,
|
||||
}
|
||||
|
||||
impl<'a> State<'a> {
|
||||
fn new(keymap: &'a XkbKeymap) -> ResultType<Self> {
|
||||
let state = unsafe { (keymap.api.xkb_state_new)(keymap.map.as_ptr()) };
|
||||
let state = NonNull::new(state).ok_or_else(|| anyhow!("Cannot create XKB state"))?;
|
||||
let mut state = Self { keymap, state };
|
||||
state.set_modifiers(0, 0);
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn set_modifiers(&mut self, depressed: u32, locked: u32) {
|
||||
unsafe {
|
||||
(self.keymap.api.xkb_state_update_mask)(
|
||||
self.state.as_ptr(),
|
||||
depressed,
|
||||
0,
|
||||
locked,
|
||||
0,
|
||||
0,
|
||||
self.keymap.group,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn symbol(&self, keycode: u16) -> u32 {
|
||||
unsafe {
|
||||
(self.keymap.api.xkb_state_key_get_one_sym)(self.state.as_ptr(), u32::from(keycode))
|
||||
}
|
||||
}
|
||||
|
||||
fn update_key(&mut self, keycode: u16, direction: xkb::xkb_key_direction) {
|
||||
unsafe {
|
||||
(self.keymap.api.xkb_state_update_key)(
|
||||
self.state.as_ptr(),
|
||||
u32::from(keycode),
|
||||
direction,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
fn locked_mask(&mut self, symbol: u32) -> u32 {
|
||||
let keycode = self
|
||||
.keymap
|
||||
.keycodes()
|
||||
.filter_map(supported_keycode)
|
||||
.find(|keycode| self.symbol(*keycode) == symbol);
|
||||
let Some(keycode) = keycode else { return 0 };
|
||||
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_DOWN);
|
||||
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_UP);
|
||||
let mask = unsafe {
|
||||
(self.keymap.api.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb::xkb_state_component::XKB_STATE_MODS_LOCKED,
|
||||
)
|
||||
};
|
||||
self.set_modifiers(0, 0);
|
||||
mask
|
||||
}
|
||||
|
||||
fn modifier(&mut self, symbols: &[u32]) -> Option<Modifier> {
|
||||
// Prefer physical modifier keys to XKB's synthetic <LVL3> keycode.
|
||||
let preferred = [
|
||||
evdev::Key::KEY_LEFTSHIFT,
|
||||
evdev::Key::KEY_RIGHTSHIFT,
|
||||
evdev::Key::KEY_RIGHTALT,
|
||||
];
|
||||
let preferred = preferred
|
||||
.iter()
|
||||
.map(|key| u32::from(key.code() + XKB_KEYCODE_OFFSET));
|
||||
for keycode in preferred
|
||||
.chain(self.keymap.keycodes())
|
||||
.filter_map(supported_keycode)
|
||||
{
|
||||
if !symbols.contains(&self.symbol(keycode)) {
|
||||
continue;
|
||||
}
|
||||
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_DOWN);
|
||||
let mask = unsafe {
|
||||
(self.keymap.api.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb::xkb_state_component::XKB_STATE_MODS_DEPRESSED,
|
||||
)
|
||||
};
|
||||
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_UP);
|
||||
self.set_modifiers(0, 0);
|
||||
if mask != 0 {
|
||||
return Some(Modifier { keycode, mask });
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn mappings(
|
||||
&mut self,
|
||||
locked: u32,
|
||||
modifiers: &[Option<Modifier>],
|
||||
held_shift: Option<Modifier>,
|
||||
) -> HashMap<char, LayoutKey> {
|
||||
let mut mappings = HashMap::new();
|
||||
let mut keypad_mappings = HashMap::new();
|
||||
for combination in 0..(1usize << modifiers.len()) {
|
||||
let selected: Vec<_> = modifiers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| combination & (1 << *index) != 0)
|
||||
.filter_map(|(_, modifier)| *modifier)
|
||||
.collect();
|
||||
// Held Shift affects the symbol, but belongs to the caller.
|
||||
let mask = selected.iter().fold(
|
||||
held_shift.map_or(0, |modifier| modifier.mask),
|
||||
|mask, modifier| mask | modifier.mask,
|
||||
);
|
||||
self.set_modifiers(mask, locked);
|
||||
for keycode in self.keymap.keycodes().filter_map(supported_keycode) {
|
||||
let symbol = self.symbol(keycode);
|
||||
// Keypad aliases can produce the same text but different shortcuts.
|
||||
let candidates = if (keysyms::KP_Space..=keysyms::KP_Equal).contains(&symbol) {
|
||||
&mut keypad_mappings
|
||||
} else {
|
||||
&mut mappings
|
||||
};
|
||||
let codepoint = unsafe { (self.keymap.api.xkb_keysym_to_utf32)(symbol) };
|
||||
if let Some(character) =
|
||||
char::from_u32(codepoint).filter(|character| *character != '\0')
|
||||
{
|
||||
candidates.entry(character).or_insert_with(|| LayoutKey {
|
||||
key: enigo::Key::Raw(keycode),
|
||||
// Press Level3 first to avoid Shift+RightAlt activating Compose.
|
||||
// Candidate preference still follows the original modifier order.
|
||||
modifiers: selected
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|modifier| modifier.keycode)
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Shift must not redirect an ordinary shortcut to a keypad alias.
|
||||
if held_shift.is_none() {
|
||||
for (character, mapping) in keypad_mappings {
|
||||
mappings.entry(character).or_insert(mapping);
|
||||
}
|
||||
}
|
||||
mappings
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for State<'_> {
|
||||
fn drop(&mut self) {
|
||||
unsafe { (self.keymap.api.xkb_state_unref)(self.state.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
fn supported_keycode(keycode: u32) -> Option<u16> {
|
||||
let keycode = u16::try_from(keycode).ok()?;
|
||||
let code = keycode.checked_sub(XKB_KEYCODE_OFFSET)?;
|
||||
// Match the keys enabled by create_uinput_keyboard().
|
||||
let supported = (evdev::Key::KEY_ESC.code()..=evdev::Key::BTN_TRIGGER_HAPPY40.code())
|
||||
.contains(&code)
|
||||
&& !format!("{:?}", evdev::Key::new(code)).contains("unknown");
|
||||
supported.then_some(keycode)
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
use super::{source::Source, Keymap, LayoutKey, CAPS_LOCK_BIT, NUM_LOCK_BIT, SHIFT_BIT};
|
||||
use crate::server::input_service::is_ascii_printable;
|
||||
use base::message_proto::{key_event, KeyEvent, KeyboardMode};
|
||||
use hbb_common::{bail, lazy_static, ResultType};
|
||||
use std::{
|
||||
sync::{mpsc, Mutex, RwLock, TryLockError},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const LAYOUT_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
|
||||
// GNOME 46/Plasma 6.6 probes (200-400 initial samples): preparation p99 7-16 ms;
|
||||
// repeated refresh medians were 2-6 ms. KDE query outliers exceeded 100 ms,
|
||||
// so this limits input waiting while the background query continues.
|
||||
const LAYOUT_INPUT_WAIT: Duration = Duration::from_millis(25);
|
||||
const LAYOUT_WARNING_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref REFRESH: Mutex<Refresh> = Mutex::new(Refresh::default());
|
||||
// Only the first relevant input takes the startup query's completion receiver.
|
||||
static ref PREWARM_RECEIVER: Mutex<Option<mpsc::Receiver<()>>> = Mutex::new(None);
|
||||
static ref CURRENT: RwLock<Result<Keymap, String>> =
|
||||
RwLock::new(Err("Uinput keyboard layout has not been detected".to_owned()));
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Refresh {
|
||||
checked: Option<Instant>,
|
||||
source: Option<Source>,
|
||||
// Cover scheduling until the worker acquires REFRESH.
|
||||
running: bool,
|
||||
}
|
||||
|
||||
pub(in crate::server::uinput) fn prepare_layout(event: &KeyEvent) {
|
||||
if !crate::server::input_service::wayland_use_uinput() || !needs_layout(event) {
|
||||
return;
|
||||
}
|
||||
let deadline = Instant::now() + LAYOUT_INPUT_WAIT;
|
||||
let receiver = {
|
||||
let mut prewarm = PREWARM_RECEIVER.lock().unwrap();
|
||||
// Prefer a due refresh over an old, already-completed startup query.
|
||||
start_refresh().or(prewarm.take())
|
||||
};
|
||||
if let Some(receiver) = receiver {
|
||||
wait_for_refresh(receiver, deadline);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::server::uinput) fn prewarm_layout() {
|
||||
// Use server startup time for discovery before the first remote character.
|
||||
// This reduces cold-start fallback; a still-pending query cannot guarantee readiness.
|
||||
let mut prewarm = PREWARM_RECEIVER.lock().unwrap();
|
||||
if let Some(receiver) = start_refresh() {
|
||||
*prewarm = Some(receiver);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_refresh() -> Option<mpsc::Receiver<()>> {
|
||||
// A stalled desktop query must not block later input or spawn more workers.
|
||||
let mut refresh = match REFRESH.try_lock() {
|
||||
Ok(refresh) => refresh,
|
||||
Err(TryLockError::WouldBlock) => return None,
|
||||
Err(TryLockError::Poisoned(error)) => {
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
error,
|
||||
"Uinput layout refresh lock is poisoned: {}",
|
||||
error
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if refresh.running
|
||||
|| refresh
|
||||
.checked
|
||||
.is_some_and(|checked| checked.elapsed() < LAYOUT_REFRESH_INTERVAL)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (completed, receiver) = mpsc::channel();
|
||||
refresh.running = true;
|
||||
if let Err(error) = thread::Builder::new()
|
||||
.name("uinput-layout".to_owned())
|
||||
.spawn(move || refresh_layout(completed))
|
||||
{
|
||||
refresh.running = false;
|
||||
refresh.checked = Some(Instant::now());
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
error,
|
||||
"Cannot start uinput layout refresh: {}",
|
||||
error
|
||||
);
|
||||
return None;
|
||||
}
|
||||
drop(refresh);
|
||||
Some(receiver)
|
||||
}
|
||||
|
||||
fn refresh_layout(completed: mpsc::Sender<()>) {
|
||||
let mut refresh = REFRESH.lock().unwrap();
|
||||
if let Err(error) = refresh.update() {
|
||||
let retained = {
|
||||
let mut current = CURRENT.write().unwrap();
|
||||
if current.is_err() {
|
||||
*current = Err(error.to_string());
|
||||
}
|
||||
current.is_ok()
|
||||
};
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
warn,
|
||||
"Uinput layout refresh failed (previous mapping retained: {}): {}",
|
||||
retained,
|
||||
error
|
||||
);
|
||||
}
|
||||
refresh.checked = Some(Instant::now());
|
||||
refresh.running = false;
|
||||
drop(refresh);
|
||||
// An input timeout drops its receiver but leaves this worker running.
|
||||
if completed.send(()).is_err() {
|
||||
hbb_common::log::trace!("Uinput layout refresh finished without an input waiter");
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_refresh(receiver: mpsc::Receiver<()>, deadline: Instant) {
|
||||
match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
|
||||
Ok(()) => {}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
warn,
|
||||
"Uinput layout refresh exceeded the {} ms input wait; query continues in the background",
|
||||
LAYOUT_INPUT_WAIT.as_millis()
|
||||
),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
error,
|
||||
"Uinput layout refresh worker stopped before completion"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
impl Refresh {
|
||||
fn update(&mut self) -> ResultType<()> {
|
||||
let source = Source::read().map_err(|error| {
|
||||
if error.is::<super::source::UnreliableSource>() {
|
||||
// Unlike a transient query failure, this invalidates the old map.
|
||||
self.source = None;
|
||||
*CURRENT.write().unwrap() = Err(error.to_string());
|
||||
}
|
||||
error
|
||||
})?;
|
||||
if self.source.as_ref() == Some(&source) {
|
||||
return Ok(());
|
||||
}
|
||||
let keymap = match Keymap::load(&source) {
|
||||
Ok(keymap) => keymap,
|
||||
Err(error) => {
|
||||
// A newly observed layout cannot use the previous layout's map.
|
||||
self.source = None;
|
||||
*CURRENT.write().unwrap() = Err(error.to_string());
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
*CURRENT.write().unwrap() = Ok(keymap);
|
||||
self.source = Some(source);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn needs_layout(event: &KeyEvent) -> bool {
|
||||
let mode = event.mode.enum_value_or(KeyboardMode::Legacy);
|
||||
if mode == KeyboardMode::Map {
|
||||
return false;
|
||||
}
|
||||
match &event.union {
|
||||
Some(key_event::Union::Seq(sequence)) => {
|
||||
// Translate shortcuts use Key::Layout even for non-ASCII text.
|
||||
!sequence.is_empty()
|
||||
&& (mode == KeyboardMode::Translate || sequence.chars().all(is_ascii_printable))
|
||||
}
|
||||
Some(key_event::Union::Chr(_)) => mode == KeyboardMode::Legacy && event.down,
|
||||
Some(key_event::Union::Unicode(character)) => {
|
||||
mode == KeyboardMode::Legacy
|
||||
&& char::from_u32(*character).is_some_and(is_ascii_printable)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::server::uinput) fn is_available() -> bool {
|
||||
let current = CURRENT.read().unwrap();
|
||||
if let Err(error) = current.as_ref() {
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
warn,
|
||||
"Uinput layout unavailable: {}; using legacy character mapping (may differ from the host layout)",
|
||||
error
|
||||
);
|
||||
}
|
||||
current.is_ok()
|
||||
}
|
||||
|
||||
pub(in crate::server::uinput) fn resolve(
|
||||
character: char,
|
||||
locks: (bool, bool),
|
||||
shortcut_shift: Option<bool>,
|
||||
) -> ResultType<LayoutKey> {
|
||||
let current = CURRENT.read().unwrap();
|
||||
let keymap = match current.as_ref() {
|
||||
Ok(keymap) => keymap,
|
||||
Err(error) => {
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
warn,
|
||||
"Uinput layout unavailable: {}; using legacy character mapping (may differ from the host layout)",
|
||||
error
|
||||
);
|
||||
return Ok(LayoutKey {
|
||||
key: enigo::Key::Layout(character),
|
||||
modifiers: Vec::new(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let index = usize::from(locks.0) * CAPS_LOCK_BIT + usize::from(locks.1) * NUM_LOCK_BIT;
|
||||
// Letter shortcuts keep their physical key even when Shift changes case.
|
||||
// Other shortcuts prefer a symbol compatible with the caller's held Shift.
|
||||
let shifted = (shortcut_shift == Some(true) && !character.is_alphabetic())
|
||||
.then(|| keymap.maps[index | SHIFT_BIT].get(&character))
|
||||
.flatten();
|
||||
if let Some(mapping) = shifted.or_else(|| keymap.maps[index].get(&character)) {
|
||||
return Ok(mapping.clone());
|
||||
}
|
||||
if shortcut_shift.is_some() && character.is_ascii_graphic() {
|
||||
return legacy_shortcut(character);
|
||||
}
|
||||
bail!("Character cannot be generated in the detected XKB layout")
|
||||
}
|
||||
|
||||
fn legacy_shortcut(character: char) -> ResultType<LayoutKey> {
|
||||
// Uppercase letters must not synthesize Shift for a shortcut, but shifted
|
||||
// punctuation still needs the legacy table's modifier.
|
||||
let (key, shift) =
|
||||
super::super::service::map_key(&enigo::Key::Layout(character.to_ascii_lowercase()))?;
|
||||
hbb_common::throttled_log!(
|
||||
LAYOUT_WARNING_INTERVAL,
|
||||
warn,
|
||||
"Uinput layout lacks an ASCII shortcut character; using its legacy physical mapping"
|
||||
);
|
||||
Ok(LayoutKey {
|
||||
key: enigo::Key::Raw(key.code() + super::XKB_KEYCODE_OFFSET),
|
||||
modifiers: if shift {
|
||||
vec![evdev::Key::KEY_LEFTSHIFT.code() + super::XKB_KEYCODE_OFFSET]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use dbus::blocking::Connection;
|
||||
use gtk::{
|
||||
gio::{self, prelude::SettingsExt},
|
||||
glib::variant::FromVariant,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, ResultType};
|
||||
use std::{error::Error, ffi::CString, fmt, time::Duration};
|
||||
|
||||
mod ibus;
|
||||
|
||||
pub(super) const DBUS_TIMEOUT: Duration = Duration::from_millis(250);
|
||||
const GNOME_INPUT_SCHEMA: &str = "org.gnome.desktop.input-sources";
|
||||
const GNOME_DEFAULT_LAYOUT: &str = "us";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct UnreliableSource(pub &'static str);
|
||||
|
||||
impl fmt::Display for UnreliableSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for UnreliableSource {}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) enum Source {
|
||||
Gnome(Names),
|
||||
Wayland { keymap: Vec<u8>, group: Option<u32> },
|
||||
Xwayland { keymap: Vec<u8>, group: Option<u32> },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) struct Names {
|
||||
pub model: CString,
|
||||
pub layout: CString,
|
||||
pub variant: CString,
|
||||
pub options: CString,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub fn read() -> ResultType<Self> {
|
||||
let connection = Connection::new_session()?;
|
||||
if name_has_owner(&connection, "org.gnome.Shell")? {
|
||||
if let Some(names) = gnome_layout()? {
|
||||
return Ok(Self::Gnome(names));
|
||||
}
|
||||
return Ok(Self::Wayland {
|
||||
keymap: super::wayland::read_keymap()?,
|
||||
group: None,
|
||||
});
|
||||
}
|
||||
let kde_layouts = name_has_owner(&connection, "org.kde.keyboard")?;
|
||||
// KWin 5 does not publish the layout service for a single-layout map.
|
||||
if kde_layouts || name_has_owner(&connection, "org.kde.KWin")? {
|
||||
return Ok(Self::Wayland {
|
||||
keymap: super::wayland::read_keymap()?,
|
||||
group: if kde_layouts {
|
||||
Some(kde_layout_group(&connection)?)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
});
|
||||
}
|
||||
// Other compositors need the effective keymap and active group of our
|
||||
// uinput device, including per-device options and custom keymap overrides.
|
||||
// wl_keyboard exposes a seat map that may belong to a physical keyboard.
|
||||
// Equal layout names/group indices do not prove map identity: Caps can
|
||||
// act as AltGr in one map and toggle CapsLock in the other.
|
||||
//
|
||||
// Sway GET_INPUTS/GET_SEATS expose names and an index, not the device map.
|
||||
// GET_CONFIG returns saved config text, not effective runtime input
|
||||
// settings; parsing it cannot reliably account for runtime overrides.
|
||||
// Hyprland's devices reply reports RMLVO (rules/model/layout/variant/options),
|
||||
// but kb_file can override it. Those fields alone cannot reconstruct the
|
||||
// loaded map. This does not rule out additional compositor-specific APIs.
|
||||
//
|
||||
// Reliable native discovery needs a compositor query associating the
|
||||
// device's actual map (or verified effective configuration) with its group.
|
||||
// uinput supplies keycodes; it cannot report the compositor's XKB policy.
|
||||
// Xwayland remains best effort; see xwayland::read for its freshness limits.
|
||||
// zwp_virtual_keyboard_manager_v1 needs a separate injection backend and
|
||||
// is not universally supported; it does not query an existing uinput map.
|
||||
super::xwayland::read()
|
||||
}
|
||||
}
|
||||
|
||||
fn name_has_owner(connection: &Connection, name: &str) -> ResultType<bool> {
|
||||
let proxy = connection.with_proxy(
|
||||
"org.freedesktop.DBus",
|
||||
"/org/freedesktop/DBus",
|
||||
DBUS_TIMEOUT,
|
||||
);
|
||||
let (owned,): (bool,) = proxy.method_call("org.freedesktop.DBus", "NameHasOwner", (name,))?;
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
fn kde_layout_group(connection: &Connection) -> ResultType<u32> {
|
||||
let proxy = connection.with_proxy("org.kde.keyboard", "/Layouts", DBUS_TIMEOUT);
|
||||
let (group,): (u32,) = proxy.method_call("org.kde.KeyboardLayouts", "getLayout", ())?;
|
||||
Ok(group)
|
||||
}
|
||||
|
||||
fn gnome_layout() -> ResultType<Option<Names>> {
|
||||
let schemas = gio::SettingsSchemaSource::default()
|
||||
.ok_or_else(|| anyhow!("GSettings schemas are unavailable"))?;
|
||||
let schema = schemas
|
||||
.lookup(GNOME_INPUT_SCHEMA, true)
|
||||
.ok_or_else(|| anyhow!("GNOME input source schema is unavailable"))?;
|
||||
let settings = gio::Settings::new_full(&schema, gio::SettingsBackend::NONE, None);
|
||||
let sources: Vec<(String, String)> = required_setting(&settings, "sources")?;
|
||||
// Focus changes restore a window's source without persisting MRU. Mark it
|
||||
// unreliable so refresh also discards a previously accepted MRU mapping.
|
||||
if sources.len() > 1 && required_setting::<bool>(&settings, "per-window")? {
|
||||
return Err(UnreliableSource(
|
||||
"GNOME per-window input sources cannot be determined from persisted MRU",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let recent: Vec<(String, String)> = required_setting(&settings, "mru-sources")?;
|
||||
// GNOME initially selects the first configured source when MRU is empty.
|
||||
// The IBus reader verifies the active engine before accepting persisted MRU.
|
||||
let selected = recent
|
||||
.iter()
|
||||
.find(|source| sources.contains(source))
|
||||
.or(sources.first());
|
||||
let Some((layout, variant)) = gnome_source_layout(selected)? else {
|
||||
// IBus engines without an XKB override use the compositor's keymap.
|
||||
return Ok(None);
|
||||
};
|
||||
if layout.is_empty() {
|
||||
bail!("GNOME input source has an empty layout");
|
||||
}
|
||||
// Match GNOME Shell's session-wide options; it does not merge IBus
|
||||
// engine layout-option metadata into the compositor keymap.
|
||||
let options: Vec<String> = required_setting(&settings, "xkb-options")?;
|
||||
// Older GNOME releases use the default model and have no xkb-model setting.
|
||||
let model: String = if schema.has_key("xkb-model") {
|
||||
required_setting(&settings, "xkb-model")?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Ok(Some(Names {
|
||||
model: CString::new(model)?,
|
||||
layout: CString::new(layout)?,
|
||||
variant: CString::new(variant)?,
|
||||
options: CString::new(options.join(","))?,
|
||||
}))
|
||||
}
|
||||
|
||||
fn gnome_source_layout(
|
||||
selected: Option<&(String, String)>,
|
||||
) -> ResultType<Option<(String, String)>> {
|
||||
let Some((kind, id)) = selected else {
|
||||
// GNOME Shell selects this layout when no input source is configured.
|
||||
return Ok(Some((GNOME_DEFAULT_LAYOUT.to_owned(), String::new())));
|
||||
};
|
||||
match kind.as_str() {
|
||||
"xkb" => {
|
||||
let (layout, variant) = id.split_once('+').unwrap_or((id.as_str(), ""));
|
||||
Ok(Some((layout.to_owned(), variant.to_owned())))
|
||||
}
|
||||
"ibus" => ibus::layout(id),
|
||||
_ => bail!("Unsupported GNOME input source type: {}", kind),
|
||||
}
|
||||
}
|
||||
|
||||
fn required_setting<T: FromVariant>(settings: &gio::Settings, key: &str) -> ResultType<T> {
|
||||
if !settings
|
||||
.settings_schema()
|
||||
.is_some_and(|schema| schema.has_key(key))
|
||||
{
|
||||
bail!("Missing GNOME setting {}", key);
|
||||
}
|
||||
settings
|
||||
.value(key)
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Invalid GNOME setting {}", key))
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use dbus::{
|
||||
arg::{RefArg, Variant},
|
||||
blocking::{stdintf::org_freedesktop_dbus::Properties, Connection},
|
||||
channel::Channel,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, ResultType};
|
||||
use std::{env, fs, io::ErrorKind, path::PathBuf};
|
||||
|
||||
const IBUS_SERVICE: &str = "org.freedesktop.IBus";
|
||||
const IBUS_PATH: &str = "/org/freedesktop/IBus";
|
||||
// IBusEngineDesc serialization preserves these field positions for its clients.
|
||||
const ENGINE_TYPE_FIELD: usize = 0;
|
||||
const ENGINE_NAME_FIELD: usize = 2;
|
||||
const ENGINE_LAYOUT_FIELD: usize = 9;
|
||||
const ENGINE_VARIANT_FIELD: usize = 14;
|
||||
|
||||
pub(super) fn layout(id: &str) -> ResultType<Option<(String, String)>> {
|
||||
let connection = Connection::from(Channel::open_private(&address()?)?);
|
||||
let bus = connection.with_proxy(
|
||||
"org.freedesktop.DBus",
|
||||
"/org/freedesktop/DBus",
|
||||
super::DBUS_TIMEOUT,
|
||||
);
|
||||
let _: (String,) = bus.method_call("org.freedesktop.DBus", "Hello", ())?;
|
||||
let proxy = connection.with_proxy(IBUS_SERVICE, IBUS_PATH, super::DBUS_TIMEOUT);
|
||||
let engine: Variant<Box<dyn RefArg>> = proxy.get(IBUS_SERVICE, "GlobalEngine")?;
|
||||
let fields: Vec<_> = engine
|
||||
.0
|
||||
.as_iter()
|
||||
.ok_or_else(|| anyhow!("Invalid IBus engine description"))?
|
||||
.collect();
|
||||
if field(&fields, ENGINE_TYPE_FIELD)? != "IBusEngineDesc" {
|
||||
bail!("IBus returned an unexpected engine description");
|
||||
}
|
||||
// GNOME may suppress IBus for password entry without updating persisted MRU.
|
||||
// Its xkb:us::eng echo engine does not identify the compositor's layout.
|
||||
if field(&fields, ENGINE_NAME_FIELD)? != id {
|
||||
return Err(
|
||||
super::UnreliableSource("MRU-selected IBus engine is not currently active").into(),
|
||||
);
|
||||
}
|
||||
let layout = field(&fields, ENGINE_LAYOUT_FIELD)?;
|
||||
if layout.is_empty() || layout == "default" {
|
||||
return Ok(None);
|
||||
}
|
||||
let variant = field(&fields, ENGINE_VARIANT_FIELD)?;
|
||||
let variant = if variant == "default" { "" } else { variant };
|
||||
Ok(Some((layout.to_owned(), variant.to_owned())))
|
||||
}
|
||||
|
||||
fn field<'a>(fields: &[&'a dyn RefArg], index: usize) -> ResultType<&'a str> {
|
||||
fields
|
||||
.get(index)
|
||||
.and_then(|value| (*value).as_str())
|
||||
.ok_or_else(|| anyhow!("Invalid IBus engine field {}", index))
|
||||
}
|
||||
|
||||
fn address() -> ResultType<String> {
|
||||
if let Some(address) = env::var_os("IBUS_ADDRESS") {
|
||||
return address
|
||||
.into_string()
|
||||
.map_err(|_| anyhow!("Invalid IBus address"));
|
||||
}
|
||||
let settings = fs::read_to_string(address_file()?)?;
|
||||
settings
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("IBUS_ADDRESS="))
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| anyhow!("IBus address file contains no address"))
|
||||
}
|
||||
|
||||
fn address_file() -> ResultType<PathBuf> {
|
||||
if let Some(path) = env::var_os("IBUS_ADDRESS_FILE") {
|
||||
return Ok(path.into());
|
||||
}
|
||||
let machine = match fs::read_to_string("/var/lib/dbus/machine-id") {
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => fs::read_to_string("/etc/machine-id")?,
|
||||
result => result?,
|
||||
};
|
||||
let display = env::var("WAYLAND_DISPLAY")?;
|
||||
Ok(gtk::glib::user_config_dir().join("ibus/bus").join(format!(
|
||||
"{}-unix-{}",
|
||||
machine.trim(),
|
||||
display
|
||||
)))
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use hbb_common::{anyhow::anyhow, bail, libc, ResultType};
|
||||
use std::{
|
||||
ffi::CStr,
|
||||
fs::File,
|
||||
io,
|
||||
os::{
|
||||
fd::{AsRawFd, OwnedFd, RawFd},
|
||||
unix::fs::FileExt,
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use wayland_client::{
|
||||
protocol::{wl_keyboard, wl_registry, wl_seat},
|
||||
Connection, Dispatch, QueueHandle, WEnum,
|
||||
};
|
||||
|
||||
const KEYMAP_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
const SEAT_VERSION: u32 = 7;
|
||||
|
||||
#[derive(Default)]
|
||||
struct KeyboardState {
|
||||
seat_bound: bool,
|
||||
keymap: Option<ResultType<Vec<u8>>>,
|
||||
}
|
||||
|
||||
pub(super) fn read_keymap() -> ResultType<Vec<u8>> {
|
||||
let connection = Connection::connect_to_env()?;
|
||||
let mut queue = connection.new_event_queue();
|
||||
connection.display().get_registry(&queue.handle(), ());
|
||||
let mut state = KeyboardState::default();
|
||||
let deadline = Instant::now() + KEYMAP_TIMEOUT;
|
||||
loop {
|
||||
queue.dispatch_pending(&mut state)?;
|
||||
if let Some(keymap) = state.keymap.take() {
|
||||
return keymap;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!("Timed out reading the Wayland keyboard map");
|
||||
}
|
||||
queue.flush()?;
|
||||
if let Some(reader) = queue.prepare_read() {
|
||||
wait_for_read(reader.connection_fd().as_raw_fd(), deadline)?;
|
||||
reader.read()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_read(fd: RawFd, deadline: Instant) -> ResultType<()> {
|
||||
let mut descriptor = libc::pollfd {
|
||||
fd,
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
let timeout = i32::try_from(remaining.as_millis())?;
|
||||
let ready = unsafe { libc::poll(&mut descriptor, 1, timeout) };
|
||||
if ready < 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
return Err(error.into());
|
||||
}
|
||||
if ready == 0 {
|
||||
bail!("Timed out reading the Wayland keyboard map");
|
||||
}
|
||||
if descriptor.revents & libc::POLLIN == 0 {
|
||||
bail!("Wayland keyboard connection closed: {}", descriptor.revents);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
fn read_keymap_file(fd: OwnedFd, size: u32) -> ResultType<Vec<u8>> {
|
||||
let file = File::from(fd);
|
||||
if file.metadata()?.len() < u64::from(size) {
|
||||
bail!("Wayland keyboard map is shorter than its advertised size");
|
||||
}
|
||||
let mut bytes = vec![0; usize::try_from(size)?];
|
||||
// Compositors can share this file description with other clients.
|
||||
file.read_exact_at(&mut bytes, 0)?;
|
||||
CStr::from_bytes_with_nul(&bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
impl Dispatch<wl_registry::WlRegistry, ()> for KeyboardState {
|
||||
fn event(
|
||||
state: &mut Self,
|
||||
registry: &wl_registry::WlRegistry,
|
||||
event: wl_registry::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
handle: &QueueHandle<Self>,
|
||||
) {
|
||||
if let wl_registry::Event::Global {
|
||||
name,
|
||||
interface,
|
||||
version,
|
||||
} = event
|
||||
{
|
||||
// Multi-seat sessions are unsupported: neither registry order nor
|
||||
// keyboard capability identifies the seat receiving our uinput events.
|
||||
// The first seat may have no keyboard or expose an unrelated keymap.
|
||||
if interface == "wl_seat" && !state.seat_bound {
|
||||
registry.bind::<wl_seat::WlSeat, _, _>(name, version.min(SEAT_VERSION), handle, ());
|
||||
state.seat_bound = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<wl_seat::WlSeat, ()> for KeyboardState {
|
||||
fn event(
|
||||
_: &mut Self,
|
||||
seat: &wl_seat::WlSeat,
|
||||
event: wl_seat::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
handle: &QueueHandle<Self>,
|
||||
) {
|
||||
if let wl_seat::Event::Capabilities {
|
||||
capabilities: WEnum::Value(capabilities),
|
||||
} = event
|
||||
{
|
||||
if capabilities.contains(wl_seat::Capability::Keyboard) {
|
||||
seat.get_keyboard(handle, ());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<wl_keyboard::WlKeyboard, ()> for KeyboardState {
|
||||
fn event(
|
||||
state: &mut Self,
|
||||
_: &wl_keyboard::WlKeyboard,
|
||||
event: wl_keyboard::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
) {
|
||||
if let wl_keyboard::Event::Keymap { format, fd, size } = event {
|
||||
state.keymap = Some(match format {
|
||||
WEnum::Value(wl_keyboard::KeymapFormat::XkbV1) => read_keymap_file(fd, size),
|
||||
_ => Err(anyhow!(
|
||||
"Wayland compositor did not provide an XKB keyboard map"
|
||||
)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
use super::{source::Source, XkbKeymap, DEFAULT_GROUP};
|
||||
use hbb_common::{anyhow::anyhow, bail, libc, libloading::Library, ResultType};
|
||||
use std::{
|
||||
ffi::{c_void, CStr, CString},
|
||||
ptr::NonNull,
|
||||
};
|
||||
use xkbcommon_dl::{self as xkb, x11};
|
||||
|
||||
struct Connection {
|
||||
pointer: NonNull<c_void>,
|
||||
disconnect: unsafe extern "C" fn(*mut c_void),
|
||||
_library: Library,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
fn open() -> ResultType<Self> {
|
||||
let display = CString::new(std::env::var("DISPLAY")?)?;
|
||||
if display.as_bytes().is_empty() {
|
||||
bail!("Xwayland DISPLAY is empty");
|
||||
}
|
||||
if !display.as_bytes().starts_with(b":")
|
||||
&& !display.as_bytes().starts_with(b"unix:")
|
||||
&& !display.as_bytes().starts_with(b"unix/:")
|
||||
{
|
||||
bail!("Xwayland layout detection requires a local DISPLAY");
|
||||
}
|
||||
unsafe {
|
||||
let library = Library::new("libxcb.so.1")?;
|
||||
let connect = *library
|
||||
.get::<unsafe extern "C" fn(*const libc::c_char, *mut libc::c_int) -> *mut c_void>(
|
||||
b"xcb_connect\0",
|
||||
)?;
|
||||
let disconnect =
|
||||
*library.get::<unsafe extern "C" fn(*mut c_void)>(b"xcb_disconnect\0")?;
|
||||
let has_error = *library.get::<unsafe extern "C" fn(*mut c_void) -> libc::c_int>(
|
||||
b"xcb_connection_has_error\0",
|
||||
)?;
|
||||
let pointer = NonNull::new(connect(display.as_ptr(), std::ptr::null_mut()))
|
||||
.ok_or_else(|| anyhow!("Cannot create Xwayland connection"))?;
|
||||
let connection = Self {
|
||||
pointer,
|
||||
disconnect,
|
||||
_library: library,
|
||||
};
|
||||
let error = has_error(connection.pointer.as_ptr());
|
||||
if error != 0 {
|
||||
bail!("Cannot connect to Xwayland (XCB error {})", error);
|
||||
}
|
||||
Ok(connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Connection {
|
||||
fn drop(&mut self) {
|
||||
unsafe { (self.disconnect)(self.pointer.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn read() -> ResultType<Source> {
|
||||
// Xwayland receives the group through focus-scoped wl_keyboard.modifiers.
|
||||
// With a native window focused, both core and slave X11 keyboards can
|
||||
// retain the last X11-focused group (verified on GNOME and KWin).
|
||||
// Reopening XCB or waiting cannot request the missing compositor update.
|
||||
// Prefer native GNOME/KDE sources; do not steal focus to refresh Xwayland.
|
||||
let api = xkb::xkbcommon_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon"))?;
|
||||
let x11 = x11::xkbcommon_x11_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon-x11"))?;
|
||||
let connection = Connection::open()?;
|
||||
let device = keyboard_device(x11, &connection)?;
|
||||
let keymap = read_keymap(x11, &connection, device)?;
|
||||
let state = unsafe {
|
||||
(x11.xkb_x11_state_new_from_device)(
|
||||
keymap.map.as_ptr(),
|
||||
connection.pointer.as_ptr(),
|
||||
device,
|
||||
)
|
||||
};
|
||||
let state =
|
||||
NonNull::new(state).ok_or_else(|| anyhow!("Cannot read Xwayland keyboard state"))?;
|
||||
let group = unsafe {
|
||||
(api.xkb_state_serialize_layout)(
|
||||
state.as_ptr(),
|
||||
xkb::xkb_state_component::XKB_STATE_LAYOUT_EFFECTIVE,
|
||||
)
|
||||
};
|
||||
unsafe { (api.xkb_state_unref)(state.as_ptr()) };
|
||||
let text = unsafe {
|
||||
(api.xkb_keymap_get_as_string)(
|
||||
keymap.map.as_ptr(),
|
||||
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||
)
|
||||
};
|
||||
let text = NonNull::new(text.cast_mut())
|
||||
.ok_or_else(|| anyhow!("Cannot serialize Xwayland keyboard map"))?;
|
||||
let bytes = unsafe { CStr::from_ptr(text.as_ptr()).to_bytes_with_nul().to_vec() };
|
||||
unsafe { libc::free(text.as_ptr().cast()) };
|
||||
Ok(Source::Xwayland {
|
||||
keymap: bytes,
|
||||
group: Some(group),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_keymap(
|
||||
x11: &x11::XkbCommonX11,
|
||||
connection: &Connection,
|
||||
device: i32,
|
||||
) -> ResultType<XkbKeymap> {
|
||||
let api = xkb::xkbcommon_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon"))?;
|
||||
let context =
|
||||
unsafe { (api.xkb_context_new)(xkb::xkb_context_flags::XKB_CONTEXT_NO_ENVIRONMENT_NAMES) };
|
||||
let context = NonNull::new(context).ok_or_else(|| anyhow!("Cannot create XKB context"))?;
|
||||
let map = unsafe {
|
||||
(x11.xkb_x11_keymap_new_from_device)(
|
||||
context.as_ptr(),
|
||||
connection.pointer.as_ptr(),
|
||||
device,
|
||||
xkb::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
unsafe { (api.xkb_context_unref)(context.as_ptr()) };
|
||||
let map = NonNull::new(map).ok_or_else(|| anyhow!("Cannot read Xwayland keyboard map"))?;
|
||||
Ok(XkbKeymap {
|
||||
api,
|
||||
map,
|
||||
group: DEFAULT_GROUP,
|
||||
})
|
||||
}
|
||||
|
||||
fn keyboard_device(api: &x11::XkbCommonX11, connection: &Connection) -> ResultType<i32> {
|
||||
let supported = unsafe {
|
||||
(api.xkb_x11_setup_xkb_extension)(
|
||||
connection.pointer.as_ptr(),
|
||||
x11::XKB_X11_MIN_MAJOR_XKB_VERSION,
|
||||
x11::XKB_X11_MIN_MINOR_XKB_VERSION,
|
||||
x11::xkb_x11_setup_xkb_extension_flags::XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if supported == 0 {
|
||||
bail!("Xwayland does not support the required XKB extension");
|
||||
}
|
||||
let device = unsafe { (api.xkb_x11_get_core_keyboard_device_id)(connection.pointer.as_ptr()) };
|
||||
if device < 0 {
|
||||
bail!("Xwayland has no core keyboard device");
|
||||
}
|
||||
Ok(device)
|
||||
}
|
||||
@@ -727,6 +727,8 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
let repeat_encode_max = 10;
|
||||
let mut encode_fail_counter = 0;
|
||||
let mut first_frame = true;
|
||||
// Set once the encoder emits its first packet; until then it may legitimately return nothing.
|
||||
let mut encoder_warmed_up = false;
|
||||
let capture_width = c.width;
|
||||
let capture_height = c.height;
|
||||
let (mut second_instant, mut send_counter) = (Instant::now(), 0);
|
||||
@@ -743,7 +745,12 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
&mut second_instant,
|
||||
&sp.name(),
|
||||
)?;
|
||||
if sp.is_option_true(OPTION_REFRESH) {
|
||||
// On macOS, a refresh here would destroy a hardware encoder that has been fed a frame but
|
||||
// not yet produced its first packet, restarting the warm-up forever. Defer until it has;
|
||||
// one that never does is still switched away from by max_fail_times in handle_one_frame.
|
||||
if sp.is_option_true(OPTION_REFRESH)
|
||||
&& refresh_allowed(first_frame, encoder_warmed_up, encoder.latency_free())
|
||||
{
|
||||
if vs.source.is_monitor() {
|
||||
let _ = try_broadcast_display_changed(&sp, display_idx, &c, true);
|
||||
}
|
||||
@@ -857,6 +864,7 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
recorder.clone(),
|
||||
&mut encode_fail_counter,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
capture_width,
|
||||
capture_height,
|
||||
)?;
|
||||
@@ -921,6 +929,7 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
recorder.clone(),
|
||||
&mut encode_fail_counter,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
capture_width,
|
||||
capture_height,
|
||||
)?;
|
||||
@@ -1233,6 +1242,12 @@ fn check_privacy_mode_changed(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn refresh_allowed(unfed: bool, warmed_up: bool, latency_free: bool) -> bool {
|
||||
// Only VideoToolbox has been seen to need this; other platforms keep refreshing as before.
|
||||
!cfg!(target_os = "macos") || unfed || warmed_up || latency_free
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn handle_one_frame(
|
||||
display: usize,
|
||||
@@ -1243,6 +1258,7 @@ fn handle_one_frame(
|
||||
recorder: Arc<Mutex<Option<Recorder>>>,
|
||||
encode_fail_counter: &mut usize,
|
||||
first_frame: &mut bool,
|
||||
encoder_warmed_up: &mut bool,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> ResultType<HashSet<i32>> {
|
||||
@@ -1261,6 +1277,7 @@ fn handle_one_frame(
|
||||
match encoder.encode_to_message(frame, ms) {
|
||||
Ok(mut vf) => {
|
||||
*encode_fail_counter = 0;
|
||||
*encoder_warmed_up = true;
|
||||
vf.display = display as _;
|
||||
let mut msg = Message::new();
|
||||
msg.set_video_frame(vf);
|
||||
@@ -1525,3 +1542,21 @@ fn handle_screenshot(screenshot: Screenshot, msg: String, w: usize, h: usize, da
|
||||
log::error!("Failed to send screenshot, {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::refresh_allowed;
|
||||
|
||||
#[test]
|
||||
fn refresh_waits_for_hw_encoder_warmup() {
|
||||
// Deferred on macOS only; everywhere else a refresh is always allowed.
|
||||
assert_eq!(
|
||||
refresh_allowed(false, false, false),
|
||||
!cfg!(target_os = "macos")
|
||||
);
|
||||
assert!(refresh_allowed(false, true, false));
|
||||
assert!(refresh_allowed(false, false, true));
|
||||
// Nothing fed yet: no warm-up to lose, and a refresh can restart a stalled capturer.
|
||||
assert!(refresh_allowed(true, false, false));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user