Saturday, September 9, 2023

Kensington Expert Mouse Linux config

#!/bin/bash
# 

LEFT_HANDED=""

show_help() {
  echo "Usage: [--left]"
  echo "--left = use lefthanded config"
  exit 1
}

parse_args() {
while [[ $# -gt 0 ]]; do
  case $1 in
    --left)
      LEFT_HANDED="yes"
      shift
      ;;
    *)
      show_help
      ;;
  esac
done
}

parse_args $@

MOUSE_NAME="Kensington Expert Mouse"
CHECK=$(xinput | grep "$MOUSE_NAME")

set -e

echo "check=$CHECK"

if [[ -z "$CHECK" ]]; then
    echo "Cannot find the device: $MOUSE_NAME"
    exit 1
fi

TRACKBALL_ID=$(xinput | grep "$MOUSE_NAME" | sed 's/^.*id=\([0-9]*\)[ \t].*$/\1/')

LEFT_TOP=2
LEFT_BOTTOM=1
RIGHT_TOP=8
RIGHT_BOTTOM=3
SCROLL_CLOCKWISE=5
SCROLL_COUNTERCW=4

# LB, LT, RB, SCCW, SCW, 6, 7, RT

MOUSE_LEFT=1
MOUSE_MIDDLE=2
MOUSE_RIGHT=3

# ---

# make scrolling with the ball smooth
SCROLLING_PIXEL_DISTANCE=50

# X clients receive events with logical button numbers, where 1, 2, 3 are usually interpreted as left, middle, right and logical buttons 4, 5, 6, 7 are usually interpreted as scroll up, down, left, right. The fourth and fifth physical buttons on a device will thus send logical buttons 8 and 9. The ButtonMapping option adjusts the logical button mapping, it does not affect how a physical button is mapped to a logical button.

if [[ -n $LEFT_HANDED ]]; then
    echo "using lefthanded config"
    SCROLLING_BUTTON=$RIGHT_TOP
    # LB, LT, RB, SCCW, SCW, 6, 7, RT
    BUTTON_MAP="$MOUSE_MIDDLE $MOUSE_RIGHT $MOUSE_LEFT 4 5 6 7 8"
else
    # right hand settings
    SCROLLING_BUTTON=$LEFT_TOP
    # LB, LT, RB, SCCW, SCW, 6, 7, RT
    BUTTON_MAP="$MOUSE_LEFT 8 $MOUSE_MIDDLE 4 5 6 7 $MOUSE_RIGHT"
fi

# -------
xinput set-prop $TRACKBALL_ID "libinput Scrolling Pixel Distance" $SCROLLING_PIXEL_DISTANCE
xinput set-prop $TRACKBALL_ID "libinput Button Scrolling Button" $SCROLLING_BUTTON
xinput set-prop $TRACKBALL_ID "libinput Scroll Method Enabled" 0, 0, 1
xinput set-button-map $TRACKBALL_ID 1 2 3 4 5 6 7 8 9
echo $BUTTON_MAP
xinput set-button-map $TRACKBALL_ID $BUTTON_MAP