pynput icon indicating copy to clipboard operation
pynput copied to clipboard

Wrong keyboard layout while typing in wayland

Open Rodot opened this issue 8 months ago • 1 comments

Description When using self.keyboard.type(char) with a "FR" keyboard layout enabled, it types as if it was a US keyboard enabled, so the output is gibberish.

Platform and pynput version Ubuntu 24.04 LTS using wayland, US language, FR keyboard layout Tested on pynput 1.8.1 and 1.7.3

To Reproduce

# Set system keyboard layout to FR
from pynput.keyboard import Controller
keyboard = Controller()
keyboard.type("a")
# Outputs "q", expected "a"

Workaround

Turns out the xwayland layout doesn't match one selected in the system. I made a workaround that manually syncs the system keyboard layout => xwayland keyboard layout.


    def _get_system_layout(self):
        """Get the system keyboard layout from localectl"""
        try:
            result = subprocess.run(
                ["localectl", "status"], stdout=subprocess.PIPE, text=True, check=True
            )

            # Parse the output to find X11 Layout
            for line in result.stdout.splitlines():
                if "X11 Layout:" in line:
                    return line.split(":", 1)[1].strip()

            return "us"  # Default to US if not found
        except Exception:
            return "us"  # Default to US on error

    def _set_xwayland_layout(self, layout):
        """Set Xwayland keyboard layout with setxkbmap"""
        try:
            subprocess.run(["setxkbmap", layout], check=True)
            return True
        except Exception:
            return False

    def type_text(self, text, delay=0.01):
        """Type text using keyboard emulation with correct layout"""
        system_layout = self._get_system_layout()
        self._set_xwayland_layout(system_layout)
        for char in text:
            time.sleep(delay)
            self.keyboard.type(char)

Rodot avatar Mar 22 '25 09:03 Rodot

I also run into the same issue with the following layouts:

$ setxkbmap -query | grep layout
layout:     us,ch,us

Is there any fix in view?

omlins avatar Apr 02 '25 08:04 omlins