File size: 8,127 Bytes
dcbeeb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use core::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use spin::Mutex;
use x86_64::instructions::port::Port;

#[derive(Debug, Clone, Copy)]
pub struct MouseState {
    pub x: i32,
    pub y: i32,
    pub scroll_delta: i32,
    pub left_button: bool,
    pub right_button: bool,
    pub middle_button: bool,
    pub left_clicked: bool,
    pub right_clicked: bool,
}

pub static MOUSE: Mutex<MouseState> = Mutex::new(MouseState {
    x: 400,
    y: 300,
    scroll_delta: 0,
    left_button: false,
    right_button: false,
    middle_button: false,
    left_clicked: false,
    right_clicked: false,
});

pub static HAS_SCROLL_WHEEL: AtomicBool = AtomicBool::new(false);
static mut PACKET_CYCLE: u8 = 0;
static mut PACKET_BYTES: [u8; 4] = [0; 4];
static mut LAST_LEFT: bool = false;
static mut LAST_RIGHT: bool = false;

pub static SCREEN_WIDTH: AtomicI32 = AtomicI32::new(800);
pub static SCREEN_HEIGHT: AtomicI32 = AtomicI32::new(600);

pub fn set_screen_bounds(width: i32, height: i32) {
    SCREEN_WIDTH.store(width, Ordering::Relaxed);
    SCREEN_HEIGHT.store(height, Ordering::Relaxed);
}

fn mouse_wait_input() {
    let mut status_port = Port::<u8>::new(0x64);
    for _ in 0..100_000 {
        if unsafe { status_port.read() } & 0x02 == 0 {
            return;
        }
    }
}

fn mouse_wait_output() {
    let mut status_port = Port::<u8>::new(0x64);
    for _ in 0..100_000 {
        if unsafe { status_port.read() } & 0x01 == 1 {
            return;
        }
    }
}

fn mouse_write(byte: u8) {
    let mut cmd_port = Port::<u8>::new(0x64);
    let mut data_port = Port::<u8>::new(0x60);
    mouse_wait_input();
    unsafe { cmd_port.write(0xD4) };
    mouse_wait_input();
    unsafe { data_port.write(byte) };
}

fn mouse_read() -> u8 {
    let mut data_port = Port::<u8>::new(0x60);
    mouse_wait_output();
    unsafe { data_port.read() }
}

pub fn init(width: i32, height: i32) {
    set_screen_bounds(width, height);

    let mut cmd_port = Port::<u8>::new(0x64);
    let mut data_port = Port::<u8>::new(0x60);

    // Flush any pending data from output buffer
    for _ in 0..100 {
        if (unsafe { cmd_port.read() } & 0x01) != 0 {
            let _ = unsafe { data_port.read() };
        } else {
            break;
        }
    }

    // Enable first PS/2 port (keyboard) and auxiliary device (mouse)
    mouse_wait_input();
    unsafe { cmd_port.write(0xAE) };
    mouse_wait_input();
    unsafe { cmd_port.write(0xA8) };

    // Read controller configuration byte
    mouse_wait_input();
    unsafe { cmd_port.write(0x20) };
    mouse_wait_output();
    let mut status = unsafe { data_port.read() };

    // Enable interrupts (bit 0 = keyboard, bit 1 = mouse)
    // Clear clock disable (bit 4 = keyboard, bit 5 = mouse)
    status |= 0x03;
    status &= !(0x30);

    // Write updated configuration byte
    mouse_wait_input();
    unsafe { cmd_port.write(0x60) };
    mouse_wait_input();
    unsafe { data_port.write(status) };

    // Reset mouse to default settings
    mouse_write(0xF6);
    let _ = mouse_read(); // ACK

    // Magic IntelliMouse sequence to enable scroll wheel (sample rates 200 -> 100 -> 80)
    mouse_write(0xF3);
    let _ = mouse_read();
    mouse_write(200);
    let _ = mouse_read();

    mouse_write(0xF3);
    let _ = mouse_read();
    mouse_write(100);
    let _ = mouse_read();

    mouse_write(0xF3);
    let _ = mouse_read();
    mouse_write(80);
    let _ = mouse_read();

    // Check device ID
    mouse_write(0xF2);
    let _ = mouse_read(); // ACK
    let dev_id = mouse_read();
    let has_wheel = dev_id == 3 || dev_id == 4;
    HAS_SCROLL_WHEEL.store(has_wheel, Ordering::SeqCst);
    crate::println!("[+] PS/2 Mouse initialized (Device ID: 0x{:02X}, Scroll Wheel: {})", dev_id, has_wheel);

    // Set sample rate to 200 Hz for high responsiveness
    mouse_write(0xF3);
    let _ = mouse_read();
    mouse_write(200);
    let _ = mouse_read();

    // Set resolution to 8 counts/mm
    mouse_write(0xE8);
    let _ = mouse_read();
    mouse_write(3);
    let _ = mouse_read();

    // Enable data reporting
    mouse_write(0xF4);
    let _ = mouse_read(); // ACK

    let mut state = MOUSE.lock();
    state.x = width / 2;
    state.y = height / 2;
    state.scroll_delta = 0;
}

