import upstream maccel baseline
Tests / test_core_function (push) Failing after 12s

This commit is contained in:
2026-03-24 12:10:31 +00:00
parent 6e948d7b39
commit 5f1254d11a
108 changed files with 18930 additions and 0 deletions
+59
View File
@@ -0,0 +1,59 @@
name: Release CLI
on:
push:
tags:
- v*
jobs:
release:
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Install latest rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Compile
id: compile
run: |
OUTPUT_DIR="built/output"
mkdir -p "$OUTPUT_DIR"
echo "BUILT_ARCHIVES=$OUTPUT_DIR" >> $GITHUB_OUTPUT
ARTIFACTS_FOLDER="${GITHUB_REPOSITORY#*/}_${GITHUB_REF_NAME}"
mkdir $ARTIFACTS_FOLDER
set -x
make build_cli
BIN=maccel
ARCHIVE=$BIN-cli.tar.gz
BIN_PATH=target/release/$BIN
strip $BIN_PATH;
cp -r $BIN_PATH LICENSE README.md $ARTIFACTS_FOLDER
tar -caf $ARCHIVE $ARTIFACTS_FOLDER/*
mv $ARCHIVE $OUTPUT_DIR
- name: Name Release
run: echo "RELEASE_NAME=${GITHUB_REPOSITORY#*/}-cli ${GITHUB_REF_NAME#v}" >> $GITHUB_ENV
- name: Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
generate_release_notes: true
name: ${{ env.RELEASE_NAME }}
files: |
${{ steps.compile.outputs.BUILT_ARCHIVES }}/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+18
View File
@@ -0,0 +1,18 @@
name: Tests
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
jobs:
test_core_function:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Test acceleration function
run: make test
- name: Test CLI
run: cargo test --all
+23
View File
@@ -0,0 +1,23 @@
# artifacts
.*.cmd
*.ko
*.mod
*.mod.*
*.symvers
*.order
*.o
# build
.cache
# misc
compile_commands.json
# Added by cargo
/target
# large generated driver snapshots (not required in this fork)
driver/tests/snapshots/*__*.snapshot
driver/tests/snapshots/SENS_*.snapshot
+165
View File
@@ -0,0 +1,165 @@
# Agent Guidelines for maccel Repository
This document outlines essential commands and style conventions for agentic coding in this repository.
## 1. Project Structure
- `driver/` - Linux kernel module (C) for mouse acceleration
- `cli/` - Rust CLI binary for controlling the driver
- `crates/core/` - Core Rust library shared by CLI and TUI
- `tui/` - Terminal UI component using ratatui
- `site/` - Documentation website (Astro/TypeScript)
- `udev_rules/` - udev rules for device permissions
- `PKGBUILD` - Arch Linux DKMS package definition
- `install.sh` - Installation script
## 2. Build, Lint, and Test Commands
### Driver (C Kernel Module)
- `make build` - Build the kernel module
- `make build_debug` - Build with debug symbols (`-g -DDEBUG`)
- `make install` - Build and load the kernel module
- `make reinstall` - Uninstall and reinstall module
- `make uninstall` - Remove module from kernel
### CLI (Rust)
- `cargo build --bin maccel --release` - Build CLI binary
- `make dev_cli` - Run CLI with auto-reload using cargo-watch
- `make install_cli` - Build and install CLI to /usr/local/bin
- `make uninstall_cli` - Remove CLI binary
### udev Rules
- `make udev_install` - Install udev rules
- `make udev_uninstall` - Remove udev rules
- `make udev_trigger` - Reload udev and trigger device discovery
### Tests
**All Tests:**
- `make test` - Run all C driver tests
- `cargo test --all` - Run all Rust tests
**Single Test:**
- `TEST_NAME=<pattern> make test` - Filter C tests by filename
- `cargo test <test_name>` - Run Rust test by name
- `cargo test --package maccel-core <test_name>` - Run test in specific crate
### Linting & Formatting
- `cargo fmt --all` - Format all Rust code
- `cargo clippy --all --fix --allow-dirty` - Rust linting with auto-fix
## 3. Code Style Guidelines
### General Principles
- Adhere to existing project conventions
- Mimic surrounding code style and patterns
- Add comments sparingly, focusing on _why_ rather than _what_
- No trailing whitespace
### Rust (CLI, Core, TUI)
**Naming:**
- `snake_case` - functions, variables, modules
- `PascalCase` - types, enums, traits
- `SCREAMING_SNAKE_CASE` - constants
**Imports (order matters):**
1. `std` imports first
2. External crates second
3. Internal modules third
4. Within each group, sort alphabetically
```rust
use std::{fmt::Debug, path::PathBuf};
use anyhow::Context;
use crate::params::Param;
```
**Error Handling:**
- Use `anyhow::Result<()>` for application-level code
- Use `thiserror` for library code when needed
- Propagate errors with `?` operator
- Add context with `.context()` for better messages
- Avoid `unwrap()` and `expect()` in production code
- Use `anyhow::bail!()` for early error returns
**Testing:**
- Unit tests in same file: `#[cfg(test)] mod tests { ... }`
- Use `#[test]` attribute for test functions
### C (Kernel Module)
**Naming:**
- `snake_case` - functions and variables
- `PascalCase` - types and structs
**Style:**
- Follow Linux kernel coding style
- Tabs for indentation
- Braces on same line (K&R style)
- Prefix internal/static functions with `_`
**Error Handling:**
- Return integer error codes (0 = success, negative = error)
- Use `goto` for cleanup on error (common kernel pattern)
**Testing:**
- Test files: `driver/tests/*.test.c`
- Use `assert_snapshot()` for snapshot testing
### TypeScript/Astro (Site)
- Use TypeScript strict mode
- Use Tailwind CSS utility-first approach
- `kebab-case` for component filenames
- `camelCase` for variables and functions
## 4. Naming Conventions Summary
| Language | Functions/Variables | Types/Enums | Files | Constants |
|----------|---------------------|-------------|-------|-----------|
| Rust | snake_case | PascalCase | snake_case.rs | SCREAMING_SNAKE_CASE |
| C | snake_case | PascalCase | snake_case.c | SCREAMING_SNAKE_CASE |
| TypeScript | camelCase | PascalCase | kebab-case.ts | SCREAMING_SNAKE_CASE |
## 5. Version Bumping
- **CLI changes:** Bump `cli/Cargo.toml` version AND create git tag
- **Driver changes:** Update `PKGBUILD` pkgver
**CLI version bump:**
1. Update `cli/Cargo.toml` version
2. `cargo update -p maccel-cli` - Update lock file
3. `git add -A && git commit -m "Bump CLI version to x.y.z"`
4. `git tag v<x.y.z> && git push origin v<x.y.z>`
## 6. Commit Messages
- Short subject line (<50 chars), imperative mood
- Capitalize first letter
- Blank line between subject and body
- No period at subject line end
Example:
```
Add new acceleration curve algorithm
Implements a cubic bezier curve for smoother acceleration
at high DPI values.
```
## 7. Key Files Reference
| Purpose | File |
|---------|------|
| CLI entry point | `cli/src/main.rs` |
| Core library exports | `crates/core/src/lib.rs` |
| Parameter definitions | `crates/core/src/params.rs` |
| Driver entry point | `driver/maccel.c` |
| Test utilities | `driver/tests/test_utils.h` |
## 8. Dependencies
- **Rust:** See `Cargo.toml` (workspace) and individual `Cargo.toml` files
- **C:** kernel headers, make, gcc
- **DKMS:** Required for driver installation
- **Site:** Node.js 24.x (`^24.0.0`), npm (see `site/package.json`)
+7
View File
@@ -0,0 +1,7 @@
## Commit Messages
- Short subject line: Keep the first line (subject) brief and descriptive, aiming for under 50 characters.
- Imperative mood: Use verbs in the present tense, like "Add", "Fix", "Update".
- Capitalization: Capitalize the first letter of the subject line.
- Blank line separation: Use a blank line to separate the subject from the body explanation.
- Detailed body (optional): If needed, provide further context and reasoning in the body, wrapping lines at around 72 characters.
- No period at the end: Do not end the subject line with a period.
Generated
+1026
View File
File diff suppressed because it is too large Load Diff
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+67
View File
@@ -0,0 +1,67 @@
DRIVERDIR?=`pwd`/driver
MODULEDIR?=/lib/modules/`uname -r`/kernel/drivers/usb
DRIVER_CFLAGS ?= -DFIXEDPT_BITS=$(shell getconf LONG_BIT)
build:
$(MAKE) DRIVER_CFLAGS="$(DRIVER_CFLAGS)" -C $(DRIVERDIR)
build_debug: override DRIVER_CFLAGS += -g -DDEBUG
build_debug: build
test:
$(MAKE) -C $(DRIVERDIR) test
test_debug:
$(MAKE) -C $(DRIVERDIR) test_debug
install_debug: build_debug install
install: build
@sudo insmod $(DRIVERDIR)/maccel.ko;
@mkdir -p $(MODULEDIR)
@sudo cp -v $(DRIVERDIR)/*.ko $(MODULEDIR);
@sudo chown -v root:root $(MODULEDIR)/*.ko;
sudo groupadd -f maccel;
sudo depmod;
sudo chown -v :maccel /sys/module/maccel/parameters/* /dev/maccel;
sudo chmod g+r /dev/maccel;
ls -l /sys/module/maccel/parameters/*
uninstall: clean
@sudo rm -fv $(MODULEDIR)/maccel.ko
@sudo rmmod maccel
reinstall: uninstall
@sudo make DRIVER_CFLAGS=$(DRIVER_CFLAGS) install
reinstall_debug: uninstall
@sudo make DRIVER_CFLAGS=$(DRIVER_CFLAGS) install_debug
dev_cli:
cargo watch -x 'run'
build_cli:
cargo build --bin maccel --release
install_cli: build_cli
sudo install -m 755 target/release/maccel /usr/local/bin/maccel
uninstall_cli:
@sudo rm -f /usr/local/bin/maccel
udev_install:
sudo install -m 644 -v -D `pwd`/udev_rules/99-maccel.rules /usr/lib/udev/rules.d/99-maccel.rules
sudo install -m 755 -v -D `pwd`/udev_rules/maccel_param_ownership_and_resets /usr/lib/udev/maccel_param_ownership_and_resets
udev_uninstall:
@sudo rm -f /usr/lib/udev/rules.d/99-maccel*.rules /usr/lib/udev/maccel_*
sudo udevadm control --reload-rules
udev_trigger: udev_install
udevadm control --reload-rules
udevadm trigger --subsystem-match=usb --subsystem-match=input --subsystem-match=hid --attr-match=bInterfaceClass=03 --attr-match=bInterfaceSubClass=01 --attr-match=bInterfaceProtocol=02
clean:
@rm -rf src pkg maccel maccel*.zst maccel-dkms*.log*
$(MAKE) -C $(DRIVERDIR) clean
+63
View File
@@ -0,0 +1,63 @@
pkgname=maccel-dkms
_pkgname="maccel"
pkgver=0.5.9
pkgrel=1
pkgdesc="Mouse acceleration driver and kernel module for Linux."
arch=("x86_64")
url="https://www.maccel.org/"
license=("GPL-2.0-or-later")
install=maccel.install
depends=("dkms")
makedepends=("git" "cargo")
# DEBUG_CFLAGS="$DEBUG_CFLAGS -DDEBUG"
options=(!debug !lto)
source=("git+https://github.com/Gnarus-G/maccel.git")
sha256sums=("SKIP")
prepare() {
export RUSTUP_TOOLCHAIN=stable
platform="$(rustc -vV | sed -n 's/host: //p')"
cargo fetch --locked --target "${platform}" --manifest-path="${srcdir}/maccel/Cargo.toml"
}
build() {
export RUSTUP_TOOLCHAIN=stable
export CARGO_TARGET_DIR=target
# Build the CLI
cargo build --bin maccel --release --frozen --manifest-path="${srcdir}/maccel/Cargo.toml"
}
package() {
# Add group
install -Dm 644 "${srcdir}/maccel/maccel.sysusers" "${pkgdir}/usr/lib/sysusers.d/${_pkgname}.conf"
# Install Driver
install -Dm 644 "${srcdir}/maccel/dkms.conf" "${pkgdir}/usr/src/${_pkgname}-${pkgver}/dkms.conf"
# Escape path separators from debug flags values
DRIVER_CFLAGS=$(echo ${DEBUG_CFLAGS} | sed -e "s/\//\\\\\\//g")
# Set name and version
sed -e "s/@_PKGNAME@/${_pkgname}/" \
-e "s/@PKGVER@/${pkgver}/" \
-e "s/@DRIVER_CFLAGS@/'${DRIVER_CFLAGS}'/" \
-i "${pkgdir}/usr/src/${_pkgname}-${pkgver}/dkms.conf"
cp -r "${srcdir}/maccel/driver/." "${pkgdir}/usr/src/${_pkgname}-${pkgver}/"
# Install CLI
install -Dm 755 "${srcdir}/target/release/maccel" "${pkgdir}/usr/bin/maccel"
# Install udev rules
install -Dm 644 "${srcdir}/maccel/udev_rules/99-maccel.rules" "${pkgdir}/usr/lib/udev/rules.d/99-maccel.rules"
install -Dm 755 "${srcdir}/maccel/udev_rules/maccel_param_ownership_and_resets" "${pkgdir}/usr/lib/udev/maccel_param_ownership_and_resets"
# Install License
install -Dm 644 "${srcdir}/maccel/LICENSE" "${pkgdir}/usr/share/licenses/${_pkgname}/LICENSE"
}
+181
View File
@@ -0,0 +1,181 @@
# maccel NixOS Flake
If you're on NixOS, maccel provides a declarative flake module to seamlessly integrate and configure the mouse acceleration driver through your system configuration.
**Benefits of the NixOS module:**
- **Declarative configuration**: All parameters defined in your NixOS config
- **Direct kernel module parameters**: More efficient than reset scripts approach
- **No manual setup**: Kernel module, udev rules, and CLI tools installed automatically
- **Seamless updates**: Update maccel alongside your system like any other flake
- **Parameter discovery**: Optional CLI/TUI for real-time parameter tuning
## Quick Start
Add to your `flake.nix` inputs:
```nix
maccel.url = "github:Gnarus-G/maccel";
```
Create your `maccel.nix` module:
```nix
{inputs, ...}: {
imports = [
inputs.maccel.nixosModules.default
];
hardware.maccel = {
enable = true;
enableCli = true; # Optional
parameters = {
# Common (all modes)
sensMultiplier = 1.0;
yxRatio = 1.0;
inputDpi = 1000.0;
angleRotation = 0.0;
mode = "synchronous";
# Linear mode
acceleration = 0.3;
offset = 2.0;
outputCap = 2.0;
# Natural mode
decayRate = 0.1;
offset = 2.0;
limit = 1.5;
# Synchronous mode
gamma = 1.0;
smooth = 0.5;
motivity = 2.5;
syncSpeed = 10.0;
};
};
# To use maccel CLI/TUI without sudo
users.groups.maccel.members = ["your_username"];
}
```
## How it Works
### Parameter Management
- **NixOS config**: Parameters are set directly as kernel module parameters at boot for maximum efficiency
- **CLI/TUI**: When `enableCli = true`, you can use `maccel tui` or `maccel set` for real-time adjustments
- **Temporary changes**: CLI/TUI modifications are session-only and revert after reboot
### Recommended Workflow
1. **Enable CLI tools**: Set `enableCli = true` for parameter discovery
2. **Find optimal values**: Use `maccel tui` to experiment with parameters in real-time
3. **Apply permanently**: Copy your optimal values to `hardware.maccel.parameters` in your NixOS config
4. **Rebuild system**: Run `sudo nixos-rebuild switch --flake .` to make settings persistent
## Maintaining the NixOS Module
When new acceleration modes or parameters are added to maccel, the [NixOS module](module.nix) needs to be updated accordingly. This section provides a step-by-step guide for maintainers.
### 1. Adding New Modes
New modes are defined in [`driver/accel/mode.h`](driver/accel/mode.h). To add support:
**In [`module.nix`](module.nix):**
#### Step 1: Add to modeMap
```nix
# Update the modeMap with new modes
modeMap = {
linear = 0;
natural = 1;
synchronous = 2;
no_accel = 3;
new_mode = 4; # Add new mode here
};
```
#### Step 2: Add the mode option
```nix
# In options.hardware.maccel.parameters
mode = mkOption {
type = types.nullOr (types.enum ["linear" "natural" "synchronous" "no_accel" "new_mode"]);
default = null;
description = "Acceleration mode.";
};
```
### 2. Adding New Parameters
New parameters are defined in [`driver/params.h`](driver/params.h). To add support:
**In [`module.nix`](module.nix):**
#### Step 1: Add to parameterMap
```nix
# In parameterMap
parameterMap = {
# Existing parameters...
NEW_PARAM = cfg.parameters.newParam;
};
```
#### Step 2: Add NixOS option
```nix
# In options.hardware.maccel.parameters
newParam = mkOption {
type = types.nullOr types.float; # or appropriate type
default = null;
description = "Description of the new parameter.";
};
```
#### Step 3: Add validation (if needed)
```nix
# For parameters with constraints
newParam = mkOption {
type = types.nullOr (types.addCheck types.float (x: x > 0.0)
// {description = "positive float";});
default = null;
description = "Description of the new parameter. Must be positive.";
};
```
### 3. Using LLMs
This NixOS module was developed with significant LLM assistance. Here's a comprehensive prompt for maintaining it:
```
I need to update the NixOS module for maccel. Please analyze the maccel codebase and help me maintain the NixOS module:
CONTEXT:
- maccel is a Linux mouse acceleration driver with kernel module and CLI tools
- The NixOS module is in module.nix and provides declarative configuration
- Parameters are defined in driver/params.h and modes in driver/accel/mode.h
- Read README_NIXOS.md section "Maintaining the NixOS Module" for detailed patterns and examples
TASKS:
1. **Discover changes**: Analyze driver/params.h and driver/accel/ for new parameters, modes, or modifications
2. **Compare with current**: Check what's missing from existing modeMap and parameterMap in module.nix
3. **Add new modes**: Update modeMap with correct enum values and add to mode option enum
4. **Add new parameters**: Add to parameterMap and create NixOS options with proper type validation, descriptions, and constraints
5. **Explain changes**: Summarize what was added and why
Follow the exact patterns shown in README_NIXOS.md and existing patterns in module.nix. Provide complete code snippets for module.nix.
```
### 4. Testing The Module
After modifying [`module.nix`](module.nix):
1. **Format nix code**: `alejandra .`
2. **Check nix syntax**: `nix flake check`
3. **Test parameter loading**: Confirm parameters load correctly on boot when set via NixOS config
+3
View File
@@ -0,0 +1,3 @@
*.o
bin
venv
+13
View File
@@ -0,0 +1,13 @@
bench_driver: build
@bin/evdriverlag
bench_handler: build
@bin/evinputlag
build: evdriverlag.c evinputlag.c
@mkdir -p bin
@cc evdriverlag.c -o bin/evdriverlag
@cc evinputlag.c -o bin/evinputlag
clean:
rm *.o
+1001
View File
File diff suppressed because it is too large Load Diff
+54
View File
@@ -0,0 +1,54 @@
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define MOUSE_DEVICE "/dev/input/event2"
static __suseconds_t to_us(struct timeval time) {
return time.tv_sec * 1000000L + time.tv_usec;
}
#define EVENT_TIME_PAIR_CNT 1000 * 2
int main(void) {
// Open the source device
int fd_source = open(MOUSE_DEVICE, O_RDONLY);
if (fd_source < 0) {
perror("Failed to open source device");
return 1;
}
__suseconds_t times[EVENT_TIME_PAIR_CNT] = {0};
int tidx = 0;
// Main loop to read, modify, and write events
struct input_event ev;
while (tidx < EVENT_TIME_PAIR_CNT && read(fd_source, &ev, sizeof(ev)) > 0) {
struct timeval now;
gettimeofday(&now, NULL);
times[tidx++] = to_us(ev.time);
times[tidx++] = to_us(now);
}
// Cleanup
close(fd_source);
tidx = 0;
printf("event_time,read_time,diff\n"); // eve'ry is in us
while (tidx < EVENT_TIME_PAIR_CNT) {
__suseconds_t event_time = times[tidx++];
__suseconds_t read_time = times[tidx++];
/* __suseconds_t diff = ; */
/* printf("event time: %luus, read time: %luus\n", event_time, read_time);
*/
/* printf("time diff: %luus\n", read_time - event_time); */
printf("%lu,%lu,%lu\n", event_time, read_time, read_time - event_time);
}
return 0;
}
+69
View File
@@ -0,0 +1,69 @@
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define MOUSE_DEVICE "/dev/input/event7"
static __suseconds_t to_us(struct timeval time) {
return time.tv_sec * 1000000L + time.tv_usec;
}
#define EVENT_TIME_PAIR_CNT 1000 * 3
/**
* NOTE: This benchmark depends on temporarily setting
* maccel_filter from input_handler.h to inject ktime_t diff (in us)
* between when the original event was received and the modified event was
* reported, as the value of the REL_Z REL_ABS event. So we can measure the
* extra lag from the input_handler. Assuming REL_Z, REL_ABS are only produced
* as carriers of the extra lag measurement.
*
*/
int main(void) {
int fd_source = open(MOUSE_DEVICE, O_RDONLY);
if (fd_source < 0) {
perror("Failed to open device");
return 1;
}
__suseconds_t times[EVENT_TIME_PAIR_CNT] = {0};
int tidx = 0;
// Main loop to read, modify, and write events
struct input_event ev;
while (tidx < EVENT_TIME_PAIR_CNT && read(fd_source, &ev, sizeof(ev)) > 0) {
struct timeval now;
gettimeofday(&now, NULL);
if (ev.type == EV_REL && (ev.code == 2 || ev.code == 3)) {
/* fprintf(stderr, "EVENT: type %d, code %d, value %d\n", ev.type,
* ev.code, */
/* ev.value); */
times[tidx++] = to_us(ev.time);
times[tidx++] = to_us(now);
times[tidx++] = ev.value;
}
}
// Cleanup
close(fd_source);
tidx = 0;
printf("event_time,read_time,naive_diff,extra_lag,diff\n"); // eve'ry is in us
while (tidx < EVENT_TIME_PAIR_CNT) {
__suseconds_t event_time = times[tidx++];
__suseconds_t read_time = times[tidx++];
__suseconds_t extra_lag_measured_by_input_handler = times[tidx++];
__suseconds_t diff = read_time - event_time;
printf("%lu,%lu,%lu,%lu,%lu\n", event_time, read_time, diff,
extra_lag_measured_by_input_handler,
diff + extra_lag_measured_by_input_handler);
}
return 0;
}
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
control_data = pd.read_csv("control.csv")
new_data = pd.read_csv("input_handler.csv")
fig, ax = plt.subplots()
ax.plot(np.arange(1000), control_data["diff"], 'b',
label=f"Hid-generic (mean = {control_data["diff"].mean()}us)")
ax.plot(np.arange(1000), new_data["diff"], 'g',
label=f"New driver (mean = {new_data["diff"].mean()}us)")
plt.ylabel('lag (us)')
plt.xlabel('reads')
legend = ax.legend(loc='upper center', fontsize='x-large')
plt.show()
""" Some extra data points out of curiosity """
virtual_minus_source = new_data["virtual_event_time"] - new_data["event_time"]
print("average lag between source and virtual device:",
virtual_minus_source.mean())
new_data["read_minus_virtual"] = new_data["read_time"] - \
new_data["virtual_event_time"]
print("average lag between virtual device and read:",
new_data["read_minus_virtual"].mean())
+11
View File
@@ -0,0 +1,11 @@
contourpy==1.2.1
cycler==0.12.1
fonttools==4.53.1
kiwisolver==1.4.5
matplotlib==3.9.1.post1
numpy==2.0.1
packaging==24.1
pillow==10.4.0
pyparsing==3.1.2
python-dateutil==2.9.0.post0
six==1.16.0
+1
View File
@@ -0,0 +1 @@
/target
+1
View File
@@ -0,0 +1 @@
/target
+36
View File
@@ -0,0 +1,36 @@
use std::{
env::{self, consts::ARCH},
path::PathBuf,
};
fn main() {
let out = PathBuf::from(
env::var("OUT_DIR").expect("Expected OUT_DIR to be defined in the environment"),
);
let fixedpt_bits = match ARCH {
"x86" => "32",
#[cfg(feature = "long_bit_32")]
"x86_64" => "32",
#[cfg(not(feature = "long_bit_32"))]
"x86_64" => "64",
a => panic!("unsupported/untested architecture: {a}"),
};
let mut compiler = cc::Build::new();
compiler
.file("src/libmaccel.c")
.define("FIXEDPT_BITS", fixedpt_bits);
if cfg!(feature = "dbg") {
compiler.define("DEBUG", "1");
compiler.debug(true);
}
compiler.compile("maccel");
println!("cargo:rust-link-search=static={}", out.display());
const DRIVER_DIR: &str = "../../driver";
println!("cargo:rerun-if-changed={DRIVER_DIR}");
println!("cargo:rerun-if-changed=src/libmaccel.c");
}
+11
View File
@@ -0,0 +1,11 @@
mod context;
pub mod inputspeed;
mod libmaccel;
mod params;
pub mod persist;
mod sens_fns;
pub use context::*;
pub use libmaccel::fixedptc;
pub use params::*;
pub use sens_fns::*;
+14
View File
@@ -0,0 +1,14 @@
#include "../../../driver/accel_rs.h"
#include "../../../driver/fixedptc.h"
char *fpt_to_str(fpt num);
fpt str_to_fpt(char *string);
double fpt_to_float(fpt value);
fpt fpt_from_float(double value);
extern char *fpt_to_str(fpt num) { return fptoa(num); }
extern fpt str_to_fpt(char *string) { return atofp(string); }
extern double fpt_to_float(fpt value) { return fpt_todouble(value); }
extern fpt fpt_from_float(double value) { return fpt_rconst(value); }
+91
View File
@@ -0,0 +1,91 @@
pub mod fixedptc {
use std::{
ffi::{CStr, CString},
str::FromStr,
};
use anyhow::Context;
use super::c_libmaccel::{self, str_to_fpt};
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct Fpt(pub i64);
impl From<Fpt> for f64 {
fn from(value: Fpt) -> Self {
unsafe { c_libmaccel::fpt_to_float(value) }
}
}
impl From<f64> for Fpt {
fn from(value: f64) -> Self {
unsafe { c_libmaccel::fpt_from_float(value) }
}
}
#[cfg(test)]
#[test]
fn fpt_and_float_conversion_to_and_fro() {
macro_rules! assert_for {
($value:literal) => {{
let fp = Fpt::from($value);
assert_eq!(f64::from(fp), $value);
}};
}
assert_for!(1.5);
assert_for!(4.5);
assert_for!(1.0);
assert_for!(0.0);
assert_for!(0.125);
assert_for!(0.5);
}
impl<'a> TryFrom<&'a Fpt> for &'a str {
type Error = anyhow::Error;
fn try_from(value: &'a Fpt) -> Result<Self, Self::Error> {
unsafe {
let s = CStr::from_ptr(c_libmaccel::fpt_to_str(*value));
let s = core::str::from_utf8(s.to_bytes())?;
Ok(s)
}
}
}
impl FromStr for Fpt {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cstr = CString::new(s).context("Failed to convert to a C string")?;
let f = unsafe { str_to_fpt(cstr.as_ptr()) };
Ok(f)
}
}
}
#[repr(C)]
pub struct Vector {
pub x: i64,
pub y: i64,
}
mod c_libmaccel {
use super::{Vector, fixedptc};
use crate::params::AccelParams;
use std::ffi::c_char;
unsafe extern "C" {
pub fn sensitivity_rs(speed_in: fixedptc::Fpt, args: AccelParams) -> Vector;
}
unsafe extern "C" {
pub fn fpt_to_str(num: fixedptc::Fpt) -> *const c_char;
pub fn str_to_fpt(string: *const c_char) -> fixedptc::Fpt;
pub fn fpt_from_float(value: f64) -> fixedptc::Fpt;
pub fn fpt_to_float(value: fixedptc::Fpt) -> f64;
}
}
pub use c_libmaccel::sensitivity_rs;
+358
View File
@@ -0,0 +1,358 @@
use crate::libmaccel::fixedptc::Fpt;
use paste::paste;
/// Declare an enum for every parameter.
macro_rules! declare_common_params {
($($param:tt,)+) => {
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Param {
$($param),+
}
paste!(
#[derive(Debug)]
pub struct AllParamArgs {
$( pub [< $param:snake:lower >]: Fpt ),+
}
);
pub const ALL_PARAMS: &[Param] = &[ $(Param::$param),+ ];
};
}
// Helper macro to create FFI-safe curve parameter structs
macro_rules! make_curve_params_struct {
// Case: has parameters
($mode:tt, $($param:tt),+) => {
paste! {
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct [< $mode CurveParams >] {
$( pub [< $param:snake:lower >]: Fpt ),+
}
}
};
// Case: no parameters, add a ZST field for FFI safety
($mode:tt, ) => {
paste! {
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct [< $mode CurveParams >] {
pub _ffi_guard: [u8; 0],
}
}
};
}
macro_rules! declare_params {
( Common { $($common_param:tt),+$(,)? } , $( $mode:tt { $($param:tt),*$(,)? }, )+) => {
declare_common_params! {
$( $common_param, )+
$( $( $param, )* )+
}
/// Array of all the common parameters for convenience.
pub const ALL_COMMON_PARAMS: &[Param] = &[ $( Param::$common_param),+ ];
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[derive(Debug, Default, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum AccelMode {
#[default]
$( $mode, )+
}
pub const ALL_MODES: &[AccelMode] = &[ $( AccelMode::$mode, )+ ];
paste! {
/// Define the complete shape (and memory layout) of the argument
/// of the sensitivity function as it is expected to be in `C`
#[repr(C)]
pub struct AccelParams {
$( pub [< $common_param:snake:lower >] : Fpt, )+
pub by_mode: AccelParamsByMode,
}
/// Represents the tagged union of curve-specific parameters.
#[repr(C, u8)]
pub enum AccelParamsByMode {
$(
$mode([< $mode CurveParams >] ),
)+
}
/// Represents the common parameters and their float values.
/// Use it to bulk set the common parameters.
#[cfg_attr(feature = "clap", derive(clap::Args))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CommonParamArgs {
$( pub [< $common_param:snake:lower >]: f64 ),+
}
}
paste! {
$(
// Use the helper macro to define the struct
make_curve_params_struct!($mode, $($param),*);
#[doc = "Array of all parameters for the `" $mode "` mode for convenience." ]
pub const [< ALL_ $mode:upper _PARAMS >]: &[Param] = &[ $( Param::$param),* ];
#[doc = "Represents the parameters for `" $mode "` curve and their float values"]
/// Use it to bulk set the curve's parameters.
#[cfg_attr(feature = "clap", derive(clap::Args))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct [< $mode ParamArgs >] {
$( pub [< $param:snake:lower >]: f64 ),*
}
)+
/// Subcommands for the CLI
#[cfg(feature = "clap")]
pub mod subcommads {
#[derive(clap::Subcommand)]
pub enum SetParamByModesSubcommands {
/// Set all the common parameters
Common(super::CommonParamArgs),
$(
#[doc = "Set all the parameters for the " $mode " curve" ]
$mode(super::[< $mode ParamArgs >]),
)+
}
#[derive(clap::Subcommand)]
pub enum CliSubcommandSetParams {
/// Set the value for a single parameter
Param { name: crate::params::Param, value: f64 },
/// Set the acceleration mode (curve)
Mode { mode: crate::params::AccelMode },
/// Set the values for all parameters for a curve in order
All {
#[clap(subcommand)]
command: SetParamByModesSubcommands
},
}
#[derive(clap::Subcommand)]
pub enum GetParamsByModesSubcommands {
/// Get all the common parameters
Common,
$(
#[doc = "Get all the parameters for the " $mode " curve" ]
$mode
),+
}
#[derive(clap::Subcommand)]
pub enum CliSubcommandGetParams {
/// Get the value for a single parameter
Param { name: crate::params::Param },
/// Get the current acceleration mode (curve)
Mode,
/// Get the values for all parameters for a curve in order
All {
/// Print the values in one line, separated by a space
#[arg(long)]
oneline: bool,
#[arg(short, long)]
/// Print only the values
quiet: bool,
#[clap(subcommand)]
command: GetParamsByModesSubcommands
},
}
}
}
};
}
declare_params!(
Common {
SensMult,
YxRatio,
InputDpi,
AngleRotation
},
Linear {
Accel,
OffsetLinear,
OutputCap,
},
Natural {
DecayRate,
OffsetNatural,
Limit,
},
Synchronous {
Gamma,
Smooth,
Motivity,
SyncSpeed,
},
NoAccel {},
);
impl AccelMode {
pub fn as_title(&self) -> &'static str {
match self {
AccelMode::Linear => "Linear Acceleration",
AccelMode::Natural => "Natural (w/ Gain)",
AccelMode::Synchronous => "Synchronous",
AccelMode::NoAccel => "No Acceleration",
}
}
}
impl AccelMode {
pub const PARAM_NAME: &'static str = "MODE";
pub fn ordinal(&self) -> i64 {
(*self as i8).into()
}
}
impl Param {
/// The canonical internal name of the parameter.
pub fn name(&self) -> &'static str {
match self {
Param::SensMult => "SENS_MULT",
Param::YxRatio => "YX_RATIO",
Param::InputDpi => "INPUT_DPI",
Param::Accel => "ACCEL",
Param::OffsetLinear => "OFFSET",
Param::OffsetNatural => "OFFSET",
Param::OutputCap => "OUTPUT_CAP",
Param::DecayRate => "DECAY_RATE",
Param::Limit => "LIMIT",
Param::Gamma => "GAMMA",
Param::Smooth => "SMOOTH",
Param::Motivity => "MOTIVITY",
Param::SyncSpeed => "SYNC_SPEED",
Param::AngleRotation => "ANGLE_ROTATION",
}
}
pub fn display_name(&self) -> &'static str {
match self {
Param::SensMult => "Sens-Multiplier",
Param::Accel => "Accel",
Param::InputDpi => "Input DPI",
Param::OffsetLinear => "Offset",
Param::OffsetNatural => "Offset",
Param::OutputCap => "Output-Cap",
Param::YxRatio => "Y/x Ratio",
Param::DecayRate => "Decay-Rate",
Param::Limit => "Limit",
Param::Gamma => "Gamma",
Param::Smooth => "Smooth",
Param::Motivity => "Motivity",
Param::SyncSpeed => "Sync Speed",
Param::AngleRotation => "Angle Rotation",
}
}
pub fn description(&self) -> &'static str {
match self {
Param::SensMult => "Base sensitivity multiplier. Adjusts overall mouse speed.",
Param::YxRatio => {
"Y to X axis sensitivity ratio. Values > 1 increase vertical sensitivity."
}
Param::InputDpi => {
"Mouse DPI. Used to normalize to 1000 DPI equivalent for consistent acceleration."
}
Param::AngleRotation => "Rotation angle in degrees for sensitivity direction.",
Param::Accel => "Acceleration strength. Higher values = faster cursor at high speeds.",
Param::OffsetLinear => "Speed threshold (counts/ms) before acceleration begins.",
Param::OutputCap => "Maximum sensitivity multiplier cap. Prevents excessive speed.",
Param::DecayRate => "How quickly acceleration decays. Higher = faster decay.",
Param::OffsetNatural => "Speed threshold (counts/ms) for natural curve activation.",
Param::Limit => "Maximum gain limit for natural acceleration.",
Param::Gamma => "Exponent controlling curve shape. Higher = more aggressive ramp-up.",
Param::Smooth => "Smoothing factor (0-1). Higher = more gradual transitions.",
Param::Motivity => "Degree of acceleration effect. Must be > 1.",
Param::SyncSpeed => "Synchronization speed. Controls how fast sync responds.",
}
}
}
pub(crate) fn format_param_value(value: f64) -> String {
let mut number = format!("{value:.5}");
for idx in (1..number.len()).rev() {
let this_char = &number[idx..idx + 1];
if this_char != "0" {
if this_char == "." {
number.remove(idx);
}
break;
}
number.remove(idx);
}
number
}
#[cfg(test)]
#[test]
fn format_param_value_works() {
assert_eq!(format_param_value(1.5), "1.5");
assert_eq!(format_param_value(1.50), "1.5");
assert_eq!(format_param_value(100.0), "100");
assert_eq!(format_param_value(0.0600), "0.06");
assert_eq!(format_param_value(0.055000), "0.055");
}
pub(crate) fn validate_param_value(param_tag: Param, value: f64) -> anyhow::Result<()> {
match param_tag {
Param::SensMult => {}
Param::YxRatio => {}
Param::InputDpi => {
if value <= 0.0 {
anyhow::bail!("Input DPI must be positive");
}
}
Param::AngleRotation => {}
Param::Accel => {}
Param::OutputCap => {}
Param::OffsetLinear | Param::OffsetNatural => {
if value < 0.0 {
anyhow::bail!("offset cannot be less than 0");
}
}
Param::DecayRate => {
if value <= 0.0 {
anyhow::bail!("decay rate must be positive");
}
}
Param::Limit => {
if value < 1.0 {
anyhow::bail!("limit cannot be less than 1");
}
}
Param::Gamma => {
if value <= 0.0 {
anyhow::bail!("Gamma must be positive");
}
}
Param::Smooth => {
if !(0.0..=1.0).contains(&value) {
anyhow::bail!("Smooth must be between 0 and 1");
}
}
Param::Motivity => {
if value <= 1.0 {
anyhow::bail!("Motivity must be greater than 1");
}
}
Param::SyncSpeed => {
if value <= 0.0 {
anyhow::bail!("'Synchronous speed' must be positive");
}
}
}
Ok(())
}
+53
View File
@@ -0,0 +1,53 @@
use crate::{
AccelParams, AccelParamsByMode, LinearCurveParams, NaturalCurveParams, SynchronousCurveParams,
libmaccel::{self, fixedptc::Fpt},
params::AllParamArgs,
};
use crate::AccelMode;
impl AllParamArgs {
fn convert_to_accel_args(&self, mode: AccelMode) -> AccelParams {
let params_by_mode = match mode {
AccelMode::Linear => AccelParamsByMode::Linear(LinearCurveParams {
accel: self.accel,
offset_linear: self.offset_linear,
output_cap: self.output_cap,
}),
AccelMode::Natural => AccelParamsByMode::Natural(NaturalCurveParams {
decay_rate: self.decay_rate,
offset_natural: self.offset_natural,
limit: self.limit,
}),
AccelMode::Synchronous => AccelParamsByMode::Synchronous(SynchronousCurveParams {
gamma: self.gamma,
smooth: self.smooth,
motivity: self.motivity,
sync_speed: self.sync_speed,
}),
AccelMode::NoAccel => {
AccelParamsByMode::NoAccel(crate::params::NoAccelCurveParams { _ffi_guard: [] })
}
};
AccelParams {
sens_mult: self.sens_mult,
yx_ratio: self.yx_ratio,
input_dpi: self.input_dpi,
angle_rotation: self.angle_rotation,
by_mode: params_by_mode,
}
}
}
pub type SensXY = (f64, f64);
/// Ratio of Output speed to Input speed
pub fn sensitivity(s_in: f64, mode: AccelMode, params: &AllParamArgs) -> SensXY {
let sens =
unsafe { libmaccel::sensitivity_rs(s_in.into(), params.convert_to_accel_args(mode)) };
let ratio_x: f64 = Fpt(sens.x).into();
let ratio_y: f64 = Fpt(sens.y).into();
(ratio_x, ratio_y)
}
+6
View File
@@ -0,0 +1,6 @@
PACKAGE_NAME="@_PKGNAME@"
PACKAGE_VERSION="@PKGVER@"
MAKE[0]="make KVER=$kernelver DRIVER_CFLAGS=@DRIVER_CFLAGS@"
BUILT_MODULE_NAME[0]="@_PKGNAME@"
DEST_MODULE_LOCATION[0]="/kernel/drivers/usb"
AUTOINSTALL="yes"
+1
View File
@@ -0,0 +1 @@
accel_test
+75
View File
@@ -0,0 +1,75 @@
#include <linux/types.h>
#ifndef __KERNEL__
#include <stdint.h>
#endif // !__KERNEL__
/**
* [Yeetmouse](https://github.com/AndyFilter/YeetMouse/blob/master/driver/FixedMath/Fixed64.h#L1360)
* has better string utils. FP64_ToString there doesn't require
* `__udivmodti4` in 64-bit mode.
*
*/
typedef int32_t FP_INT;
typedef int64_t FP_LONG;
#define FP64_Shift 32
static inline FP_LONG FP64_Mul(FP_LONG a, FP_LONG b) {
return (FP_LONG)(((__int128_t)a * (__int128_t)b) >> FP64_Shift);
}
static char *FP_64_itoa_loop(char *buf, uint64_t scale, uint64_t value,
int skip) {
while (scale) {
unsigned digit = (value / scale);
if (!skip || digit || scale == 1) {
skip = 0;
*buf++ = '0' + digit;
value %= scale;
}
scale /= 10;
}
return buf;
}
void FP64_ToString(FP_LONG value, char *buf);
void FP64_ToString(FP_LONG value, char *buf) {
uint64_t uvalue = (value >= 0) ? value : -value;
if (value < 0)
*buf++ = '-';
#define SCALE 9
static const uint64_t FP_64_scales[10] = {
/* 18 decimals is enough for full 64bit fixed point precision */
1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000};
/* Separate the integer and decimal parts of the value */
uint64_t intpart = uvalue >> 32;
uint64_t fracpart = uvalue & 0xFFFFFFFF;
uint64_t scale = FP_64_scales[SCALE];
fracpart = FP64_Mul(fracpart, scale);
if (fracpart >= scale) {
/* Handle carry from decimal part */
intpart++;
fracpart -= scale;
}
/* Format integer part */
buf = FP_64_itoa_loop(buf, 1000000000, intpart, 1);
/* Format decimal part (if any) */
if (scale != 1) {
*buf++ = '.';
buf = FP_64_itoa_loop(buf, scale / 10, fracpart, 0);
}
*buf = '\0';
}
+31
View File
@@ -0,0 +1,31 @@
ifneq ($(KERNELRELEASE),)
obj-m := maccel.o
ccflags-y += $(DRIVER_CFLAGS)
endif
KVER ?= $(shell uname -r)
KDIR ?= /lib/modules/$(KVER)/build
DRIVER_CFLAGS ?= -DFIXEDPT_BITS=$(shell getconf LONG_BIT)
ifneq ($(CC),clang)
CC=gcc
else
export LLVM=1
endif
build:
$(MAKE) CC=$(CC) -C $(KDIR) M=$(CURDIR)
build_debug: DRIVER_CFLAGS += -g -DDEBUG
build_debug: build
clean:
$(MAKE) -C $(KDIR) M=$(CURDIR) clean
test_debug: DRIVER_CFLAGS += -g -DDEBUG
test_debug: test
test: **/*.test.c
@mkdir -p tests/snapshots
DRIVER_CFLAGS="$(DRIVER_CFLAGS)" TEST_NAME=$(name) sh tests/run_tests.sh
+140
View File
@@ -0,0 +1,140 @@
#ifndef _ACCEL_H_
#define _ACCEL_H_
#include "accel/linear.h"
#include "accel/mode.h"
#include "accel/natural.h"
#include "accel/synchronous.h"
#include "dbg.h"
#include "fixedptc.h"
#include "math.h"
#include "speed.h"
struct no_accel_curve_args {};
union __accel_args {
struct natural_curve_args natural;
struct linear_curve_args linear;
struct synchronous_curve_args synchronous;
struct no_accel_curve_args no_accel;
};
struct accel_args {
fpt sens_mult;
fpt yx_ratio;
fpt input_dpi;
fpt angle_rotation_deg;
enum accel_mode tag;
union __accel_args args;
};
const fpt NORMALIZED_DPI = fpt_fromint(1000);
/**
* Calculate the factor by which to multiply the input vector
* in order to get the desired output speed.
*
*/
static inline struct vector sensitivity(fpt input_speed,
struct accel_args args) {
fpt sens;
switch (args.tag) {
case synchronous:
dbg("accel mode %d: synchronous", args.tag);
sens = __synchronous_sens_fun(input_speed, args.args.synchronous);
break;
case natural:
dbg("accel mode %d: natural", args.tag);
sens = __natural_sens_fun(input_speed, args.args.natural);
break;
case linear:
dbg("accel mode %d: linear", args.tag);
sens = __linear_sens_fun(input_speed, args.args.linear);
break;
case no_accel:
dbg("accel mode %d: no_accel", args.tag);
sens = FIXEDPT_ONE;
break;
default:
sens = FIXEDPT_ONE;
}
sens = fpt_mul(sens, args.sens_mult);
return (struct vector){sens, fpt_mul(sens, args.yx_ratio)};
}
const fpt DEG_TO_RAD_FACTOR = fpt_xdiv(FIXEDPT_PI, fpt_rconst(180));
static inline void f_accelerate(int *x, int *y, fpt time_interval_ms,
struct accel_args args) {
static fpt carry_x = 0;
static fpt carry_y = 0;
fpt dx = fpt_fromint(*x);
fpt dy = fpt_fromint(*y);
{
if (args.angle_rotation_deg == 0) {
goto accel_routine;
}
// Add rotation of input vector
fpt degrees = args.angle_rotation_deg;
fpt radians =
fpt_mul(degrees, DEG_TO_RAD_FACTOR); // Convert degrees to radians
fpt cos_angle = fpt_cos(radians);
fpt sin_angle = fpt_sin(radians);
dbg("rotation angle(deg): %s deg", fptoa(degrees));
dbg("rotation angle(rad): %s rad", fptoa(radians));
dbg("cosine of rotation: %s", fptoa(cos_angle));
dbg("sine of rotation: %s", fptoa(sin_angle));
// Rotate input vector
fpt dx_rot = fpt_mul(dx, cos_angle) - fpt_mul(dy, sin_angle);
fpt dy_rot = fpt_mul(dx, sin_angle) + fpt_mul(dy, cos_angle);
dbg("rotated x: %s", fptoa(dx_rot));
dbg("rotated y: %s", fptoa(dy_rot));
dx = dx_rot;
dy = dy_rot;
}
accel_routine:
dbg("in (%d, %d)", *x, *y);
dbg("in: x (fpt conversion) %s", fptoa(dx));
dbg("in: y (fpt conversion) %s", fptoa(dy));
fpt dpi_factor = fpt_div(NORMALIZED_DPI, args.input_dpi);
dbg("dpi adjustment factor: %s", fptoa(dpi_factor));
dx = fpt_mul(dx, dpi_factor);
dy = fpt_mul(dy, dpi_factor);
fpt speed_in = input_speed(dx, dy, time_interval_ms);
struct vector sens = sensitivity(speed_in, args);
dbg("scale x %s", fptoa(sens.x));
dbg("scale y %s", fptoa(sens.y));
fpt dx_out = fpt_mul(dx, sens.x);
fpt dy_out = fpt_mul(dy, sens.y);
dx_out = fpt_add(dx_out, carry_x);
dy_out = fpt_add(dy_out, carry_y);
dbg("out: x %s", fptoa(dx_out));
dbg("out: y %s", fptoa(dy_out));
*x = fpt_toint(dx_out);
*y = fpt_toint(dy_out);
dbg("out (int conversion) (%d, %d)", *x, *y);
carry_x = fpt_sub(dx_out, fpt_fromint(*x));
carry_y = fpt_sub(dy_out, fpt_fromint(*y));
dbg("carry (%s, %s)", fptoa(carry_x), fptoa(carry_x));
}
#endif
+50
View File
@@ -0,0 +1,50 @@
#ifndef __ACCEL_LINEAR_H_
#define __ACCEL_LINEAR_H_
#include "../dbg.h"
#include "../fixedptc.h"
#include "../math.h"
struct linear_curve_args {
fpt accel;
fpt offset;
fpt output_cap;
};
static inline fpt linear_base_fn(fpt x, fpt accel,
fpt input_offset) {
fpt _x = x - input_offset;
fpt _x_square = fpt_mul(
_x, _x); // because linear in rawaccel is classic with exponent = 2
return fpt_mul(accel, fpt_div(_x_square, x));
}
/**
* Sensitivity Function for Linear Acceleration
*/
static inline fpt __linear_sens_fun(fpt input_speed,
struct linear_curve_args args) {
dbg("linear: accel %s", fptoa(args.accel));
dbg("linear: offset %s", fptoa(args.offset));
dbg("linear: output_cap %s", fptoa(args.output_cap));
if (input_speed <= args.offset) {
return FIXEDPT_ONE;
}
fpt sens = linear_base_fn(input_speed, args.accel, args.offset);
dbg("linear: base_fn sens %s", fptoa(args.accel));
fpt sign = FIXEDPT_ONE;
if (args.output_cap > 0) {
fpt cap = fpt_sub(args.output_cap, FIXEDPT_ONE);
if (cap < 0) {
cap = -cap;
sign = -sign;
}
sens = minsd(sens, cap);
}
return fpt_add(FIXEDPT_ONE, fpt_mul(sign, sens));
}
#endif // !__ACCEL_LINEAR_H_
+6
View File
@@ -0,0 +1,6 @@
#ifndef __ACCEL_MODE_H
#define __ACCEL_MODE_H
enum accel_mode : unsigned char { linear, natural, synchronous, no_accel };
#endif // !__ACCEL_MODE_H
+48
View File
@@ -0,0 +1,48 @@
#ifndef __ACCEL_NATURAL_H_
#define __ACCEL_NATURAL_H_
#include "../fixedptc.h"
struct natural_curve_args {
fpt decay_rate;
fpt offset;
fpt limit;
};
/**
* Gain Function for Natural Acceleration
*/
static inline fpt __natural_sens_fun(fpt input_speed,
struct natural_curve_args args) {
dbg("natural: decay_rate %s", fptoa(args.decay_rate));
dbg("natural: offset %s", fptoa(args.offset));
dbg("natural: limit %s", fptoa(args.limit));
if (input_speed <= args.offset) {
return FIXEDPT_ONE;
}
if (args.limit <= FIXEDPT_ONE) {
return FIXEDPT_ONE;
}
if (args.decay_rate <= 0) {
return FIXEDPT_ONE;
}
fpt limit = args.limit - FIXEDPT_ONE;
fpt accel = fpt_div(args.decay_rate, fpt_abs(limit));
fpt constant = fpt_div(-limit, accel);
dbg("natural: constant %s", fptoa(constant));
fpt offset_x = args.offset - input_speed;
fpt decay = fpt_exp(fpt_mul(accel, offset_x));
dbg("natural: decay %s", fptoa(decay));
fpt output_denom = fpt_div(decay, accel) - offset_x;
fpt output = fpt_mul(limit, output_denom) + constant;
return fpt_div(output, input_speed) + FIXEDPT_ONE;
}
#endif
+64
View File
@@ -0,0 +1,64 @@
#ifndef __ACCEL_SYNCHRONOUS_H_
#define __ACCEL_SYNCHRONOUS_H_
#include "../fixedptc.h"
struct synchronous_curve_args {
fpt gamma;
fpt smooth;
fpt motivity;
fpt sync_speed;
};
/**
* Sensitivity Function for `Synchronous` Acceleration
*/
static inline fpt __synchronous_sens_fun(fpt input_speed,
struct synchronous_curve_args args) {
fpt log_motivity = fpt_ln(args.motivity);
fpt gamma_const = fpt_div(args.gamma, log_motivity);
fpt log_syncspeed = fpt_ln(args.sync_speed);
fpt syncspeed = args.sync_speed;
fpt sharpness = args.smooth == 0 ? fpt_rconst(16.0)
: fpt_div(fpt_rconst(0.5), args.smooth);
int use_linear_clamp = sharpness >= fpt_rconst(16.0);
fpt sharpness_recip = fpt_div(FIXEDPT_ONE, sharpness);
fpt minimum_sens = fpt_div(FIXEDPT_ONE, args.motivity);
fpt maximum_sens = args.motivity;
// if sharpness >= 16, use linear clamp for activation function.
// linear clamp means: fpt_clamp(input_speed, -1, 1).
if (use_linear_clamp) {
fpt log_space = fpt_mul(gamma_const, (fpt_ln(input_speed) - log_syncspeed));
if (log_space < -FIXEDPT_ONE) {
return minimum_sens;
}
if (log_space > FIXEDPT_ONE) {
return maximum_sens;
}
return fpt_exp(fpt_mul(log_space, log_motivity));
}
if (input_speed == syncspeed) {
return FIXEDPT_ONE;
}
fpt log_x = fpt_ln(input_speed);
fpt log_diff = log_x - log_syncspeed;
if (log_diff > 0) {
fpt log_space = fpt_mul(gamma_const, log_diff);
fpt exponent =
fpt_pow(fpt_tanh(fpt_pow(log_space, sharpness)), sharpness_recip);
return fpt_exp(fpt_mul(exponent, log_motivity));
} else {
fpt log_space = fpt_mul(-gamma_const, log_diff);
fpt exponent =
-fpt_pow(fpt_tanh(fpt_pow(log_space, sharpness)), sharpness_recip);
return fpt_exp(fpt_mul(exponent, log_motivity));
}
}
#endif
+87
View File
@@ -0,0 +1,87 @@
#ifndef _ACCELK_H_
#define _ACCELK_H_
#include "accel.h"
#include "accel/linear.h"
#include "accel/mode.h"
#include "fixedptc.h"
#include "linux/ktime.h"
#include "params.h"
#include "speed.h"
static struct accel_args collect_args(void) {
struct accel_args accel = {0};
enum accel_mode mode = PARAM_MODE;
accel.tag = mode;
accel.sens_mult = atofp(PARAM_SENS_MULT);
accel.yx_ratio = atofp(PARAM_YX_RATIO);
accel.input_dpi = atofp(PARAM_INPUT_DPI);
accel.angle_rotation_deg = atofp(PARAM_ANGLE_ROTATION);
switch (mode) {
case synchronous: {
accel.args.synchronous.gamma = atofp(PARAM_GAMMA);
accel.args.synchronous.smooth = atofp(PARAM_SMOOTH);
accel.args.synchronous.motivity = atofp(PARAM_MOTIVITY);
accel.args.synchronous.sync_speed = atofp(PARAM_SYNC_SPEED);
break;
}
case natural: {
accel.args.natural.decay_rate = atofp(PARAM_DECAY_RATE);
accel.args.natural.offset = atofp(PARAM_OFFSET);
accel.args.natural.limit = atofp(PARAM_LIMIT);
break;
}
case linear: {
accel.args.linear.accel = atofp(PARAM_ACCEL);
accel.args.linear.offset = atofp(PARAM_OFFSET);
accel.args.linear.output_cap = atofp(PARAM_OUTPUT_CAP);
break;
}
case no_accel:
default: {
}
};
return accel;
}
#if FIXEDPT_BITS == 64
const fpt UNIT_PER_MS = fpt_rconst(1000000); // 1 million nanoseconds
#else
const fpt UNIT_PER_MS = fpt_rconst(1000); // 1 thousand microsends
#endif
static inline void accelerate(int *x, int *y) {
dbg("FIXEDPT_BITS = %d", FIXEDPT_BITS);
static ktime_t last_time;
ktime_t now = ktime_get();
#if FIXEDPT_BITS == 64
s64 unit_time = ktime_to_ns(now - last_time);
dbg("ktime interval -> now (%llu) vs last_ktime (%llu), diff = %llins", now,
last_time, unit_time);
#else
s64 unit_time = ktime_to_us(now - last_time);
dbg("ktime interval -> now (%llu) vs last_ktime (%llu), diff = %llius", now,
last_time, unit_time);
#endif
last_time = now;
fpt _unit_time = fpt_fromint(unit_time);
fpt millisecond = fpt_div(_unit_time, UNIT_PER_MS);
#if FIXEDPT_BITS == 64
dbg("ktime interval -> converting to ns: %lluns -> %sms", unit_time,
fptoa(millisecond));
#else
dbg("ktime interval, converting to us: %lluus -> %sms", unit_time,
fptoa(millisecond));
#endif
return f_accelerate(x, y, millisecond, collect_args());
}
#endif // !_ACCELK_H_
+6
View File
@@ -0,0 +1,6 @@
#include "accel.h"
extern inline struct vector sensitivity_rs(fpt input_speed,
struct accel_args args) {
return sensitivity(input_speed, args);
}
+39
View File
@@ -0,0 +1,39 @@
#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif
#ifdef __KERNEL__
#include <linux/printk.h>
#define dbg(fmt, ...) dbg_k(fmt, __VA_ARGS__)
#else
#include <stdio.h>
#define dbg(fmt, ...) dbg_std(fmt, __VA_ARGS__)
#endif
#if defined __KERNEL__ && defined __clang__
#define dbg_k(fmt, ...) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wstatic-local-in-inline\"") do { \
if (DEBUG_TEST) \
printk(KERN_INFO "%s:%d:%s(): " #fmt "\n", __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} \
while (0) \
_Pragma("clang diagnostic pop")
#elif defined __KERNEL__
#define dbg_k(fmt, ...) \
do { \
if (DEBUG_TEST) \
printk(KERN_INFO "%s:%d:%s(): " #fmt "\n", __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} while (0)
#else
#define dbg_std(fmt, ...) \
do { \
if (DEBUG_TEST) \
fprintf(stderr, "%s:%d:%s(): " fmt "\n", __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} while (0)
#endif
+437
View File
@@ -0,0 +1,437 @@
#ifndef _FIXEDPTC_H_
#define _FIXEDPTC_H_
/*
* fixedptc.h is a 32-bit or 64-bit fixed point numeric library.
*
* The symbol FIXEDPT_BITS, if defined before this library header file
* is included, determines the number of bits in the data type (its "width").
* The default width is 32-bit (FIXEDPT_BITS=32) and it can be used
* on any recent C99 compiler. The 64-bit precision (FIXEDPT_BITS=64) is
* available on compilers which implement 128-bit "long long" types. This
* precision has been tested on GCC 4.2+.
*
* The FIXEDPT_WBITS symbols governs how many bits are dedicated to the
* "whole" part of the number (to the left of the decimal point). The larger
* this width is, the larger the numbers which can be stored in the fixedpt
* number. The rest of the bits (available in the FIXEDPT_FBITS symbol) are
* dedicated to the fraction part of the number (to the right of the decimal
* point).
*
* Since the number of bits in both cases is relatively low, many complex
* functions (more complex than div & mul) take a large hit on the precision
* of the end result because errors in precision accumulate.
* This loss of precision can be lessened by increasing the number of
* bits dedicated to the fraction part, but at the loss of range.
*
* Adventurous users might utilize this library to build two data types:
* one which has the range, and one which has the precision, and carefully
* convert between them (including adding two number of each type to produce
* a simulated type with a larger range and precision).
*
* The ideas and algorithms have been cherry-picked from a large number
* of previous implementations available on the Internet.
* Tim Hartrick has contributed cleanup and 64-bit support patches.
*
* == Special notes for the 32-bit precision ==
* Signed 32-bit fixed point numeric library for the 24.8 format.
* The specific limits are -8388608.999... to 8388607.999... and the
* most precise number is 0.00390625. In practice, you should not count
* on working with numbers larger than a million or to the precision
* of more than 2 decimal places. Make peace with the fact that PI
* is 3.14 here. :)
*/
/*-
* Copyright (c) 2010-2012 Ivan Voras <ivoras@freebsd.org>
* Copyright (c) 2012 Tim Hartrick <tim@edgecast.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "utils.h"
#ifndef FIXEDPT_BITS
#define FIXEDPT_BITS 64
#endif
#ifdef __KERNEL__
#include <linux/math64.h>
#include <linux/stddef.h>
#include <linux/types.h>
#else
#include <stddef.h>
#include <stdint.h>
#endif
#if FIXEDPT_BITS == 32
typedef int32_t fpt;
typedef int64_t fptd;
typedef uint32_t fptu;
typedef uint64_t fptud;
#define FIXEDPT_WBITS 16
#elif FIXEDPT_BITS == 64
#include "Fixed64.utils.h"
typedef int64_t fpt;
typedef __int128_t fptd;
typedef uint64_t fptu;
typedef __uint128_t fptud;
#define FIXEDPT_WBITS 32
#else
#error "FIXEDPT_BITS must be equal to 32 or 64"
#endif
#if FIXEDPT_WBITS >= FIXEDPT_BITS
#error "FIXEDPT_WBITS must be less than or equal to FIXEDPT_BITS"
#endif
#define FIXEDPT_VCSID "$Id$"
#define FIXEDPT_FBITS (FIXEDPT_BITS - FIXEDPT_WBITS)
#define FIXEDPT_FMASK (((fpt)1 << FIXEDPT_FBITS) - 1)
#define fpt_rconst(R) ((fpt)((R) * FIXEDPT_ONE + ((R) >= 0 ? 0.5 : -0.5)))
#define fpt_fromint(I) ((fptd)(I) << FIXEDPT_FBITS)
#define fpt_toint(F) ((F) >> FIXEDPT_FBITS)
#define fpt_add(A, B) ((A) + (B))
#define fpt_sub(A, B) ((A) - (B))
#define fpt_xmul(A, B) ((fpt)(((fptd)(A) * (fptd)(B)) >> FIXEDPT_FBITS))
#define fpt_xdiv(A, B) ((fpt)(((fptd)(A) << FIXEDPT_FBITS) / (fptd)(B)))
#define fpt_fracpart(A) ((fpt)(A) & FIXEDPT_FMASK)
#define FIXEDPT_ONE ((fpt)((fpt)1 << FIXEDPT_FBITS))
#define FIXEDPT_ONE_HALF (FIXEDPT_ONE >> 1)
#define FIXEDPT_TWO (FIXEDPT_ONE + FIXEDPT_ONE)
#define FIXEDPT_PI fpt_rconst(3.14159265358979323846)
#define FIXEDPT_TWO_PI fpt_rconst(2 * 3.14159265358979323846)
#define FIXEDPT_HALF_PI fpt_rconst(3.14159265358979323846 / 2)
#define FIXEDPT_E fpt_rconst(2.7182818284590452354)
#define fpt_abs(A) ((A) < 0 ? -(A) : (A))
/* fpt is meant to be usable in environments without floating point support
* (e.g. microcontrollers, kernels), so we can't use floating point types
* directly. Putting them only in macros will effectively make them optional. */
#define fpt_tofloat(T) \
((float)((T) * ((float)(1) / (float)(1L << FIXEDPT_FBITS))))
#define fpt_todouble(T) \
((double)((T) * ((double)(1) / (double)(1L << FIXEDPT_FBITS))))
/* Multiplies two fpt numbers, returns the result. */
static inline fpt fpt_mul(fpt A, fpt B) {
return (((fptd)A * (fptd)B) >> FIXEDPT_FBITS);
}
#if FIXEDPT_BITS == 64
static inline fpt div128_s64_s64(fpt dividend, fpt divisor) {
fpt high = dividend >> FIXEDPT_FBITS;
fpt low = dividend << FIXEDPT_FBITS;
fpt result = div128_s64_s64_s64(high, low, divisor);
return result;
}
#endif
/* Divides two fpt numbers, returns the result. */
static inline fpt fpt_div(fpt A, fpt B) {
#if FIXEDPT_BITS == 64
return div128_s64_s64(A, B);
#endif
return (((fptd)A << FIXEDPT_FBITS) / (fptd)B);
}
/*
* Note: adding and subtracting fpt numbers can be done by using
* the regular integer operators + and -.
*/
/**
* Convert the given fpt number to a decimal string.
* The max_dec argument specifies how many decimal digits to the right
* of the decimal point to generate. If set to -1, the "default" number
* of decimal digits will be used (2 for 32-bit fpt width, 10 for
* 64-bit fpt width); If set to -2, "all" of the digits will
* be returned, meaning there will be invalid, bogus digits outside the
* specified precisions.
*/
static inline void fpt_str(fpt A, char *str, int max_dec) {
int ndec = 0, slen = 0;
char tmp[12] = {0};
fptud fr, ip;
const fptud one = (fptud)1 << FIXEDPT_BITS;
const fptud mask = one - 1;
if (max_dec == -1)
#if FIXEDPT_BITS == 32
#if FIXEDPT_WBITS > 16
max_dec = 2;
#else
max_dec = 4;
#endif
#elif FIXEDPT_BITS == 64
max_dec = 10;
#else
#error Invalid width
#endif
else if (max_dec == -2)
max_dec = 15;
if (A < 0) {
str[slen++] = '-';
A *= -1;
}
ip = fpt_toint(A);
do {
tmp[ndec++] = '0' + ip % 10;
ip /= 10;
} while (ip != 0);
while (ndec > 0)
str[slen++] = tmp[--ndec];
str[slen++] = '.';
fr = (fpt_fracpart(A) << FIXEDPT_WBITS) & mask;
do {
fr = (fr & mask) * 10;
str[slen++] = '0' + (fr >> FIXEDPT_BITS) % 10;
ndec++;
} while (fr != 0 && ndec < max_dec);
if (ndec > 1 && str[slen - 1] == '0')
str[slen - 1] = '\0'; /* cut off trailing 0 */
else
str[slen] = '\0';
}
/* Converts the given fpt number into a string, using a static
* (non-threadsafe) string buffer */
static inline char *fptoa(const fpt A) {
static char str[25];
#if FIXEDPT_BITS == 64
FP64_ToString(A, str);
#else
fpt_str(A, str, 10);
#endif
return (str);
}
static fpt atofp(char *num_string) {
fptu n = 0;
int sign = 0;
for (int idx = 0; num_string[idx] != '\0'; idx++) {
char c = num_string[idx];
switch (c) {
case ' ':
continue;
case '\n':
continue;
case '-':
sign = 1;
continue;
default:
if (is_digit(c)) {
int digit = c - '0';
n = n * 10 + digit;
} else {
dbg("Hit an unsupported character while parsing a number: '%c'", c);
}
}
}
return sign ? -n : n;
}
/* Returns the square root of the given number, or -1 in case of error */
static inline fpt fpt_sqrt(fpt A) {
int invert = 0;
int iter = FIXEDPT_FBITS;
int i;
fpt l;
if (A < 0)
return (-1);
if (A == 0 || A == FIXEDPT_ONE)
return (A);
if (A < FIXEDPT_ONE && A > 6) {
invert = 1;
A = fpt_div(FIXEDPT_ONE, A);
}
if (A > FIXEDPT_ONE) {
fpt s = A;
iter = 0;
while (s > 0) {
s >>= 2;
iter++;
}
}
/* Newton's iterations */
l = (A >> 1) + 1;
for (i = 0; i < iter; i++)
l = (l + fpt_div(A, l)) >> 1;
if (invert)
return (fpt_div(FIXEDPT_ONE, l));
return (l);
}
/* Returns the sine of the given fpt number.
* Note: the loss of precision is extraordinary! */
static inline fpt fpt_sin(fpt fp) {
int sign = 1;
fpt sqr, result;
const fpt SK[2] = {fpt_rconst(7.61e-03), fpt_rconst(1.6605e-01)};
fp %= 2 * FIXEDPT_PI;
if (fp < 0)
fp = FIXEDPT_PI * 2 + fp;
if ((fp > FIXEDPT_HALF_PI) && (fp <= FIXEDPT_PI))
fp = FIXEDPT_PI - fp;
else if ((fp > FIXEDPT_PI) && (fp <= (FIXEDPT_PI + FIXEDPT_HALF_PI))) {
fp = fp - FIXEDPT_PI;
sign = -1;
} else if (fp > (FIXEDPT_PI + FIXEDPT_HALF_PI)) {
fp = (FIXEDPT_PI << 1) - fp;
sign = -1;
}
sqr = fpt_mul(fp, fp);
result = SK[0];
result = fpt_mul(result, sqr);
result -= SK[1];
result = fpt_mul(result, sqr);
result += FIXEDPT_ONE;
result = fpt_mul(result, fp);
return sign * result;
}
/* Returns the cosine of the given fpt number */
static inline fpt fpt_cos(fpt A) { return (fpt_sin(FIXEDPT_HALF_PI - A)); }
/* Returns the tangent of the given fpt number */
static inline fpt fpt_tan(fpt A) { return fpt_div(fpt_sin(A), fpt_cos(A)); }
/* Returns the value exp(x), i.e. e^x of the given fpt number. */
static inline fpt fpt_exp(fpt fp) {
fpt xabs, k, z, R, xp;
const fpt LN2 = fpt_rconst(0.69314718055994530942);
const fpt LN2_INV = fpt_rconst(1.4426950408889634074);
const fpt EXP_P[5] = {
fpt_rconst(1.66666666666666019037e-01),
fpt_rconst(-2.77777777770155933842e-03),
fpt_rconst(6.61375632143793436117e-05),
fpt_rconst(-1.65339022054652515390e-06),
fpt_rconst(4.13813679705723846039e-08),
};
if (fp == 0)
return (FIXEDPT_ONE);
xabs = fpt_abs(fp);
k = fpt_mul(xabs, LN2_INV);
k += FIXEDPT_ONE_HALF;
k &= ~FIXEDPT_FMASK;
if (fp < 0)
k = -k;
fp -= fpt_mul(k, LN2);
z = fpt_mul(fp, fp);
/* Taylor */
R = FIXEDPT_TWO +
fpt_mul(
z,
EXP_P[0] +
fpt_mul(
z, EXP_P[1] +
fpt_mul(z, EXP_P[2] +
fpt_mul(z, EXP_P[3] +
fpt_mul(z, EXP_P[4])))));
xp = FIXEDPT_ONE + fpt_div(fpt_mul(fp, FIXEDPT_TWO), R - fp);
if (k < 0)
k = FIXEDPT_ONE >> (-k >> FIXEDPT_FBITS);
else
k = FIXEDPT_ONE << (k >> FIXEDPT_FBITS);
return (fpt_mul(k, xp));
}
/* Returns the hyperbolic tangent of the given fpt number */
static inline fpt fpt_tanh(fpt X) {
fpt e_to_the_2_x = fpt_exp(fpt_mul(FIXEDPT_TWO, X));
fpt sinh = e_to_the_2_x - FIXEDPT_ONE;
fpt cosh = e_to_the_2_x + FIXEDPT_ONE;
return fpt_div(sinh, cosh);
}
/* Returns the natural logarithm of the given fpt number. */
static inline fpt fpt_ln(fpt x) {
fpt log2, xi;
fpt f, s, z, w, R;
const fpt LN2 = fpt_rconst(0.69314718055994530942);
const fpt LG[7] = {fpt_rconst(6.666666666666735130e-01),
fpt_rconst(3.999999999940941908e-01),
fpt_rconst(2.857142874366239149e-01),
fpt_rconst(2.222219843214978396e-01),
fpt_rconst(1.818357216161805012e-01),
fpt_rconst(1.531383769920937332e-01),
fpt_rconst(1.479819860511658591e-01)};
if (x < 0)
return (0);
if (x == 0)
return 0xffffffff;
log2 = 0;
xi = x;
while (xi > FIXEDPT_TWO) {
xi >>= 1;
log2++;
}
f = xi - FIXEDPT_ONE;
s = fpt_div(f, FIXEDPT_TWO + f);
z = fpt_mul(s, s);
w = fpt_mul(z, z);
R = fpt_mul(w, LG[1] + fpt_mul(w, LG[3] + fpt_mul(w, LG[5]))) +
fpt_mul(z, LG[0] +
fpt_mul(w, LG[2] + fpt_mul(w, LG[4] + fpt_mul(w, LG[6]))));
return (fpt_mul(LN2, (log2 << FIXEDPT_FBITS)) + f - fpt_mul(s, f - R));
}
/* Returns the logarithm of the given base of the given fpt number */
static inline fpt fpt_log(fpt x, fpt base) {
return (fpt_div(fpt_ln(x), fpt_ln(base)));
}
/* Return the power value (n^exp) of the given fpt numbers */
static inline fpt fpt_pow(fpt n, fpt exp) {
if (exp == 0)
return (FIXEDPT_ONE);
if (n < 0)
return 0;
return (fpt_exp(fpt_mul(fpt_ln(n), exp)));
}
#endif
+93
View File
@@ -0,0 +1,93 @@
#ifndef _INPUT_ECHO_
#define _INPUT_ECHO_
#include "fixedptc.h"
#include "linux/cdev.h"
#include "linux/fs.h"
#include "speed.h"
#include <linux/version.h>
int create_char_device(void);
void destroy_char_device(void);
static struct cdev device;
static struct class *device_class;
static dev_t device_number;
/*
* Convert an int into an array of four/eight bytes, in big endian (MSB first)
*/
static void fpt_to_int_be_bytes(fpt num, char bytes[sizeof(fpt)]) {
#define byte(i) (FIXEDPT_BITS - (i * 8))
bytes[0] = (num >> byte(1)) & 0xFF; // Most significant byte
bytes[1] = (num >> byte(2)) & 0xFF;
bytes[2] = (num >> byte(3)) & 0xFF;
#if FIXEDPT_BITS == 64
if (sizeof(fpt) == 8) {
bytes[3] = (num >> byte(4)) & 0xFF;
bytes[4] = (num >> byte(5)) & 0xFF;
bytes[5] = (num >> byte(6)) & 0xFF;
bytes[6] = (num >> byte(7)) & 0xFF;
bytes[7] = num & 0xFF; // Least significant byte
return;
}
#else
bytes[3] = num & 0xFF; // Least significant byte
#endif
}
static ssize_t read(struct file *f, char __user *user_buffer, size_t size,
loff_t *offset) {
dbg("echoing speed to userspace: %s", fptoa(LAST_INPUT_MOUSE_SPEED));
char be_bytes_for_int[sizeof(fpt)] = {0};
fpt_to_int_be_bytes(LAST_INPUT_MOUSE_SPEED, be_bytes_for_int);
int err =
copy_to_user(user_buffer, be_bytes_for_int, sizeof(be_bytes_for_int));
if (err)
return -EFAULT;
return sizeof(be_bytes_for_int);
}
struct file_operations fops = {.owner = THIS_MODULE, .read = read};
int create_char_device(void) {
int err;
err = alloc_chrdev_region(&device_number, 0, 1, "maccel");
if (err)
return -EIO;
cdev_init(&device, &fops);
cdev_add(&device, device_number, 1);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(6, 4, 0))
device_class = class_create(THIS_MODULE, "maccel");
#else
device.owner = THIS_MODULE;
device_class = class_create("maccel");
#endif
if (IS_ERR(device_class)) {
goto err_free_cdev;
}
device_create(device_class, NULL, device_number, NULL, "maccel");
return 0;
err_free_cdev:
cdev_del(&device);
unregister_chrdev_region(device_number, 1);
return -EIO;
}
void destroy_char_device(void) {
device_destroy(device_class, device_number);
class_destroy(device_class);
cdev_del(&device);
unregister_chrdev_region(device_number, 1);
}
#endif // !_INPUT_ECHO_
+231
View File
@@ -0,0 +1,231 @@
#include "./accel_k.h"
#include "linux/input.h"
#include "mouse_move.h"
#include <linux/hid.h>
#include <linux/version.h>
#if (LINUX_VERSION_CODE < KERNEL_VERSION(6, 11, 0))
#define __cleanup_events 0
#else
#define __cleanup_events 1
#endif
static inline bool rotation_is_enabled(void) {
/* Fast check: the default is "0", so skip atofp unless the string differs */
return PARAM_ANGLE_ROTATION[0] != '0' || PARAM_ANGLE_ROTATION[1] != '\0';
}
/*
* Collect the events EV_REL REL_X and EV_REL REL_Y, once we have both then
* we accelerate the (x, y) vector and set the EV_REL event's value
* through the `value_ptr` of each collected event.
*/
static void event(struct input_handle *handle, struct input_value *value_ptr) {
/* printk(KERN_INFO "type %d, code %d, value %d", type, code, value); */
switch (value_ptr->type) {
case EV_REL: {
dbg("EV_REL => code %d, value %d", value_ptr->code, value_ptr->value);
update_mouse_move(value_ptr);
return;
}
case EV_SYN: {
int x = get_x(MOVEMENT);
int y = get_y(MOVEMENT);
if (x || y) {
dbg("EV_SYN => code %d", value_ptr->code);
/*
* When rotation is active and one axis is missing from this frame,
* point the missing axis to synthetic storage so f_accelerate can
* write the rotated cross-axis component into it. The synthetic
* value is later injected into the event stream by maccel_events().
*
* Only on >= 6.11.0: injection into the event buffer is not
* possible on older kernels, so there is no point in computing
* the cross-axis component.
*/
#if __cleanup_events
if (rotation_is_enabled()) {
ensure_axes_for_rotation();
}
#endif
accelerate(&x, &y);
dbg("accelerated -> (%d, %d)", x, y);
set_x_move(x);
set_y_move(y);
clear_mouse_move();
}
return;
}
default:
return;
}
}
#if __cleanup_events
static unsigned int maccel_events(struct input_handle *handle,
struct input_value *vals,
unsigned int count) {
#else
static void maccel_events(struct input_handle *handle,
const struct input_value *vals, unsigned int count) {
#endif
struct input_value *v;
for (v = vals; v != vals + count; v++) {
event(handle, v);
}
struct input_value *end = vals;
for (v = vals; v != vals + count; v++) {
if (v->type == EV_REL && v->value == NONE_EVENT_VALUE)
continue;
if (end != v) {
*end = *v;
}
end++;
}
int _count = end - vals;
#if __cleanup_events
/*
* Inject synthetic EV_REL events for axes that rotation produced
* but weren't present in the original frame. Insert before SYN_REPORT
* so downstream handlers see a valid event sequence.
*
* Gated to >= 6.11.0 only: on older kernels the handler returns void
* and cannot communicate a new event count to the input subsystem.
* Writing extra events into the buffer on those kernels is undefined
* behavior — the kernel won't deliver them and may behave erratically.
*/
{
struct input_value *syn_pos = NULL;
unsigned int max = handle->dev->max_vals;
/* Find the last SYN_REPORT so we can insert before it */
for (v = vals; v != end; v++) {
if (v->type == EV_SYN && v->code == SYN_REPORT)
syn_pos = v;
}
if (injected_x && synthetic_x_val != NONE_EVENT_VALUE && _count < max) {
if (syn_pos) {
/* Shift SYN_REPORT and everything after it forward by one */
memmove(syn_pos + 1, syn_pos, (end - syn_pos) * sizeof(*syn_pos));
syn_pos->type = EV_REL;
syn_pos->code = REL_X;
syn_pos->value = synthetic_x_val;
syn_pos++;
end++;
_count++;
}
dbg("rotation: injected synthetic REL_X = %d", synthetic_x_val);
}
if (injected_y && synthetic_y_val != NONE_EVENT_VALUE && _count < max) {
if (syn_pos) {
memmove(syn_pos + 1, syn_pos, (end - syn_pos) * sizeof(*syn_pos));
syn_pos->type = EV_REL;
syn_pos->code = REL_Y;
syn_pos->value = synthetic_y_val;
end++;
_count++;
}
dbg("rotation: injected synthetic REL_Y = %d", synthetic_y_val);
}
}
#endif
handle->dev->num_vals = _count;
#if __cleanup_events
return _count;
#endif
}
/* Same as Linux's input_register_handle but we always add the handle to the
* head of handlers */
static int input_register_handle_head(struct input_handle *handle) {
struct input_handler *handler = handle->handler;
struct input_dev *dev = handle->dev;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 7))
/* In 6.11.7 an additional handler pointer was added:
* https://github.com/torvalds/linux/commit/071b24b54d2d05fbf39ddbb27dee08abd1d713f3
*/
if (handler->events)
handle->handle_events = handler->events;
#endif
int error = mutex_lock_interruptible(&dev->mutex);
if (error)
return error;
list_add_rcu(&handle->d_node, &dev->h_list);
mutex_unlock(&dev->mutex);
list_add_tail_rcu(&handle->h_node, &handler->h_list);
if (handler->start)
handler->start(handle);
return 0;
}
static int maccel_connect(struct input_handler *handler, struct input_dev *dev,
const struct input_device_id *id) {
struct input_handle *handle;
int error;
handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
handle->dev = input_get_device(dev);
handle->handler = handler;
handle->name = "maccel";
error = input_register_handle_head(handle);
if (error)
goto err_free_mem;
error = input_open_device(handle);
if (error)
goto err_unregister_handle;
printk(KERN_INFO pr_fmt("maccel flags: DEBUG=%s; FIXEDPT_BITS=%d"),
DEBUG_TEST ? "true" : "false", FIXEDPT_BITS);
printk(KERN_INFO pr_fmt("maccel connecting to device: %s (%s at %s)"),
dev_name(&dev->dev), dev->name ?: "unknown", dev->phys ?: "unknown");
return 0;
err_unregister_handle:
input_unregister_handle(handle);
err_free_mem:
kfree(handle);
return error;
}
static void maccel_disconnect(struct input_handle *handle) {
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
static const struct input_device_id my_ids[] = {
{.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
.evbit = {BIT_MASK(EV_REL)}}, // Match all relative pointer values
{},
};
MODULE_DEVICE_TABLE(input, my_ids);
struct input_handler maccel_handler = {.events = maccel_events,
.connect = maccel_connect,
.disconnect = maccel_disconnect,
.name = "maccel",
.id_table = my_ids};
+35
View File
@@ -0,0 +1,35 @@
#include "./input_handler.h"
#include "input_echo.h"
/*
* We initialize the character driver for the userspace visualizations,
* and we register the input_handler.
*/
static int __init driver_initialization(void) {
int error;
error = create_char_device();
if (error)
return error;
error = input_register_handler(&maccel_handler);
if (error)
goto err_free_chrdev;
return 0;
err_free_chrdev:
destroy_char_device();
return error;
}
static void __exit driver_exit(void) {
input_unregister_handler(&maccel_handler);
destroy_char_device();
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Gnarus-G");
MODULE_DESCRIPTION("Mouse acceleration driver.");
module_init(driver_initialization);
module_exit(driver_exit);
+25
View File
@@ -0,0 +1,25 @@
#ifndef _MATH_H_
#define _MATH_H_
#include "fixedptc.h"
struct vector {
fpt x;
fpt y;
};
static inline fpt magnitude(struct vector v) {
fpt x_square = fpt_mul(v.x, v.x);
fpt y_square = fpt_mul(v.y, v.y);
fpt x_square_plus_y_square = fpt_add(x_square, y_square);
dbg("dx^2 (in) %s", fptoa(x_square));
dbg("dy^2 (in) %s", fptoa(y_square));
dbg("square modulus (in) %s", fptoa(x_square_plus_y_square));
return fpt_sqrt(x_square_plus_y_square);
}
static inline fpt minsd(fpt a, fpt b) { return (a < b) ? a : b; }
#endif // !_MATH_H_
+93
View File
@@ -0,0 +1,93 @@
#include "dbg.h"
#include "linux/input.h"
#include <linux/stddef.h>
#define NONE_EVENT_VALUE 0
typedef struct {
int *x;
int *y;
} mouse_move;
static mouse_move MOVEMENT = {.x = NULL, .y = NULL};
/*
* Track whether we injected synthetic storage for a missing axis.
* When rotation is active and the mouse only reports one axis (e.g. pure
* horizontal movement -> only REL_X), we need a place for f_accelerate
* to write the rotated cross-axis component. These synthetic values
* are later injected into the event stream by maccel_events().
*/
static bool injected_x = false;
static bool injected_y = false;
static int synthetic_x_val = 0;
static int synthetic_y_val = 0;
static inline void update_mouse_move(struct input_value *value) {
switch (value->code) {
case REL_X:
MOVEMENT.x = &value->value;
break;
case REL_Y:
MOVEMENT.y = &value->value;
break;
default:
dbg("bad movement input_value: (code, value) = (%d, %d)", value->code,
value->value);
}
}
static inline int get_x(mouse_move movement) {
if (movement.x == NULL) {
return NONE_EVENT_VALUE;
}
return *movement.x;
}
static inline int get_y(mouse_move movement) {
if (movement.y == NULL) {
return NONE_EVENT_VALUE;
}
return *movement.y;
}
static inline void set_x_move(int value) {
if (MOVEMENT.x == NULL) {
return;
}
*MOVEMENT.x = value;
}
static inline void set_y_move(int value) {
if (MOVEMENT.y == NULL) {
return;
}
*MOVEMENT.y = value;
}
/*
* When rotation is active and one axis is missing from the frame,
* point the missing axis to synthetic storage so f_accelerate can
* write the rotated component into it.
*/
static inline void ensure_axes_for_rotation(void) {
if (MOVEMENT.x == NULL) {
synthetic_x_val = 0;
MOVEMENT.x = &synthetic_x_val;
injected_x = true;
dbg("rotation: injecting synthetic REL_X storage (x=%d)", 0);
}
if (MOVEMENT.y == NULL) {
synthetic_y_val = 0;
MOVEMENT.y = &synthetic_y_val;
injected_y = true;
dbg("rotation: injecting synthetic REL_Y storage (y=%d)", 0);
}
}
static inline void clear_mouse_move(void) {
MOVEMENT.x = NULL;
MOVEMENT.y = NULL;
injected_x = false;
injected_y = false;
}
+90
View File
@@ -0,0 +1,90 @@
#ifndef _PARAM_H_
#define _PARAM_H_
#include "accel/mode.h"
#include "fixedptc.h"
#include "linux/moduleparam.h"
#define RW_USER_GROUP 0664
#define PARAM(param, default_value, desc) \
char *PARAM_##param = #default_value; \
module_param_named(param, PARAM_##param, charp, RW_USER_GROUP); \
MODULE_PARM_DESC(param, desc);
#if FIXEDPT_BITS == 64
PARAM(
SENS_MULT, 4294967296, // 1 << 32
"A factor applied by the sensitivity calculation after ACCEL is applied.");
PARAM(YX_RATIO, 4294967296, // 1 << 32
"A factor (Y/X) by which the final sensitivity calculated is multiplied "
"to produce the sensitivity applied to the Y axis.");
PARAM(INPUT_DPI, 4294967296000, // 1000 << 32
"The DPI of the mouse, used to normalize input to 1000 DPI equivalent "
"for consistent acceleration across different mice.");
#else
PARAM(SENS_MULT, 65536, // 1 << 16
"A factor applied the sensitivity calculation after ACCEL is applied.");
PARAM(YX_RATIO, 65536, // 1 << 16
"A factor (Y/X) by which the final sensitivity calculated is multiplied "
"to produce the sensitivity applied to the Y axis.");
PARAM(INPUT_DPI, 65536000, // 1000 << 16
"The DPI of the mouse, used to normalize input to 1000 DPI equivalent "
"for consistent acceleration across different mice.");
#endif
PARAM(ANGLE_ROTATION, 0,
"Apply rotation (degrees) to the mouse movement input");
// For Linear Mode
PARAM(ACCEL, 0, "Control the sensitivity calculation.");
PARAM(OFFSET, 0, "Input speed threshold (counts/ms) before acceleration begins.");
PARAM(OUTPUT_CAP, 0, "Control the maximum sensitivity.");
// For Natural Mode
#if FIXEDPT_BITS == 64
PARAM(DECAY_RATE, 429496730, // 0.1 << 32
"Decay rate of the Natural curve.");
PARAM(LIMIT, 6442450944, // 1.5 << 32
"Limit of the Natural curve.");
#else
PARAM(DECAY_RATE, 6554, // 0.1 << 16
"Decay rate of the Natural curve");
PARAM(LIMIT, 98304, // 1.5 << 16
"Limit of the Natural curve");
#endif
// For Synchronous Mode
#if FIXEDPT_BITS == 64
PARAM(GAMMA, 4294967296, // 1 << 32
"Control how fast you get from low to fast around the midpoint");
PARAM(SMOOTH, 2147483648, // 0.5 << 32
"Control the suddeness of the sensitivity increase.");
PARAM(MOTIVITY, 6442450944, // 1.5 << 32
"Set the maximum sensitivity while also setting the minimum to "
"1/MOTIVITY");
PARAM(SYNC_SPEED, 21474836480, // 5 << 32
"Set The middle sensitivity between you min and max sensitivity");
#else
PARAM(GAMMA, 65536, // 1 << 16
"Control how fast you get from low to fast around the midpoint");
PARAM(SMOOTH, 32768, // 0.5 << 16
"Control the suddeness of the sensitivity increase.");
PARAM(MOTIVITY, 98304, // 1.5 << 16
"Set the maximum sensitivity while also setting the minimum to "
"1/MOTIVITY");
PARAM(SYNC_SPEED, 327680, // 5 << 16
"Set The middle sensitivity between you min and max sensitivity");
#endif
// Flags
#define PARAM_FLAG(param, default_value, desc) \
unsigned char PARAM_##param = default_value; \
module_param_named(param, PARAM_##param, byte, RW_USER_GROUP); \
MODULE_PARM_DESC(param, desc);
PARAM_FLAG(MODE, linear, "Desired type of acceleration.");
#endif // !_PARAM_H_
+34
View File
@@ -0,0 +1,34 @@
#ifndef __SPEED_H__
#define __SPEED_H__
#include "dbg.h"
#include "fixedptc.h"
#include "math.h"
/**
* Track this to enable the UI to show the last noted
* input counts/ms (speed).
*/
static fpt LAST_INPUT_MOUSE_SPEED = 0;
static inline fpt input_speed(fpt dx, fpt dy, fpt time_ms) {
fpt distance = magnitude((struct vector){dx, dy});
if (distance == -1) {
dbg("distance calculation failed: t = %s", fptoa(time_ms));
return 0;
}
dbg("distance (in) %s", fptoa(distance));
fpt speed = fpt_div(distance, time_ms);
LAST_INPUT_MOUSE_SPEED = speed;
dbg("time interval %s", fptoa(time_ms));
dbg("speed (in) %s", fptoa(speed));
return speed;
}
#endif // !__SPEED_H__
+187
View File
@@ -0,0 +1,187 @@
#include "../accel.h"
#include "test_utils.h"
#include <stdio.h>
static int test_acceleration(const char *filename, struct accel_args args) {
const int LINE_LEN = 26;
const int MIN = -128;
const int MAX = 127;
char content[256 * 256 * LINE_LEN + 1];
strcpy(content, ""); // initialize as an empty string
for (int x = MIN; x < MAX; x++) {
for (int y = MIN; y < MAX; y++) {
int x_out = x;
int y_out = y;
f_accelerate(&x_out, &y_out, FIXEDPT_ONE, args);
char curr_debug_print[LINE_LEN];
sprintf(curr_debug_print, "(%d, %d) => (%d, %d)\n", x, y, x_out, y_out);
strcat(content, curr_debug_print);
}
}
assert_snapshot(filename, content);
return 0;
}
static int test_linear_acceleration(const char *filename, fpt param_sens_mult,
fpt param_yx_ratio, fpt param_accel,
fpt param_offset, fpt param_output_cap) {
struct linear_curve_args _args =
(struct linear_curve_args){.accel = param_accel,
.offset = param_offset,
.output_cap = param_output_cap};
struct accel_args args = {
.sens_mult = param_sens_mult,
.yx_ratio = param_yx_ratio,
.input_dpi = fpt_fromint(1000),
.tag = linear,
.args = (union __accel_args){.linear = _args},
};
return test_acceleration(filename, args);
}
static int test_natural_acceleration(const char *filename, fpt param_sens_mult,
fpt param_yx_ratio, fpt param_decay_rate,
fpt param_offset, fpt param_limit) {
struct natural_curve_args _args =
(struct natural_curve_args){.decay_rate = param_decay_rate,
.offset = param_offset,
.limit = param_limit};
struct accel_args args = {
.sens_mult = param_sens_mult,
.yx_ratio = param_yx_ratio,
.input_dpi = fpt_fromint(1000),
.tag = natural,
.args = (union __accel_args){.natural = _args},
};
return test_acceleration(filename, args);
}
static int test_synchronous_acceleration(const char *filename,
fpt param_sens_mult,
fpt param_yx_ratio, fpt param_gamma,
fpt param_smooth, fpt param_motivity,
fpt param_sync_speed) {
struct synchronous_curve_args _args =
(struct synchronous_curve_args){.gamma = param_gamma,
.smooth = param_smooth,
.motivity = param_motivity,
.sync_speed = param_sync_speed};
struct accel_args args = {
.sens_mult = param_sens_mult,
.yx_ratio = param_yx_ratio,
.input_dpi = fpt_fromint(1000),
.tag = synchronous,
.args = (union __accel_args){.synchronous = _args},
};
return test_acceleration(filename, args);
}
static int test_no_accel_acceleration(const char *filename, fpt param_sens_mult,
fpt param_yx_ratio) {
struct no_accel_curve_args _args = (struct no_accel_curve_args){};
struct accel_args args = {
.sens_mult = param_sens_mult,
.yx_ratio = param_yx_ratio,
.input_dpi = fpt_fromint(1000),
.tag = no_accel,
.args = (union __accel_args){.no_accel = _args},
};
return test_acceleration(filename, args);
}
static int test_rotation_no_accel(const char *filename, fpt param_sens_mult,
fpt param_angle_deg) {
struct no_accel_curve_args _args = (struct no_accel_curve_args){};
struct accel_args args = {
.sens_mult = param_sens_mult,
.yx_ratio = FIXEDPT_ONE,
.input_dpi = fpt_fromint(1000),
.angle_rotation_deg = param_angle_deg,
.tag = no_accel,
.args = (union __accel_args){.no_accel = _args},
};
return test_acceleration(filename, args);
}
#define test_linear(sens_mult, yx_ratio, accel, offset, cap) \
assert(test_linear_acceleration( \
"SENS_MULT-" #sens_mult "-ACCEL-" #accel "-OFFSET" #offset \
"-OUTPUT_CAP-" #cap ".snapshot", \
fpt_rconst(sens_mult), fpt_rconst(yx_ratio), fpt_rconst(accel), \
fpt_rconst(offset), fpt_rconst(cap)) == 0);
#define test_natural(sens_mult, yx_ratio, decay_rate, offset, limit) \
assert(test_natural_acceleration( \
"Natural__SENS_MULT-" #sens_mult "-DECAY_RATE-" #decay_rate \
"-OFFSET" #offset "-LIMIT-" #limit ".snapshot", \
fpt_rconst(sens_mult), fpt_rconst(yx_ratio), \
fpt_rconst(decay_rate), fpt_rconst(offset), \
fpt_rconst(limit)) == 0);
#define test_synchronous(sens_mult, yx_ratio, gamma, smooth, motivity, \
sync_speed) \
assert(test_synchronous_acceleration( \
"Synchronous__SENS_MULT-" #sens_mult "-GAMMA-" #gamma \
"-SMOOTH" #smooth "-MOTIVITY-" #motivity \
"-SYNC_SPEED-" #sync_speed ".snapshot", \
fpt_rconst(sens_mult), fpt_rconst(yx_ratio), fpt_rconst(gamma), \
fpt_rconst(smooth), fpt_rconst(motivity), \
fpt_rconst(sync_speed)) == 0);
#define test_no_accel(sens_mult, yx_ratio) \
assert(test_no_accel_acceleration( \
"NoAccel__SENS_MULT-" #sens_mult "-YX_RATIO-" #yx_ratio \
".snapshot", \
fpt_rconst(sens_mult), fpt_rconst(yx_ratio)) == 0);
#define test_rotation(sens_mult, angle_deg) \
assert(test_rotation_no_accel( \
"Rotation__SENS_MULT-" #sens_mult "-ANGLE-" #angle_deg \
".snapshot", \
fpt_rconst(sens_mult), fpt_rconst(angle_deg)) == 0);
int main(void) {
test_linear(1, 1, 0, 0, 0);
test_linear(1, 1, 0.3, 2, 2);
test_linear(0.1325, 1, 0.3, 21.333333, 2);
test_linear(0.1875, 1, 0.05625, 10.6666666, 2);
test_linear(0.0917, 1, 0.002048, 78.125, 2.0239);
test_linear(0.07, 1.15, 0.055, 21, 3);
test_natural(1, 1, 0, 0, 0);
test_natural(1, 1, 0.1, 0, 0);
test_natural(1, 1, 0.1, 8, 0);
test_natural(1, 1, 0.03, 8, 1.5);
test_synchronous(1, 1.15, 0.8, 0.5, 1.5, 32);
test_no_accel(1, 1);
test_no_accel(0.5, 1.5);
/* Rotation tests: verify cross-axis output when one axis is 0.
* At 45 degrees, (10, 0) should produce roughly (7, 7) - not (10, 0).
* At 90 degrees, (10, 0) should produce roughly (0, 10). */
test_rotation(1, 45);
test_rotation(1, 90);
print_success;
}
+41
View File
@@ -0,0 +1,41 @@
#include "../fixedptc.h"
#include "./test_utils.h"
#include <assert.h>
#include <stdio.h>
#include <time.h>
void test_eq(char *value, double expected) {
fpt n = atofp(value);
double actual = fpt_todouble(n);
dbg("actual: (%li) %.15f, vs expected: %.15f\n", n, actual, expected);
assert(actual == expected);
}
void super_tiny_micro_minuscule_bench() {
int iterations = 100000;
double sum = 0;
for (int i = 0; i < iterations; i++) {
struct timespec begin, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &begin);
fpt n = atofp("1826512586328");
dbg("atofp(\"1826512586328\") = %li\n", n);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
sum += (double)(end.tv_nsec - begin.tv_nsec);
}
double avg = sum / iterations;
printf(" Avg run time is %fns\n", avg);
}
int main(void) {
test_eq("1073741824", 0.25);
test_eq("536870912", 0.125);
test_eq("1342177280", 0.3125);
test_eq("-335007449088", -78);
print_success;
super_tiny_micro_minuscule_bench();
}
+45
View File
@@ -0,0 +1,45 @@
#include "../dbg.h"
#include "../fixedptc.h"
#include "test_utils.h"
#include <assert.h>
#include <stdint.h>
void test_custom_division_against_fixedpt(double a, double b) {
#if FIXEDPT_BITS == 32
return;
#else
fpt n = fpt_rconst(a);
fpt divisor = fpt_rconst(b);
fpt quotient = div128_s64_s64(n, divisor);
fpt quotient1 = fpt_xdiv(n, divisor);
double actual = fpt_todouble(quotient);
double expected = fpt_todouble(quotient1);
dbg("actual = (%li) -> %.10f", quotient, actual);
dbg("expect = (%li) -> %.10f", quotient1, expected);
assert(actual == expected);
#endif
}
int main(void) {
test_custom_division_against_fixedpt(57, 5.5);
test_custom_division_against_fixedpt(0, 2.57);
test_custom_division_against_fixedpt(-1, 3);
test_custom_division_against_fixedpt(-128, 4);
test_custom_division_against_fixedpt(127, 1.5);
/* test_custom_division_against_fixedpth(135, 0); */ // You only crash once!
print_success;
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
#include "../fixedptc.h"
#include "test_utils.h"
#include <assert.h>
#include <linux/limits.h>
#include <unistd.h>
int assert_string_value(char *filename, double value) {
fpt v = fpt_rconst(value);
char *_v = fptoa(v);
dbg("to_string %f = %s", value, _v);
assert_snapshot(filename, _v);
return 0;
}
#define test_str(value) \
assert(assert_string_value(__FILE_NAME__ "_" #value ".snapshot", value) == 0)
int main(void) {
test_str(0.25);
test_str(0.125);
test_str(0.3125);
test_str(-785);
print_success;
}
+48
View File
@@ -0,0 +1,48 @@
#include "../speed.h"
#include "./test_utils.h"
#include <stdio.h>
int assert_string_value(char *filename, double x, double y, double t) {
fpt dx = fpt_rconst(x);
fpt dy = fpt_rconst(y);
fpt dt = fpt_rconst(t);
dbg("in (%f, %f)", x, y);
dbg("in: x (fpt conversion) %s", fptoa(x));
dbg("in: y (fpt conversion) %s", fptoa(y));
fpt s = input_speed(dx, dy, dt);
double res = fpt_todouble(s);
dbg("(%f, %f) dt = %f -> %f\n", x, y, t, res);
char content[100];
sprintf(content, "(sqrt(%f, %f) / %f) = %f\n", x, y, t, res);
assert_snapshot(filename, content);
return 0;
}
#define test(x, y, time) \
assert(assert_string_value(__FILE_NAME__ "_sqrt_" #x "_" #y "_" #time \
".snapshot", \
x, y, time) == 0)
int main(void) {
test(1, 1, 1);
test(1, 21, 1);
test(64, -37, 1);
test(1, 4, 1);
test(-1, 1, 4);
test(1, 0, 100);
test(1, -1, 100);
test(-1, -24, 1);
print_success;
return 0;
}
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
for test in tests/*.test.c; do
if [[ ! $test =~ $TEST_NAME ]]; then
continue
fi
gcc ${test} -o maccel_test -lm $DRIVER_CFLAGS || exit 1
./maccel_test || exit 1
rm maccel_test
done
@@ -0,0 +1 @@
-785.000000000
@@ -0,0 +1 @@
0.125000000
@@ -0,0 +1 @@
0.250000000
@@ -0,0 +1 @@
0.312500000
@@ -0,0 +1 @@
(sqrt(-1.000000, -24.000000) / 1.000000) = 24.020824
@@ -0,0 +1 @@
(sqrt(-1.000000, 1.000000) / 4.000000) = 0.353553
@@ -0,0 +1 @@
(sqrt(1.000000, -1.000000) / 100.000000) = 0.014142
@@ -0,0 +1 @@
(sqrt(1.000000, 0.000000) / 100.000000) = 0.010000
@@ -0,0 +1 @@
(sqrt(1.000000, 1.000000) / 1.000000) = 1.414214
@@ -0,0 +1 @@
(sqrt(1.000000, 21.000000) / 1.000000) = 21.023796
@@ -0,0 +1 @@
(sqrt(1.000000, 4.000000) / 1.000000) = 4.123106
@@ -0,0 +1 @@
(sqrt(64.000000, -37.000000) / 1.000000) = 73.925638
+137
View File
@@ -0,0 +1,137 @@
#include <assert.h>
#include <linux/limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
static int diff(const char *content, const char *filename) {
int pipe_fd[2];
pid_t child_pid;
// Create a pipe for communication
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
// Fork the process
if ((child_pid = fork()) == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { // Child process
// Close the write end of the pipe
close(pipe_fd[1]);
// Redirect stdin to read from the pipe
dup2(pipe_fd[0], STDIN_FILENO);
// Execute a command (e.g., "wc -l")
execlp("diff", "diff", "-u", "--color", filename, "-", NULL);
// If execlp fails
perror("Exec failed");
exit(EXIT_FAILURE);
} else { // Parent process
// Close the read end of the pipe
close(pipe_fd[0]);
// Write data to the child process
if (write(pipe_fd[1], content, strlen(content)) == -1) {
perror("failed to write content to the pipe for diff");
}
close(pipe_fd[1]);
// Wait for the child process to finish
wait(NULL);
}
return 0;
}
static int get_current_working_dir(char *buf, size_t buf_size) {
if (getcwd(buf, buf_size) != NULL) {
return 0;
}
perror("getcwd() error");
return 1;
}
static char *create_snapshot_file_path(const char *filename) {
char cwd[PATH_MAX];
if (get_current_working_dir(cwd, PATH_MAX)) {
return NULL;
};
static char filepath[PATH_MAX];
sprintf(filepath, "%s/tests/snapshots/%s", cwd, filename);
return filepath;
}
static void assert_snapshot(const char *__filename, const char *content) {
char *filename = create_snapshot_file_path(__filename);
if (filename == NULL) {
fprintf(stderr, "failed to create snapshot file: %s\n", filename);
exit(1);
}
int snapshot_file_exists = access(filename, F_OK) != -1;
FILE *snapshot_file;
if (snapshot_file_exists) {
snapshot_file = fopen(filename, "r");
} else {
snapshot_file = fopen(filename, "w");
}
if (snapshot_file == NULL) {
fprintf(stderr, "failed to open or create the snapshot file: %s\n",
filename);
exit(1);
}
if (snapshot_file_exists) {
struct stat stats;
int file_size;
stat(filename, &stats);
file_size = stats.st_size;
char *snapshot = (char *)malloc(stats.st_size + 1);
if (snapshot == NULL) {
fprintf(stderr,
"failed to allocate %zd bytes of a string for the snapshot "
"content in file: %s\n",
stats.st_size, filename);
exit(1);
}
size_t bytes_read = fread(snapshot, 1, file_size, snapshot_file);
if (bytes_read != file_size) {
fprintf(stderr, "failed to read a snapshot file %s\n", filename);
exit(1);
}
snapshot[file_size] = 0; // null byte terminator
int string_test_diff = strcmp(snapshot, content);
diff(content, filename);
/* dbg("diff in content = %d: snapshot '%s' vs now '%s'", string_test, */
/* snapshot, content); */
assert(string_test_diff == 0);
} else {
fprintf(snapshot_file, "%s", content);
printf("created a snapshot file %s\n", filename);
}
fclose(snapshot_file);
}
#define print_success printf("[%s]\t\tAll tests passed!\n", __FILE_NAME__)
+28
View File
@@ -0,0 +1,28 @@
#ifndef _UTILS_H_
#define _UTILS_H_
#ifdef __KERNEL__
#include <linux/types.h>
#else
#include <stdint.h>
#endif
#include "dbg.h"
static inline int64_t div128_s64_s64_s64(int64_t high, int64_t low,
int64_t divisor) {
int64_t result;
// s.high.low
// high -> rdx
// low -> rax
uint64_t remainder;
__asm__("idivq %[B]"
: "=a"(result), "=d"(remainder)
: [B] "r"(divisor), "a"(low), "d"(high));
return result;
}
static inline int is_digit(char c) { return '0' <= c && c <= '9'; }
#endif
Executable
+203
View File
@@ -0,0 +1,203 @@
#!/bin/sh
BRANCH=${BRANCH:-""}
DEBUG=${DEBUG:-0}
BUILD_CLI_FROM_SOURCE=${BUILD_CLI_FROM_SOURCE:-0}
set -e
bold_start() {
printf "\e[1m"
}
bold_end() {
printf "\e[22m"
}
print_bold() {
bold_start
printf "$1"
bold_end
}
print_yellow() {
printf "\e[33m$1\e[0m"
}
print_green() {
printf "\e[32m$1\e[0m"
}
underline_start() {
printf "\e[4m"
}
underline_end() {
printf "\e[24m\n"
}
get_current_version(){
if ! which maccel &>/dev/null; then
return
fi
maccel -V | awk '{ print $2 }'
}
get_version() {
wget -qO- https://github.com/Gnarus-G/maccel/releases/latest | grep -oP 'v\d+\.\d+\.\d+' | tail -n 1 | cut -c 2-
}
CURR_VERSION=$(get_current_version)
VERSION=$(get_version)
set -e
setup_dirs() {
rm -rf /opt/maccel && mkdir -p /opt/maccel
cd /opt/maccel
if [ -n "$BRANCH" ]; then
print_bold "Will do an install, using the branch: $BRANCH\n"
git clone --depth 1 --no-single-branch https://github.com/Gnarus-G/maccel.git .
git switch $BRANCH
else
git clone --depth 1 https://github.com/Gnarus-G/maccel.git .
fi
}
version_update_warning() {
if [ -z "$CURR_VERSION" ]; then
return
fi
MARKER_VERSION="0.4.0"
if [ "$CURR_VERSION" = "$MARKER_VERSION" ]; then
return
fi
if [[ "$CURR_VERSION" < "$MARKER_VERSION" ]]; then
print_yellow $(print_bold "ATTENTION!")
printf "\n\n"
print_yellow "The precision for the processed values has been updated since version '$CURR_VERSION';\n"
EMPHASIS=$(print_bold "MUST re-enter your parameter values in maccel")
print_yellow "This means that you $EMPHASIS.\n"
print_yellow "Otherwise your curve and mouse movement won't behave as expected.\n"
printf "\nHere were your values as maccel understands them in '$CURR_VERSION':\n"
print_bold "SENS MULT: "
maccel get param sens-mult
print_bold "ACCEL: "
maccel get param accel
print_bold "OFFSET: "
maccel get param offset
print_bold "OUTPUT CAP: "
maccel get param output-cap
fi
}
install_udev_rules() {
make udev_uninstall
make udev_install
}
install_driver_dkms() {
dkms_version=$(cat PKGBUILD | grep "pkgver=" | grep -oP '\d.\d.\d')
! sudo rmmod maccel 2>/dev/null; # It's obviously okay if this fails
# Uninstall if this version already exists
test -n "$(sudo dkms status maccel/$dkms_version)" && {
sudo dkms remove maccel/$dkms_version
}
# Install Driver
install -Dm 644 "$(pwd)/dkms.conf" "/usr/src/maccel-${dkms_version}/dkms.conf"
DEBUG_CFLAGS=""
if [ $DEBUG -eq 1 ]; then
print_bold "Debug build enabled\n"
DEBUG_CFLAGS="-g -DDEBUG"
fi
# Set name and version
sudo sed -e "s/@_PKGNAME@/maccel/" \
-e "s/@PKGVER@/${dkms_version}/" \
-e "s/@DRIVER_CFLAGS@/'${DEBUG_CFLAGS}'/" \
-i "/usr/src/maccel-${dkms_version}/dkms.conf"
sudo cp -r "$(pwd)/driver/." "/usr/src/maccel-${dkms_version}/"
sudo dkms install --force "maccel/${dkms_version}"
# Note(Gnarus):
# This wouldn't ok in the .install file as noted in https://wiki.archlinux.org/title/DKMS_package_guidelines#Module_loading_automatically_in_.install
# But I think it's ok here.
sudo modprobe maccel
}
install_cli() {
if [ $(getconf LONG_BIT) -lt 64 ]; then
BUILD_CLI_FROM_SOURCE=1
fi
if [ $BUILD_CLI_FROM_SOURCE -eq 1 ]; then
export RUSTUP_TOOLCHAIN=stable
cargo build --bin maccel --release
sudo install -m 755 `pwd`/target/release/maccel /usr/local/bin/maccel
else
print_bold "Preparing to download and install the CLI tool...\n"
printf "If you want to build the CLI tool from source, then next time run: \n"
print_bold " curl -fsSL https://maccel.org/install.sh | sudo BUILD_CLI_FROM_SOURCE=1 sh \n"
curl -fsSL https://github.com/Gnarus-G/maccel/releases/download/v$VERSION/maccel-cli.tar.gz -o maccel-cli.tar.gz
tar -zxvf maccel-cli.tar.gz maccel_v$VERSION/maccel
mkdir -p bin
sudo install -m 755 -v -D maccel_v$VERSION/maccel* bin/
sudo ln -vfs $(pwd)/bin/maccel* /usr/local/bin/
fi
sudo groupadd -f maccel
}
# ---- Install Process ----
ATTENTION=$(version_update_warning)
underline_start
print_bold "\nFetching the maccel github repo"
underline_end
setup_dirs
underline_start
print_bold "\nInstalling udev rules..."
underline_end
install_udev_rules
underline_start
print_bold "\nInstalling the driver (kernel module)"
underline_end
install_driver_dkms
underline_start
print_bold "\nInstalling the CLI"
underline_end
install_cli
print_bold $(print_green "[Recommended]")
print_bold ' Add yourself to the "maccel" group\n'
print_bold $(print_green "[Recommended]")
print_bold ' usermod -aG maccel $USER\n'
if [ -n "$ATTENTION" ]; then
printf "\n$ATTENTION\n"
fi
+16
View File
@@ -0,0 +1,16 @@
post_install() {
echo ''
echo ' Add yourself to the "maccel" group and install the module!'
echo ' usermod -aG maccel $USER;'
echo ' modprobe maccel;'
echo ''
}
post_upgrade() {
echo ''
echo ' Remember to reload the module!'
echo ' rmmod maccel && modprobe maccel'
echo ''
}
# post_remove() { }
+1
View File
@@ -0,0 +1 @@
g maccel - -
+275
View File
@@ -0,0 +1,275 @@
# NixOS module for maccel mouse acceleration driver
{
config,
lib,
pkgs,
...
}:
with lib; let
cfg = config.hardware.maccel;
# Extract version from PKGBUILD
pkgbuildContent = builtins.readFile ./PKGBUILD;
kernelModuleVersion = builtins.head (builtins.match ".*pkgver=([^[:space:]]+).*" pkgbuildContent);
# Extract version from cli/Cargo.toml
cliCargoToml = builtins.fromTOML (builtins.readFile ./cli/Cargo.toml);
cliVersion = cliCargoToml.package.version;
# Convert float to fixed-point integer (64-bit, 32 fractional bits)
fixedPointScale = 4294967296; # 2^32
toFixedPoint = value: builtins.floor (value * fixedPointScale + 0.5);
# Mode enum mapping (from driver/accel/mode.h)
modeMap = {
linear = 0;
natural = 1;
synchronous = 2;
no_accel = 3;
};
# Parameter mapping (from driver/params.h)
parameterMap = {
# Common parameters
SENS_MULT = cfg.parameters.sensMultiplier;
YX_RATIO = cfg.parameters.yxRatio;
INPUT_DPI = cfg.parameters.inputDpi;
ANGLE_ROTATION = cfg.parameters.angleRotation;
MODE = cfg.parameters.mode;
# Linear mode parameters
ACCEL = cfg.parameters.acceleration;
OFFSET = cfg.parameters.offset;
OUTPUT_CAP = cfg.parameters.outputCap;
# Natural mode parameters
DECAY_RATE = cfg.parameters.decayRate;
LIMIT = cfg.parameters.limit;
# Synchronous mode parameters
GAMMA = cfg.parameters.gamma;
SMOOTH = cfg.parameters.smooth;
MOTIVITY = cfg.parameters.motivity;
SYNC_SPEED = cfg.parameters.syncSpeed;
};
# Generate modprobe parameter string
kernelModuleParams = let
validParams = filterAttrs (_: v: v != null) parameterMap;
formatParam = name: value:
if name == "MODE"
then "${name}=${toString (modeMap.${value})}"
else "${name}=${toString (toFixedPoint value)}";
in
concatStringsSep " " (mapAttrsToList formatParam validParams);
# Build kernel module
maccel-kernel-module = config.boot.kernelPackages.callPackage ({
lib,
stdenv,
kernel,
}:
stdenv.mkDerivation rec {
pname = "maccel-dkms";
version = kernelModuleVersion;
src = ./.;
nativeBuildInputs = kernel.moduleBuildDependencies;
makeFlags =
[
"KVER=${kernel.modDirVersion}"
"KDIR=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
"DRIVER_CFLAGS=-DFIXEDPT_BITS=64"
]
++ optionals cfg.debug ["DRIVER_CFLAGS+=-g -DDEBUG"];
preBuild = "cd driver";
installPhase = ''
mkdir -p $out/lib/modules/${kernel.modDirVersion}/kernel/drivers/usb
cp maccel.ko $out/lib/modules/${kernel.modDirVersion}/kernel/drivers/usb/
'';
meta = with lib; {
description = "Mouse acceleration driver and kernel module for Linux.";
homepage = "https://www.maccel.org/";
license = licenses.gpl2Plus;
platforms = platforms.linux;
};
}) {};
# Optional CLI tools
maccel-cli = pkgs.rustPlatform.buildRustPackage rec {
pname = "maccel-cli";
version = cliVersion;
src = ./.;
cargoLock.lockFile = "${src}/Cargo.lock";
cargoBuildFlags = ["--bin" "maccel"];
meta = with lib; {
description = "CLI and TUI tools for configuring maccel.";
homepage = "https://www.maccel.org/";
license = licenses.gpl2Plus;
platforms = platforms.linux;
};
};
in {
options.hardware.maccel = {
enable = mkEnableOption "Enable maccel mouse acceleration driver (kernel module). Parameters must be configured via `hardware.maccel.parameters`.";
debug = mkOption {
type = types.bool;
default = false;
description = "Enable debug build of the kernel module.";
};
enableCli = mkOption {
type = types.bool;
default = false;
description = "Install CLI and TUI tools for real-time parameter tuning. You may add your user to the `maccel` group using `users.groups.maccel.members = [\"your_username\"];` to run maccel CLI/TUI without sudo. Note: Changes made via CLI/TUI are temporary and do not persist across reboots. Use this to discover optimal parameter values, then apply them permanently via `hardware.maccel.parameters`.";
};
parameters = {
# Common parameters
sensMultiplier = mkOption {
type = types.nullOr types.float;
default = null;
description = "Sensitivity multiplier applied after acceleration calculation.";
};
yxRatio = mkOption {
type = types.nullOr types.float;
default = null;
description = "Y/X ratio - factor by which Y-axis sensitivity is multiplied.";
};
inputDpi = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x > 0.0)
// {description = "positive float";});
default = null;
description = "DPI of the mouse, used to normalize effective DPI. Must be positive.";
};
angleRotation = mkOption {
type = types.nullOr types.float;
default = null;
description = "Apply rotation in degrees to mouse movement input.";
};
mode = mkOption {
type = types.nullOr (types.enum ["linear" "natural" "synchronous" "no_accel"]);
default = null;
description = "Acceleration mode.";
};
# Linear mode parameters
acceleration = mkOption {
type = types.nullOr types.float;
default = null;
description = "Linear acceleration factor.";
};
offset = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x >= 0.0)
// {description = "non-negative float";});
default = null;
description = "Input speed past which to allow acceleration. Cannot be negative.";
};
outputCap = mkOption {
type = types.nullOr types.float;
default = null;
description = "Maximum sensitivity multiplier cap.";
};
# Natural mode parameters
decayRate = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x > 0.0)
// {description = "positive float";});
default = null;
description = "Decay rate of the Natural acceleration curve. Must be positive.";
};
limit = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x >= 1.0)
// {description = "float >= 1.0";});
default = null;
description = "Limit of the Natural acceleration curve. Cannot be less than 1.";
};
# Synchronous mode parameters
gamma = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x > 0.0)
// {description = "positive float";});
default = null;
description = "Controls how fast you get from low to fast around the midpoint. Must be positive.";
};
smooth = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x >= 0.0 && x <= 1.0)
// {description = "float between 0.0 and 1.0";});
default = null;
description = "Controls the suddenness of the sensitivity increase. Must be between 0 and 1.";
};
motivity = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x > 1.0)
// {description = "float > 1.0";});
default = null;
description = "Sets max sensitivity while setting min to 1/motivity. Must be greater than 1.";
};
syncSpeed = mkOption {
type =
types.nullOr (types.addCheck types.float (x: x > 0.0)
// {description = "positive float";});
default = null;
description = "Sets the middle sensitivity between min and max sensitivity. Must be positive.";
};
};
};
config = mkIf cfg.enable {
# Add kernel module
boot.extraModulePackages = [maccel-kernel-module];
# Load module with parameters
boot.kernelModules = ["maccel"];
boot.extraModprobeConfig = mkIf (kernelModuleParams != "") ''
options maccel ${kernelModuleParams}
'';
# Create maccel group
users.groups.maccel = {};
# Install CLI tools if requested
environment.systemPackages = mkIf cfg.enableCli [maccel-cli];
# Create reset scripts directory
systemd.tmpfiles.rules = mkIf cfg.enableCli [
"d /var/opt/maccel/resets 0775 root maccel"
];
# Add udev rules
services.udev.extraRules = mkIf cfg.enableCli ''
# Set sysfs parameter permissions
ACTION=="add", SUBSYSTEM=="module", DEVPATH=="/module/maccel", \
RUN+="${pkgs.coreutils}/bin/chgrp -R maccel /sys/module/maccel/parameters"
# Set /dev/maccel character device permissions
ACTION=="add", KERNEL=="maccel", \
GROUP="maccel", MODE="0640"
'';
};
}
+21
View File
@@ -0,0 +1,21 @@
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store
+4
View File
@@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}
+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}
+54
View File
@@ -0,0 +1,54 @@
# Astro Starter Kit: Basics
```sh
npm create astro@latest -- --template basics
```
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/astro/tree/latest/examples/basics)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/astro/tree/latest/examples/basics)
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/withastro/astro?devcontainer_path=.devcontainer/basics/devcontainer.json)
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
![just-the-basics](https://github.com/withastro/astro/assets/2244813/a0a5533c-a856-4198-8470-2d67b1d7c554)
## 🚀 Project Structure
Inside of your Astro project, you'll see the following folders and files:
```text
/
├── public/
│ └── favicon.svg
├── src/
│ ├── components/
│ │ └── Card.astro
│ ├── layouts/
│ │ └── Layout.astro
│ └── pages/
│ └── index.astro
└── package.json
```
Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
Any static assets, like images, can be placed in the `public/` directory.
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from "astro/config";
import tailwind from "@astrojs/tailwind";
// https://astro.build/config
export default defineConfig({
site: "https://www.maccel.org",
integrations: [tailwind()],
});
Executable
BIN
View File
Binary file not shown.
+5580
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "maccel-site",
"type": "module",
"version": "0.0.1",
"engines": {
"node": "^24.0.0"
},
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro check && astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@astrojs/check": "^0.4.1",
"@astrojs/tailwind": "^5.1.0",
"@types/node": "^20.11.16",
"astro": "^4.2.8",
"tailwindcss": "^3.4.1",
"typescript": "^5.3.3"
},
"devDependencies": {
"@tailwindcss/typography": "^0.5.10"
}
}
+4660
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

