ailloli_ui_winit/
devtools.rs

1//! In-process developer-tools overlay and loopback JSONL remote bridge.
2//!
3//! The visual overlay shares the inspected window's retained runtime and text
4//! resources. Remote commands are wake-coalesced and applied on the UI thread.
5
6use ailloli_ui_core::event::keyboard::{Key, KeyState, NamedKey};
7use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
8use ailloli_ui_core::{Color, Constraints, ElementId, Event, Rect};
9use ailloli_ui_devtools_core::{
10    collect_debug_snapshot_with_state, debug_draw_cmds, pick_element_at, DebugDrawCmd,
11    DebugSnapshot, DevToolsClientMessage, DevToolsMode, DevToolsServerMessage,
12};
13use ailloli_ui_devtools_ui::{
14    build_devtools_overlay, DevToolsAction, DevToolsState, DEVTOOLS_PANEL_KEY,
15};
16use ailloli_ui_runtime::app::{Runtime, RuntimeHandle, UiWake, UiWakeError};
17use ailloli_ui_runtime::element::ElementTree;
18use ailloli_ui_runtime::input::{absolute_paint_bounds, InputRouter};
19use ailloli_ui_runtime::scene::{ClipStackSnapshot, DrawCmd, DrawRect, Layer, Scene};
20use ailloli_ui_text::TextSystem;
21
22use std::io::{Read, Write};
23use std::net::{SocketAddr, TcpListener, TcpStream};
24use std::sync::atomic::{AtomicUsize, Ordering};
25use std::sync::mpsc::{self, Receiver, Sender};
26use std::sync::{Arc, Mutex};
27use std::thread;
28use std::time::Duration;
29
30/// Maximum concurrent loopback TCP clients; additional connections are dropped.
31const MAX_DEVTOOLS_CLIENTS: usize = 8;
32/// Maximum bytes before one JSONL newline; oversized clients are disconnected.
33const MAX_DEVTOOLS_MESSAGE_BYTES: usize = 64 * 1024;
34
35/// Per-window devtools interaction, snapshot, overlay-runtime, and remote state.
36///
37/// [`Self::new`] starts disabled unless the modern or legacy remote environment
38/// variable contains a valid loopback socket address. Keyboard shortcuts are
39/// Ctrl+Shift+I for visibility, Ctrl+Shift+C for the picker, and Escape to leave
40/// picker mode or hide the overlay.
41///
42/// # Examples
43///
44/// ```
45/// use ailloli_ui_devtools_core::DevToolsMode;
46/// let state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
47/// assert_eq!(state.mode, DevToolsMode::Overlay);
48/// assert!(!state.picker_active);
49/// ```
50pub struct DevToolsWindowState {
51    /// Whether the local overlay may render and consume panel input.
52    pub enabled: bool,
53    /// Current overlay placement or hidden mode.
54    pub mode: DevToolsMode,
55    /// Whether pointer motion/click selects inspected elements.
56    pub picker_active: bool,
57    /// Selected inspected element's numeric id, or none.
58    pub selected: Option<u64>,
59    /// Picker-hovered inspected element's numeric id, or none.
60    pub hovered: Option<u64>,
61    /// Retained runtime dedicated to the overlay controls.
62    runtime: Runtime<DevToolsAction>,
63    /// Input router dedicated to the overlay tree.
64    input: InputRouter,
65    /// Saturating debug-snapshot sequence number.
66    frame_index: u64,
67    /// Most recent inspected-tree snapshot used for picking.
68    last_snapshot: Option<DebugSnapshot>,
69    /// Absolute logical bounds used to intercept panel pointer events.
70    last_panel_bounds: Option<Rect>,
71    /// Optional loopback remote server channels.
72    remote: Option<DevToolsRemote>,
73    /// Late-bound native host wake retained across remote replacement.
74    host_wake: Option<Arc<dyn UiWake>>,
75}
76
77/// Window-local devtools lifecycle, event handling, and scene construction.
78impl DevToolsWindowState {
79    /// Creates overlay state and optionally starts the environment-configured remote.
80    ///
81    /// `AILLOLI_UI_DEVTOOLS_REMOTE` wins over `OCTAVUI_DEVTOOLS_REMOTE`. Invalid,
82    /// non-loopback, or unbindable addresses behave as no remote and leave the
83    /// local overlay disabled.
84    ///
85    /// # Examples
86    ///
87    /// ```
88    /// let state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
89    /// assert!(state.selected.is_none() && state.hovered.is_none());
90    /// ```
91    pub fn new() -> Self {
92        let remote = DevToolsRemote::from_env();
93        Self {
94            enabled: remote.is_some(),
95            mode: DevToolsMode::Overlay,
96            picker_active: false,
97            selected: None,
98            hovered: None,
99            runtime: Runtime::new(RuntimeHandle::new()),
100            input: InputRouter::default(),
101            frame_index: 0,
102            last_snapshot: None,
103            last_panel_bounds: None,
104            remote,
105            host_wake: None,
106        }
107    }
108
109    /// Replaces the remote server with an optional loopback address.
110    ///
111    /// `None` drops this handle's channels but does not forcibly disable an
112    /// already-enabled local overlay. A successful server enables the overlay
113    /// and receives the previously installed host wake. Startup failure leaves
114    /// no remote.
115    ///
116    /// # Examples
117    ///
118    /// ```
119    /// let mut state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
120    /// state.set_remote_addr(None);
121    /// assert_eq!(state.mode, ailloli_ui_devtools_core::DevToolsMode::Overlay);
122    /// ```
123    pub fn set_remote_addr(&mut self, addr: Option<SocketAddr>) {
124        self.remote = addr.and_then(DevToolsRemote::start);
125        if let Some(remote) = self.remote.as_ref() {
126            if let Some(wake) = self.host_wake.as_ref() {
127                let _ = remote.install_wake(wake.clone());
128            }
129            self.enabled = true;
130        }
131    }
132
133    /// Stores the native wake and installs it into the current remote bridge.
134    ///
135    /// # Errors
136    ///
137    /// Returns a late-bound wake failure while the remote also latches it.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// // `WinitHost` installs this wake before entering the native event loop.
143    /// let state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
144    /// assert!(!state.enabled || state.mode == ailloli_ui_devtools_core::DevToolsMode::Overlay);
145    /// ```
146    pub(crate) fn install_host_wake(&mut self, wake: Arc<dyn UiWake>) -> Result<(), UiWakeError> {
147        self.host_wake = Some(wake.clone());
148        self.remote
149            .as_ref()
150            .map_or(Ok(()), |remote| remote.install_wake(wake))
151    }
152
153    /// Rearms remote wake coalescing and reports whether commands remain queued.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// // Host service uses the boolean to request a redraw before draining commands.
159    /// let state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
160    /// assert!(!state.picker_active);
161    /// ```
162    pub(crate) fn begin_host_service(&self) -> bool {
163        self.remote
164            .as_ref()
165            .is_some_and(DevToolsRemote::begin_host_service)
166    }
167
168    /// Consumes the remote bridge's first non-fatal wake error.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// // No remote means there is no remote wake error.
174    /// let state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
175    /// let _ = state;
176    /// ```
177    pub(crate) fn take_wake_error(&self) -> Option<UiWakeError> {
178        self.remote
179            .as_ref()
180            .and_then(DevToolsRemote::take_wake_error)
181    }
182
183    /// Applies queued remote commands, shortcuts, panel input, and picker input.
184    ///
185    /// Returns `true` only when devtools consumed the event. Panel pointer input
186    /// is routed before application content; picker motion updates hover, and a
187    /// released primary click selects then disables picking.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// use ailloli_ui_core::Event;
193    /// let mut state = ailloli_ui_winit::devtools::DevToolsWindowState::new();
194    /// let _handler: fn(&mut _, &Event) -> bool =
195    ///     ailloli_ui_winit::devtools::DevToolsWindowState::handle_event;
196    /// let _ = &mut state;
197    /// ```
198    pub fn handle_event(&mut self, event: &Event) -> bool {
199        self.apply_remote_commands();
200        match event {
201            Event::Keyboard(key) if key.state == KeyState::Pressed => {
202                if key.modifiers.ctrl
203                    && key.modifiers.shift
204                    && matches!(&key.key, Key::Character(c) if c.eq_ignore_ascii_case("i"))
205                {
206                    self.enabled = !self.enabled;
207                    if self.enabled && matches!(self.mode, DevToolsMode::Hidden) {
208                        self.mode = DevToolsMode::Overlay;
209                    }
210                    return true;
211                }
212                if key.modifiers.ctrl
213                    && key.modifiers.shift
214                    && matches!(&key.key, Key::Character(c) if c.eq_ignore_ascii_case("c"))
215                {
216                    self.enabled = true;
217                    self.picker_active = !self.picker_active;
218                    return true;
219                }
220                if matches!(&key.key, Key::Named(NamedKey::Escape)) {
221                    if self.picker_active {
222                        self.picker_active = false;
223                    } else if self.enabled {
224                        self.enabled = false;
225                    } else {
226                        return false;
227                    }
228                    return true;
229                }
230            }
231            Event::Pointer(PointerEvent::Moved { pos, .. })
232            | Event::Pointer(PointerEvent::Button { pos, .. })
233            | Event::Pointer(PointerEvent::Wheel { pos, .. })
234                if self.enabled && self.panel_contains(*pos) =>
235            {
236                self.input
237                    .route_event(&self.runtime.tree, self.runtime.runtime.clone(), event);
238                self.apply_runtime_actions();
239                return true;
240            }
241            Event::Pointer(PointerEvent::Moved { pos, .. }) if self.picker_active => {
242                self.hovered = self
243                    .last_snapshot
244                    .as_ref()
245                    .and_then(|snapshot| pick_element_at(snapshot, *pos));
246                return true;
247            }
248            Event::Pointer(PointerEvent::Button {
249                pos,
250                button: MouseButton::Left,
251                pressed: false,
252                ..
253            }) if self.picker_active => {
254                self.selected = self
255                    .last_snapshot
256                    .as_ref()
257                    .and_then(|snapshot| pick_element_at(snapshot, *pos));
258                self.picker_active = false;
259                return true;
260            }
261            _ => {}
262        }
263        false
264    }
265
266    /// Updates the inspected snapshot and optionally builds the local overlay scene.
267    ///
268    /// Remote-only mode still snapshots and publishes while returning `None`.
269    /// Visible mode reconciles, lays out, and paints a separate overlay runtime,
270    /// then inserts selection/hover rectangles as the first overlay layer. The
271    /// frame index saturates at `u64::MAX`.
272    ///
273    /// # Examples
274    ///
275    /// ```no_run
276    /// use ailloli_ui_core::{ElementId, Rect};
277    /// use ailloli_ui_core::math::Scale;
278    /// use ailloli_ui_runtime::element::ElementTree;
279    /// use ailloli_ui_text::TextSystem;
280    /// fn build<A: 'static>(state: &mut ailloli_ui_winit::devtools::DevToolsWindowState,
281    ///     tree: &ElementTree<A>, root: ElementId, text: &mut TextSystem) {
282    ///     let scene: Option<ailloli_ui_runtime::scene::Scene> = state.build_scene(
283    ///         tree, root, Rect::new(0.0, 0.0, 800.0, 600.0), Scale::new(1.0), text);
284    ///     let _ = scene;
285    /// }
286    /// ```
287    pub fn build_scene<A: 'static>(
288        &mut self,
289        tree: &ElementTree<A>,
290        root: ElementId,
291        viewport: Rect,
292        scale: ailloli_ui_core::math::Scale,
293        text_system: &mut TextSystem,
294    ) -> Option<Scene> {
295        self.apply_remote_commands();
296        if !self.enabled && self.remote.is_none() {
297            return None;
298        }
299
300        self.frame_index = self.frame_index.saturating_add(1);
301        let snapshot = collect_debug_snapshot_with_state(
302            tree,
303            root,
304            viewport,
305            self.selected.map(ElementId),
306            self.hovered.map(ElementId),
307            self.frame_index,
308        );
309        if let Some(remote) = &self.remote {
310            remote.publish_snapshot(snapshot.clone());
311        }
312        self.last_snapshot = Some(snapshot.clone());
313
314        if !self.enabled || matches!(self.mode, DevToolsMode::Hidden) {
315            return None;
316        }
317
318        let ui_state = DevToolsState {
319            enabled: self.enabled,
320            mode: self.mode,
321            picker_active: self.picker_active,
322            selected: self.selected,
323            hovered: self.hovered,
324            filter: String::new(),
325        };
326        let overlay = build_devtools_overlay(&snapshot, &ui_state);
327        self.runtime.reconcile(overlay);
328        self.runtime.layout(
329            Constraints::tight(viewport.w, viewport.h),
330            scale,
331            text_system,
332        );
333        self.last_panel_bounds = self.resolve_panel_bounds();
334        self.apply_runtime_actions();
335        let mut scene = self.runtime.paint(text_system);
336        let draw_cmds = debug_draw_cmds(&snapshot)
337            .into_iter()
338            .flat_map(debug_draw_to_runtime)
339            .collect::<Vec<_>>();
340        if !draw_cmds.is_empty() {
341            let mut layer = Layer::overlay(ClipStackSnapshot::empty());
342            layer.cmds = draw_cmds;
343            scene.layers.insert(0, layer);
344        }
345        Some(scene)
346    }
347
348    /// Tests whether a logical pointer coordinate lies in the last panel bounds.
349    fn panel_contains(&self, pos: ailloli_ui_core::Point) -> bool {
350        self.last_panel_bounds
351            .is_some_and(|bounds| bounds.contains(pos.x, pos.y))
352    }
353
354    /// Resolves the panel's retained view key to absolute logical paint bounds.
355    fn resolve_panel_bounds(&self) -> Option<Rect> {
356        let id = self
357            .runtime
358            .tree
359            .resolve_element_by_view_key(DEVTOOLS_PANEL_KEY)
360            .ok()?;
361        absolute_paint_bounds(&self.runtime.tree, id)
362    }
363
364    /// Drains overlay-runtime actions in emission order.
365    fn apply_runtime_actions(&mut self) {
366        for action in self.runtime.runtime.take_actions() {
367            self.apply_action(action);
368        }
369    }
370
371    /// Applies one overlay action to visible mode, picker, or selection state.
372    fn apply_action(&mut self, action: DevToolsAction) {
373        match action {
374            DevToolsAction::Select(id) => {
375                self.selected = id;
376                self.enabled = true;
377            }
378            DevToolsAction::Hover(id) => {
379                self.hovered = id;
380            }
381            DevToolsAction::SetMode(mode) => {
382                self.mode = mode;
383                self.enabled = !matches!(mode, DevToolsMode::Hidden);
384            }
385            DevToolsAction::TogglePicker => {
386                self.enabled = true;
387                self.picker_active = !self.picker_active;
388            }
389            DevToolsAction::SetFilter(filter) => {
390                let _ = filter;
391            }
392        }
393    }
394
395    /// Drains and applies all queued remote commands; pings are server-local no-ops here.
396    fn apply_remote_commands(&mut self) {
397        let Some(remote) = &self.remote else {
398            return;
399        };
400        for cmd in remote.drain_commands() {
401            match cmd {
402                DevToolsClientMessage::Select { id } => {
403                    self.apply_action(DevToolsAction::Select(id));
404                }
405                DevToolsClientMessage::Hover { id } => {
406                    self.apply_action(DevToolsAction::Hover(id));
407                }
408                DevToolsClientMessage::SetMode { mode } => {
409                    self.apply_action(DevToolsAction::SetMode(mode));
410                }
411                DevToolsClientMessage::Ping => {}
412            }
413        }
414    }
415}
416
417/// Delegates to environment-aware [`Self::new`].
418impl Default for DevToolsWindowState {
419    /// Creates the same state as [`DevToolsWindowState::new`].
420    fn default() -> Self {
421        Self::new()
422    }
423}
424
425/// Converts debug geometry to runtime draw commands; text labels are omitted.
426fn debug_draw_to_runtime(cmd: DebugDrawCmd) -> Vec<DrawCmd> {
427    match cmd {
428        DebugDrawCmd::RectOutline {
429            rect,
430            color,
431            thickness,
432        } => outline_rect(
433            Rect::new(rect.x, rect.y, rect.w, rect.h),
434            Color::f32(color.r, color.g, color.b, color.a),
435            thickness,
436        ),
437        DebugDrawCmd::RectFill { rect, color } => vec![DrawCmd::Rect(DrawRect {
438            rect: Rect::new(rect.x, rect.y, rect.w, rect.h),
439            color: Color::f32(color.r, color.g, color.b, color.a),
440        })],
441        DebugDrawCmd::TextLabel { .. } => Vec::new(),
442    }
443}
444
445/// Builds four logical-pixel rectangles, clamping thickness to at least one.
446fn outline_rect(rect: Rect, color: Color, thickness: f32) -> Vec<DrawCmd> {
447    let t = thickness.max(1.0);
448    vec![
449        DrawCmd::Rect(DrawRect {
450            rect: Rect::new(rect.x, rect.y, rect.w, t),
451            color,
452        }),
453        DrawCmd::Rect(DrawRect {
454            rect: Rect::new(rect.x, rect.bottom() - t, rect.w, t),
455            color,
456        }),
457        DrawCmd::Rect(DrawRect {
458            rect: Rect::new(rect.x, rect.y, t, rect.h),
459            color,
460        }),
461        DrawCmd::Rect(DrawRect {
462            rect: Rect::new(rect.right() - t, rect.y, t, rect.h),
463            color,
464        }),
465    ]
466}
467
468/// Handle to a detached loopback JSONL server and its UI-thread command queue.
469///
470/// Server/event and command channels are unbounded. The detached server thread
471/// polls at approximately 60 Hz, accepts at most eight clients, and terminates
472/// only when the process exits or the listener becomes permanently unusable.
473///
474/// # Examples
475///
476/// ```no_run
477/// use std::net::SocketAddr;
478/// use ailloli_ui_winit::devtools::DevToolsRemote;
479/// let addr: SocketAddr = "127.0.0.1:9229".parse().unwrap();
480/// let remote: Option<DevToolsRemote> = DevToolsRemote::start(addr);
481/// ```
482pub struct DevToolsRemote {
483    /// Snapshot events sent to the server thread for broadcast.
484    events: Sender<RemoteEvent>,
485    /// Commands accepted by the server and drained on the UI thread.
486    commands: Receiver<DevToolsClientMessage>,
487    /// Pending-count and late-bound wake coordination shared with the server.
488    command_wake: Arc<DevToolsCommandWake>,
489}
490
491/// Environment startup, explicit loopback startup, and channel drains.
492impl DevToolsRemote {
493    /// Starts the configured loopback remote, if the environment value is valid.
494    ///
495    /// `AILLOLI_UI_DEVTOOLS_REMOTE` wins over the legacy variable. Empty,
496    /// non-Unicode, malformed, non-loopback, unbindable, or nonblocking setup
497    /// failures return `None`.
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// let loader: fn() -> Option<ailloli_ui_winit::devtools::DevToolsRemote> =
503    ///     ailloli_ui_winit::devtools::DevToolsRemote::from_env;
504    /// let _ = loader;
505    /// ```
506    pub fn from_env() -> Option<Self> {
507        let addr =
508            crate::framework_env_var_os("AILLOLI_UI_DEVTOOLS_REMOTE", "OCTAVUI_DEVTOOLS_REMOTE")?;
509        let addr = addr.to_string_lossy().parse::<SocketAddr>().ok()?;
510        Self::start(addr)
511    }
512
513    /// Binds a nonblocking loopback TCP listener and detaches its server thread.
514    ///
515    /// Non-loopback addresses are refused even if locally bindable. Port zero is
516    /// accepted by the OS, but this handle does not expose the selected port.
517    /// Any bind or nonblocking-configuration failure returns `None`.
518    ///
519    /// # Examples
520    ///
521    /// ```no_run
522    /// use std::net::SocketAddr;
523    /// let address: SocketAddr = "127.0.0.1:9229".parse().unwrap();
524    /// let remote = ailloli_ui_winit::devtools::DevToolsRemote::start(address);
525    /// let _ = remote;
526    /// ```
527    pub fn start(addr: SocketAddr) -> Option<Self> {
528        if !addr.ip().is_loopback() {
529            eprintln!("ailloli_ui devtools remote refused non-loopback addr {addr}");
530            return None;
531        }
532        let listener = TcpListener::bind(addr).ok()?;
533        listener.set_nonblocking(true).ok()?;
534        let (events_tx, events_rx) = mpsc::channel();
535        let (commands_tx, commands_rx) = mpsc::channel();
536        let command_wake = Arc::new(DevToolsCommandWake::default());
537        let command_sender = DevToolsCommandSender {
538            commands: commands_tx,
539            wake: command_wake.clone(),
540        };
541        thread::spawn(move || run_remote_server(listener, events_rx, command_sender));
542        Some(Self {
543            events: events_tx,
544            commands: commands_rx,
545            command_wake,
546        })
547    }
548
549    /// Queues a complete debug snapshot for best-effort broadcast to all clients.
550    ///
551    /// The unbounded channel preserves order. If the detached server has ended,
552    /// the snapshot is silently dropped.
553    ///
554    /// # Examples
555    ///
556    /// ```no_run
557    /// fn publish(remote: &ailloli_ui_winit::devtools::DevToolsRemote,
558    ///     snapshot: ailloli_ui_devtools_core::DebugSnapshot) {
559    ///     remote.publish_snapshot(snapshot);
560    /// }
561    /// ```
562    pub fn publish_snapshot(&self, snapshot: DebugSnapshot) {
563        let _ = self.events.send(RemoteEvent::Snapshot(snapshot));
564    }
565
566    /// Drains every currently queued client command in FIFO order.
567    ///
568    /// Each drained command decrements the atomic pending count. Commands that
569    /// arrive concurrently after `try_recv` observes empty wait for later service.
570    ///
571    /// # Examples
572    ///
573    /// ```no_run
574    /// fn drain(remote: &ailloli_ui_winit::devtools::DevToolsRemote) {
575    ///     let commands: Vec<ailloli_ui_devtools_core::DevToolsClientMessage> =
576    ///         remote.drain_commands();
577    ///     let _ = commands;
578    /// }
579    /// ```
580    pub fn drain_commands(&self) -> Vec<DevToolsClientMessage> {
581        let mut out = Vec::new();
582        while let Ok(cmd) = self.commands.try_recv() {
583            self.command_wake.command_drained();
584            out.push(cmd);
585        }
586        out
587    }
588
589    /// Installs/replaces the host wake and immediately signals queued commands.
590    ///
591    /// # Errors
592    ///
593    /// Propagates [`UiWakeError`] when pending work requires an immediate wake
594    /// and the newly installed callback fails.
595    fn install_wake(&self, wake: Arc<dyn UiWake>) -> Result<(), UiWakeError> {
596        self.command_wake.install(wake)
597    }
598
599    /// Rearms wake coalescing and reports whether the atomic pending count is non-zero.
600    fn begin_host_service(&self) -> bool {
601        self.command_wake.begin_host_service()
602    }
603
604    /// Consumes the first latched wake error.
605    fn take_wake_error(&self) -> Option<UiWakeError> {
606        self.command_wake.take_error()
607    }
608}
609
610#[derive(Default)]
611/// Mutex-protected late-bound wake, coalescing latch, and first failure.
612struct DevToolsCommandWakeState {
613    /// Current native host wake target.
614    wake: Option<Arc<dyn UiWake>>,
615    /// Whether this service interval already received a successful wake request.
616    signaled: bool,
617    /// First wake failure retained until diagnostic drain.
618    error: Option<UiWakeError>,
619}
620
621#[derive(Default)]
622/// Cross-thread pending-command counter paired with mutex-protected wake state.
623struct DevToolsCommandWake {
624    /// Late-bound callback and coalescing/error slots.
625    state: Mutex<DevToolsCommandWakeState>,
626    /// Saturating-decremented count of successfully queued, undrained commands.
627    pending_commands: AtomicUsize,
628}
629
630/// Command reservation, drain accounting, wake coalescing, and error observation.
631impl DevToolsCommandWake {
632    /// Reserves one pending count before channel submission using release ordering.
633    ///
634    /// The atomic increment wraps at `usize::MAX`; reaching that value requires
635    /// an infeasible number of queued network commands.
636    fn reserve_command(&self) {
637        self.pending_commands.fetch_add(1, Ordering::Release);
638    }
639
640    /// Rolls back a reservation when command channel submission fails.
641    fn cancel_command(&self) {
642        self.command_drained();
643    }
644
645    /// Saturating-decrements the pending count for one drained/cancelled command.
646    fn command_drained(&self) {
647        let _ =
648            self.pending_commands
649                .fetch_update(Ordering::AcqRel, Ordering::Acquire, |pending| {
650                    Some(pending.saturating_sub(1))
651                });
652    }
653
654    /// Sends at most one wake per host-service interval.
655    ///
656    /// Missing late-bound wakes are successful no-ops and leave `signaled` false.
657    ///
658    /// # Errors
659    ///
660    /// Propagates [`UiWakeError`] from the installed callback after unlatching
661    /// and best-effort recording the first failure.
662    ///
663    /// # Panics
664    ///
665    /// Panics if the wake-state mutex is poisoned.
666    fn signal(&self) -> Result<(), UiWakeError> {
667        let wake = {
668            let mut state = self.state.lock().expect("devtools wake lock poisoned");
669            if state.signaled {
670                None
671            } else {
672                let wake = state.wake.clone();
673                state.signaled = wake.is_some();
674                wake
675            }
676        };
677        self.invoke(wake)
678    }
679
680    /// Replaces the wake and signals immediately when pending commands exist.
681    ///
682    /// # Errors
683    ///
684    /// Propagates [`UiWakeError`] when pending commands trigger the newly
685    /// installed callback and it fails.
686    ///
687    /// # Panics
688    ///
689    /// Panics if the wake-state mutex is poisoned.
690    fn install(&self, wake: Arc<dyn UiWake>) -> Result<(), UiWakeError> {
691        let wake = {
692            let mut state = self.state.lock().expect("devtools wake lock poisoned");
693            state.wake = Some(wake.clone());
694            state.signaled = self.pending_commands.load(Ordering::Acquire) > 0;
695            state.signaled.then_some(wake)
696        };
697        self.invoke(wake)
698    }
699
700    /// Clears the coalescing latch and returns whether work remains pending.
701    fn begin_host_service(&self) -> bool {
702        if let Ok(mut state) = self.state.lock() {
703            state.signaled = false;
704        }
705        self.pending_commands.load(Ordering::Acquire) > 0
706    }
707
708    /// Consumes the first stored wake error; poisoning returns `None`.
709    fn take_error(&self) -> Option<UiWakeError> {
710        self.state
711            .lock()
712            .ok()
713            .and_then(|mut state| state.error.take())
714    }
715
716    /// Calls the wake outside the mutex, unlatching and storing its first failure.
717    ///
718    /// # Errors
719    ///
720    /// Propagates the callback's [`UiWakeError`]. An absent wake is a successful
721    /// no-op; failure latching is best effort if the mutex is poisoned.
722    fn invoke(&self, wake: Option<Arc<dyn UiWake>>) -> Result<(), UiWakeError> {
723        let Some(wake) = wake else {
724            return Ok(());
725        };
726        if let Err(error) = wake.wake() {
727            if let Ok(mut state) = self.state.lock() {
728                state.signaled = false;
729                state.error.get_or_insert(error);
730            }
731            return Err(error);
732        }
733        Ok(())
734    }
735}
736
737/// Server-thread command sender paired with pending/wake accounting.
738struct DevToolsCommandSender {
739    /// Unbounded FIFO client-command channel.
740    commands: Sender<DevToolsClientMessage>,
741    /// Shared accounting and wake coordinator.
742    wake: Arc<DevToolsCommandWake>,
743}
744
745/// Atomic reserve-send-signal operation for accepted client commands.
746impl DevToolsCommandSender {
747    /// Queues a command or rolls back its pending count if the UI receiver closed.
748    fn send(&self, command: DevToolsClientMessage) {
749        self.wake.reserve_command();
750        if self.commands.send(command).is_err() {
751            self.wake.cancel_command();
752            return;
753        }
754        let _ = self.wake.signal();
755    }
756}
757
758/// UI-to-server events broadcast to all currently connected clients.
759enum RemoteEvent {
760    /// Complete inspected-tree snapshot.
761    Snapshot(DebugSnapshot),
762}
763
764/// One nonblocking TCP client and its incomplete JSONL input buffer.
765struct Client {
766    /// Connected loopback stream.
767    stream: TcpStream,
768    /// UTF-8-lossy decoded bytes received after the last newline.
769    read_buf: String,
770}
771
772/// Runs the detached accept/broadcast/read loop with a 16 ms polling interval.
773///
774/// At most eight clients are retained. New clients receive protocol version 1;
775/// write/read failures drop only that client. Snapshot broadcast preserves event
776/// order but slow nonblocking clients may be disconnected on `WouldBlock` writes.
777fn run_remote_server(
778    listener: TcpListener,
779    events: Receiver<RemoteEvent>,
780    commands: DevToolsCommandSender,
781) {
782    let mut clients = Vec::<Client>::new();
783    loop {
784        loop {
785            match listener.accept() {
786                Ok((mut stream, _)) if clients.len() < MAX_DEVTOOLS_CLIENTS => {
787                    let _ = stream.set_nonblocking(true);
788                    let hello = DevToolsServerMessage::Hello { protocol: 1 };
789                    let _ = write_jsonl(&mut stream, &hello);
790                    clients.push(Client {
791                        stream,
792                        read_buf: String::new(),
793                    });
794                }
795                Ok((_stream, _)) => {}
796                Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => break,
797                Err(_) => break,
798            }
799        }
800
801        while let Ok(event) = events.try_recv() {
802            match event {
803                RemoteEvent::Snapshot(snapshot) => {
804                    let message = DevToolsServerMessage::Snapshot { snapshot };
805                    clients.retain_mut(|client| write_jsonl(&mut client.stream, &message).is_ok());
806                }
807            }
808        }
809
810        clients.retain_mut(|client| read_client_commands(client, &commands));
811        thread::sleep(Duration::from_millis(16));
812    }
813}
814
815/// Serializes one server message, appends newline, and requires a complete write.
816///
817/// # Errors
818///
819/// Returns [`std::io::ErrorKind::InvalidData`] when JSON serialization fails, or
820/// propagates the socket's complete-write error.
821fn write_jsonl(stream: &mut TcpStream, message: &DevToolsServerMessage) -> std::io::Result<()> {
822    let mut line = serde_json::to_vec(message)
823        .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
824    line.push(b'\n');
825    stream.write_all(&line)
826}
827
828/// Drains one nonblocking client and returns whether it should stay connected.
829///
830/// Empty trimmed lines are ignored. Ping receives Pong without entering the UI
831/// queue; invalid JSON receives an Error and remains connected if the write
832/// succeeds. A line longer than 65,536 buffered UTF-8 bytes receives an Error
833/// and is disconnected. Invalid UTF-8 is lossily replaced before parsing.
834fn read_client_commands(client: &mut Client, commands: &DevToolsCommandSender) -> bool {
835    let mut buf = [0u8; 4096];
836    loop {
837        match client.stream.read(&mut buf) {
838            Ok(0) => return false,
839            Ok(n) => {
840                client
841                    .read_buf
842                    .push_str(&String::from_utf8_lossy(&buf[..n]));
843                if client.read_buf.len() > MAX_DEVTOOLS_MESSAGE_BYTES
844                    && !client.read_buf[..MAX_DEVTOOLS_MESSAGE_BYTES].contains('\n')
845                {
846                    let message = DevToolsServerMessage::Error {
847                        message: "devtools message exceeds the 65536-byte limit".to_string(),
848                    };
849                    let _ = write_jsonl(&mut client.stream, &message);
850                    return false;
851                }
852                while let Some(pos) = client.read_buf.find('\n') {
853                    if pos > MAX_DEVTOOLS_MESSAGE_BYTES {
854                        let message = DevToolsServerMessage::Error {
855                            message: "devtools message exceeds the 65536-byte limit".to_string(),
856                        };
857                        let _ = write_jsonl(&mut client.stream, &message);
858                        return false;
859                    }
860                    let line = client.read_buf[..pos].trim().to_string();
861                    client.read_buf = client.read_buf[pos + 1..].to_string();
862                    if line.is_empty() {
863                        continue;
864                    }
865                    match serde_json::from_str::<DevToolsClientMessage>(&line) {
866                        Ok(DevToolsClientMessage::Ping) => {
867                            if write_jsonl(&mut client.stream, &DevToolsServerMessage::Pong)
868                                .is_err()
869                            {
870                                return false;
871                            }
872                        }
873                        Ok(cmd) => {
874                            commands.send(cmd);
875                        }
876                        Err(err) => {
877                            let message = DevToolsServerMessage::Error {
878                                message: format!("invalid devtools message: {err}"),
879                            };
880                            if write_jsonl(&mut client.stream, &message).is_err() {
881                                return false;
882                            }
883                        }
884                    }
885                }
886            }
887            Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => return true,
888            Err(_) => return false,
889        }
890    }
891}
892
893#[cfg(test)]
894/// Remote protocol, size/security boundary, wake, overlay layout, and input scenarios.
895mod tests {
896    use super::*;
897    use std::io::{BufRead, BufReader};
898    use std::sync::atomic::AtomicUsize;
899
900    use ailloli_ui_core::event::keyboard::Modifiers;
901    use ailloli_ui_core::math::Scale;
902    use ailloli_ui_core::Point;
903    use ailloli_ui_devtools_ui::DEVTOOLS_MODE_BOTTOM_KEY;
904    use ailloli_ui_runtime::component::IntoView;
905    use ailloli_ui_runtime::scene::DrawCmd;
906    use ailloli_ui_widgets::layout::Container;
907    use ailloli_ui_widgets::text::Text;
908
909    #[derive(Default)]
910    /// Wake fixture counting successful callbacks.
911    struct CountingWake(AtomicUsize);
912
913    /// Relaxed counter implementation sufficient for single-test observation.
914    impl UiWake for CountingWake {
915        /// Increments and succeeds.
916        ///
917        /// # Errors
918        ///
919        /// This test wake is infallible and never returns an error.
920        fn wake(&self) -> Result<(), UiWakeError> {
921            self.0.fetch_add(1, Ordering::Relaxed);
922            Ok(())
923        }
924    }
925
926    /// Wake fixture that always reports a closed target.
927    struct FailingWake;
928
929    /// Deterministic failure implementation for retry/error diagnostics.
930    impl UiWake for FailingWake {
931        /// Returns `TargetClosed` without side effects.
932        ///
933        /// # Errors
934        ///
935        /// Always returns [`UiWakeError::TargetClosed`].
936        fn wake(&self) -> Result<(), UiWakeError> {
937            Err(UiWakeError::TargetClosed)
938        }
939    }
940
941    /// Creates an unbounded command channel paired with shared wake accounting.
942    fn command_channel() -> (
943        DevToolsCommandSender,
944        Receiver<DevToolsClientMessage>,
945        Arc<DevToolsCommandWake>,
946    ) {
947        let (commands, receiver) = mpsc::channel();
948        let wake = Arc::new(DevToolsCommandWake::default());
949        (
950            DevToolsCommandSender {
951                commands,
952                wake: wake.clone(),
953            },
954            receiver,
955            wake,
956        )
957    }
958
959    /// Builds and lays out a minimal inspected application tree.
960    fn app_runtime() -> (Runtime<()>, TextSystem) {
961        let mut runtime = Runtime::new(RuntimeHandle::new());
962        runtime.reconcile(
963            Container::new()
964                .fill()
965                .child(Text::new("application text"))
966                .into_view(),
967        );
968        let mut text_system = TextSystem::new();
969        runtime.layout(
970            Constraints::tight(800.0, 600.0),
971            Scale::new(1.0),
972            &mut text_system,
973        );
974        (runtime, text_system)
975    }
976
977    /// Counts text commands emitted across all scene layers.
978    fn text_cmd_count(scene: &Scene) -> usize {
979        scene
980            .layers
981            .iter()
982            .flat_map(|layer| layer.cmds.iter())
983            .filter(|cmd| matches!(cmd, DrawCmd::Text(_)))
984            .count()
985    }
986
987    /// Creates a primary left-button pointer event at a logical position.
988    fn pointer_button(pos: Point, pressed: bool) -> Event {
989        Event::Pointer(PointerEvent::Button {
990            pos,
991            button: MouseButton::Left,
992            pressed,
993            modifiers: Modifiers::default(),
994        })
995    }
996
997    /// Resolves a unique overlay key and returns the center of its absolute bounds.
998    fn center_of_key(state: &DevToolsWindowState, key: &str) -> Point {
999        let id = state
1000            .runtime
1001            .tree
1002            .resolve_element_by_view_key(key)
1003            .expect("keyed devtools element");
1004        let bounds = absolute_paint_bounds(&state.runtime.tree, id).expect("element bounds");
1005        Point::new(bounds.x + bounds.w / 2.0, bounds.y + bounds.h / 2.0)
1006    }
1007
1008    /// Creates a nonblocking loopback TCP pair and wraps the server side as a client.
1009    fn connected_client() -> (Client, TcpStream) {
1010        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
1011        let addr = listener.local_addr().expect("read listener addr");
1012        let client_stream = TcpStream::connect(addr).expect("connect client");
1013        let (server_stream, _) = listener.accept().expect("accept client");
1014        server_stream
1015            .set_nonblocking(true)
1016            .expect("server stream nonblocking");
1017        client_stream
1018            .set_read_timeout(Some(Duration::from_secs(1)))
1019            .expect("client read timeout");
1020        (
1021            Client {
1022                stream: server_stream,
1023                read_buf: String::new(),
1024            },
1025            client_stream,
1026        )
1027    }
1028
1029    #[test]
1030    fn remote_reader_accepts_select_command() {
1031        let (mut server_client, mut client_stream) = connected_client();
1032        let (commands_tx, commands_rx, command_wake) = command_channel();
1033        let wake = Arc::new(CountingWake::default());
1034        command_wake.install(wake.clone()).unwrap();
1035
1036        client_stream
1037            .write_all(br#"{"type":"select","id":42}"#)
1038            .expect("write command");
1039        client_stream.write_all(b"\n").expect("write newline");
1040
1041        assert!(read_client_commands(&mut server_client, &commands_tx));
1042        assert_eq!(
1043            commands_rx.try_recv().expect("command queued"),
1044            DevToolsClientMessage::Select { id: Some(42) }
1045        );
1046        assert_eq!(wake.0.load(Ordering::Relaxed), 1);
1047    }
1048
1049    #[test]
1050    fn remote_reader_replies_to_ping() {
1051        let (mut server_client, mut client_stream) = connected_client();
1052        let (commands_tx, commands_rx, _) = command_channel();
1053
1054        client_stream
1055            .write_all(br#"{"type":"ping"}"#)
1056            .expect("write ping");
1057        client_stream.write_all(b"\n").expect("write newline");
1058
1059        assert!(read_client_commands(&mut server_client, &commands_tx));
1060
1061        let mut line = String::new();
1062        let mut reader = BufReader::new(client_stream);
1063        reader.read_line(&mut line).expect("read pong");
1064        let message: DevToolsServerMessage = serde_json::from_str(line.trim()).expect("parse pong");
1065        assert_eq!(message, DevToolsServerMessage::Pong);
1066        assert!(commands_rx.try_recv().is_err());
1067    }
1068
1069    #[test]
1070    fn remote_reader_reports_unknown_message() {
1071        let (mut server_client, mut client_stream) = connected_client();
1072        let (commands_tx, commands_rx, _) = command_channel();
1073
1074        client_stream
1075            .write_all(br#"{"type":"unknown"}"#)
1076            .expect("write unknown command");
1077        client_stream.write_all(b"\n").expect("write newline");
1078
1079        assert!(read_client_commands(&mut server_client, &commands_tx));
1080
1081        let mut line = String::new();
1082        let mut reader = BufReader::new(client_stream);
1083        reader.read_line(&mut line).expect("read error");
1084        let message: DevToolsServerMessage =
1085            serde_json::from_str(line.trim()).expect("parse error");
1086        assert!(matches!(message, DevToolsServerMessage::Error { .. }));
1087        assert!(commands_rx.try_recv().is_err());
1088    }
1089
1090    #[test]
1091    fn remote_reader_disconnects_when_input_exceeds_limit() {
1092        let (mut server_client, mut client_stream) = connected_client();
1093        let (commands_tx, commands_rx, _) = command_channel();
1094        server_client.read_buf = "x".repeat(MAX_DEVTOOLS_MESSAGE_BYTES + 1);
1095        client_stream.write_all(b"x").expect("write trigger byte");
1096
1097        assert!(!read_client_commands(&mut server_client, &commands_tx));
1098        assert!(commands_rx.try_recv().is_err());
1099
1100        let mut line = String::new();
1101        let mut reader = BufReader::new(client_stream);
1102        reader.read_line(&mut line).expect("read size error");
1103        let message: DevToolsServerMessage =
1104            serde_json::from_str(line.trim()).expect("parse size error");
1105        assert!(matches!(message, DevToolsServerMessage::Error { .. }));
1106    }
1107
1108    #[test]
1109    fn remote_server_refuses_non_loopback_address() {
1110        let addr = "192.0.2.1:0"
1111            .parse()
1112            .expect("reserved documentation address");
1113        assert!(DevToolsRemote::start(addr).is_none());
1114    }
1115
1116    #[test]
1117    fn remote_command_queued_before_host_wake_is_late_bound_and_drained_once() {
1118        let (commands, receiver, command_wake) = command_channel();
1119        commands.send(DevToolsClientMessage::Select { id: Some(7) });
1120        assert_eq!(command_wake.pending_commands.load(Ordering::Acquire), 1);
1121
1122        let wake = Arc::new(CountingWake::default());
1123        command_wake.install(wake.clone()).unwrap();
1124        assert_eq!(wake.0.load(Ordering::Relaxed), 1);
1125        assert!(command_wake.begin_host_service());
1126
1127        let (events, _) = mpsc::channel();
1128        let remote = DevToolsRemote {
1129            events,
1130            commands: receiver,
1131            command_wake: command_wake.clone(),
1132        };
1133        assert_eq!(
1134            remote.drain_commands(),
1135            vec![DevToolsClientMessage::Select { id: Some(7) }]
1136        );
1137        assert!(!remote.begin_host_service());
1138        assert_eq!(command_wake.pending_commands.load(Ordering::Acquire), 0);
1139    }
1140
1141    #[test]
1142    fn failed_devtools_wake_is_diagnosable_and_replacement_retries_pending_work() {
1143        let (commands, _receiver, command_wake) = command_channel();
1144        commands.send(DevToolsClientMessage::Hover { id: Some(9) });
1145
1146        assert_eq!(
1147            command_wake.install(Arc::new(FailingWake)),
1148            Err(UiWakeError::TargetClosed)
1149        );
1150        assert_eq!(command_wake.take_error(), Some(UiWakeError::TargetClosed));
1151
1152        let wake = Arc::new(CountingWake::default());
1153        command_wake.install(wake.clone()).unwrap();
1154        assert_eq!(wake.0.load(Ordering::Relaxed), 1);
1155        assert!(command_wake.begin_host_service());
1156    }
1157
1158    #[test]
1159    fn devtools_scene_uses_shared_text_system_and_emits_text() {
1160        let (app, mut text_system) = app_runtime();
1161        let mut devtools = DevToolsWindowState::new();
1162        devtools.enabled = true;
1163
1164        let scene = devtools
1165            .build_scene(
1166                &app.tree,
1167                app.root.expect("app root"),
1168                Rect::new(0.0, 0.0, 800.0, 600.0),
1169                Scale::new(1.0),
1170                &mut text_system,
1171            )
1172            .expect("devtools scene");
1173
1174        assert!(
1175            text_cmd_count(&scene) > 0,
1176            "devtools scene should include text draw commands"
1177        );
1178        assert!(
1179            !text_system.face_blobs_snapshot().is_empty(),
1180            "shared text system should contain font blobs for renderer upload"
1181        );
1182    }
1183
1184    #[test]
1185    fn devtools_panel_click_changes_mode() {
1186        let (app, mut text_system) = app_runtime();
1187        let mut devtools = DevToolsWindowState::new();
1188        devtools.enabled = true;
1189        devtools
1190            .build_scene(
1191                &app.tree,
1192                app.root.expect("app root"),
1193                Rect::new(0.0, 0.0, 800.0, 600.0),
1194                Scale::new(1.0),
1195                &mut text_system,
1196            )
1197            .expect("devtools scene");
1198
1199        let pos = center_of_key(&devtools, DEVTOOLS_MODE_BOTTOM_KEY);
1200        assert!(devtools.handle_event(&pointer_button(pos, true)));
1201        assert!(devtools.handle_event(&pointer_button(pos, false)));
1202
1203        assert_eq!(devtools.mode, DevToolsMode::DockBottom);
1204    }
1205
1206    #[test]
1207    fn devtools_click_outside_panel_is_not_consumed() {
1208        let (app, mut text_system) = app_runtime();
1209        let mut devtools = DevToolsWindowState::new();
1210        devtools.enabled = true;
1211        devtools
1212            .build_scene(
1213                &app.tree,
1214                app.root.expect("app root"),
1215                Rect::new(0.0, 0.0, 800.0, 600.0),
1216                Scale::new(1.0),
1217                &mut text_system,
1218            )
1219            .expect("devtools scene");
1220
1221        assert!(!devtools.handle_event(&pointer_button(Point::new(10.0, 580.0), true)));
1222    }
1223}