pub fn handle_packet_byte(byte: u8) {
    unsafe {
        let has_wheel = HAS_SCROLL_WHEEL.load(Ordering::Relaxed);
        match PACKET_CYCLE {
            0 => {
                // Bit 3 must be 1 for a valid PS/2 mouse first packet byte
                if (byte & 0x08) != 0 {
                    PACKET_BYTES[0] = byte;
                    PACKET_CYCLE = 1;
                }
            }
            1 => {
                PACKET_BYTES[1] = byte;
                PACKET_CYCLE = 2;
            }
            2 => {
                PACKET_BYTES[2] = byte;
                if has_wheel {
                    PACKET_CYCLE = 3;
                } else {
                    PACKET_CYCLE = 0;
                    process_packet(PACKET_BYTES[0], PACKET_BYTES[1], PACKET_BYTES[2], 0);
                }
            }
            3 => {
                PACKET_BYTES[3] = byte;
                PACKET_CYCLE = 0;
                process_packet(PACKET_BYTES[0], PACKET_BYTES[1], PACKET_BYTES[2], PACKET_BYTES[3]);
            }
            _ => {
                PACKET_CYCLE = 0;
            }
        }
    }
}

fn process_packet(b0: u8, b1: u8, b2: u8, b3: u8) {
    unsafe {
        // Check for overflow bits
        if (b0 & 0xC0) != 0 {
            return;
        }

        let mut rel_x = b1 as i16;
        let mut rel_y = b2 as i16;

        // Sign extension
        if (b0 & 0x10) != 0 {
            rel_x |= 0xFF00u16 as i16;
        }
        if (b0 & 0x20) != 0 {
            rel_y |= 0xFF00u16 as i16;
        }

        // In PS/2, positive Y is UP, but in screen coordinates positive Y is DOWN
        rel_y = -rel_y;

        let left = (b0 & 0x01) != 0;
        let right = (b0 & 0x02) != 0;
        let middle = (b0 & 0x04) != 0;

        let left_click = left && !LAST_LEFT;
        let right_click = right && !LAST_RIGHT;

        LAST_LEFT = left;
        LAST_RIGHT = right;

        let max_w = SCREEN_WIDTH.load(Ordering::Relaxed);
        let max_h = SCREEN_HEIGHT.load(Ordering::Relaxed);

        // Smooth, Precise & Comfortable Mouse Speed:
        // 1x base speed for pixel-accurate desktop control, with gentle 2x acceleration on fast swipes
        let abs_x = rel_x.abs() as i32;
        let abs_y = rel_y.abs() as i32;
        let mult_x = if abs_x > 10 { 2 } else { 1 };
        let mult_y = if abs_y > 10 { 2 } else { 1 };

        let delta_x = (rel_x as i32) * mult_x;
        let delta_y = (rel_y as i32) * mult_y;

        // Microsoft PS/2 IntelliMouse 4-byte packet scroll wheel decoding:
        // Byte 3 bits 0..3 are 4-bit 2's complement value:
        //   0x01..0x07 = +1..+7 (Scroll UP)
        //   0x08..0x0F = -8..-1 (Scroll DOWN, e.g. 0x0F is -1)
        let low_nibble = b3 & 0x0F;
        let scroll = if low_nibble != 0 {
            if (low_nibble & 0x08) != 0 {
                (low_nibble as i32) - 16 // Sign-extend 4-bit negative: 15 - 16 = -1 (DOWN)
            } else {
                low_nibble as i32 // Positive: +1 (UP)
            }
        } else {
            0
        };

        let mut state = MOUSE.lock();
        state.x = (state.x + delta_x).clamp(0, max_w - 1);
        state.y = (state.y + delta_y).clamp(0, max_h - 1);
        state.scroll_delta += scroll;
        state.left_button = left;
        state.right_button = right;
        state.middle_button = middle;
        if left_click {
            state.left_clicked = true;
        }
        if right_click {
            state.right_clicked = true;
        }
    }
}

pub fn get_mouse_state() -> MouseState {
    x86_64::instructions::interrupts::without_interrupts(|| {
        let mut state = MOUSE.lock();
        let current = *state;
        // Clear edge-triggered click & scroll flags on read
        state.left_clicked = false;
        state.right_clicked = false;
        state.scroll_delta = 0;
        current
    })
}