Ideally there is an event that we can respond to and have this happen automatically, but it looks like this is still an open issue:
https://bugs.launchpad.net/ubuntu/+source/udev/+bug/1535008
Also see: https://askubuntu.com/a/732830/519324
So I'm going to combine the following answers:
1. Find keyboard & trackpad IDs
Find the IDs for your keyboard/trackpad or what ever you want to disable using the following command. Mine is 12 for keyboard and 13 for Touchpad. Write it down.
xinput list
2. Find your display ID
Run the followiing command to find the connected screen, it's the ID that's followed by "connected". Mine is "eDP1".
xrandr
3. Write tablet mode script
sudo nano /usr/local/bin/tablet-mode.sh
Fill with the following script. Change 12 and 13 to your keyboard/trackpad IDs and change eDP1 to your display ID.
#!/bin/bash
xinput set-int-prop 12 "Device Enabled" 8 0 #Disable Keyboard
xinput set-int-prop 13 "Device Enabled" 8 0 #Disable Pad
xrandr --output eDP1 --rotate inverted #Rotate screen
onboard & #Turn on onscreen keyboard
Give it executable rights:
sudo chmod +x /usr/local/bin/tablet-mode.sh
4. Write laptop mode script
sudo nano /usr/local/bin/laptop-mode.sh
Fill with:
#!/bin/bash
xinput set-int-prop 12 "Device Enabled" 8 1 #Enable Keyboard
xinput set-int-prop 13 "Device Enabled" 8 1 #Enable Pad
xrandr --output eDP1 --rotate normal #Rotate screen back
killall onboard #Turn off onscreen keyboard
Give it executable rights:
sudo chmod +x /usr/local/bin/laptop-mode.sh
5. Create tablet mode icon
sudo nano /usr/share/applications/tablet-mode.desktop
Fill with:
[Desktop Entry]
Type=Application
Terminal=false
Name=Tablet Mode
Icon=/usr/share/icons/Adwaita/32x32/actions/media-playback-stop.png
Exec=/usr/local/bin/tablet-mode.sh
6. Create laptop mode icon
sudo nano /usr/share/applications/laptop-mode.desktop
Fill with:
[Desktop Entry]
Type=Application
Terminal=false
Name=Laptop Mode
Icon=/usr/share/icons/Adwaita/32x32/actions/media-playback-stop.png
Exec=/usr/local/bin/laptop-mode.sh
You probably need to re-login to get the icons.
/usr/share/icons/suru/devices/scalable/{computer-laptop,input-tablet}-symbolic.svg
for icons. Nice hack! +1 – nekketsuuu Mar 24 '17 at 22:43