1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Linux IME bridge — in-process composition state with optional IBus probe.
//!
//! The bridge tracks marked text, cursor position, focus and composition
//! state, and (when the `linux-a11y`/zbus feature is active) probes the IBus
//! daemon over DBus to detect availability.
//!
//! **Protocol status**: the full IBus *engine* protocol (CreateInputContext,
//! ProcessKeyEvent round-trips, preedit streaming from the daemon) is not
//! wired here; that requires the active engine context, which this bridge
//! does not own. Commit/preedit operations are therefore modeled in-process
//! and published through the [`ImeBridge`](crate::platform::ime::ImeBridge) state, which the compositor or
//! host toolkit layer consumes.
#![cfg(target_os = "linux")]
use crate::compat::{lock, Mutex, String, ToString};
use crate::core::ObjectId;
use crate::platform::ime::{ImeBridge, ImeCandidatePosition, ImeComposition};
// ──────────────────────────────────────────────
// IBus connection handle (feature-gated).
// ──────────────────────────────────────────────
/// Real IBus DBus proxy connection plus its input context.
///
/// Connects to the session bus, resolves the IBus service, and creates an
/// `org.freedesktop.IBus.InputContext` on the `org.freedesktop.IBus` interface.
/// The input context is the object the engine protocol operates on
/// (`FocusIn`/`FocusOut`/`SetCursorLocation`/`ProcessKeyEvent`), so holding it
/// is what turns the bridge from a state model into a real IME client.
#[cfg(feature = "linux-a11y")]
struct IbusConnection {
/// Active zbus session connection.
connection: zbus::Connection,
/// Object path of the input context owned by this connection.
///
/// IBus destroys the context when the owning bus connection drops, which is
/// why the connection is held here for the bridge's lifetime.
input_context_path: String,
}
/// IBus input-context interface name.
#[cfg(feature = "linux-a11y")]
const IBUS_IC_INTERFACE: &str = "org.freedesktop.IBus.InputContext";
#[cfg(feature = "linux-a11y")]
impl IbusConnection {
/// Attempt to connect to the IBus daemon and create an input context.
///
/// Uses the `org.freedesktop.IBus` well-known name on the session bus.
/// If the IBus daemon is not running, the session bus is unavailable, or
/// `CreateInputContext` fails, this returns `None` and the bridge falls
/// back to state-machine mode.
fn try_connect() -> Option<Self> {
// Connect to the DBus session bus.
let conn = pollster::block_on(zbus::Connection::session()).ok()?;
let (owner, context_path): (String, String) = pollster::block_on(async {
// Resolve the IBus daemon on the session bus.
let dbus = zbus::Proxy::new(
&conn,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
)
.await
.ok()?;
// `GetNameOwner` returns a plain string (`s`), not a variant (`v`);
// asking for `OwnedValue` fails the signature check and makes the
// whole probe silently report "IBus unavailable".
let owner: String = dbus.call("GetNameOwner", &("org.freedesktop.IBus",)).await.ok()?;
// Create an input context owned by this connection.
let ibus = zbus::Proxy::new(
&conn,
"org.freedesktop.IBus",
"/org/freedesktop/IBus",
"org.freedesktop.IBus",
)
.await
.ok()?;
let path: zbus::zvariant::OwnedObjectPath =
ibus.call("CreateInputContext", &("rust_widgets",)).await.ok()?;
Some((owner, path.to_string()))
})?;
log::info!("[Linux IME] IBus connected (owner: {owner}); input context: {context_path}");
Some(IbusConnection { connection: conn, input_context_path: context_path })
}
/// Invoke a void method on this connection's input context with no arguments.
fn call_input_context_no_args(&self, method: &str) -> bool {
let conn = self.connection.clone();
let path = self.input_context_path.clone();
let method = method.to_string();
pollster::block_on(async move {
let proxy =
zbus::Proxy::new(&conn, "org.freedesktop.IBus", path.as_str(), IBUS_IC_INTERFACE)
.await
.ok()?;
match proxy.call_method(method.as_str(), &()).await {
Ok(_) => Some(()),
Err(e) => {
log::warn!("[Linux IME] IBus {method} call failed: {e}");
None
}
}
})
.is_some()
}
/// Invoke a void method on this connection's input context with one `u` argument.
fn call_input_context_u(&self, method: &str, arg: u32) -> bool {
let conn = self.connection.clone();
let path = self.input_context_path.clone();
let method = method.to_string();
pollster::block_on(async move {
let proxy =
zbus::Proxy::new(&conn, "org.freedesktop.IBus", path.as_str(), IBUS_IC_INTERFACE)
.await
.ok()?;
match proxy.call_method(method.as_str(), &(arg,)).await {
Ok(_) => Some(()),
Err(e) => {
log::warn!("[Linux IME] IBus {method} call failed: {e}");
None
}
}
})
.is_some()
}
/// Invoke a void method on this connection's input context with four `i` args.
fn call_input_context_iiii(&self, method: &str, a: i32, b: i32, c: i32, d: i32) -> bool {
let conn = self.connection.clone();
let path = self.input_context_path.clone();
let method = method.to_string();
pollster::block_on(async move {
let proxy =
zbus::Proxy::new(&conn, "org.freedesktop.IBus", path.as_str(), IBUS_IC_INTERFACE)
.await
.ok()?;
match proxy.call_method(method.as_str(), &(a, b, c, d)).await {
Ok(_) => Some(()),
Err(e) => {
log::warn!("[Linux IME] IBus {method} call failed: {e}");
None
}
}
})
.is_some()
}
/// Set input capabilities advertised to the engine.
///
/// Signature: `SetCapabilities(u)`. `IBUS_CAP_PREEDIT_TEXT | IBUS_CAP_FOCUS`
/// (1 | 4 = 5) tells the engine we can display preedit text and track focus,
/// which is what the bridge models.
fn set_capabilities(&self, flags: u32) -> bool {
self.call_input_context_u("SetCapabilities", flags)
}
/// Notify the engine that focus entered the input context.
///
/// Signature: `FocusIn()` — takes no arguments.
fn focus_in(&self) -> bool {
self.call_input_context_no_args("FocusIn")
}
/// Notify the engine that focus left the input context.
///
/// Signature: `FocusOut()` — takes no arguments.
fn focus_out(&self) -> bool {
self.call_input_context_no_args("FocusOut")
}
/// Tell the engine where the insertion point is (candidate window anchor).
///
/// Signature: `SetCursorLocation(iiii)` in screen coordinates.
fn set_cursor_location(&self, x: i32, y: i32, w: u32, h: u32) -> bool {
self.call_input_context_iiii("SetCursorLocation", x, y, w as i32, h as i32)
}
/// Forward a key event to the engine.
///
/// Signature: `ProcessKeyEvent(uuu)` returning `b`. `keyval`/`keycode`
/// follow the X11 conventions IBus expects; `state` is the X11 modifier
/// mask. Returns `Some(true)` when the engine consumed the event (it is
/// composing and will deliver preedit/commit as signals), `Some(false)`
/// when it declined and the key should be handled locally, and `None` when
/// the call itself failed (engine/connection gone).
fn process_key_event(&self, keyval: u32, keycode: u32, state: u32) -> Option<bool> {
let conn = self.connection.clone();
let path = self.input_context_path.clone();
pollster::block_on(async move {
let proxy =
zbus::Proxy::new(&conn, "org.freedesktop.IBus", path.as_str(), IBUS_IC_INTERFACE)
.await
.ok()?;
match proxy.call_method("ProcessKeyEvent", &(keyval, keycode, state)).await {
Ok(reply) => reply.body().deserialize::<bool>().ok(),
Err(e) => {
log::warn!("[Linux IME] IBus ProcessKeyEvent call failed: {e}");
None
}
}
})
}
}
/// `IBUS_CAP_PREEDIT_TEXT | IBUS_CAP_FOCUS`.
#[cfg(feature = "linux-a11y")]
const IBUS_CAP_PREEDIT_TEXT_FOCUS: u32 = 1 | 4;
// ──────────────────────────────────────────────
// Bridge struct
// ──────────────────────────────────────────────
/// Linux IME bridge backed by state tracking and optional IBus DBus
/// integration.
pub struct LinuxImeBridge {
/// The widget that currently has IME focus.
focused_widget: Mutex<Option<ObjectId>>,
/// Whether the IME session is active.
active: Mutex<bool>,
// ── Composition / marked-text state ──
/// Current preedit (marked) text string.
marked_text: Mutex<String>,
/// Cursor position within the composition (byte offset).
cursor_pos: Mutex<usize>,
/// Last insertion-point rectangle in screen coordinates.
cursor_rect: Mutex<(i32, i32, u32, u32)>,
/// Last requested candidate window position.
candidate_position: Mutex<ImeCandidatePosition>,
// ── Native IBus handle ──
/// Whether an IBus connection was successfully established (probe result).
ibus_available: Mutex<bool>,
/// Opaque IBus session-bus connection plus its input context.
///
/// Held open for the bridge's lifetime: IBus destroys the input context as
/// soon as the owning bus connection drops, so this is also the keep-alive.
#[cfg(feature = "linux-a11y")]
ibus_connection: Mutex<Option<IbusConnection>>,
}
crate::impl_default_via_new!(LinuxImeBridge);
impl LinuxImeBridge {
/// Create a new Linux IME bridge.
///
/// When the `linux-a11y` feature (zbus) is active, this attempts to
/// connect to the IBus daemon. On failure or in headless builds it
/// falls back to pure state tracking.
pub fn new() -> Self {
let ibus_avail: bool;
#[cfg(feature = "linux-a11y")]
let ibus_connection: Option<IbusConnection>;
#[cfg(feature = "linux-a11y")]
{
match IbusConnection::try_connect() {
Some(c) => {
ibus_avail = true;
ibus_connection = Some(c);
}
None => {
ibus_avail = false;
ibus_connection = None;
}
}
}
#[cfg(not(feature = "linux-a11y"))]
{
ibus_avail = false;
}
Self {
focused_widget: Mutex::new(None),
active: Mutex::new(false),
marked_text: Mutex::new(String::new()),
cursor_pos: Mutex::new(0),
cursor_rect: Mutex::new((0, 0, 0, 0)),
candidate_position: Mutex::new(ImeCandidatePosition { x: 0, y: 0 }),
ibus_available: Mutex::new(ibus_avail),
#[cfg(feature = "linux-a11y")]
ibus_connection: Mutex::new(ibus_connection),
}
}
/// Whether the IBus daemon was reachable when the bridge was created.
pub fn is_ibus_available(&self) -> bool {
*lock(&self.ibus_available)
}
// ── Native IME interface (exposed for platform event dispatch) ──
/// Set the cursor (insertion-point) rectangle — tells IBus where
/// to place the candidate popup.
///
/// Forwards to `SetCursorLocation` on the IBus input context when IBus is
/// connected, and always records the rectangle locally so candidate
/// placement works without a daemon too.
pub fn set_cursor_rect(&self, x: i32, y: i32, w: u32, h: u32) {
log::debug!("[Linux IME] set_cursor_rect: x={x}, y={y}, w={w}, h={h}");
*lock(&self.cursor_rect) = (x, y, w, h);
#[cfg(feature = "linux-a11y")]
if let Some(conn) = lock(&self.ibus_connection).as_ref() {
if !conn.set_cursor_location(x, y, w, h) {
log::warn!("[Linux IME] SetCursorLocation failed (engine may be gone)");
}
}
}
/// Process a raw key event through the IBus IME subsystem.
///
/// Returns `Some(text)` for committed text, `None` if consumed for
/// composition.
pub fn process_key_event(
&self,
key_code: u32,
modifiers: u32,
pressed: bool,
) -> Option<String> {
log::debug!(
"[Linux IME] process_key_event: key={key_code}, mods={modifiers:#x}, pressed={pressed}",
);
// Forward to the engine first: IBus decides whether the key is consumed
// for composition or passed through, and delivers preedit/commit back
// through signals. Only when no engine consumed the key do we fall back
// to the local printable-ASCII passthrough.
#[cfg(feature = "linux-a11y")]
if pressed {
let consumed = {
let guard = lock(&self.ibus_connection);
guard
.as_ref()
.and_then(|conn| conn.process_key_event(key_code, key_code, modifiers))
};
if consumed == Some(true) {
// The engine owns the decision; preedit/commit arrive as signals.
return None;
}
}
if self.has_marked_text() {
// During composition, IBus consumes all key events.
return None;
}
if !pressed {
return None;
}
// Printable ASCII passthrough.
if (0x20..=0x7e).contains(&key_code) {
let ch = char::from_u32(key_code)?;
let final_char = if modifiers & 0x02 != 0 { ch.to_ascii_uppercase() } else { ch };
return Some(final_char.to_string());
}
if key_code == 0x0d || key_code == 0x03 {
return Some("\n".to_string());
}
if key_code == 0x09 {
return Some("\t".to_string());
}
None
}
/// Set marked (preedit) text with selection endpoints.
///
/// `sel_start` / `sel_end` are byte offsets within the composition.
/// `-1` for both indicates cursor at end.
pub fn set_marked_text(&self, text: &str, sel_start: i32, sel_end: i32) {
log::debug!("[Linux IME] set_marked_text: '{text}'");
let len = text.len();
let cursor = if sel_start >= 0 && sel_end >= 0 {
sel_end.min(len as i32).max(0) as usize
} else {
len
};
*lock(&self.marked_text) = text.to_string();
*lock(&self.cursor_pos) = cursor;
}
/// Get the current marked (preedit) text, if any.
pub fn get_marked_text(&self) -> Option<String> {
let text = lock(&self.marked_text);
if text.is_empty() {
None
} else {
Some(text.clone())
}
}
/// Returns `true` when there is an active composition.
pub fn has_marked_text(&self) -> bool {
!lock(&self.marked_text).is_empty()
}
/// Discard the current composition without committing.
pub fn discard_marked_text(&self) {
log::debug!("[Linux IME] discard_marked_text");
*lock(&self.marked_text) = String::new();
*lock(&self.cursor_pos) = 0;
}
/// Clear internal composition state (shared helper).
fn clear_composition(&self) {
*lock(&self.marked_text) = String::new();
*lock(&self.cursor_pos) = 0;
}
}
// ──────────────────────────────────────────────
// ImeBridge trait implementation
// ──────────────────────────────────────────────
impl ImeBridge for LinuxImeBridge {
fn focus_in(&self, widget_id: ObjectId) {
*lock(&self.focused_widget) = Some(widget_id);
*lock(&self.active) = true;
log::info!("[Linux IME] focus_in: widget={widget_id}");
// Announce capabilities once per connection, then focus the engine so it
// starts composing into this context.
#[cfg(feature = "linux-a11y")]
if let Some(conn) = lock(&self.ibus_connection).as_ref() {
conn.set_capabilities(IBUS_CAP_PREEDIT_TEXT_FOCUS);
if !conn.focus_in() {
log::warn!("[Linux IME] IBus FocusIn failed (engine may be gone)");
}
}
}
fn focus_out(&self, widget_id: ObjectId) {
*lock(&self.focused_widget) = None;
*lock(&self.active) = false;
self.clear_composition();
log::info!("[Linux IME] focus_out: widget={widget_id}");
#[cfg(feature = "linux-a11y")]
if let Some(conn) = lock(&self.ibus_connection).as_ref() {
if !conn.focus_out() {
log::warn!("[Linux IME] IBus FocusOut failed (engine may be gone)");
}
}
}
fn commit_text(&self, text: &str) {
log::info!("[Linux IME] commit_text: '{text}'");
self.clear_composition();
// Hand the committed string to the focused widget as `Event::ImeCommit`.
//
// # The defect this closes
//
// This used to only log and clear the local composition state, so a control that matched
// `Event::ImeCommit` (the code editor, `tag_input`, `search_bar`) never received the text —
// the join the bridge's `commit_text` exists to make was missing, and the whole bridge-to-
// widget path was a no-op the host could not observe. With no focused widget there is no
// caret to commit into, so the delivery is skipped (the honest answer that
// `deliver_commit` documents).
#[cfg(not(alloc_frugal))]
{
// Copy the focused widget out of the lock and release the guard before
// delivering: `deliver_commit` dispatches to the widget, whose handler may
// change focus, cancel or re-submit — any of which re-enters this bridge's
// own `focused_widget` mutex. Holding the guard across that call deadlocks.
let focused = *lock(&self.focused_widget);
if let Some(widget_id) = focused {
if !crate::platform::ime::deliver_commit(widget_id, text) {
log::debug!(
"[Linux IME] commit_text: widget {widget_id} is no longer mounted; the \
commit was not delivered"
);
}
} else {
log::debug!("[Linux IME] commit_text with no focused widget; nothing to deliver");
}
}
}
fn set_composition(&self, composition: &ImeComposition) {
log::debug!("[Linux IME] set_composition: '{}'", composition.text);
let text = &composition.text;
let len = text.len();
let cursor = composition.cursor_position.min(len);
*lock(&self.marked_text) = text.to_string();
*lock(&self.cursor_pos) = cursor;
}
fn set_candidate_window_position(&self, position: ImeCandidatePosition) {
log::debug!("[Linux IME] set_candidate_window_position: ({}, {})", position.x, position.y);
*lock(&self.candidate_position) = position;
}
/// Whether an IME session is **actually connected** to a focused widget.
///
/// # Why focus alone is not enough
///
/// `focus_in` sets the `active` flag unconditionally so the state machine knows a caret is
/// present, but that flag says nothing about whether a system IME connection exists: without the
/// `linux-a11y` feature IBus availability is `false`, and with it a failed `try_connect` leaves
/// the connection `None`. Reporting `active` alone therefore claimed a connected IME whenever a
/// widget merely gained focus, so a host that gates its own IME UI on this would enable it over a
/// bridge that can never deliver a composition. This reports the conjunction — focus **and** a
/// live IBus connection — which is what `is_active` promises (see
/// [`ImeBridge::is_active`](crate::platform::ime::ImeBridge::is_active)).
fn is_active(&self) -> bool {
if !*lock(&self.active) {
return false;
}
#[cfg(feature = "linux-a11y")]
{
lock(&self.ibus_connection).is_some()
}
#[cfg(not(feature = "linux-a11y"))]
{
false
}
}
}
// ──────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use crate::platform::ime::ImeComposition;
#[test]
fn test_focus_in_out() {
let bridge = LinuxImeBridge::new();
assert!(!bridge.is_active());
assert!(lock(&bridge.focused_widget).is_none());
bridge.focus_in(42);
// Focus is tracked unconditionally — the widget that would receive a commit is recorded —
// but `is_active` additionally requires a live IBus connection. This build has no
// `linux-a11y` feature, so IBus availability is false and `is_active` must stay false even
// with focus: focus is not a connection.
assert_eq!(*lock(&bridge.focused_widget), Some(42));
assert!(
!bridge.is_active(),
"focus alone must not report a live IME connection (no IBus without `linux-a11y`)"
);
bridge.focus_out(42);
assert!(!bridge.is_active());
assert!(lock(&bridge.focused_widget).is_none());
}
/// `is_active` is exactly "focused **and** connected", not "a widget has focus".
///
/// # What this pins (BLUE-issue P-12)
///
/// `focus_in` used to make `is_active` true unconditionally, so a bridge with no IBus at all
/// advertised a live IME session. The `active` flag still tracks focus, but the public answer
/// must also require the connection.
#[test]
fn is_active_requires_a_live_connection_not_only_focus() {
let bridge = LinuxImeBridge::new();
bridge.focus_in(7);
if !bridge.is_ibus_available() {
assert!(
!bridge.is_active(),
"without IBus, focus must not be reported as an active IME connection"
);
}
// When IBus *is* available the connection exists, so focus + connection is active; the point
// of this test is the no-connection half, which every CI host without a session bus exercises.
}
#[test]
fn test_commit_text_clears_composition() {
let bridge = LinuxImeBridge::new();
bridge.set_marked_text("hello", 5, 5);
assert!(bridge.has_marked_text());
bridge.commit_text("hello");
assert!(!bridge.has_marked_text());
assert_eq!(bridge.get_marked_text(), None);
}
#[test]
fn test_commit_text_via_trait() {
let bridge = LinuxImeBridge::new();
bridge.set_marked_text("你好", 6, 6);
assert!(bridge.has_marked_text());
ImeBridge::commit_text(&bridge, "你好");
assert!(!bridge.has_marked_text());
}
#[test]
fn test_set_composition_trait() {
let bridge = LinuxImeBridge::new();
let comp = ImeComposition {
text: "composing".to_string(),
cursor_position: 5,
selection_length: 0,
};
bridge.set_composition(&comp);
assert!(bridge.has_marked_text());
assert_eq!(bridge.get_marked_text(), Some("composing".to_string()));
assert_eq!(*lock(&bridge.cursor_pos), 5);
}
#[test]
fn test_set_composition_empty_clears() {
let bridge = LinuxImeBridge::new();
bridge.set_marked_text("something", 5, 0);
let empty = ImeComposition::default();
bridge.set_composition(&empty);
assert!(!bridge.has_marked_text());
}
#[test]
fn test_discard_marked_text() {
let bridge = LinuxImeBridge::new();
bridge.set_marked_text("你好世界", 4, 8);
assert!(bridge.has_marked_text());
assert_eq!(*lock(&bridge.cursor_pos), 8);
bridge.discard_marked_text();
assert!(!bridge.has_marked_text());
assert_eq!(bridge.get_marked_text(), None);
assert_eq!(*lock(&bridge.cursor_pos), 0);
}
#[test]
fn test_is_active_after_events() {
let bridge = LinuxImeBridge::new();
assert!(!bridge.is_active());
bridge.focus_in(1);
assert!(bridge.is_active());
bridge.focus_out(1);
assert!(!bridge.is_active());
}
#[test]
fn test_process_key_event_no_composition() {
let bridge = LinuxImeBridge::new();
// 'A' with shift
let result = bridge.process_key_event(0x61, 0x02, true);
assert_eq!(result, Some("A".to_string()));
// 'a' no shift
let result = bridge.process_key_event(0x61, 0x00, true);
assert_eq!(result, Some("a".to_string()));
// Enter
let result = bridge.process_key_event(0x0d, 0x00, true);
assert_eq!(result, Some("\n".to_string()));
// Escape (function key) => None
let result = bridge.process_key_event(0x1b, 0x00, true);
assert_eq!(result, None);
}
#[test]
fn test_process_key_event_during_composition() {
let bridge = LinuxImeBridge::new();
bridge.set_marked_text(" composing", 10, 0);
let result = bridge.process_key_event(0x61, 0x00, true);
assert_eq!(result, None);
}
#[test]
fn test_process_key_event_released() {
let bridge = LinuxImeBridge::new();
let result = bridge.process_key_event(0x61, 0x00, false);
assert_eq!(result, None);
}
#[test]
fn test_set_candidate_window_position() {
let bridge = LinuxImeBridge::new();
bridge.set_candidate_window_position(ImeCandidatePosition { x: 100, y: 200 });
assert_eq!(*lock(&bridge.candidate_position), ImeCandidatePosition { x: 100, y: 200 });
}
#[test]
fn test_focus_out_discards_composition() {
let bridge = LinuxImeBridge::new();
bridge.set_marked_text("pending", 7, 0);
assert!(bridge.has_marked_text());
bridge.focus_out(1);
assert!(!bridge.has_marked_text());
assert!(!bridge.is_active());
}
#[test]
fn test_set_cursor_rect() {
let bridge = LinuxImeBridge::new();
bridge.set_cursor_rect(10, 20, 100, 30);
assert_eq!(*lock(&bridge.cursor_rect), (10, 20, 100, 30));
}
#[test]
fn test_ibus_availability_matches_feature() {
// Without `linux-a11y` there is no DBus probe, so IBus must be reported
// unavailable. With the feature the result depends on whether a session
// bus and IBus daemon are reachable, so assert the consistency of the
// reported flag with the feature gate rather than a fixed value.
let bridge = LinuxImeBridge::new();
#[cfg(not(feature = "linux-a11y"))]
assert!(!bridge.is_ibus_available(), "no linux-a11y feature => no IBus probe");
#[cfg(feature = "linux-a11y")]
{
// `is_ibus_available` reflects whether an input context was created;
// the call must not panic regardless of the host environment.
let _ = bridge.is_ibus_available();
}
}
/// End-to-end check against a real IBus daemon.
///
/// Runs only when `linux-a11y` is on and an IBus service owns
/// `org.freedesktop.IBus` on the session bus. It asserts the bridge created
/// an input context and that every engine-protocol call
/// (`SetCapabilities`, `FocusIn`, `SetCursorLocation`, `ProcessKeyEvent`,
/// `FocusOut`) is accepted by the daemon with its real D-Bus signature.
///
/// Note on `ProcessKeyEvent`: the default `keyboard-us` engine *declines*
/// plain ASCII (returns `false`) and only consumes keys while composing, so
/// the test asserts the call is accepted rather than that it was consumed.
#[cfg(feature = "linux-a11y")]
#[test]
fn test_real_ibus_input_context_when_daemon_present() {
let bridge = LinuxImeBridge::new();
if !bridge.is_ibus_available() {
// No IBus on this host/CI runner: nothing to verify, and silently
// passing would overstate coverage, so say so explicitly.
eprintln!("skipped: no IBus daemon on the session bus");
return;
}
let context_path = {
let guard = lock(&bridge.ibus_connection);
guard.as_ref().expect("available implies a connection").input_context_path.clone()
};
assert!(
context_path.starts_with("/org/freedesktop/IBus/InputContext_"),
"unexpected input-context path: {context_path}"
);
// Every engine call must be accepted by the daemon.
{
let guard = lock(&bridge.ibus_connection);
let conn = guard.as_ref().unwrap();
assert!(conn.set_capabilities(IBUS_CAP_PREEDIT_TEXT_FOCUS), "SetCapabilities");
assert!(conn.focus_in(), "FocusIn");
assert!(conn.set_cursor_location(10, 20, 100, 30), "SetCursorLocation");
assert!(
conn.process_key_event('a' as u32, 38, 0).is_some(),
"ProcessKeyEvent must reach the engine"
);
assert!(conn.focus_out(), "FocusOut");
}
// The bridge-level path must also reach the engine (no silent fallback
// to the local state machine while an engine is attached).
bridge.focus_in(1);
assert!(bridge.is_active(), "focus_in must mark the session active");
bridge.set_cursor_rect(10, 20, 100, 30);
bridge.focus_out(1);
assert!(!bridge.is_active(), "focus_out must clear active state");
}
/// A commit callback that re-enters the bridge (focus_out) must not deadlock.
///
/// `commit_text` used to hold the `focused_widget` lock for the whole synchronous
/// `deliver_commit`, so a widget whose `ImeCommit` handler changed focus re-locked
/// the same mutex and hung. The lock must be released before delivery.
#[cfg(not(alloc_frugal))]
#[test]
fn commit_text_releases_the_focus_lock_before_delivery() {
use crate::event::{Event, EventHandler};
use std::rc::Rc;
let bridge = Rc::new(LinuxImeBridge::new());
let reentered = Rc::new(core::cell::Cell::new(false));
let id_cell = Rc::new(core::cell::Cell::new(0u64));
struct Reentrant {
bridge: Rc<LinuxImeBridge>,
id: Rc<core::cell::Cell<u64>>,
reentered: Rc<core::cell::Cell<bool>>,
base: crate::widget::BaseWidget,
}
impl crate::widget::Widget for Reentrant {
fn base(&self) -> &crate::widget::BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut crate::widget::BaseWidget {
&mut self.base
}
}
impl EventHandler for Reentrant {
fn handle_event(&mut self, event: &Event) {
if matches!(event, Event::ImeCommit { .. }) {
assert!(
crate::compat::try_lock(&self.bridge.focused_widget).is_some(),
"commit delivery must not hold the focused_widget lock"
);
self.bridge.focus_out(self.id.get());
self.reentered.set(true);
}
}
}
let id = crate::widget::runtime::register(Box::new(Reentrant {
bridge: Rc::clone(&bridge),
id: Rc::clone(&id_cell),
reentered: Rc::clone(&reentered),
base: crate::widget::BaseWidget::new(
crate::widget::WidgetKind::LineEdit,
crate::core::Rect::new(0, 0, 10, 10),
"reentrant",
),
}))
.expect("mount the reentrant widget");
id_cell.set(id);
bridge.focus_in(id);
bridge.commit_text("hi");
assert!(reentered.get(), "the commit handler must have run");
assert!(
lock(&bridge.focused_widget).is_none(),
"focus_out must have re-entered and cleared"
);
crate::widget::runtime::unregister(id);
}
}