├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── Changelog.md ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── rust-toolchain └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - "master" 7 | - "develop" 8 | tags: 9 | - "*" 10 | schedule: 11 | - cron: "40 4 * * *" # every day at 4:40 12 | pull_request: 13 | 14 | jobs: 15 | test: 16 | name: "Test" 17 | 18 | strategy: 19 | matrix: 20 | os: [ubuntu-latest, macos-latest, windows-latest] 21 | 22 | runs-on: ${{ matrix.os }} 23 | timeout-minutes: 15 24 | 25 | steps: 26 | - name: "Checkout Repository" 27 | uses: actions/checkout@v1 28 | 29 | - name: Install Rustup 30 | run: | 31 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain nightly 32 | echo "$HOME/.cargo/bin" >> $GITHUB_PATH 33 | if: runner.os == 'macOS' 34 | 35 | - name: "Print Rust Version" 36 | run: | 37 | rustc -Vv 38 | cargo -Vv 39 | 40 | - name: "Run cargo build" 41 | run: cargo build 42 | 43 | - name: "Run cargo test" 44 | run: cargo test 45 | 46 | check_formatting: 47 | name: "Check Formatting" 48 | runs-on: ubuntu-latest 49 | timeout-minutes: 2 50 | steps: 51 | - uses: actions/checkout@v1 52 | - run: rustup toolchain install nightly --profile minimal --component rustfmt 53 | - run: cargo +nightly fmt -- --check 54 | 55 | clippy: 56 | name: "Clippy" 57 | runs-on: ubuntu-latest 58 | timeout-minutes: 10 59 | steps: 60 | - uses: actions/checkout@v1 61 | - run: rustup toolchain install nightly --profile minimal --component clippy 62 | - run: cargo +nightly clippy -- -D warnings 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ps2-mouse" 3 | version = "0.1.4" 4 | authors = ["Ryan Kennedy "] 5 | edition = "2018" 6 | description = "This crate provides basic access to a ps2 mouse in x86 environments." 7 | documentation = "https://docs.rs/ps2-mouse" 8 | keywords = [ 9 | "x86_64", 10 | "no_std", 11 | ] 12 | categories = [ 13 | "no-std", 14 | ] 15 | license = "MIT/Apache-2.0" 16 | readme = "README.md" 17 | repository = "https://github.com/rust-osdev/ps2-mouse" 18 | 19 | [dependencies] 20 | bitflags = "1.2.1" 21 | x86_64 = "0.14.2" 22 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | # 0.1.3 2 | 3 | - Updated `x86_64` to `0.12.2` 4 | 5 | # 0.1.2 6 | 7 | - Updated `x86_64` to fix deprecated `asm!` macro. 8 | 9 | # 0.1.1 10 | 11 | - `Mouse::new()` is now a const fn. 12 | - `MouseState::new()` is now a const fn. 13 | - Added `MouseState::get_x()` and `MouseState::get_y()`. 14 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Philipp Oppermann 4 | Copyright (c) 2015 Gerd Zellweger 5 | Copyright (c) 2015 The libcpu Developers 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in 15 | all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/rust-osdev/ps2-mouse/workflows/Build/badge.svg)](https://github.com/rust-osdev/ps2-mouse/actions?query=workflow%3ABuild) [![Docs.rs Badge](https://docs.rs/ps2-mouse/badge.svg)](https://docs.rs/ps2-mouse/) 2 | 3 | # ps2 mouse 4 | This crate provides a basic interface for interacting with a ps2 mouse. 5 | 6 | ## Basic Example 7 | ```rust 8 | use ps2_mouse::{Mouse, MouseState}; 9 | use spinning_top::Spinlock; 10 | use x86_64::instructions::port::PortReadOnly; 11 | 12 | pub static MOUSE: Lazy> = Lazy::new(|| Spinlock::new(Mouse::new())); 13 | 14 | // Initialize the mouse and set the on complete event. 15 | fn init_mouse() { 16 | MOUSE.lock().init().unwrap(); 17 | MOUSE.lock().set_on_complete(on_complete); 18 | } 19 | 20 | // This will be fired when a packet is finished being processed. 21 | fn on_complete(mouse_state: MouseState) { 22 | println!("{:?}", mouse_state); 23 | } 24 | 25 | // An example interrupt based on https://os.phil-opp.com/hardware-interrupts/. The ps2 mouse is configured to fire 26 | // interrupts at PIC offset 12. 27 | extern "x86-interrupt" fn mouse_interrupt_handler(_stack_frame: &mut InterruptStackFrame) { 28 | let mut port = PortReadOnly::new(0x60); 29 | let packet = unsafe { port.read() }; 30 | MOUSE.lock().process_packet(packet); 31 | 32 | unsafe { 33 | PICS.lock() 34 | .notify_end_of_interrupt(InterruptIndex::Mouse.into()); 35 | } 36 | } 37 | ``` 38 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly 2 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate provides basic access to a ps2 mouse in x86 environments. 2 | 3 | #![no_std] 4 | #![warn(missing_docs)] 5 | #![feature(const_fn_fn_ptr_basics)] 6 | 7 | use bitflags::bitflags; 8 | use x86_64::instructions::port::Port; 9 | 10 | const ADDRESS_PORT_ADDRESS: u16 = 0x64; 11 | const DATA_PORT_ADDRESS: u16 = 0x60; 12 | const GET_STATUS_BYTE: u8 = 0x20; 13 | const SET_STATUS_BYTE: u8 = 0x60; 14 | 15 | bitflags! { 16 | /// Represents the flags currently set for the mouse. 17 | #[derive(Default)] 18 | pub struct MouseFlags: u8 { 19 | /// Whether or not the left mouse button is pressed. 20 | const LEFT_BUTTON = 0b0000_0001; 21 | 22 | /// Whether or not the right mouse button is pressed. 23 | const RIGHT_BUTTON = 0b0000_0010; 24 | 25 | /// Whether or not the middle mouse button is pressed. 26 | const MIDDLE_BUTTON = 0b0000_0100; 27 | 28 | /// Whether or not the packet is valid or not. 29 | const ALWAYS_ONE = 0b0000_1000; 30 | 31 | /// Whether or not the x delta is negative. 32 | const X_SIGN = 0b0001_0000; 33 | 34 | /// Whether or not the y delta is negative. 35 | const Y_SIGN = 0b0010_0000; 36 | 37 | /// Whether or not the x delta overflowed. 38 | const X_OVERFLOW = 0b0100_0000; 39 | 40 | /// Whether or not the y delta overflowed. 41 | const Y_OVERFLOW = 0b1000_0000; 42 | } 43 | } 44 | 45 | #[repr(u8)] 46 | enum Command { 47 | EnablePacketStreaming = 0xF4, 48 | SetDefaults = 0xF6, 49 | } 50 | 51 | /// A basic interface to interact with a PS2 mouse. 52 | #[derive(Debug)] 53 | pub struct Mouse { 54 | command_port: Port, 55 | data_port: Port, 56 | current_packet: u8, 57 | current_state: MouseState, 58 | completed_state: MouseState, 59 | on_complete: Option, 60 | } 61 | 62 | impl Default for Mouse { 63 | fn default() -> Mouse { 64 | Mouse::new() 65 | } 66 | } 67 | 68 | /// A snapshot of the mouse flags, x delta and y delta. 69 | #[derive(Debug, Copy, Clone, Default)] 70 | pub struct MouseState { 71 | flags: MouseFlags, 72 | x: i16, 73 | y: i16, 74 | } 75 | 76 | impl MouseState { 77 | /// Returns a new `MouseState`. 78 | pub const fn new() -> MouseState { 79 | MouseState { 80 | flags: MouseFlags::empty(), 81 | x: 0, 82 | y: 0, 83 | } 84 | } 85 | 86 | /// Returns true if the left mouse button is currently down. 87 | pub fn left_button_down(&self) -> bool { 88 | self.flags.contains(MouseFlags::LEFT_BUTTON) 89 | } 90 | 91 | /// Returns true if the left mouse button is currently up. 92 | pub fn left_button_up(&self) -> bool { 93 | !self.flags.contains(MouseFlags::LEFT_BUTTON) 94 | } 95 | 96 | /// Returns true if the right mouse button is currently down. 97 | pub fn right_button_down(&self) -> bool { 98 | self.flags.contains(MouseFlags::RIGHT_BUTTON) 99 | } 100 | 101 | /// Returns true if the right mouse button is currently up. 102 | pub fn right_button_up(&self) -> bool { 103 | !self.flags.contains(MouseFlags::RIGHT_BUTTON) 104 | } 105 | 106 | /// Returns true if the x axis has moved. 107 | pub fn x_moved(&self) -> bool { 108 | self.x != 0 109 | } 110 | 111 | /// Returns true if the y axis has moved. 112 | pub fn y_moved(&self) -> bool { 113 | self.y != 0 114 | } 115 | 116 | /// Returns true if the x or y axis has moved. 117 | pub fn moved(&self) -> bool { 118 | self.x_moved() || self.y_moved() 119 | } 120 | 121 | /// Returns the x delta of the mouse state. 122 | pub fn get_x(&self) -> i16 { 123 | self.x 124 | } 125 | 126 | /// Returns the y delta of the mouse state. 127 | pub fn get_y(&self) -> i16 { 128 | self.y 129 | } 130 | } 131 | 132 | impl Mouse { 133 | /// Creates a new `Mouse`. 134 | pub const fn new() -> Mouse { 135 | Mouse { 136 | command_port: Port::new(ADDRESS_PORT_ADDRESS), 137 | data_port: Port::new(DATA_PORT_ADDRESS), 138 | current_packet: 0, 139 | current_state: MouseState::new(), 140 | completed_state: MouseState::new(), 141 | on_complete: None, 142 | } 143 | } 144 | 145 | /// Returns the last completed state of the mouse. 146 | pub fn get_state(&self) -> MouseState { 147 | self.completed_state 148 | } 149 | 150 | /// Attempts to initialize a `Mouse`. If successful, interrupts will be generated 151 | /// as `PIC offset + 12`. 152 | pub fn init(&mut self) -> Result<(), &'static str> { 153 | self.write_command_port(GET_STATUS_BYTE)?; 154 | let status = self.read_data_port()? | 0x02; 155 | self.write_command_port(SET_STATUS_BYTE)?; 156 | self.write_data_port(status & 0xDF)?; 157 | self.send_command(Command::SetDefaults)?; 158 | self.send_command(Command::EnablePacketStreaming)?; 159 | Ok(()) 160 | } 161 | 162 | /// Attempts to process a packet. 163 | pub fn process_packet(&mut self, packet: u8) { 164 | match self.current_packet { 165 | 0 => { 166 | let flags = MouseFlags::from_bits_truncate(packet); 167 | if !flags.contains(MouseFlags::ALWAYS_ONE) { 168 | return; 169 | } 170 | self.current_state.flags = flags; 171 | } 172 | 1 => self.process_x_movement(packet), 173 | 2 => { 174 | self.process_y_movement(packet); 175 | self.completed_state = self.current_state; 176 | if let Some(on_complete) = self.on_complete { 177 | on_complete(self.completed_state); 178 | } 179 | } 180 | _ => unreachable!(), 181 | } 182 | self.current_packet = (self.current_packet + 1) % 3; 183 | } 184 | 185 | /// Sets the `on_complete` function to be called when a packet is completed. 186 | pub fn set_on_complete(&mut self, handler: fn(MouseState)) { 187 | self.on_complete = Some(handler); 188 | } 189 | 190 | fn process_x_movement(&mut self, packet: u8) { 191 | if !self.current_state.flags.contains(MouseFlags::X_OVERFLOW) { 192 | self.current_state.x = if self.current_state.flags.contains(MouseFlags::X_SIGN) { 193 | self.sign_extend(packet) 194 | } else { 195 | packet as i16 196 | }; 197 | } 198 | } 199 | 200 | fn process_y_movement(&mut self, packet: u8) { 201 | if !self.current_state.flags.contains(MouseFlags::Y_OVERFLOW) { 202 | self.current_state.y = if self.current_state.flags.contains(MouseFlags::Y_SIGN) { 203 | self.sign_extend(packet) 204 | } else { 205 | packet as i16 206 | }; 207 | } 208 | } 209 | 210 | fn read_data_port(&mut self) -> Result { 211 | self.wait_for_read()?; 212 | Ok(unsafe { self.data_port.read() }) 213 | } 214 | 215 | fn send_command(&mut self, command: Command) -> Result<(), &'static str> { 216 | self.write_command_port(0xD4)?; 217 | self.write_data_port(command as u8)?; 218 | if self.read_data_port()? != 0xFA { 219 | return Err("mouse did not respond to the command"); 220 | } 221 | Ok(()) 222 | } 223 | 224 | fn sign_extend(&self, packet: u8) -> i16 { 225 | ((packet as u16) | 0xFF00) as i16 226 | } 227 | 228 | fn write_command_port(&mut self, value: u8) -> Result<(), &'static str> { 229 | self.wait_for_write()?; 230 | unsafe { 231 | self.command_port.write(value); 232 | } 233 | Ok(()) 234 | } 235 | 236 | fn write_data_port(&mut self, value: u8) -> Result<(), &'static str> { 237 | self.wait_for_write()?; 238 | unsafe { 239 | self.data_port.write(value); 240 | } 241 | Ok(()) 242 | } 243 | 244 | fn wait_for_read(&mut self) -> Result<(), &'static str> { 245 | let timeout = 100_000; 246 | for _ in 0..timeout { 247 | let value = unsafe { self.command_port.read() }; 248 | if (value & 0x1) == 0x1 { 249 | return Ok(()); 250 | } 251 | } 252 | Err("wait for mouse read timeout") 253 | } 254 | 255 | fn wait_for_write(&mut self) -> Result<(), &'static str> { 256 | let timeout = 100_000; 257 | for _ in 0..timeout { 258 | let value = unsafe { self.command_port.read() }; 259 | if (value & 0x2) == 0x0 { 260 | return Ok(()); 261 | } 262 | } 263 | Err("wait for mouse write timeout") 264 | } 265 | } 266 | 267 | #[cfg(test)] 268 | mod test { 269 | use super::*; 270 | 271 | const EMPTY_PACKET: u8 = 0; 272 | const VALID_PACKET: u8 = MouseFlags::ALWAYS_ONE.bits(); 273 | const NEGATIVE_PACKET: u8 = 274 | MouseFlags::ALWAYS_ONE.bits() | MouseFlags::X_SIGN.bits() | MouseFlags::Y_SIGN.bits(); 275 | const NEGATIVE_PACKET_WITH_OVERFLOW: u8 = MouseFlags::ALWAYS_ONE.bits() 276 | | MouseFlags::X_SIGN.bits() 277 | | MouseFlags::Y_SIGN.bits() 278 | | MouseFlags::X_OVERFLOW.bits() 279 | | MouseFlags::Y_OVERFLOW.bits(); 280 | const LEFT_MOUSE_BUTTON_DOWN_PACKET: u8 = 281 | MouseFlags::ALWAYS_ONE.bits() | MouseFlags::LEFT_BUTTON.bits(); 282 | const RIGHT_MOUSE_BUTTON_DOWN_PACKET: u8 = 283 | MouseFlags::ALWAYS_ONE.bits() | MouseFlags::RIGHT_BUTTON.bits(); 284 | const POSITIVE_X_PACKET: u8 = 0x5; 285 | const POSITIVE_Y_PACKET: u8 = 0x8; 286 | const NEGATIVE_X_PACKET: u8 = 0xD8; 287 | const NEGATIVE_Y_PACKET: u8 = 0xD9; 288 | 289 | #[test] 290 | fn process_packets() { 291 | let mut mouse = Mouse::new(); 292 | 293 | mouse.process_packet(VALID_PACKET); 294 | assert_eq!(mouse.current_packet, 1); 295 | 296 | mouse.process_packet(EMPTY_PACKET); 297 | assert_eq!(mouse.current_packet, 2); 298 | 299 | mouse.process_packet(EMPTY_PACKET); 300 | assert_eq!(mouse.current_packet, 0); 301 | 302 | let mouse_state = mouse.completed_state; 303 | assert_eq!(mouse_state.flags, MouseFlags::ALWAYS_ONE); 304 | assert_eq!(mouse_state.x, 0); 305 | assert_eq!(mouse_state.y, 0); 306 | } 307 | 308 | #[test] 309 | fn always_one_bit_not_set() { 310 | let mut mouse = Mouse::new(); 311 | mouse.process_packet(EMPTY_PACKET); 312 | assert_eq!(mouse.current_packet, 0); 313 | } 314 | 315 | #[test] 316 | fn positive_movement() { 317 | let mut mouse = Mouse::new(); 318 | mouse.process_packet(VALID_PACKET); 319 | mouse.process_packet(POSITIVE_X_PACKET); 320 | mouse.process_packet(POSITIVE_Y_PACKET); 321 | 322 | let mouse_state = mouse.completed_state; 323 | assert_eq!(mouse_state.x, POSITIVE_X_PACKET as i16); 324 | assert_eq!(mouse_state.y, POSITIVE_Y_PACKET as i16); 325 | } 326 | 327 | #[test] 328 | fn negative_movement() { 329 | let mut mouse = Mouse::new(); 330 | mouse.process_packet(NEGATIVE_PACKET); 331 | mouse.process_packet(NEGATIVE_X_PACKET); 332 | mouse.process_packet(NEGATIVE_Y_PACKET); 333 | 334 | let mouse_state = mouse.get_state(); 335 | assert_eq!(mouse_state.x, -40); 336 | assert_eq!(mouse_state.y, -39); 337 | } 338 | 339 | #[test] 340 | fn discard_overflow() { 341 | let mut mouse = Mouse::new(); 342 | mouse.process_packet(VALID_PACKET); 343 | mouse.process_packet(POSITIVE_X_PACKET); 344 | mouse.process_packet(POSITIVE_Y_PACKET); 345 | 346 | mouse.process_packet(NEGATIVE_PACKET_WITH_OVERFLOW); 347 | mouse.process_packet(NEGATIVE_X_PACKET); 348 | mouse.process_packet(NEGATIVE_Y_PACKET); 349 | 350 | let mouse_state = mouse.completed_state; 351 | assert_eq!(mouse_state.x, POSITIVE_X_PACKET as i16); 352 | assert_eq!(mouse_state.y, POSITIVE_Y_PACKET as i16); 353 | } 354 | 355 | #[test] 356 | fn left_mouse_button_down() { 357 | let mut mouse = Mouse::new(); 358 | mouse.process_packet(LEFT_MOUSE_BUTTON_DOWN_PACKET); 359 | assert_eq!(mouse.current_state.left_button_down(), true); 360 | } 361 | 362 | #[test] 363 | fn left_mouse_button_up() { 364 | let mut mouse = Mouse::new(); 365 | mouse.process_packet(VALID_PACKET); 366 | assert_eq!(mouse.current_state.left_button_up(), true); 367 | } 368 | 369 | #[test] 370 | fn right_mouse_button_down() { 371 | let mut mouse = Mouse::new(); 372 | mouse.process_packet(RIGHT_MOUSE_BUTTON_DOWN_PACKET); 373 | assert_eq!(mouse.current_state.right_button_down(), true); 374 | } 375 | 376 | #[test] 377 | fn right_mouse_button_up() { 378 | let mut mouse = Mouse::new(); 379 | mouse.process_packet(VALID_PACKET); 380 | assert_eq!(mouse.current_state.right_button_up(), true); 381 | } 382 | } 383 | --------------------------------------------------------------------------------