0

I have configured correctly two keyboard layouts, one for the incorporated keyboard (english) and one for an external usb keyboard (spanish), so for I have to switch manually between them.

enter image description here

Is there a way to configure Ubuntu so that when I connect the external USB keyboard it automatically changes to the Spanish layout ? (and when disconnected it goes back to English)

1 Answers1

0

These are the steps to make linux switch between keyboard layouts when you connect an external USB keyboard

  1. Create a script called switchKeyboard.sh that switches between the two layouts that you have
#!/bin/bash
# Get current index of keyboard layout
curKB=$(gsettings get org.gnome.desktop.input-sources current)
isExternalKBconnected=$(lsusb | grep Keyboard | wc -l)
newKB=-1
#If you have more keyboard layouts or in different order or their names are different you need to change this logic

if [[ "$curKB" = "uint32 1" && $isExternalKBconnected -eq 1 ]]; then newKB=0 newLY='latam' fi if [[ "$curKB" = "uint32 0" && $isExternalKBconnected -eq 0 ]]; then newKB=1 newLY='us' fi
echo ----------------------- date if [[ newKB -ne -1 && "uint32 ${newKB}" != $curKB ]]; then # Change Gnome keyboard layout gsettings set org.gnome.desktop.input-sources current $newKB

echo loadkeys $newLY
echo setxkbmap $newLY

# Change the console and X keyboard layout
sudo loadkeys $newLY
sudo setxkbmap $newLY

else echo current keyboard layout is kept fi

Show the current keyboard layouts and current keyboard index

gsettings get org.gnome.desktop.input-sources sources gsettings get org.gnome.desktop.input-sources current

Note that running the above script will not reflect in the visual keyboard indicator on top, but if you type on any console or app you will notice the changes, also there is room for improvement to make it more generic and readable

  1. Use python and pyudev to monitor usb devices getting connected/disconnected, and call the script of the first step every time the 'Keyboard' usb device changes between connected/disconnected call this script as keyboardDisConnected.py
#!/usr/bin/env python3

import pyudev import subprocess

def main(): context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') monitor.start()

for device in iter(monitor.poll, None):

    dt = device.get('DEVTYPE')

    if (dt == 'usb_device'):
      # change this path to your home, using ~ does not work
      subprocess.call(['/home/mgg/switchKeyboard.sh'])  

if name == 'main': main()

  1. run python keyboardDisConnected.py, connect and disconnect your usb keyboard you should see something similar to this:

enter image description here

  1. Optionally run the python command as soon as the system starts

References: