Wednesday, September 21, 2016

Using the Apple Magic Mouse with Ubuntu (16.0.4)

 ... Detailed description on how to use the Apple Magic Mouse on Ubuntu, including how to make the settings permanent ...

I love my Apple Magic Mouse.

When I tried using it on a Ubuntu system, it took me a while to get it working as I could not find an authoritative guide on how to properly install it. I just found a bunch of posts that gave partial information. So I decided to write this blog to hopefully help anyone out there that tries to do the same thing.

I have a Magic Mouse V1, so hopefully the same applies to the more recent version as well. This blog really covers two things:
  1. How to manually play with the settings so that you may find the right ones for you.
  2. Describe the changes you have to make to automate the loading of the settings and make them permanent.

Before starting, it is important to understand that the settings of the mouse are distributed into two areas:
  1. The Magic Mouse Kernel Module, and
  2. The mouse driver
I will cover both.

Manual Set Up

  1. Ubuntu 16 has all the drivers it needs, so there is no need to do anything complicated.  Connect the Magic Mouse as you would any other Bluetooth device. If you need help, see this link.
  2. Once the Magic Mouse is connected, you can see the current Kernel Module settings by executing the following command:
    $ systool -avm hid_magicmouse
    Module = "hid_magicmouse"
    [. . .]
    Parameters:
      emulate_3button = "Y"
      emulate_scroll_wheel= "Y"
      report_undeciphered = "N"
      scroll_acceleration = "N"
      scroll_speed = "35"
    [. . .]
    Note that if you are missing a package to run systool, Ubuntu will give you instructions on the package you need to load.
  3. We can now update the settings in the hid_magicmouse Kernel Module.  Here is a brief description of each:
    • emulate_3button = enables the third button when your finger presses the middle.  I find this finicky, so I disable it.  In MacOS only the left/right buttons are used. (boolean)
    • emulate_scroll_wheel = the module interprets horizontal and vertical swipes as wheel ticks.  The vertical function works fine by emulating both press and release for each tick, but the horizontal one only emulates presses and not releases which causes problems in the back and forth swipes in Chrome, so I disable it in the driver (see more in the driver section). (boolean)
    • report_undeciphered = no need to turn it on. (boolean)
    • scroll_acceleration = the faster you move your finger, the more ticks per distance it generates. (boolean)
    • scroll_speed = this tells it how many ticks to generate when you swipe your finger a given distance; I like it to be sensitive, so I set it to 55. (0 - 63)
    To update the settings, the easiest way is to unload the module and reload it with the new settings.  You can do this at the terminal prompt as follows:
    $ sudo rmmod hid_magicmouse
    $ sudo modprobe hid_magicmouse emulate_3button=0 scroll_acceleration=1 scroll_speed=55
    You can check that the parameters have taken hold by running the above systool command again.
  4. Before we can play with the mouse driver settings, we have to figure out the Product name.  We will also get the assigned ID which will be used further down.  Once the mouse is connected, this information can be found by executing 'xinput list'.
    $ xinput list
    ⎡ Virtual core pointer id=2 [master pointer (3)]
    ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)]
    ⎜ ↳ USB Optical Mouse id=10 [slave pointer (2)]
    ⎜ ↳ MCE IR Keyboard/Mouse (nuvoton-cir) id=13 [slave pointer (2)]
    ⎜ ↳ Steve’s Mouse id=15 [slave pointer (2)]
    ⎣ Virtual core keyboard id=3 [master keyboard (2)]
    ↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)]
    ↳ Power Button id=6 [slave keyboard (3)]
    ↳ Video Bus id=7 [slave keyboard (3)]
    ↳ Power Button id=8 [slave keyboard (3)]
    ↳ Sleep Button id=9 [slave keyboard (3)]
    ↳ AT Raw Set 2 keyboard id=11 [slave keyboard (3)]
    ↳ Nuvoton w836x7hg Infrared Remote Transceiver id=12 [slave keyboard (3)]
    ↳ Steve’s Keyboard id=14 [slave keyboard (3)]
    In my case above, the Product name is 'Steve's Mouse', and the id is '15'.
  5. Excellent, now we can look at the driver settings and change them as desired.  First, lets take a look at the current settings:
    $ xinput list-props "Steve’s Mouse"
    Device 'Steve’s Mouse':
      Device Enabled (133): 1
      Coordinate Transformation Matrix (135): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
      Device Accel Profile (257): 0
      Device Accel Constant Deceleration (258): 5.000000
      Device Accel Adaptive Deceleration (259): 1.000000
      Device Accel Velocity Scaling (260): 8.000000
      Device Product ID (251): 1452, 781
      Device Node (252): "/dev/input/event14"
      Evdev Axis Inversion (261): 0, 0
      Evdev Axes Swap (263): 0
      Axis Labels (264): "Rel X" (143), "Rel Y" (144), "Rel Horiz Wheel" (255), "Rel Vert Wheel" (256)
      Button Labels (265): "Button Left" (136), "Button Unknown" (254), "Button Right" (138), "Button Wheel Up" (139), "Button Wheel Down" (140), "Button Horiz Wheel Left" (141), "Button Horiz Wheel Right" (142)
    [. . .]
    The more useful settings are as follows:
    • Device Accel Profile = This selects the algorithm used for accelerating the cursor in relation to the speed of the mouse. It can take a number of settings, check this link for the Xorg man pages.
    • Device Accel Constant Deceleration = This decelerates the mouse by a given factor, the higher the number, the slower the cursor will move.
    • Device Accel Velocity Scaling = This one is profile dependent, and it scales the acceleration.
    • Device Accel Adaptive Deceleration = Allows the acceleration profile to actually decelerate the pointer by the given factor. Adaptive deceleration is a good tool allowing precise pointing, while maintaining pointer speed in general.
    • set-button-map = This allows you to remap the buttons. The first number is the assigned ID that we recovered earlier (15 in this case).  For the rest, the positional order is as outlined in the 'Button Labels' string above, starting with the number 1 and ending with 7. A value of zero disables the relative button (note that we have disabled the middle button at the kernel module, so no need to do it here). For Natural scrolling, I like to reverse the left/right scroll, as well as the up/down scroll; however, due to the left/right issue already mentioned (only emulates presses and not releases), I like to disable the left/right scroll.  If it was not disabled, below instead of '0 0' at the end it would be '7 6'
    You can read more about all the available settings at the above link. I have settled on these changes from the default to give me what I like (remember to change the items in red to match your setup):
    $ xinput set-prop "Steve’s Mouse" "Device Accel Constant Deceleration" 5
    $ xinput set-prop "Steve’s Mouse" "Device Accel Velocity Scaling" 8
    $ xinput set-button-map 15 1 2 3 5 4 0 0
    You can execute the xinput list-props command again to check that the commands have taken.
  6. That's it . . . now you can experiment with different values and find ones that you like.  Feel free to share in the comments different settings that you think work better . . . describe why they are better so that other people can try them to.

Automatic Set Up

Now that you found the settings you want, it is time to make them permanent.  This is the part that I had the toughest time to get right.  Basically you have to set up configuration files for both the kernel module as well as the driver that gets loaded every time the mouse gets attached.
  1. For setting up the Kernel module, you have to add the following one liner configuration file, call it 'magicmouse.conf' and put it in the '/etc/modprobe.d/' directory:
    options hid_magicmouse emulate_3button=0 scroll_acceleration=1 scroll_speed=55
  2. For the driver settings, you have to add the following configuration file, call it '50-magicmouse.conf' and put it in the '/usr/share/X11/xorg.conf.d/' directory (note that the leading spaces are single tabs, but I don't think that it matters . . . also, don't forget to update the red item with the name of your mouse, per instructions in the previous section):
    Section "InputClass"
      Identifier "Apple Magic Mouse" # This can be anything
      MatchIsPointer "on"
      MatchDevicePath "/dev/input/event*"
      MatchProduct "Steve’s Mouse" # Product name from 'xinput list'
      Driver "evdev" # From '/var/log/Xorg.0.log' after mouse connected
      Option "AccelerationProfile" "0"
      Option "ConstantDeceleration" "5"
      Option "AdaptiveDeceleration" "1"
      Option "VelocityScale" "8"
      Option "ButtonMapping" "1 2 3 5 4 0 0"
    EndSection
    See below on how I derived the driver.
  3. Now it is time to reboot and see if it all works as expected.  Before you do that, make sure that there are no spelling mistakes in all the keywords as otherwise your system will fail to boot (purple screen). If this happens, start the computer in safe mode by holding 'left-shift' during boot-up or repeatedly pressing the 'esc' key during boot up; once you are at the prompt, look at the most recent Xorg log, such as '/var/log/Xorg.0.log' and check for the detected error and fix it ... or remove the '50-magicmouse.conf' file.

Some Additional Notes

Hopefully I have done a good job at explaining this. In case you run into some issues, here are some additional notes that may help you debug them:
  • Once the mouse is connected, you can find the kernel module by executing 'lsmod | grep mouse'.  This will yield the module name of 'hid_magicmouse'.
  • The driver is loaded every time that the mouse attaches via Bluetooth. You can gleam a lot of information from the logs of when it attaches and how the settings are assigned:
    $ more /var/log/Xorg.0.log
    [. . .]
    [ 239.508] (II) config/udev: Adding input device Steve’s Mouse (/dev/input/mouse2)
    [ 239.508] (II) No input driver specified, ignoring this device.
    [ 239.508] (II) This device may have been added with another device file.
    [ 239.540] (II) config/udev: Adding input device Steve’s Mouse (/dev/input/event14)
    [ 239.540] (**) Steve’s Mouse: Applying InputClass "evdev pointer catchall"
    [ 239.540] (**) Steve’s Mouse: Applying InputClass "Apple Magic Mouse"
    [ 239.540] (II) Using input driver 'evdev' for 'Steve’s Mouse'
    [ 239.540] (**) Steve’s Mouse: always reports core events
    [ 239.540] (**) evdev: Steve’s Mouse: Device: "/dev/input/event14"
    [. . .]
    As you can see, it uses the 'evdev' driver.
  • To look at how the mouse is generating events, run the following command and move the mouse to the displayed square and perform the various activities. This is how I noticed that the left/right scroll only registers presses but no releases, I am not sure if this is intentional but it did cause strange behavior in Chrome. It should generate back and forward browsing commands, but instead it cause the window to scroll and display the other page, but it does not activate it until something times out.
    $ xev | grep button
      state 0x0, button 1, same_screen YES
      state 0x100, button 1, same_screen YES
      state 0x0, button 3, same_screen YES
      state 0x400, button 3, same_screen YES
      state 0x0, button 5, same_screen YES
      state 0x1000, button 5, same_screen YES
      state 0x0, button 5, same_screen YES
      state 0x1000, button 5, same_screen YES
That's it for now . . . good luck.  Feel free to leave a comment if you have any additional suggestion.

