Skip to content

One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.

Beamer 1.3.3

Toby Kalkman387aeff00f52
diff --git a/README.md b/README.md
index 6d48b4f..4202937 100644
--- a/README.md
+++ b/README.md
@@ -27,9 +27,9 @@ Free, with no account. Every installer is on the [releases page](https://github.
## Quick start
1. **Install on both machines.** On the Mac, drag Beamer to Applications, open it, and press the
- two Grant buttons on the Permissions page (Accessibility, then Input Monitoring). Then quit
- Beamer from its menu bar icon and open it again: macOS only passes keys to an app started after
- the grant, so until then the pointer crosses but the keyboard does not. On Windows,
+ two Grant buttons on the Permissions page (Accessibility, then Input Monitoring), then Relaunch
+ Beamer on the same page: macOS only passes keys to an app started after the grant, so until then
+ the pointer crosses but the keyboard does not. On Windows,
run the installer. It is not code-signed, because a certificate costs money and Beamer is free,
so Windows says "Windows protected your PC" the first time: choose More info, then Run anyway.
winget does not show that warning. Beamer on Windows runs as administrator, so expect one UAC
@@ -112,9 +112,8 @@ step, so the border is always the same one seen from both ends.
keyboard there.
- **Files do not cross**, only text and images, up to 256KB of text and an 8MB image.
- **AltGr is out of reach from the Mac.**
-- **Layouts that move letters, such as AZERTY and QWERTZ, are not handled yet.** Shortcuts sent
- from the Mac, and letters typed from the PC onto the Mac, follow US key positions, and a dead key
- typed on the PC does not cross. US and UK layouts are unaffected.
+- **A dead key typed on the PC does not cross**, so an accent typed as two keys on the PC's
+ layout arrives on the Mac without it. Shortcuts and letters follow each machine's own layout.
- **Intel Macs are not supported yet.** The Mac app is built for Apple silicon only.
- **The Windows installer is unsigned.** SmartScreen warns until it has a download history; winget
avoids it.
@@ -207,12 +206,12 @@ Mac's Keyboard page can switch this to positional, where Cmd sends the Windows k
So Cmd+C, Cmd+V, Cmd+Z and Cmd+T are copy, paste, undo and new tab, Ctrl+E opens Explorer and Ctrl
on its own opens Start. The PC's keys arrive on the Mac the reverse way. Chords with Ctrl, Alt or
Windows held are sent as real virtual-key presses, so they land on the right key for the active
-Windows keyboard layout. The `key_map` object in each app's config JSON can still override single
-keys.
+Windows keyboard layout. The Mac reads its own layout too, so on a German or French Mac Cmd+Z is
+still undo and Cmd+A still selects all, and a letter typed from the PC lands on the key that types
+it. The `key_map` object in each app's config JSON can still override single keys.
-The trigger key is never forwarded. On the Mac it is recorded by pressing it, Right Option to start
-with; on the PC it is one of eight modifier and Menu keys, Right Ctrl to start with. Either can
-double-tap or hold.
+The trigger key is never forwarded. On both machines it is recorded by pressing it: Right Option on
+the Mac and Right Ctrl on the PC to start with. Either can double-tap or hold.
The stays-here list is per machine, because a Mac keycode and a Windows virtual key are different
numbers for the same key. It takes keys, the right, middle, back and forward mouse buttons, and on
diff --git a/VERSION b/VERSION
index 1892b92..31e5c84 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.3.2
+1.3.3
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index 80b537b..e4c5416 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -19,12 +19,12 @@ import desktop_mac
from input_injector_mac import INJECTED_MARK
import gestures
import ignored
+import keyboard_layout
import media_keys
import protocol
from key_codes import (
KEY_NAME_TO_CODE,
MODIFIER_KEY_CODES,
- PRINTABLE_KEY_FALLBACKS,
SPECIAL_KEY_NAMES,
)
@@ -211,9 +211,13 @@ class QuartzEventTranslator:
if special_messages:
return KeyResult(False, is_down, is_repeat, special_messages)
if is_down:
- character = self._unicode_character(event, keycode)
- if character is not None and not is_repeat:
- self.printable_down[keycode] = character
+ # A repeat sends what the first press sent, so switching layout mid-hold cannot start
+ # a second key on Windows that the release, which sends the saved one, never lets go.
+ character = self.printable_down.get(keycode) if is_repeat else None
+ if character is None:
+ character = self._unicode_character(event, keycode)
+ if character is not None and not is_repeat:
+ self.printable_down[keycode] = character
else:
character = self.printable_down.pop(keycode, None)
if character is None:
@@ -356,11 +360,12 @@ class QuartzEventTranslator:
# chord never exists on the other side. Ctrl behaves the same way with
# control characters, and only survives today because those are not
# printable and already fall through. So while one of those is down,
- # the key's own unshifted character is what Windows needs. Shift and
+ # the key's own unshifted character is what Windows needs, read from
+ # this Mac's layout so a German Cmd+Z is Ctrl+Z, not Ctrl+Y. Shift and
# caps lock are deliberately not in that set -- they are meant to
# change the character, and the receiver reconciles them.
if self.modifier_down & CHORD_MODIFIER_KEY_CODES:
- base = PRINTABLE_KEY_FALLBACKS.get(keycode)
+ base = keyboard_layout.char_for(keycode)
if base is not None:
return base
length, characters = self.quartz.CGEventKeyboardGetUnicodeString(
@@ -368,7 +373,7 @@ class QuartzEventTranslator:
)
if length and isinstance(characters, str) and len(characters) == 1 and characters.isprintable():
return characters
- return PRINTABLE_KEY_FALLBACKS.get(keycode)
+ return keyboard_layout.char_for(keycode)
class _GestureEventView:
diff --git a/mac_app/ignored_titles.py b/mac_app/ignored_titles.py
index fb97acd..261055a 100644
--- a/mac_app/ignored_titles.py
+++ b/mac_app/ignored_titles.py
@@ -5,7 +5,8 @@ out of the AppKit recorder in widgets.py so both are testable without it.
import ignored
import media_keys
from bridge import NX_DEVICE_MODIFIER_BITS, WIRE_OTHER_BUTTONS
-from key_codes import PRINTABLE_KEY_FALLBACKS, SPECIAL_KEY_NAMES, key_title
+import keyboard_layout
+from key_codes import SPECIAL_KEY_NAMES, key_title
BUTTON_TITLES = {
"right": "Right button",
@@ -32,7 +33,7 @@ def entry_title(entry):
name = SPECIAL_KEY_NAMES.get(code)
if name is not None:
return key_title(name)
- fallback = PRINTABLE_KEY_FALLBACKS.get(code)
+ fallback = keyboard_layout.char_for(code)
return fallback.upper() if fallback is not None else f"Key {code}"
if kind == "button":
return BUTTON_TITLES.get(value, f"Button {value}")
diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.py
index efb02e1..5727e3d 100644
--- a/mac_app/input_injector_mac.py
+++ b/mac_app/input_injector_mac.py
@@ -23,7 +23,8 @@ import threading
import time
from typing import Dict, List, Optional, Set, Tuple
-from key_codes import KEY_NAME_TO_CODE, PRINTABLE_KEY_FALLBACKS
+import keyboard_layout
+from key_codes import KEY_NAME_TO_CODE
try:
import Quartz
@@ -36,14 +37,6 @@ LOGGER = logging.getLogger("Beamer")
# value would do; this one is recognisable in a log.
INJECTED_MARK = 0xBEA3
-# A US-layout character to the key that produces it, so a chord like Cmd+C
-# lands on the right key rather than arriving as text with no key code. The
-# table is the inverse of the one bridge.py reads keys with, so the two
-# directions cannot disagree about which key is which.
-CHAR_TO_KEY_CODE: Dict[str, int] = {}
-for _code, _char in PRINTABLE_KEY_FALLBACKS.items():
- CHAR_TO_KEY_CODE.setdefault(_char, _code)
-
MODIFIER_FLAG_NAMES = {
"cmd": "kCGEventFlagMaskCommand",
"cmd_r": "kCGEventFlagMaskCommand",
@@ -72,6 +65,7 @@ DOUBLE_CLICK_SLOP_PX = 5
LINES_PER_NOTCH = 1.0
_mods_down: Set[str] = set()
+_held_codes: Dict[str, int] = {}
_buttons_down: Set[str] = set()
_last_click: Dict[str, Tuple[float, int, int, int]] = {}
_warned_names: Set[str] = set()
@@ -106,10 +100,12 @@ def current_flags(mods_down: Set[str]) -> int:
return flags
-def plan_key_event(name: str, down: bool, mods_down: Set[str]) -> Optional[Tuple[int, Optional[str]]]:
+def plan_key_event(name: str, down: bool, mods_down: Set[str], held: Optional[Dict[str, int]] = None) -> Optional[Tuple[int, Optional[str]]]:
"""Pure planning: (key code, unicode string or None) for one key, or None
when there is nothing to send. Mutates `mods_down` exactly as inject_key
- does, so a test can inspect the bookkeeping."""
+ does, so a test can inspect the bookkeeping. `held` keeps the key each
+ character went down on, so its release lets go of that key even if the
+ layout changed in between."""
lowered = name.lower()
if lowered in MODIFIER_FLAG_NAMES:
# Recorded before the event is built, so the modifier's own event
@@ -127,8 +123,16 @@ def plan_key_event(name: str, down: bool, mods_down: Set[str]) -> Optional[Tuple
LOGGER.warning("Unknown key name ignored: %r", name)
_warned_names.add(name)
return None
- key_code = CHAR_TO_KEY_CODE.get(name.lower())
+ # The key that types it on this Mac's own layout, so a chord like Cmd+C lands on the right
+ # key, and a plain "z" from the PC is not posted as the US Z key, which types "y" on a
+ # German Mac. keyboard_layout is also what bridge.py reads keys with, so the two directions
+ # agree about which key is which.
+ if held is not None and not down and name in held:
+ return held.pop(name), None
+ key_code = keyboard_layout.code_for(name.lower())
if key_code is not None and (name.islower() or not name.isalpha() or mods_down):
+ if held is not None and down:
+ held[name] = key_code
return key_code, None
# A character this layout table cannot place -- an accent, an em dash, a
# capital with no shift held. Typed as text: it lands correctly in a text
@@ -139,7 +143,7 @@ def plan_key_event(name: str, down: bool, mods_down: Set[str]) -> Optional[Tuple
@_locked
def inject_key(name: str, down: bool) -> None:
quartz = _require()
- plan = plan_key_event(name, down, _mods_down)
+ plan = plan_key_event(name, down, _mods_down, _held_codes)
if plan is None:
return
key_code, text = plan
@@ -310,7 +314,7 @@ def release_all() -> None:
"""Let go of every key and button this module is holding. Called when the
link drops mid-chord, so a Command key held at the moment the PC went
away does not stay down on the Mac."""
- for name in sorted(_mods_down):
+ for name in sorted(_mods_down) + sorted(_held_codes):
try:
inject_key(name, down=False)
except Exception:
@@ -321,4 +325,5 @@ def release_all() -> None:
except Exception:
LOGGER.exception("Could not release the %s mouse button", button)
_mods_down.clear()
+ _held_codes.clear()
_buttons_down.clear()
diff --git a/mac_app/keyboard_layout.py b/mac_app/keyboard_layout.py
new file mode 100644
index 0000000..22186e9
--- /dev/null
+++ b/mac_app/keyboard_layout.py
@@ -0,0 +1,176 @@
+"""What each key types on this Mac's current keyboard layout.
+
+The wire carries characters, and two places must turn a key into a character, or a character into
+a key, the way the layout printed on the keys does: a shortcut sent to Windows (Cmd+Z has to arrive
+as Ctrl+Z on a German Mac, whose Z sits where a US keyboard has Y) and a letter typed from the PC
+onto this Mac (posting the US Z key code types "y" on that same Mac). A US table got both wrong for
+every layout that moves letters, while US and UK, which share letter positions, never showed it.
+
+The table is read with UCKeyTranslate from the layout's own `uchr` data, with no modifiers, so it
+holds the key's unshifted character. Dead keys are left out: posting one starts an accent instead
+of typing, so a dead key has no character here and no US one either: a "=" from the PC must not
+land on German's accent key, which is where US keeps "=", but be typed as text.
+
+⚠ The Text Input Sources calls must run on the main thread (macOS asserts on it), while the event
+tap and the injector read the table from their own threads. So `refresh()` runs on the main thread,
+at start and whenever the selected input source changes, and swaps in a new pair of dicts that the
+readers only ever look up.
+"""
+
+import ctypes
+import ctypes.util
+import logging
+from typing import Dict, Optional
+
+from key_codes import PRINTABLE_KEY_FALLBACKS
+
+LOGGER = logging.getLogger("Beamer")
+
+# The keys worth reading: every key the US table covers, plus the ISO key beside Z (0x0A), which
+# the US table has no character for.
+LAYOUT_KEY_CODES = tuple(sorted(set(PRINTABLE_KEY_FALLBACKS) | {0x0A}))
+
+INPUT_SOURCE_CHANGED = "com.apple.Carbon.TISNotifySelectedKeyboardInputSourceChanged"
+
+_K_UC_KEY_ACTION_DOWN = 0
+_K_UC_KEY_TRANSLATE_NO_DEAD_KEYS = 1
+
+_chars: Dict[int, Optional[str]] = dict(PRINTABLE_KEY_FALLBACKS)
+_codes: Dict[str, int] = {}
+for _code, _char in sorted(PRINTABLE_KEY_FALLBACKS.items()):
+ _codes.setdefault(_char, _code)
+
+
+def char_for(keycode) -> Optional[str]:
+ """The unshifted character `keycode` types on the current layout, or None."""
+ return _chars.get(keycode)
+
+
+def code_for(character) -> Optional[int]:
+ """The key that types `character` unshifted on the current layout, or None."""
+ return _codes.get(character)
+
+
+def install(chars: Dict[int, Optional[str]]) -> None:
+ """Swaps in a table read from a layout, where a dead key maps to None. Keys the layout leaves
+ out keep the US answer, so a shortcut on an unreadable key still goes somewhere sensible."""
+ global _chars, _codes
+ merged: Dict[int, Optional[str]] = dict(PRINTABLE_KEY_FALLBACKS)
+ merged.update(chars)
+ codes: Dict[str, int] = {}
+ for code, char in sorted(chars.items()):
+ if char is not None:
+ codes.setdefault(char, code)
+ # A US character this layout does not type at all still has somewhere to go; one it types on
+ # another key does not keep its US key.
+ for code, char in sorted(PRINTABLE_KEY_FALLBACKS.items()):
+ if code not in chars and char not in codes:
+ codes[char] = code
+ _chars, _codes = merged, codes
+
+
+class _Carbon:
+ def __init__(self):
+ carbon = ctypes.CDLL("/System/Library/Frameworks/Carbon.framework/Carbon")
+ core = ctypes.CDLL(ctypes.util.find_library("CoreFoundation"))
+ self.carbon = carbon
+ self.core = core
+ carbon.TISCopyCurrentKeyboardLayoutInputSource.restype = ctypes.c_void_p
+ carbon.TISGetInputSourceProperty.restype = ctypes.c_void_p
+ carbon.TISGetInputSourceProperty.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+ carbon.LMGetKbdType.restype = ctypes.c_uint8
+ carbon.UCKeyTranslate.restype = ctypes.c_int32
+ carbon.UCKeyTranslate.argtypes = [
+ ctypes.c_void_p, ctypes.c_uint16, ctypes.c_uint16, ctypes.c_uint32, ctypes.c_uint32,
+ ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32), ctypes.c_ulong,
+ ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_uint16),
+ ]
+ core.CFDataGetBytePtr.restype = ctypes.c_void_p
+ core.CFDataGetBytePtr.argtypes = [ctypes.c_void_p]
+ core.CFRelease.argtypes = [ctypes.c_void_p]
+ self.layout_data_key = ctypes.c_void_p.in_dll(carbon, "kTISPropertyUnicodeKeyLayoutData").value
+
+ def translate(self, layout, keycode, kbd_type, options):
+ dead = ctypes.c_uint32(0)
+ length = ctypes.c_ulong(0)
+ buffer = (ctypes.c_uint16 * 8)()
+ status = self.carbon.UCKeyTranslate(
+ layout, keycode, _K_UC_KEY_ACTION_DOWN, 0, kbd_type, options,
+ ctypes.byref(dead), len(buffer), ctypes.byref(length), buffer,
+ )
+ if status != 0:
+ return None, 0
+ text = bytes(bytearray(ctypes.string_at(buffer, 2 * length.value))).decode("utf-16-le", "ignore")
+ return text, dead.value
+
+ def layout_chars(self, source) -> Dict[int, Optional[str]]:
+ """The table for one input source (a TISInputSourceRef), None for a dead key, and empty
+ when it has no `uchr` data."""
+ data = self.carbon.TISGetInputSourceProperty(source, self.layout_data_key)
+ if not data:
+ return {}
+ layout = self.core.CFDataGetBytePtr(data)
+ kbd_type = self.carbon.LMGetKbdType()
+ chars = {}
+ for code in LAYOUT_KEY_CODES:
+ text, dead = self.translate(layout, code, kbd_type, 0)
+ if dead:
+ chars[code] = None
+ continue
+ if text and len(text) == 1 and text.isprintable() and not text.isspace():
+ chars[code] = text
+ return chars
+
+ def current_chars(self) -> Dict[int, Optional[str]]:
+ source = self.carbon.TISCopyCurrentKeyboardLayoutInputSource()
+ if not source:
+ return {}
+ try:
+ return self.layout_chars(source)
+ finally:
+ self.core.CFRelease(source)
+
+
+_carbon = None
+
+
+def refresh() -> bool:
+ """Main thread only. Re-reads the current layout into the table; on any failure the table
+ keeps what it had, and the US answers stay underneath."""
+ global _carbon
+ try:
+ if _carbon is None:
+ _carbon = _Carbon()
+ chars = _carbon.current_chars()
+ except Exception:
+ LOGGER.exception("could not read the keyboard layout; keys follow US positions")
+ return False
+ if not chars:
+ LOGGER.info("the keyboard layout has no key table; keys follow US positions")
+ return False
+ install(chars)
+ return True
+
+
+try:
+ import Foundation
+except ImportError: # pragma: no cover - off macOS
+ Foundation = None
+else:
+ class _LayoutObserver(Foundation.NSObject):
+ def layoutChanged_(self, _note):
+ refresh()
+
+
+def watch():
+ """Main thread. Refreshes now and on every change of input source, which macOS announces on the
+ distributed centre and delivers on this thread's run loop. Returns the observer, which the
+ caller keeps alive."""
+ refresh()
+ if Foundation is None: # pragma: no cover - off macOS
+ return None
+ observer = _LayoutObserver.alloc().init()
+ Foundation.NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(
+ observer, "layoutChanged:", INPUT_SOURCE_CHANGED, None
+ )
+ return observer
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index e8424ec..522b9fc 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -5,6 +5,7 @@ import logging
import logging.handlers
import os
import re
+import subprocess
import sys
import threading
import time
@@ -24,6 +25,7 @@ import config as config_module
import crossing
import gestures
import ignored_titles
+import keyboard_layout
import notch_beam
import previews
from notch_beam import NotchBeam
@@ -762,6 +764,9 @@ class ControlWindow(AppKit.NSObject):
# Set by TrayApp: saves one direction's switch, as its menu ticks do.
self.direction_handler = None
self.last_capture_attempt = 0.0
+ # macOS passes keys only to a process started after Input Monitoring is granted, so a grant
+ # made during this run needs a relaunch before the keyboard crosses, however ready the tap looks.
+ self.granted_at_launch = accessibility_granted() and input_monitoring_granted()
# Set by TrayApp: the beacon listener whose PCs the Pair module lists.
self.discovery = None
self._pcs = []
@@ -1663,7 +1668,12 @@ class ControlWindow(AppKit.NSObject):
module.add(widgets.hairline())
self.input_status, self.input_button = self._permission_row(module, "Input Monitoring", "requestInputMonitoring:")
self.capture_status = widgets.note()
- module.add(self.capture_status.view)
+ line = widgets.stack(vertical=False, spacing=12)
+ line.addArrangedSubview_(widgets.hug(self.capture_status.view, AppKit.NSLayoutPriorityDefaultLow))
+ self.relaunch_button = widgets.Button("Relaunch Beamer", self, "relaunch:", style="primary", scale="small")
+ self.relaunch_button.view.setHidden_(True)
+ line.addArrangedSubview_(self.relaunch_button.view)
+ module.add(line)
return module
@objc.python_method
@@ -1850,6 +1860,19 @@ class ControlWindow(AppKit.NSObject):
Quartz.CGRequestListenEventAccess()
self.refresh()
+ def relaunch_(self, _sender):
+ """Opens this app again once this process has gone, which the single-instance lock needs,
+ then quits. Run from source there is no bundle to reopen, so it only says what to do."""
+ bundle = AppKit.NSBundle.mainBundle().bundlePath()
+ if not bundle.endswith(".app"):
+ self.capture_status.set("Quit Beamer and start it again.", ink="amber")
+ return
+ subprocess.Popen(
+ ["/bin/sh", "-c", 'while kill -0 "$0" 2>/dev/null; do sleep 0.2; done; exec /usr/bin/open "$1"', str(os.getpid()), bundle],
+ start_new_session=True,
+ )
+ self.quit_handler()
+
def toggleRedirect_(self, _sender):
if not self.controller.input_ready:
self._say("Grant both Mac permissions first.", "fault")
@@ -1935,7 +1958,9 @@ class ControlWindow(AppKit.NSObject):
self.pc_empty.set(f"Beamer cannot look for PCs: {discovery.error}", ink="fault")
else:
self.pc_empty.set(
- "Looking for PCs running Beamer on this network. Open Beamer on the PC and it appears here.", ink="ink_2"
+ "Looking for PCs running Beamer. Open it on the PC and it appears here; across a VPN or "
+ "on guest Wi-Fi it cannot, so enter its address and a shared token on Connection instead.",
+ ink="ink_2",
)
self.pc_frame.setHidden_(not pcs)
self.pc_empty.view.setHidden_(bool(pcs))
@@ -2066,7 +2091,11 @@ class ControlWindow(AppKit.NSObject):
if now - self.last_capture_attempt >= CAPTURE_RETRY_INTERVAL_SECONDS:
self.last_capture_attempt = now
controller.start_input_capture()
- if controller.input_ready:
+ needs_relaunch = access and listening and not self.granted_at_launch
+ self.relaunch_button.view.setHidden_(not needs_relaunch)
+ if needs_relaunch:
+ self.capture_status.set("Both granted. Relaunch Beamer so macOS passes it the keyboard.", ink="amber")
+ elif controller.input_ready:
self.capture_status.set("Input capture ready.", ink="signal")
elif access and listening:
detail = controller.input_error
@@ -2190,6 +2219,8 @@ class TrayApp(rumps.App):
self.controller = controller
self.settings_store = settings_store
self.logger = logger
+ # Before anything reads or posts a key: the table follows this Mac's layout from here on.
+ self.layout_observer = keyboard_layout.watch()
self.control_window = ControlWindow.alloc().initWithController_settingsStore_logger_(
controller, settings_store, logger
)
diff --git a/mac_app/setup.py b/mac_app/setup.py
index 674ef74..6ab0f59 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -26,6 +26,7 @@ setup(
"ignored",
"input_injector_mac",
"key_codes",
+ "keyboard_layout",
"link_state",
"media_keys",
"notch_beam",
diff --git a/mac_app/tests/test_keyboard_layout.py b/mac_app/tests/test_keyboard_layout.py
new file mode 100644
index 0000000..43392e8
--- /dev/null
+++ b/mac_app/tests/test_keyboard_layout.py
@@ -0,0 +1,166 @@
+"""Keys follow this Mac's own layout in both directions. UK and US share letter positions, so every
+test here uses a layout that moves them: German swaps Y and Z and puts ü where US has [, and French
+puts A where US has Q. The tables are what UCKeyTranslate reads from macOS's own German and French
+layouts (checked 27-09-2026); the last class reads them from the system to prove that."""
+
+import ctypes
+import sys
+import unittest
+
+import config
+import keyboard_layout
+import input_injector_mac as injector
+import protocol
+from bridge import QuartzEventTranslator
+from tests.test_bridge import FakeQuartz
+
+GERMAN = {0x00: "a", 0x06: "y", 0x07: "x", 0x08: "c", 0x09: "v", 0x0C: "q", 0x10: "z", 0x18: None, 0x21: "ü", 0x29: "ö", 0x32: "<"}
+FRENCH = {0x00: "q", 0x06: "w", 0x0C: "a", 0x0D: "z", 0x10: "y", 0x12: "&", 0x29: "m"}
+
+
+class LayoutTest(unittest.TestCase):
+ def tearDown(self):
+ keyboard_layout.install({})
+
+
+class TableTests(LayoutTest):
+ def test_us_positions_until_a_layout_is_read(self):
+ self.assertEqual(keyboard_layout.char_for(0x06), "z")
+ self.assertEqual(keyboard_layout.code_for("z"), 0x06)
+
+ def test_a_german_layout_swaps_y_and_z_both_ways(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(keyboard_layout.char_for(0x06), "y")
+ self.assertEqual(keyboard_layout.code_for("z"), 0x10)
+ self.assertEqual(keyboard_layout.code_for("ü"), 0x21)
+
+ def test_a_us_character_on_a_key_the_layout_retypes_has_no_key(self):
+ # US [ is ü on a German Mac, so posting that key would type ü.
+ keyboard_layout.install(GERMAN)
+ self.assertIsNone(keyboard_layout.code_for("["))
+
+ def test_a_dead_key_has_no_character_and_its_us_one_has_no_key(self):
+ # German 0x18 is the acute accent; US keeps "=" there. Posting it would start an accent.
+ keyboard_layout.install(GERMAN)
+ self.assertIsNone(keyboard_layout.char_for(0x18))
+ self.assertIsNone(keyboard_layout.code_for("="))
+
+ def test_a_key_the_layout_leaves_out_keeps_its_us_character(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(keyboard_layout.char_for(0x0E), "e")
+ self.assertEqual(keyboard_layout.code_for("e"), 0x0E)
+
+
+class ShortcutToWindowsTests(LayoutTest):
+ def press(self, keycode, unicode, modifier=0x37):
+ translator = QuartzEventTranslator(FakeQuartz)
+ translator.modifier_down.add(modifier)
+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "unicode": unicode}
+ result = translator.key_result(FakeQuartz.kCGEventKeyDown, event, 0x3D, dict(config.DEFAULT_KEY_MAP))
+ return result.messages
+
+ def test_german_cmd_z_is_undo_not_redo(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(self.press(0x10, "z"), [{"type": protocol.MSG_KEYDOWN, "data": {"key": "z"}}])
+
+ def test_french_cmd_a_selects_all(self):
+ keyboard_layout.install(FRENCH)
+ self.assertEqual(self.press(0x0C, "a"), [{"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}}])
+
+ def test_a_repeat_after_a_layout_switch_sends_the_first_press_character(self):
+ translator = QuartzEventTranslator(FakeQuartz)
+ key_map = dict(config.DEFAULT_KEY_MAP)
+
+ def key(event_type, repeat):
+ event = {FakeQuartz.kCGKeyboardEventKeycode: 0x06, FakeQuartz.kCGKeyboardEventAutorepeat: repeat, "unicode": keyboard_layout.char_for(0x06)}
+ return translator.key_result(event_type, event, 0x3D, key_map).messages
+
+ self.assertEqual(key(FakeQuartz.kCGEventKeyDown, 0), [{"type": protocol.MSG_KEYDOWN, "data": {"key": "z"}}])
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(key(FakeQuartz.kCGEventKeyDown, 1), [{"type": protocol.MSG_KEYDOWN, "data": {"key": "z"}}])
+ self.assertEqual(key(FakeQuartz.kCGEventKeyUp, 0), [{"type": protocol.MSG_KEYUP, "data": {"key": "z"}}])
+
+ def test_option_still_sends_the_key_not_the_composed_character(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(self.press(0x06, "¥", modifier=0x3A), [{"type": protocol.MSG_KEYDOWN, "data": {"key": "y"}}])
+
+
+class TypingOntoThisMacTests(LayoutTest):
+ def plan(self, name, mods=None):
+ return injector.plan_key_event(name, True, set() if mods is None else mods)
+
+ def test_z_from_the_pc_is_z_on_a_german_mac(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(self.plan("z"), (0x10, None))
+
+ def test_ctrl_a_from_the_pc_is_cmd_a_on_a_french_mac(self):
+ keyboard_layout.install(FRENCH)
+ self.assertEqual(self.plan("a", {"cmd"}), (0x0C, None))
+
+ def test_an_accented_letter_the_layout_has_lands_on_its_key(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(self.plan("ü"), (0x21, None))
+
+ def test_an_equals_sign_is_typed_not_posted_on_the_german_accent_key(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(self.plan("="), (0, "="))
+
+ def test_a_release_lets_go_of_the_key_its_press_went_down_on(self):
+ held, mods = {}, set()
+ self.assertEqual(injector.plan_key_event("z", True, mods, held), (0x06, None))
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(injector.plan_key_event("z", False, mods, held), (0x06, None))
+ self.assertEqual(held, {})
+
+ def test_a_character_the_layout_cannot_place_is_typed_as_text(self):
+ keyboard_layout.install(GERMAN)
+ self.assertEqual(self.plan("["), (0, "["))
+
+
[email protected](sys.platform == "darwin", "reads macOS's own layouts")
+class SystemLayoutTests(unittest.TestCase):
+ """The same answers read from the system's German and French layouts through UCKeyTranslate,
+ without selecting either, so the machine running the tests keeps its own."""
+
+ def chars(self, source_id):
+ import Foundation
+ import objc
+
+ carbon = keyboard_layout._Carbon()
+ lib, core = carbon.carbon, carbon.core
+ lib.TISCreateInputSourceList.restype = ctypes.c_void_p
+ lib.TISCreateInputSourceList.argtypes = [ctypes.c_void_p, ctypes.c_bool]
+ core.CFArrayGetCount.restype = ctypes.c_long
+ core.CFArrayGetCount.argtypes = [ctypes.c_void_p]
+ core.CFArrayGetValueAtIndex.restype = ctypes.c_void_p
+ core.CFArrayGetValueAtIndex.argtypes = [ctypes.c_void_p, ctypes.c_long]
+ key = objc.objc_object(c_void_p=ctypes.c_void_p.in_dll(lib, "kTISPropertyInputSourceID").value)
+ query = Foundation.NSDictionary.dictionaryWithObject_forKey_(source_id, key)
+ sources = lib.TISCreateInputSourceList(objc.pyobjc_id(query), True)
+ if not sources or not core.CFArrayGetCount(sources):
+ self.skipTest(f"{source_id} is not installed")
+ try:
+ return carbon.layout_chars(core.CFArrayGetValueAtIndex(sources, 0))
+ finally:
+ core.CFRelease(sources)
+
+ def test_german(self):
+ chars = self.chars("com.apple.keylayout.German")
+ for code, char in GERMAN.items():
+ if code != 0x32: # the key by Shift differs between ISO and ANSI hardware
+ self.assertEqual(chars.get(code), char, hex(code))
+
+ def test_french(self):
+ chars = self.chars("com.apple.keylayout.French")
+ for code, char in FRENCH.items():
+ self.assertEqual(chars.get(code), char, hex(code))
+
+ def test_dead_keys_are_marked(self):
+ # German's 0x18 is ´, which starts an accent rather than typing.
+ chars = self.chars("com.apple.keylayout.German")
+ self.assertIn(0x18, chars)
+ self.assertIsNone(chars[0x18])
+
+ def test_this_macs_own_layout_reads(self):
+ self.assertTrue(keyboard_layout.refresh())
+ keyboard_layout.install({})