Skip to main content

strat9_kernel/shell/
vga_input.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Lock-free mouse -> console command hand-off.
24//!
25//! The mouse task must never hold `VGA_WRITER`: it publishes the input work
26//! here and the console-render task (which already owns the writer) applies it.
27//! Single-producer/single-consumer ring: the mouse task pushes, the console
28//! task pops. No allocation, no locks.
29//!
30//! Press/release ordering is preserved: the mouse task's local button state
31//! machine emits `Press` before `Release` for a turn that observes both, and
32//! each turn is published as one unit (a single `tail` store) so the renderer
33//! never observes a half-written turn.
34
35use core::{
36    cell::UnsafeCell,
37    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
38};
39
40/// Ring slot count. One slot is reserved to distinguish full from empty, so
41/// the usable capacity is `INPUT_RING_CAPACITY - 1` (63) commands.
42pub const INPUT_RING_CAPACITY: usize = 64;
43const RING_MASK: usize = INPUT_RING_CAPACITY - 1;
44
45/// Maximum commands the mouse task can emit for one turn, including the
46/// trailing [`InputCommand::EndTurn`] marker.
47pub const MAX_TURN_COMMANDS: usize = 8;
48
49/// Minimum ticks between scrollbar-drag applies (was in `mouse.rs`).
50const SCROLLBAR_DRAG_MIN_TICKS: u64 = 1;
51/// Minimum ticks between mouse visual renders (was in `mouse.rs`).
52const MOUSE_RENDER_MIN_TICKS: u64 = 1;
53/// Text lines moved per mouse-wheel notch. The wheel is eased: the console
54/// tick applies one line per frame, so a notch settles over three frames.
55const LINES_PER_NOTCH: isize = 3;
56
57/// A deferred input action, applied by the console-render task.
58#[derive(Clone, Copy)]
59pub enum InputCommand {
60    /// Unused slot initializer (never enqueued by the producer).
61    Empty,
62    /// Inverted wheel: raw `dz` sign convention as before; the render step
63    /// multiplies by 3 lines exactly as the old mouse task did.
64    Wheel(i32),
65    /// Left button pressed at pixel `(x, y)`; the render step decides between
66    /// scrollbar click and text-selection start.
67    Press(i32, i32),
68    /// Pointer moved while the left button stayed held.
69    Held(i32, i32),
70    /// Left button released.
71    Release,
72    /// Pointer moved without a button transition.
73    Cursor(i32, i32),
74    /// End of one mouse turn; never applied.
75    EndTurn,
76}
77
78struct Ring {
79    slots: UnsafeCell<[InputCommand; INPUT_RING_CAPACITY]>,
80    head: AtomicUsize,
81    tail: AtomicUsize,
82}
83
84// SAFETY: single producer (mouse task) writes slots and `tail`, single
85// consumer (console task) writes `head`; atomics order the publication and no
86// slot is written and read at the same time.
87unsafe impl Sync for Ring {}
88
89impl Ring {
90    const fn new() -> Self {
91        Self {
92            slots: UnsafeCell::new([InputCommand::Empty; INPUT_RING_CAPACITY]),
93            head: AtomicUsize::new(0),
94            tail: AtomicUsize::new(0),
95        }
96    }
97
98    fn free_slots(&self) -> usize {
99        let head = self.head.load(Ordering::Acquire);
100        let tail = self.tail.load(Ordering::Relaxed);
101        let used = tail.wrapping_add(INPUT_RING_CAPACITY).wrapping_sub(head) & RING_MASK;
102        RING_MASK - used
103    }
104
105    /// Publish one whole turn atomically. Returns `false` when it does not fit.
106    fn push_turn(&self, cmds: &[InputCommand]) -> bool {
107        if cmds.len() > self.free_slots() {
108            return false;
109        }
110        let mut tail = self.tail.load(Ordering::Relaxed);
111        for &cmd in cmds {
112            // SAFETY: `tail` is producer-owned until the single `tail` store
113            // below publishes the whole turn.
114            unsafe {
115                (*self.slots.get())[tail] = cmd;
116            }
117            tail = (tail + 1) & RING_MASK;
118        }
119        self.tail.store(tail, Ordering::Release);
120        true
121    }
122
123    fn pop(&self) -> Option<InputCommand> {
124        let head = self.head.load(Ordering::Relaxed);
125        if head == self.tail.load(Ordering::Acquire) {
126            return None;
127        }
128        // SAFETY: the producer has published this slot via `tail`; it cannot
129        // touch it again until `head` advances below.
130        let cmd = unsafe { (*self.slots.get())[head] };
131        self.head.store((head + 1) & RING_MASK, Ordering::Release);
132        Some(cmd)
133    }
134}
135
136static RING: Ring = Ring::new();
137static INPUT_PENDING: AtomicBool = AtomicBool::new(false);
138
139/// Publish one turn (the slice must end with [`InputCommand::EndTurn`]).
140/// Returns `false` when the ring cannot hold the whole turn.
141pub fn push_turn(cmds: &[InputCommand]) -> bool {
142    RING.push_turn(cmds)
143}
144
145/// Whether a full turn can be enqueued without dropping any command.
146pub fn has_space(n: usize) -> bool {
147    RING.free_slots() >= n
148}
149
150/// Publish that input work is ready; consumed by [`take_pending`].
151pub fn wake() {
152    INPUT_PENDING.store(true, Ordering::Release);
153}
154
155/// Take and clear the pending flag.
156pub fn take_pending() -> bool {
157    INPUT_PENDING.swap(false, Ordering::AcqRel)
158}
159
160/// Drop every queued command (used when the console is unavailable).
161pub fn discard() {
162    while RING.pop().is_some() {}
163    INPUT_PENDING.store(false, Ordering::Release);
164}
165
166/// Renderer-owned state carried across ticks; identical to the state the mouse
167/// task used to keep locally.
168pub struct InputState {
169    selecting: bool,
170    scrollbar_dragging: bool,
171    last_scrollbar_drag_tick: u64,
172    last_mouse_render_tick: u64,
173    pending_scrollbar_drag_y: Option<usize>,
174    pending_selection_pos: Option<(usize, usize)>,
175    pending_mouse_cursor: Option<(i32, i32)>,
176    pending_scroll_delta: i32,
177}
178
179impl InputState {
180    pub const fn new() -> Self {
181        Self {
182            selecting: false,
183            scrollbar_dragging: false,
184            last_scrollbar_drag_tick: 0,
185            last_mouse_render_tick: 0,
186            pending_scrollbar_drag_y: None,
187            pending_selection_pos: None,
188            pending_mouse_cursor: None,
189            pending_scroll_delta: 0,
190        }
191    }
192}
193
194/// Drain complete turns and apply each to `writer` with the exact call
195/// sequence/order of the old in-lock mouse loop. Returns whether anything was
196/// applied (commands consumed or a pending visual rendered).
197pub fn apply_input(
198    writer: &mut crate::arch::x86_64::vga::VgaWriter,
199    state: &mut InputState,
200) -> bool {
201    let ticks = crate::process::scheduler::ticks();
202    let mut applied = false;
203
204    loop {
205        let mut cmds = [InputCommand::Empty; MAX_TURN_COMMANDS];
206        let mut n = 0;
207        let mut complete = false;
208        while n < MAX_TURN_COMMANDS {
209            let Some(cmd) = RING.pop() else {
210                break;
211            };
212            if let InputCommand::EndTurn = cmd {
213                complete = true;
214                break;
215            }
216            cmds[n] = cmd;
217            n += 1;
218        }
219        if n == 0 && !complete {
220            break;
221        }
222        applied |= apply_turn(&cmds[..n], writer, state, ticks);
223        if !complete {
224            break;
225        }
226    }
227
228    // A visual update deferred by the tick gate (e.g. a drag throttled from the
229    // previous turn) must still land on this tick even without new events.
230    applied |= render_pending(writer, state, ticks, false, false);
231
232    applied
233}
234
235/// Apply the commands of one mouse turn, preserving the original batching.
236fn apply_turn(
237    cmds: &[InputCommand],
238    writer: &mut crate::arch::x86_64::vga::VgaWriter,
239    state: &mut InputState,
240    ticks: u64,
241) -> bool {
242    let mut wheel_delta: i32 = 0;
243    let mut press: Option<(i32, i32)> = None;
244    let mut held: Option<(i32, i32)> = None;
245    let mut released = false;
246    let mut cursor: Option<(i32, i32)> = None;
247
248    for &cmd in cmds {
249        match cmd {
250            InputCommand::Wheel(dz) => wheel_delta += dz,
251            InputCommand::Press(x, y) => press = Some((x, y)),
252            InputCommand::Held(x, y) => held = Some((x, y)),
253            InputCommand::Release => released = true,
254            InputCommand::Cursor(x, y) => cursor = Some((x, y)),
255            InputCommand::Empty | InputCommand::EndTurn => {}
256        }
257    }
258
259    state.pending_scroll_delta += wheel_delta;
260
261    if let Some((x, y)) = press {
262        let (mx, my) = (x as usize, y as usize);
263        if writer.scrollbar_hit_test(mx, my) {
264            writer.scrollbar_click(mx, my);
265            writer.clear_selection();
266            state.selecting = false;
267            state.scrollbar_dragging = true;
268            state.pending_scrollbar_drag_y = None;
269        } else {
270            writer.start_selection(mx, my);
271            state.selecting = true;
272            state.scrollbar_dragging = false;
273            state.pending_selection_pos = None;
274        }
275        state.last_mouse_render_tick = ticks;
276    } else if let Some((x, y)) = held {
277        if state.scrollbar_dragging {
278            state.pending_scrollbar_drag_y = Some(y as usize);
279        } else if state.selecting {
280            state.pending_selection_pos = Some((x as usize, y as usize));
281        }
282    }
283    // A press and release may both occur in this bounded batch: complete the
284    // release even if a press was also observed.
285    if released {
286        if state.selecting {
287            writer.end_selection();
288            state.selecting = false;
289            state.pending_selection_pos = None;
290        }
291        if state.scrollbar_dragging {
292            if let Some(py) = state.pending_scrollbar_drag_y.take() {
293                writer.scrollbar_drag_to(py);
294            }
295        }
296        state.scrollbar_dragging = false;
297        state.last_mouse_render_tick = ticks;
298    }
299
300    if let Some((cx, cy)) = cursor {
301        state.pending_mouse_cursor = Some((cx, cy));
302    }
303
304    let rendered = render_pending(writer, state, ticks, press.is_some(), released);
305    !cmds.is_empty() || rendered
306}
307
308fn has_pending_visual(state: &InputState) -> bool {
309    state.pending_scroll_delta != 0
310        || state.pending_scrollbar_drag_y.is_some()
311        || state.pending_selection_pos.is_some()
312        || state.pending_mouse_cursor.is_some()
313}
314
315/// Apply the pending visual updates under the original tick gates.
316fn render_pending(
317    writer: &mut crate::arch::x86_64::vga::VgaWriter,
318    state: &mut InputState,
319    ticks: u64,
320    pressed: bool,
321    released: bool,
322) -> bool {
323    if !has_pending_visual(state) {
324        return false;
325    }
326    let render_due = ticks.saturating_sub(state.last_mouse_render_tick) >= MOUSE_RENDER_MIN_TICKS;
327    let drag_due = ticks.saturating_sub(state.last_scrollbar_drag_tick) >= SCROLLBAR_DRAG_MIN_TICKS;
328    if !(render_due || pressed || released) {
329        return false;
330    }
331
332    let mut rendered = false;
333
334    // Inverted wheel: wheel up (dz>0) -> scroll down (history forward).
335    // `request_scroll_delta` takes positive as history-back (offset grows), so
336    // the raw wheel sign is negated here.
337    if state.pending_scroll_delta != 0 {
338        let lines = (state.pending_scroll_delta as isize).saturating_mul(LINES_PER_NOTCH);
339        writer.request_scroll_delta(lines.saturating_neg());
340        state.pending_scroll_delta = 0;
341        rendered = true;
342    }
343
344    if drag_due {
345        if state.selecting {
346            if let Some((sx, sy)) = state.pending_selection_pos.take() {
347                writer.update_selection(sx, sy);
348                rendered = true;
349            }
350        }
351        if state.scrollbar_dragging {
352            if let Some(py) = state.pending_scrollbar_drag_y.take() {
353                writer.scrollbar_drag_to(py);
354                state.last_scrollbar_drag_tick = ticks;
355                rendered = true;
356            }
357        }
358    }
359
360    if let Some((cx, cy)) = state.pending_mouse_cursor.take() {
361        writer.update_mouse_cursor(cx, cy);
362        rendered = true;
363    }
364
365    if rendered {
366        state.last_mouse_render_tick = ticks;
367    }
368    rendered
369}