47 comments:

  1. Thanks for you post, It's every thing needed for use MAgicMouse in Ubuntu.

    I have a problem that I could never solve: My Magic Mouse disconnects each 2 minutes (aprox), and reconnects after 30seconds, and this is very annoying.

    Do you know something about this issue? Do you know How to solve it?

    Thanks again

    ReplyDelete
    Replies
    1. I have also seen my Magic Mouse momentarily getting disconnected once in a while, but only ~once a day ... my Bluetooth speaker also seems to have the same issue (except I have to reconnect it manually), so i thought it was likely a Bluetooth driver issue, but have not look into it. If someone figures it out, please post a reply here.

      Delete
  2. Thanks for the guide, I really appreciate it.

    ReplyDelete
  3. Hi, i have a magic mouse 2 on Ubuntu 16.
    The mouse is work as a simple 2 buttons mouse, the scroll is not working.

    The output of lsinput contains:

    /dev/input/event13
    bustype : BUS_BLUETOOTH
    vendor : 0x4c
    product : 0x269
    version : 100
    name : "Ratón de Hector Andrés Funes"
    phys : "c0:38:96:5e:49:0a"
    uniq : "04:4b:ed:c5:96:41"
    bits ev : EV_SYN EV_KEY EV_REL EV_ABS EV_MSC

    and systool:
    systool -avm hid_magicmouse
    Error opening module hid_magicmouse

    and modprobe:
    modprobe hid_magicmouse emulate_3button=0 scroll_acceleration=1 scroll_speed=55
    modprobe: FATAL: Module hid_magicmouse not found in directory /lib/modules/4.4.0-53-generic


    Any ideas?

    ReplyDelete
    Replies
    1. Same issue. Anyone have a solution?

      Delete
    2. I was able to resolve this issue using the mm2 builder (https://github.com/biggreenogre/mm2), but now the rigth click is gone and also the scroll not works. For compile correctly the mm2 driver i had to modify some files to match the actual kernel version

      Delete
    3. Hi, I also had this first. You need to connect the magic mouse first. Then this command with systool will work.
      Connecting just with the settings on ubuntu did not work for me. But it worked using Bluetooth-Manager:

      run in terminal: sudo apt-get install blueman
      and run it with following command: blueman-manager

      a window will open. Your Laptops Bluetooth should be turned on. Select the magic mouse in that window and click on "Setup". Then Pair and connect the device.
      If you get problems on connecting, turn off and on the magic mouse and try again.

      I found this info on this site: https://tutorialforlinux.com/2018/04/15/how-to-connect-apple-bluetooth-magic-mouse-on-ubuntu-18-04-easy-guide/

      Delete
  4. I have magic Mouse 2,the scrolling does not work. Any idea?

    ReplyDelete
  5. magic mouse 2 scrolling doesn't work on certain Macos's they changed the protocol.

    ReplyDelete
    Replies
    1. Hi, does magic mouse 2 scrolling works on Ubuntu for you?

      Delete
  6. Thanks for this blog, but the magic mouse on ubuntu is nowhere near as nice as it is on a mac unfortunately

    ReplyDelete
  7. This was just what I was looking for, so thanks for sharing your findings. I've just switched to a Dell XPS13 Ubunty, after being a Mac man for the past 10 years. Was finding it really frustrating getting the Magic Mouse to work and was just about to go out and buy a cheap USB mouse. Thanks again!

    ReplyDelete
  8. Thank you Steve!
    Magic Mouse 1 Working real smooth now on Ubuntu 16.04. And, my Driver Settings stuck first try.😁✌

    ReplyDelete
  9. Thank you for this nice guide. Now I'm able to use my imac as I used to under macOS. If I'm not mistaken, the so called "Natural Scrolling" isn't working in all GTK Applications the same way. For example, scrolling down my music library in Rhythmbox is not same as scrolling webpages in FF. I've found another guide of which I'm not sure if it's compatible with your workaround: https://kofler.info/natural-scrolling-mit-dem-mausrad/#more-1956

    Altough it is written in german, the author refers to a post in the fedora Forum:

    http://forums.fedoraforum.org/showthread.php?t=298702



    ReplyDelete
  10. Thank you so much for writing up suck a detailed guide. This worked perfectly!

    ReplyDelete
  11. systool doesn't know the name

    pat@pat-mbp-ubuntu:~$ systool -avm hid_magicmouse
    Error opening module hid_magicmouse

    I renamed the mouse (you can only do this on macOS) and repaired to no avail. Is there a file that contains the hid names?

    ReplyDelete
  12. I'm running Ubuntu 17.04 and GNOME 3.24 and when I run `sudo apt-get install systool` it indicates it doesn't exist. When searching Google for install instructions I find none. How did you get it on your system?

    ReplyDelete
    Replies
    1. That is because you need to run this instead
      sudo apt-get install sysfsutils

      Cheers,
      GBR_422777

      Delete
    2. Thank you! That worked perfectly.

      Delete
  13. I really appreciate this post. I got a magic mouse from Craigslist for $25 and I didn't want it go to waste since I have Ubuntu, but I plan to get a MAC when I'm rich! You're awesome bro!
    --Asus X502CA with Ubuntu 16.04 --

    ReplyDelete
  14. Thank you for your tutorial. Unfortunately when I run "xinput list-props" I don't get any of the settings you're talking about in my list:
    Device 'Apple Magic Mouse':
    Device Enabled (141): 1
    Coordinate Transformation Matrix (143): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Accel Speed (313): 0.000000
    libinput Accel Speed Default (314): 0.000000
    libinput Accel Profiles Available (315): 1, 1
    libinput Accel Profile Enabled (316): 1, 0
    libinput Accel Profile Enabled Default (317): 1, 0
    libinput Natural Scrolling Enabled (318): 0
    libinput Natural Scrolling Enabled Default (319): 0
    libinput Send Events Modes Available (264): 1, 0
    libinput Send Events Mode Enabled (265): 0, 0
    libinput Send Events Mode Enabled Default (266): 0, 0
    libinput Left Handed Enabled (320): 0
    libinput Left Handed Enabled Default (321): 0
    libinput Scroll Methods Available (322): 0, 0, 1
    libinput Scroll Method Enabled (323): 0, 0, 0
    libinput Scroll Method Enabled Default (324): 0, 0, 0
    libinput Button Scrolling Button (325): 3
    libinput Button Scrolling Button Default (326): 3
    Device Node (267): "/dev/input/event13"
    Device Product ID (268): 1452, 781
    libinput Drag Lock Buttons (329):
    libinput Horizontal Scroll Enabled (330): 1


    And I guess that's why it is not working when I try to run:
    xinput set-prop "Apple Magic Mouse" "Device Accel Constant Deceleration" 5

    I get the message:
    property 'Device Accel Constant Deceleration' doesn't exist, you need to specify its type and format

    You have an idea why the property does not exist?

    ReplyDelete
  15. May be this is nice for old X, but what about Wayland?
    No xinput with Wayland (anymore).

    ReplyDelete
  16. Thank's Steve!!
    Following your guide I was able to setup my Magic Mouse v1 on 16.04 LTS at the first attempt.
    There was no need to modify the driver part as the default values are just fine for me.

    The only thing I'm not able to properly set is the auto pair or auto connect of the mouse at the boot, to let the mouse connected I must manually switch it to Connection ON from Off.

    I have seen instruction at https://wiki.ubuntu.com/Multitouch/AppleMagicMouse but there is nothing usable to solve.

    Is there someone able to drive me in the right direction to the solution?

    Best regards and Happy Easter !!
    Barth

    ReplyDelete
    Replies
    1. Solved the same problem.
      Look in `sudo rfkill list`, if there is" soft / hard block on "- then try `sudo rfkill unblock bluetooth`.
      If it helps - add `/etc/systemd/system/rfkill-unblock.service` this command (the command text is on stackoverflow)

      Delete
  17. I added the settings for my Magic Mouse v1 as described, which stopped the problem with the middle button. But now my mouse is single finger scrolling.

    All the wheel and scroll controls look the same. Any suggestions for what the pro

    ReplyDelete
    Replies
    1. Well I'm going to revert.

      These settings have removed the middle button, but given me super-sensitive sideways and vertical scrolling which is a nightmare, particularly as it switches browser tabs and causes buttons and entry boxes to jump around.

      Delete
    2. It's actually single-finger scrolling. Which is reversed in Chrome compared with Terminal.

      Delete
  18. Thank you for you post.
    I have a Magic Mouse 2 and Ubuntu 18.10, everything works fine up to "Automatic Set Up".
    I've created the files

    /etc/modprobe.d/magicmouse.conf
    /usr/share/X11/xorg.conf.d/50-magicmouse.conf

    but when I reboot the system, it does not take the configuration and I have to do manual set up everytime

    $ sudo rmmod hid_magicmouse
    $ sudo modprobe hid_magicmouse emulate_3button=0 scroll_acceleration=1 scroll_speed=55

    What I'm doing wrong?

    PS. I have downloaded the Magic Mouse 2 driver from

    https://github.com/rohitpid/Linux-Magic-Trackpad-2-Driver

    ReplyDelete
    Replies
    1. I have the same problem.
      and also the same output to xinput list-props than ms2000r.

      Delete
  19. Just did this on Ubuntu 18.05 ( Actually Pop! OS ) but it's the same thing. Blueman sets up the mouse and everything works including scrolling. I am suffering from intermittent pauses/disconnects that I haven't worked on yet.

    https://tutorialforlinux.com/2018/04/15/how-to-connect-apple-bluetooth-magic-mouse-on-ubuntu-18-04-easy-guide/

    ReplyDelete
  20. I constantly get "rmmod: ERROR: Module hid_magicmouse is in use"

    ReplyDelete
  21. Thanks for explanation, I had the exact issue. When searching for solution I found another site where one creates a /etc/modprobe.d/hid_magicmouse.conf file and store the "option" lines in this. It works for me and seems to involve fewer steps. However I am not sure if there are other implication with each method. Here the link https://wiki.archlinux.org/index.php/Bluetooth_mouse

    ReplyDelete
  22. Great blog. Is there any to reverse the scroll function like on the Mac? I think the setting is "reverse scroll" Thanks!

    ReplyDelete
  23. The only way I can get my scrolling to work is by running the two manual commands each time I boot or or start from Suspend
    sudo rmmod hid_magicmouse
    sudo modprobe hid_magicmouse scroll_speed=40 scroll-acceleration=1

    xinput set-prop 'My Mouse' 'libinput Scroll Method Enabled' 0, 0, 1
    and this has no effect. What am I missing? Anyone?

    ReplyDelete
  24. Read the article above for Automatic Setup. That is how I have mine and works fine.

    ReplyDelete
  25. Oh and instead of disabling middle button I mapped it to left button using this:

    Option "ButtonMapping" "1 1"

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Thanks a lot, Steve, you made my day :)

    ReplyDelete
  29. Very good post! We are linking to this great article on our site. Keep up the good writing FREE BEAT MAKING SOFTWARE FOR MAC

    ReplyDelete
  30. Magic Trackpad 2 in UAE, Space Gray Trackpad in UAE, Trackpad in UAE
    https://gccgamers.com/magic-trackpad-2.html
    Magic Trackpad 2 in UAE, Safe Shopping Multiple Payment Options Express Delivery GCC Gamers Moneyback Guarantee.
    1634273143810-7

    ReplyDelete