+109
View File
@@ -0,0 +1,109 @@
## Mouse Pointer Acceleration on Linux.
### Why?
Many gamers, specifically those whom enjoy first person shooters, know that you should disable the mouse pointer acceleration
that windows has enabled by default. You disable it so that you get a 1:1 correlation between how you mouse physically and how
the pointer moves.
Some of us, however, know that mouse acceleration, if done right, can be very useful and that windows just does it very poorly.
I became convinced of this after some youtube videos on the subject, mainly this [video](https://www.youtube.com/watch?v=SBXv0xi-wyQ) by [pinguefy](https://www.youtube.com/@Pinguefy).
We also know that [Raw Accel](https://github.com/a1xd/rawaccel/blob/master/doc/Guide.md), a mouse pointer acceleration driver for **windows**, does it right.
### Linux
We want rawaccel on **linux** too, but we won't get it.
So we're relegated to projects like [leetmouse](https://github.com/Skyl3r/leetmouse) that I found difficult to install,
and user unfriendly; or [libinput](https://wiki.archlinux.org/title/Libinput) with a [custom acceleration profile](https://wayland.freedesktop.org/libinput/doc/latest/pointer-acceleration.html#the-custom-acceleration-profile).
Now, my gripe with `leetmouse` comes down to, mostly, skill issue. I eventually got it working, but it was still hard to change
parameters since I had to recompile the source code to do so.
My gripe with `libinput` is that while having a terrible user experience on par `leetmouse`, it is also impossible to express
certain curves. I even built a [cli tool](https://github.com/Gnarus-G/libinput-custom-points-gen) to generate the configuration that will approximate the curve I want.
Accel=0.3; Offset=2; CAP=2;
```sh
libinput-points 0.3 2 2 -x
```
```
Section "InputClass"
Identifier "My Mouse"
Driver "libinput"
MatchIsPointer "yes"
Option "AccelProfile" "custom"
Option "AccelStepMotion" "1"
Option "AccelPointsMotion" "0 1 2 3.3 5.2 7.699999999999999 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 110 112 114 116 118 120 122 124"
EndSection
```
If you need more context on this, refer to [libinput xorg configuration](https://wiki.archlinux.org/title/Libinput#Via_Xorg_configuration_file), and [libinput properties](https://man.archlinux.org/man/libinput.4#SUPPORTED_PROPERTIES).
I don't recommend using `libinput-points` to mimic Rawaccel's linear acceleration because, when I built it, I understood much less than I do now
about how the math works.
Note then, that my main goal, and only goal for the moment, is to replicate the linear type acceleration option from `Rawaccel`
### Solution: Home-made driver
So we need an easy install story, and a very easy configuration story.
I made my own driver, [maccel](https://github.com/Gnarus-G/maccel). It's easy enough for me to install. Sometimes a system might be missing some
dependencies and it can be a chore getting them; But past that hurdle is a decent enough cli tool with a user friendly Terminal UI.
```sh
maccel tui
```
![image](https://github.com/Gnarus-G/maccel/assets/37311893/dd62fc9a-3558-46a4-847e-05f691c31054)
## Install Dependencies
Make sure to have these dependencies installed on your machine:
`curl`, `git`, `make`, `gcc`, and the linux headers in `/lib/modules/`
### gcc
The version matters, it must match the version with which the kernel was built.
For example you might encounter such an error:
![image](https://github.com/Gnarus-G/maccel/assets/37311893/6147e20a-a132-4132-a45e-2af3dc035552)
And you'll have to find a version of `gcc` that matches. This will be more or less annoying
depending on your distro and/or how familiar you are with it.
### linux headers
You want to make sure that `/lib/modules/` is not empty. For example mine looks like this:
```
total 0
drwxr-xr-x 1 root root 114 Jan 29 17:59 .
drwxr-xr-x 1 root root 159552 Jan 29 22:39 ..
drwxr-xr-x 1 root root 10 Jan 29 17:59 6.6.14-1-lts
drwxr-xr-x 1 root root 12 Jan 29 17:59 6.7.0-zen3-1-zen
drwxr-xr-x 1 root root 494 Jan 29 17:59 6.7.2-arch1-1
drwxr-xr-x 1 root root 494 Jan 31 21:54 6.7.2-zen1-1-zen
```
You want to find headers that match your kernel as represented by
```
uname -r
```
On an arch based distro you list the available headers with
```
sudo pacman -Ss linux headers
```
## Uninstall
```sh
sudo sh /opt/maccel/uninstall.sh
```
+42
View File
@@ -0,0 +1,42 @@
<script>
const copyButtons = document.querySelectorAll("code > [data-copy-button]")
copyButtons.forEach(button => {
const content = button.parentElement?.textContent?.trim();
if (content) {
button.addEventListener("click", async () => {
await navigator.clipboard.writeText(content)
button.setAttribute("data-copied", "");
setTimeout(() => {
button.removeAttribute("data-copied");
}, 2000)
})
}
})
</script>
<button class="absolute right-0 group" data-copy-button>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-6 w-6 group-data-[copied]:hidden"
>
<path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-6 w-6 hidden group-data-[copied]:inline"
>
<path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z"/>
</svg>
</button>
+21
View File
@@ -0,0 +1,21 @@
---
const today = new Date();
---
<footer class="flex flex-col gap-5 items-center p-5 text-slate-100">
<p>
&copy; {today.getFullYear()} Gnarus G. Powered by <a href="https://astro.build" target="_blank">Astro</a>. All rights reserved.
</p>
<div class="flex justify-center">
<a class="hover:text-slate-500" href="https://github.com/Gnarus-G" target="_blank">
<span class="sr-only">Go to my github</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32" astro-icon="social/github"
><path
fill="currentColor"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"
></path></svg
>
</a>
</div>
</footer>
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
+42
View File
@@ -0,0 +1,42 @@
---
import Footer from "../components/Footer.astro"
interface Props {
title: string;
description: string;
}
const { title, description } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content={description}/>
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
<meta name="og:image" content={new URL("/logo.png", Astro.url)}/>
</head>
<body class="bg-slate-800">
<slot />
<Footer/>
</body>
</html>
<style is:global>
html {
font-family: system-ui, sans-serif;
}
code {
font-family:
Menlo,
Monaco,
Lucida Console,
Liberation Mono,
DejaVu Sans Mono,
Bitstream Vera Sans Mono,
Courier New,
monospace;
}
</style>
+76
View File
@@ -0,0 +1,76 @@
---
import Layout from '../layouts/Layout.astro';
import CopyButton from '../components/CopyButton.astro';
import Why from "../WHY.md"
const installUrl = new URL("install.sh", Astro.site);
---
<Layout title="maccel" description="Maccel is a mouse pointer acceleration driver with a CLI and TUI to customize acceleration curves (Linear, Natural, Synchronous) and their parameters.">
<header class="flex justify-between items-center p-5 bg-gray-900">
<img class="object-cover rounded-full" width="32" src="/logo.png" alt=""/>
<section id="links" class="flex justify-center">
<a class="text-slate-100 hover:text-slate-500" href="https://github.com/Gnarus-G/maccel" target="_blank">
<span class="sr-only">Go see the project on github</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32" astro-icon="social/github"
><path
fill="currentColor"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"
></path>
</svg>
</a>
</section>
</header>
<main>
<div>
<section id="cta" class="w-full px-3 py-12 md:py-24 lg:py-32 bg-gray-900">
<div class="container mx-auto max-w-[65ch] space-y-4">
<div class="space-y-2">
<h1 class="text-gray-100 text-3xl font-bold tracking-tighter sm:text-4xl md:text-5xl lg:text-6xl/none">
maccel
</h1>
<p class="max-w-lg text-gray-300 md:text-xl">
A mouse pointer <strong>acceleration</strong> driver with a <strong>CLI</strong> and <strong>TUI</strong> to easily customize acceleration curves and their <strong>parameters</strong>.
Install now and enhance your aim.
</p>
</div>
<div>
<div class="w-full p-4 bg-gray-950 text-gray-50 rounded-md border border-solid border-amber-800">
<code class="relative flex items-center gap-5 text-sm text-gray-400">
<a title="Make sure your system has some things installed." href="#install-dependencies">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-5 w-5 text-yellow-500"
>
<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
<path d="M12 9v4"></path>
<path d="M12 17h.01"></path>
</svg>
</a>
curl -fsSL {installUrl} | sudo sh
<CopyButton />
</code>
</div>
<div class="flex justify-end">
<a class="text-slate-500" href="/install.sh">View source</a>
</div>
</div>
</div>
</section>
<section id="why" class="w-full px-3 py-12 md:py-24 lg:py-32">
<div class="container mx-auto prose lg:prose-xl prose-invert">
<Why/>
</div>
</section>
</div>
</main>
</Layout>
+8
View File
@@ -0,0 +1,8 @@
import fs from "node:fs/promises";
const url = new URL("../../../install.sh", import.meta.url);
const script = await fs.readFile(url, "utf-8");
export async function GET() {
return new Response(script);
}
+8
View File
@@ -0,0 +1,8 @@
import fs from "node:fs/promises";
const url = new URL("../../../uninstall.sh", import.meta.url);
const script = await fs.readFile(url, "utf-8");
export async function GET() {
return new Response(script);
}
+8
View File
@@ -0,0 +1,8 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
theme: {
extend: {},
},
plugins: [require("@tailwindcss/typography")],
};
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "astro/tsconfigs/strict"
}
+23
View File
@@ -0,0 +1,23 @@
use gsf_core::AccelMode;
#[derive(Debug, PartialEq)]
pub enum InputAction {
Enter,
Focus,
Reset,
}
#[derive(Debug, PartialEq)]
pub enum Action {
Tick,
Input(InputAction),
SelectNextInput,
SelectPreviousInput,
SetMode(AccelMode),
ScrollDown,
ScrollUp,
ScrollPageDown,
ScrollPageUp,
}
pub type Actions = Vec<Action>;
+285
View File
@@ -0,0 +1,285 @@
use crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen};
use gsf_core::ALL_COMMON_PARAMS;
use gsf_core::ALL_LINEAR_PARAMS;
use gsf_core::ALL_MODES;
use gsf_core::ALL_NATURAL_PARAMS;
use gsf_core::ALL_NOACCEL_PARAMS;
use gsf_core::ALL_SYNCHRONOUS_PARAMS;
use gsf_core::Param;
use gsf_core::get_param_value_from_ctx;
use gsf_core::persist::ParamStore;
use gsf_core::persist::SysFsStore;
use gsf_core::{ALL_PARAMS, AccelMode, ContextRef, TuiContext};
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::crossterm::event::{DisableMouseCapture, EnableMouseCapture, KeyCode, KeyEventKind};
use std::{io, time::Instant};
use std::{panic, time::Duration};
use tracing::debug;
use crate::action::{Action, Actions};
use crate::component::TuiComponent;
use crate::event::{Event, EventHandler};
use crate::graph::SensitivityGraph;
use crate::param_input::ParameterInput;
use crate::screen::Screen;
use crate::utils::CyclingIdx;
pub struct App {
context: ContextRef<SysFsStore>,
screens: Vec<Screen<SysFsStore>>,
screen_idx: CyclingIdx,
pub(crate) is_running: bool,
last_tick_at: Instant,
}
pub fn collect_inputs_for_params(
params: &[Param],
context: ContextRef<SysFsStore>,
) -> Vec<ParameterInput<SysFsStore>> {
ALL_COMMON_PARAMS
.iter()
.chain(params)
.filter_map(|&p| context.get().parameter(p).copied())
.map(|param| ParameterInput::new(&param, context.clone()))
.collect()
}
impl App {
pub fn new() -> Self {
let context = ContextRef::new(
TuiContext::init(SysFsStore, ALL_PARAMS).expect("Failed to initialize the Tui Context"),
);
Self {
screens: vec![
Screen::new(
AccelMode::Linear,
collect_inputs_for_params(ALL_LINEAR_PARAMS, context.clone()),
Box::new(
SensitivityGraph::new(context.clone()).on_y_axix_bounds_update(|ctx| {
// Appropriate dynamic bounds for the Linear sens graph
let upper_bound = f64::from(get_param_value_from_ctx!(ctx, SensMult))
* f64::from(get_param_value_from_ctx!(ctx, OutputCap)).max(1.0)
* 2.0;
[0.0, upper_bound]
}),
),
),
Screen::new(
AccelMode::Natural,
collect_inputs_for_params(ALL_NATURAL_PARAMS, context.clone()),
Box::new(
SensitivityGraph::new(context.clone()).on_y_axix_bounds_update(|ctx| {
// Appropriate dynamic bounds for the Natural sens graph
let upper_bound = f64::from(get_param_value_from_ctx!(ctx, SensMult))
* f64::from(get_param_value_from_ctx!(ctx, Limit)).max(1.0)
* 2.0;
[0.0, upper_bound]
}),
),
),
Screen::new(
AccelMode::Synchronous,
collect_inputs_for_params(ALL_SYNCHRONOUS_PARAMS, context.clone()),
Box::new(
SensitivityGraph::new(context.clone()).on_y_axix_bounds_update(|ctx| {
// Appropriate dynamic bounds for the Synchronous sens graph
let upper_bound = f64::from(get_param_value_from_ctx!(ctx, SensMult))
* f64::from(get_param_value_from_ctx!(ctx, Motivity)).max(1.0)
* 2.0;
[0.0, upper_bound]
}),
),
),
Screen::new(
AccelMode::NoAccel,
collect_inputs_for_params(ALL_NOACCEL_PARAMS, context.clone()),
Box::new(
SensitivityGraph::new(context.clone()).on_y_axix_bounds_update(|ctx| {
// Appropriate dynamic bounds for the NoAccel sens graph
let upper_bound =
f64::from(get_param_value_from_ctx!(ctx, SensMult)) * 2.0; // No other factor, sens is 1.0
[0.0, upper_bound.max(1.0)] // Ensure at least a small visible range
}),
),
),
],
screen_idx: CyclingIdx::new_starting_at(
ALL_MODES.len(),
context.clone().get().current_mode.ordinal() as usize,
),
context,
is_running: true,
last_tick_at: Instant::now(),
}
}
pub(crate) fn tick(&mut self) -> bool {
#[cfg(not(debug_assertions))]
let tick_rate = 16;
#[cfg(debug_assertions)]
let tick_rate = 100;
let do_tick = self.last_tick_at.elapsed() >= Duration::from_millis(tick_rate);
do_tick.then(|| {
self.last_tick_at = Instant::now();
});
do_tick
}
fn current_screen_mut(&mut self) -> &mut Screen<SysFsStore> {
let screen_idx = self.screen_idx.current();
self.screens.get_mut(screen_idx).unwrap_or_else(|| {
panic!(
"Failed to get a Screen for mode id {}: {:?}",
screen_idx, ALL_MODES[screen_idx]
);
})
}
fn current_screen(&self) -> &Screen<SysFsStore> {
let screen_idx = self.screen_idx.current();
self.screens.get(screen_idx).unwrap_or_else(|| {
panic!(
"Failed to get a Screen for mode id {}: {:?}",
screen_idx, ALL_MODES[screen_idx]
);
})
}
fn can_switch_screens(&self) -> bool {
self.screens.len() > 1 && !self.current_screen().is_in_editing_mode()
}
}
impl App {
pub(crate) fn handle_event(&mut self, event: &Event, actions: &mut Actions) {
debug!("received event: {:?}", event);
if let Event::Key(crossterm::event::KeyEvent {
kind: KeyEventKind::Press,
code,
..
}) = event
{
match code {
KeyCode::Char('q') => {
self.is_running = false;
return;
}
KeyCode::Right => {
if self.can_switch_screens() {
self.screen_idx.forward();
actions.push(Action::SetMode(
self.screens[self.screen_idx.current()].accel_mode,
));
}
}
KeyCode::Left => {
if self.can_switch_screens() {
self.screen_idx.back();
actions.push(Action::SetMode(
self.screens[self.screen_idx.current()].accel_mode,
));
}
}
_ => {}
}
}
self.current_screen_mut().handle_event(event, actions);
}
pub(crate) fn update(&mut self, actions: &mut Vec<Action>) {
debug!("performing actions: {actions:?}");
for action in actions.drain(..) {
if let Action::SetMode(accel_mode) = action {
self.context.get_mut().current_mode = accel_mode;
SysFsStore
.set_current_accel_mode(accel_mode)
.expect("Failed to set accel mode in TUI");
self.context.get_mut().reset_current_parameters();
}
self.current_screen_mut().update(&action);
}
}
pub(crate) fn draw(&self, frame: &mut ratatui::Frame, area: ratatui::prelude::Rect) {
self.current_screen().draw(frame, area);
}
}
/// Representation of a terminal user interface.
///
/// It is responsible for setting up the terminal,
/// initializing the interface and handling the draw events.
#[derive(Debug)]
pub struct Tui<B: Backend> {
/// Interface to the Terminal.
terminal: Terminal<B>,
/// Terminal event handler.
pub events: EventHandler,
}
impl<B: Backend> Tui<B> {
/// Constructs a new instance of [`Tui`].
pub fn new(terminal: Terminal<B>, events: EventHandler) -> Self {
Self { terminal, events }
}
/// Initializes the terminal interface.
///
/// It enables the raw mode and sets terminal properties.
pub fn init(&mut self) -> anyhow::Result<()> {
crossterm::terminal::enable_raw_mode()?;
crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;
// Define a custom panic hook to reset the terminal properties.
// This way, you won't have your terminal messed up if an unexpected error happens.
let panic_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic| {
Self::reset().expect("failed to reset the terminal");
panic_hook(panic);
}));
self.terminal.hide_cursor()?;
self.terminal.clear()?;
Ok(())
}
/// [`Draw`] the terminal interface by [`rendering`] the widgets.
///
/// [`Draw`]: ratatui::Terminal::draw
/// [`rendering`]: crate::ui::render
pub fn draw(&mut self, app: &mut App) -> anyhow::Result<()> {
self.terminal.draw(|frame| app.draw(frame, frame.area()))?;
Ok(())
}
/// Resets the terminal interface.
///
/// This function is also used for the panic hook to revert
/// the terminal properties if unexpected errors occur.
fn reset() -> anyhow::Result<()> {
crossterm::terminal::disable_raw_mode()?;
crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?;
Ok(())
}
/// Exits the terminal interface.
///
/// It disables the raw mode and reverts back the terminal properties.
pub fn exit(&mut self) -> anyhow::Result<()> {
Self::reset()?;
self.terminal.show_cursor()?;
Ok(())
}
}
+38
View File
@@ -0,0 +1,38 @@
use std::fmt::Debug;
use crossterm::event::{KeyEvent, MouseEvent};
use ratatui::{Frame, layout::Rect};
use super::{
action::{Action, Actions},
event::Event,
};
pub trait TuiComponent {
fn handle_event(&mut self, event: &Event, actions: &mut Actions) {
match event {
Event::Key(key_event) => self.handle_key_event(key_event, actions),
Event::Mouse(mouse_event) => self.handle_mouse_event(mouse_event, actions),
}
}
fn handle_key_event(&mut self, event: &KeyEvent, actions: &mut Actions);
fn handle_mouse_event(&mut self, event: &MouseEvent, actions: &mut Actions);
/// Stuff to do on any action derived from an event
fn update(&mut self, action: &Action);
fn draw(&self, frame: &mut Frame, area: Rect);
}
#[derive(Debug)]
pub struct NoopComponent;
impl TuiComponent for NoopComponent {
fn handle_key_event(&mut self, _event: &KeyEvent, _actions: &mut Actions) {}
fn handle_mouse_event(&mut self, _event: &MouseEvent, _actions: &mut Actions) {}
fn update(&mut self, _action: &Action) {}
fn draw(&self, _frame: &mut Frame, _area: Rect) {}
}
+52
View File
@@ -0,0 +1,52 @@
use std::sync::mpsc::TryRecvError;
use crossterm::event::Event as CrosstermEvent;
use crossterm::event::MouseEventKind;
#[derive(Debug)]
pub enum Event {
Key(crossterm::event::KeyEvent),
Mouse(crossterm::event::MouseEvent),
}
#[derive(Debug)]
pub struct EventHandler {
rx: std::sync::mpsc::Receiver<Event>,
}
impl EventHandler {
pub fn new() -> Self {
let tick_rate = std::time::Duration::from_millis(33);
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || -> anyhow::Result<()> {
loop {
if crossterm::event::poll(tick_rate)? {
match crossterm::event::read()? {
CrosstermEvent::Key(e) => tx.send(Event::Key(e)),
CrosstermEvent::Mouse(e) => {
if e.kind == MouseEventKind::Moved {
// These are annoying because they get buffered
// while you move your mouse a bunch and delay
// other events, e.g 'q' quitting could much longer than it should.
continue;
}
tx.send(Event::Mouse(e))
}
CrosstermEvent::Resize(_col, _row) => continue,
event => unimplemented!("event {event:?}"),
}?
}
}
});
EventHandler { rx }
}
pub fn next(&self) -> anyhow::Result<Option<Event>> {
Ok(match self.rx.try_recv() {
Ok(e) => Some(e),
Err(TryRecvError::Empty) => None,
Err(err) => return Err(err.into()),
})
}
}

Some files were not shown because too many files have changed in this diff Show More