Skip to content

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

Beamer 1.5.14

Toby Kalkman324edd5731bc
diff --git a/VERSION b/VERSION
index fa85d4d..8df6b88 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.13
+1.5.14
diff --git a/core/tests/test_mac_key_repeat.py b/core/tests/test_mac_key_repeat.py
new file mode 100644
index 0000000..74b45af
--- /dev/null
+++ b/core/tests/test_mac_key_repeat.py
@@ -0,0 +1,190 @@
+"""Mac key injection with native frameworks blocked before the module loads."""
+
+import importlib.util
+from collections import namedtuple
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+
+def load_injector():
+ directory = Path(__file__).resolve().parents[2] / "mac_app"
+ spec = importlib.util.spec_from_file_location("mac_repeat_injector", directory / "input_injector_mac.py")
+ module = importlib.util.module_from_spec(spec)
+ with patch.dict(sys.modules, {"Quartz": None, "AppKit": None, "Foundation": None}), \
+ patch.object(sys, "path", [str(directory)] + sys.path):
+ spec.loader.exec_module(module)
+ return module
+
+
+class QuartzRecorder:
+ kCGKeyboardEventAutorepeat = 8
+ kCGEventSourceUserData = 42
+ kCGHIDEventTap = 0
+ kCGEventFlagMaskShift = 1 << 17
+ kCGEventFlagMaskControl = 1 << 18
+ kCGEventFlagMaskAlternate = 1 << 19
+ kCGEventFlagMaskCommand = 1 << 20
+ kCGEventFlagMaskAlphaShift = 1 << 16
+ kCGEventFlagMaskSecondaryFn = 1 << 23
+ kCGEventFlagMaskNumericPad = 1 << 21
+
+ def __init__(self):
+ self.events = []
+
+ def CGEventCreateKeyboardEvent(self, source, code, down):
+ return {"code": code, "down": down, 8: 0}
+
+ def CGEventSetIntegerValueField(self, event, field, value):
+ event[field] = value
+
+ def CGEventSetFlags(self, event, flags):
+ event["flags"] = flags
+
+ def CGEventKeyboardSetUnicodeString(self, event, length, text):
+ event["text"] = text
+
+ def CGEventPost(self, tap, event):
+ self.events.append(event)
+
+
+class MacKeyRepeatTests(unittest.TestCase):
+ def setUp(self):
+ self.injector = load_injector()
+ layout = self.injector.keyboard_layout
+ self.enterContext(patch.multiple(layout, _chars=dict(layout._chars), _codes=dict(layout._codes)))
+ self.quartz = QuartzRecorder()
+ self.injector.Quartz = self.quartz
+
+ def feed(self, name, states):
+ for down in states:
+ self.injector.inject_key(name, down)
+
+ def repeats(self):
+ return [event[8] for event in self.quartz.events]
+
+ def deliver(self, messages):
+ from core import receiver
+ responder = SimpleNamespace(_injector_module=lambda: self.injector)
+ link = SimpleNamespace(held={}, name="peer")
+ for message in messages:
+ receiver.LinkResponder._inject_locked(responder, link, message)
+ return responder, link
+
+ def test_held_letters_and_named_keys_mark_only_subsequent_downs_as_repeats(self):
+ for name in ("a", "n", "backspace", "left", "f5", "enter", "é"):
+ with self.subTest(name=name):
+ self.quartz.events.clear()
+ self.feed(name, (True, True, True, False, True, False))
+ self.assertEqual(self.repeats(), [0, 1, 1, 0, 0, 0])
+ self.assertEqual([e["down"] for e in self.quartz.events],
+ [True, True, True, False, True, False])
+
+ def test_each_key_has_its_own_hold(self):
+ for name, down in (("a", True), ("n", True), ("a", True),
+ ("n", True), ("a", False), ("n", True), ("n", False)):
+ self.injector.inject_key(name, down)
+ self.assertEqual(self.repeats(), [0, 0, 1, 1, 0, 1, 0])
+
+ def test_held_modifier_flags_survive_letter_repeat_and_modifiers_do_not_repeat(self):
+ self.feed("ctrl", (True, True))
+ self.feed("c", (True, True, False))
+ self.feed("ctrl", (False,))
+ self.assertEqual(self.repeats(), [0, 0, 0, 1, 0, 0])
+ self.assertEqual([e["flags"] for e in self.quartz.events], [1 << 18] * 5 + [0])
+
+ def test_layout_change_during_hold_keeps_the_original_keycode(self):
+ self.injector.inject_key("z", True)
+ self.injector.keyboard_layout.install({6: "y", 16: "z"})
+ self.feed("z", (True, False, True, False))
+ self.assertEqual([e["code"] for e in self.quartz.events], [6, 6, 6, 16, 16])
+ self.assertEqual(self.repeats(), [0, 1, 0, 0, 0])
+
+ def test_release_all_ends_holds_and_the_next_press_is_fresh(self):
+ self.feed("shift", (True,))
+ for name in ("a", "left", "é"):
+ self.feed(name, (True, True))
+ self.injector.release_all()
+ released = {e["code"] for e in self.quartz.events if not e["down"]}
+ self.assertEqual(released, {56, 0, 123})
+ self.assertTrue(all(e[8] == 0 for e in self.quartz.events if not e["down"]))
+ self.quartz.events.clear()
+ for name in ("a", "left", "é"):
+ self.feed(name, (True,))
+ self.assertEqual(self.repeats(), [0, 0, 0])
+
+ def test_windows_hook_repeats_survive_sender_wire_and_mac_receiver(self):
+ from core.tests import test_windows_accent_releases as windows
+ case = windows.WindowsReleaseTests()
+ case.setUp()
+ self.addCleanup(case.doCleanups)
+ for down in (True, True, False):
+ case.feed(0x45, down, 0x12)
+ _, link = self.deliver(case.messages())
+ self.assertEqual(self.repeats(), [0, 1, 0])
+ self.assertEqual(link.held, {})
+
+ def test_x11_capture_repeats_survive_sender_wire_and_mac_receiver(self):
+ from core.tests import test_linux_accents as accents
+ import capture_x11
+ sender = accents.AccentTests.link_sender()
+ hooks = capture_x11.Hooks(sender.on_key, lambda *args: False, lambda *args: None)
+ hooks._connection = SimpleNamespace(keymap=accents.AccentKeymap())
+ for down, repeat in ((True, False), (True, True), (False, False)):
+ hooks._key(26, down, 0, 0, False, repeat=repeat)
+ _, link = self.deliver(accents.AccentTests.messages(sender))
+ self.assertEqual(self.repeats(), [0, 1, 0])
+ self.assertEqual(link.held, {})
+
+ def test_wayland_capture_forwards_repeated_libei_downs_without_a_wire_change(self):
+ from core.tests import test_linux_accents as accents
+ import capture_portal
+ sender = accents.AccentTests.link_sender()
+ hooks = capture_portal.Hooks(sender.on_key, lambda *args: False, lambda *args: None,
+ tokens=SimpleNamespace())
+ hooks._keymap = accents.AccentKeymap()
+ hooks._keymap.core_mods = lambda mods: 0
+ device = object()
+ for down in (True, True, False):
+ hooks._key_event(18, down, device)
+ _, link = self.deliver(accents.AccentTests.messages(sender))
+ self.assertEqual(self.repeats(), [0, 1, 0])
+ self.assertEqual(link.held, {})
+
+ def test_mac_capture_retains_repeated_downs_for_mac_receiver(self):
+ from core import protocol
+ from core.tests.app_methods import load_methods
+ namespace = {"KeyResult": namedtuple("KeyResult", "is_trigger is_down is_repeat messages"),
+ "SPECIAL_KEY_NAMES": {}, "MODIFIER_KEY_CODES": set(),
+ "PRINTABLE_KEY_FALLBACKS": {0: "a"}, "protocol": protocol}
+ Translator = load_methods("mac_app/bridge.py", "QuartzEventTranslator", ["key_result"], namespace)
+ translator = Translator()
+ translator.quartz = SimpleNamespace(kCGKeyboardEventKeycode=9, kCGKeyboardEventAutorepeat=8,
+ kCGEventFlagsChanged=12, kCGEventKeyDown=10, kCGEventKeyUp=11,
+ CGEventGetIntegerValueField=lambda event, field: event[field])
+ translator.printable_down = {}
+ translator._unicode_character = lambda event, code: "a"
+ translator._special_key_messages = lambda *args: []
+ messages = []
+ for kind, repeat in ((10, 0), (10, 1), (11, 0)):
+ result = translator.key_result(kind, {9: 0, 8: repeat}, 99, {})
+ for message in result.messages:
+ message["data"]["seq"] = len(messages) + 1
+ messages.append(protocol.read_input(protocol.parse_message(protocol.dumps_message(message))))
+ _, link = self.deliver(messages)
+ self.assertEqual(self.repeats(), [0, 1, 0])
+ self.assertEqual(link.held, {})
+
+ def test_receiver_release_after_repeat_ends_hold_before_next_owner(self):
+ from core import receiver
+ responder, link = self.deliver([{"type": "keydown", "key": "a", "us": "a"}] * 2)
+ receiver.LinkResponder._release_locked(responder, link)
+ self.injector.inject_key("a", True)
+ self.assertEqual(self.repeats(), [0, 1, 0, 0])
+ self.assertEqual(link.held, {})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xml
index 4caaa09..db32ec6 100644
--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml
+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml
@@ -43,6 +43,9 @@
</screenshots>
<content_rating type="oars-1.1"/>
<releases>
+ <release version="1.5.14" date="2026-10-26">
+ <description><p>Scrolling a settings page no longer changes a slider or a drop-down list that the pointer stops over: a control takes the scroll wheel only after it is clicked or reached with the keyboard. When a Windows PC, another Mac or a Linux PC on X11 drives a Mac, holding a letter now opens the macOS accent menu in apps that offer it.</p></description>
+ </release>
<release version="1.5.13" date="2026-10-24">
<description><p>Explains on Wayland that the desktop controls pointer visibility while input is shared, and that Beamer cannot hide another application's idle pointer. Pointer hiding on macOS, Windows and X11 is unchanged.</p></description>
</release>
diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.py
index 2cd696a..1c0158c 100644
--- a/mac_app/input_injector_mac.py
+++ b/mac_app/input_injector_mac.py
@@ -126,6 +126,7 @@ _FN_CODES |= {KEY_NAME_TO_CODE[f"f{number}"] for number in range(1, 21)}
_mods_down: Set[str] = set()
_held_codes: Dict[str, int] = {}
+_keys_down: Set[str] = set()
_buttons_down: Set[str] = set()
_last_click: Dict[str, Tuple[float, int, int, int]] = {}
_warned_names: Set[str] = set()
@@ -372,6 +373,9 @@ def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:
event = quartz.CGEventCreateKeyboardEvent(None, key_code, bool(down))
if event is None:
raise RuntimeError(f"CGEventCreateKeyboardEvent failed for {name!r}")
+ # Repeated downs arrive without a wire flag. Fresh CGEvents otherwise turn a hold into taps.
+ quartz.CGEventSetIntegerValueField(event, quartz.kCGKeyboardEventAutorepeat,
+ int(down and name in _keys_down))
if text is None:
quartz.CGEventSetFlags(event, current_flags(_mods_down) | key_flags(key_code))
else:
@@ -380,6 +384,11 @@ def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:
# leaving shift set would have some apps type it twice over.
quartz.CGEventSetFlags(event, 0)
_post(event)
+ if lowered not in MODIFIER_FLAG_NAMES:
+ if down:
+ _keys_down.add(name)
+ else:
+ _keys_down.discard(name)
def clamp_to_displays(x: int, y: int, rects) -> Tuple[int, int]:
@@ -616,7 +625,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) + sorted(_held_codes):
+ for name in sorted(_mods_down) + sorted(_keys_down | _held_codes.keys()):
try:
inject_key(name, down=False)
except Exception:
@@ -628,5 +637,6 @@ def release_all() -> None:
LOGGER.exception("Could not release the %s mouse button", button)
_mods_down.clear()
_held_codes.clear()
+ _keys_down.clear()
_buttons_down.clear()
reset_scroll_remainders()
diff --git a/mac_app/requirements-mac.txt b/mac_app/requirements-mac.txt
index 455e62c..2eaf3ff 100644
--- a/mac_app/requirements-mac.txt
+++ b/mac_app/requirements-mac.txt
@@ -6,3 +6,4 @@ rumps==0.4.0
py2app==0.28.10
PyNaCl>=1.6
dmgbuild==1.6.7
+pycparser==3.0
diff --git a/mac_app/tests/test_driven_mac.py b/mac_app/tests/test_driven_mac.py
index f910f45..46721f3 100644
--- a/mac_app/tests/test_driven_mac.py
+++ b/mac_app/tests/test_driven_mac.py
@@ -23,6 +23,7 @@ class FakeEvent:
class FakeQuartz:
kCGEventSourceUserData = 42
+ kCGKeyboardEventAutorepeat = 8
kCGScrollEventUnitLine = 1
kCGScrollEventUnitPixel = 0
kCGEventFlagMaskCommand = 1 << 20
diff --git a/win_app/tests/test_scroll_wheel_focus.py b/win_app/tests/test_scroll_wheel_focus.py
new file mode 100644
index 0000000..d666968
--- /dev/null
+++ b/win_app/tests/test_scroll_wheel_focus.py
@@ -0,0 +1,238 @@
+"""Scrolling past settings must not edit them until the control has focus."""
+
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from PySide6.QtCore import QPoint, QPointF, Qt
+from PySide6.QtGui import QWheelEvent
+from PySide6.QtTest import QTest
+from PySide6.QtWidgets import (
+ QApplication, QComboBox, QDialog, QDoubleSpinBox, QLineEdit, QScrollArea,
+ QSlider, QSpinBox, QVBoxLayout, QWidget,
+)
+
+import diagram
+import widgets
+
+
+class ScrollWheelFocusTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+ widgets.keyboard_navigation()
+
+ def setUp(self):
+ self.dialog = QDialog()
+ layout = QVBoxLayout(self.dialog)
+ self.scroll = QScrollArea()
+ layout.addWidget(self.scroll)
+ self.page = QWidget()
+ self.page.setFixedSize(400, 1600)
+ self.scroll.setWidget(self.page)
+ self.other = QLineEdit(self.page)
+ self.other.setGeometry(20, 650, 240, 30)
+ self.dialog.resize(500, 300)
+
+ def tearDown(self):
+ self.dialog.close()
+ self.dialog.deleteLater()
+ self.app.processEvents()
+
+ def prepare(self, control):
+ control.setParent(self.page)
+ control.setGeometry(20, 700, 240, 80)
+ if isinstance(control, QComboBox):
+ control.addItems(["First", "Second", "Third"])
+ control.setCurrentIndex(1)
+ else:
+ control.setRange(0, 100)
+ control.setValue(50)
+ control.show()
+ self.dialog.show()
+ self.dialog.activateWindow()
+ self.app.processEvents()
+ self.scroll.verticalScrollBar().setValue(600)
+ self.other.setFocus()
+ self.app.processEvents()
+ self.assertTrue(self.other.hasFocus())
+ self.assertFalse(control.hasFocus())
+ return control
+
+ def value(self, control):
+ return control.currentIndex() if isinstance(control, QComboBox) else control.value()
+
+ def wheel(self, control, *, pixels=False):
+ point = control.rect().center()
+ event = QWheelEvent(
+ QPointF(point), QPointF(control.mapToGlobal(point)),
+ QPoint(0, -30) if pixels else QPoint(), QPoint(0, -120),
+ Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier,
+ Qt.ScrollPhase.ScrollUpdate if pixels else Qt.ScrollPhase.NoScrollPhase, False,
+ )
+ self.app.sendEvent(control, event)
+ self.app.processEvents()
+
+ def assert_scrolls_without_editing(self, control, **kwargs):
+ value = self.value(control)
+ position = self.scroll.verticalScrollBar().value()
+ self.wheel(control, **kwargs)
+ self.assertEqual(self.value(control), value)
+ self.assertFalse(control.hasFocus(), "the wheel must not acquire focus")
+ self.assertGreater(self.scroll.verticalScrollBar().value(), position)
+
+ def test_unfocused_controls_scroll_the_dialog_instead_of_editing(self):
+ factories = (
+ lambda: QSlider(Qt.Orientation.Horizontal),
+ lambda: widgets.Ruler("Shortcut", 100),
+ lambda: widgets.Ruler("Length", 100, ticks=(0, 50, 100)),
+ diagram.PushStrip, QSpinBox, QDoubleSpinBox, QComboBox,
+ )
+ for factory in factories:
+ control = self.prepare(factory())
+ with self.subTest(control=type(control).__name__):
+ self.assert_scrolls_without_editing(control)
+ control.deleteLater()
+ self.app.processEvents()
+
+ def test_touchpad_scroll_leaves_unfocused_slider_unchanged(self):
+ control = self.prepare(widgets.Ruler("Length", 100))
+ self.assert_scrolls_without_editing(control, pixels=True)
+
+ def test_native_wheel_does_not_acquire_focus_or_scroll_twice(self):
+ for factory in (lambda: widgets.Ruler("Length", 100), QSpinBox, QComboBox):
+ control = self.prepare(factory())
+ with self.subTest(control=type(control).__name__):
+ value = self.value(control)
+ point = control.mapTo(self.dialog, control.rect().center())
+ QTest.wheelEvent(self.dialog.windowHandle(), QPointF(point), QPoint(0, -120))
+ self.app.processEvents()
+ self.assertEqual(self.value(control), value)
+ self.assertTrue(self.other.hasFocus())
+ distance = self.scroll.verticalScrollBar().value() - 600
+ self.assertGreater(distance, 0)
+ self.scroll.verticalScrollBar().setValue(600)
+ viewport = self.scroll.viewport()
+ point = viewport.mapTo(self.dialog, QPoint(350, 100))
+ QTest.wheelEvent(self.dialog.windowHandle(), QPointF(point), QPoint(0, -120))
+ self.app.processEvents()
+ self.assertEqual(self.scroll.verticalScrollBar().value() - 600, distance)
+ control.deleteLater()
+ self.app.processEvents()
+
+ def test_focused_controls_take_the_wheel_and_stop_after_focus_moves(self):
+ for factory in (lambda: widgets.Ruler("Length", 100), diagram.PushStrip,
+ QSpinBox, QDoubleSpinBox, QComboBox):
+ control = self.prepare(factory())
+ with self.subTest(control=type(control).__name__):
+ control.setFocus(Qt.FocusReason.TabFocusReason)
+ self.assertTrue(control.hasFocus())
+ before = self.value(control)
+ position = self.scroll.verticalScrollBar().value()
+ self.wheel(control)
+ self.assertNotEqual(self.value(control), before)
+ self.assertEqual(self.scroll.verticalScrollBar().value(), position)
+ self.other.setFocus()
+ self.assert_scrolls_without_editing(control)
+ control.deleteLater()
+ self.app.processEvents()
+
+ def test_tab_and_arrow_keys_still_edit_the_slider(self):
+ control = self.prepare(widgets.Ruler("Length", 100))
+ QWidget.setTabOrder(self.other, control)
+ QTest.keyClick(self.other, Qt.Key.Key_Tab)
+ self.assertTrue(control.hasFocus())
+ QTest.keyClick(control, Qt.Key.Key_Right)
+ self.assertEqual(control.value(), 60)
+ self.wheel(control)
+ self.assertNotEqual(control.value(), 60)
+
+ def test_click_focus_allows_wheel_on_custom_sliders(self):
+ for factory in (lambda: widgets.Ruler("Length", 100, ticks=(0, 50, 100)),
+ diagram.PushStrip):
+ control = self.prepare(factory())
+ with self.subTest(control=type(control).__name__):
+ QTest.mouseClick(control, Qt.MouseButton.LeftButton,
+ pos=QPoint(control.width() // 2, 25))
+ self.assertTrue(control.hasFocus())
+ value = control.value()
+ self.wheel(control)
+ self.assertNotEqual(control.value(), value)
+ control.deleteLater()
+ self.app.processEvents()
+
+ def test_spin_box_editor_does_not_swallow_unfocused_wheel(self):
+ control = self.prepare(QSpinBox())
+ value = control.value()
+ position = self.scroll.verticalScrollBar().value()
+ self.wheel(control.lineEdit())
+ self.assertEqual(control.value(), value)
+ self.assertGreater(self.scroll.verticalScrollBar().value(), position)
+
+ def test_slider_outside_scroll_area_keeps_its_wheel_behaviour(self):
+ control = QSlider(Qt.Orientation.Horizontal, self.dialog)
+ self.dialog.layout().addWidget(control)
+ control.setValue(50)
+ self.dialog.show()
+ self.dialog.activateWindow()
+ self.other.setFocus()
+ self.app.processEvents()
+ self.wheel(control)
+ self.assertNotEqual(control.value(), 50)
+
+ def test_all_settings_pages_protect_their_wheel_controls(self):
+ import theme
+ from test_settings_layout_acceptance import SyntheticWindow, write_synthetic_settings
+
+ theme.init_fonts()
+ with tempfile.TemporaryDirectory() as folder:
+ window = SyntheticWindow(write_synthetic_settings(Path(folder)))
+ try:
+ window.full_screen_timer.stop()
+ window.refresh_timer.stop()
+ window.resize(1100, 500)
+ window.show()
+ window.activateWindow()
+ found = set()
+ for key in ("overview", "crossing", "keyboard", "design", "connection"):
+ window._select_page(key)
+ self.app.processEvents()
+ area = window.stack.currentWidget()
+ controls = [control for control in area.findChildren(QWidget)
+ if isinstance(control, (QSlider, QComboBox, QSpinBox, QDoubleSpinBox))]
+ for control in controls:
+ with self.subTest(page=key, control=control.accessibleName()):
+ self.assertNotEqual(control.focusPolicy(), Qt.FocusPolicy.WheelFocus)
+ if not control.isVisibleTo(window) or not control.isEnabled():
+ continue
+ found.add(key)
+ area.ensureWidgetVisible(control)
+ control.clearFocus()
+ bar = area.verticalScrollBar()
+ before = bar.value()
+ value = self.value(control)
+ event = QWheelEvent(
+ QPointF(control.rect().center()),
+ QPointF(control.mapToGlobal(control.rect().center())),
+ QPoint(), QPoint(0, 120 if before else -120),
+ Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier,
+ Qt.ScrollPhase.NoScrollPhase, False)
+ self.app.sendEvent(control, event)
+ self.assertEqual(self.value(control), value)
+ if bar.maximum() > 0:
+ self.assertNotEqual(bar.value(), before)
+ self.assertEqual(found, {"crossing", "keyboard", "design"})
+ finally:
+ window.server.stop()
+ window.close()
+ window.deleteLater()
+ self.app.processEvents()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/widgets.py b/win_app/widgets.py
index 4e2ea63..4a65d6b 100644
--- a/win_app/widgets.py
+++ b/win_app/widgets.py
@@ -8,13 +8,15 @@ import math
from shiboken6 import isValid
from PySide6.QtCore import QEvent, QObject, QPointF, QRect, QRectF, QSignalBlocker, QSize, Qt
-from PySide6.QtGui import QAction, QColor, QFont, QFontMetrics, QLinearGradient, QPainter, QPalette, QPen
+from PySide6.QtGui import QAction, QColor, QFont, QFontMetrics, QLinearGradient, QPainter, QPalette, QPen, QWheelEvent
from PySide6.QtWidgets import (
QAbstractButton,
+ QAbstractSpinBox,
QApplication,
QBoxLayout,
QButtonGroup,
QCheckBox,
+ QComboBox,
QFrame,
QGraphicsOpacityEffect,
QGridLayout,
@@ -23,6 +25,7 @@ from PySide6.QtWidgets import (
QLabel,
QLayout,
QPushButton,
+ QScrollArea,
QSizePolicy,
QSlider,
QSystemTrayIcon,
@@ -68,6 +71,7 @@ _NAVIGATION_KEYS = {Qt.Key.Key_Tab, Qt.Key.Key_Backtab, Qt.Key.Key_Left, Qt.Key.
Qt.Key.Key_Up, Qt.Key.Key_Down}
_SHORTCUT_MODIFIERS = (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier
| Qt.KeyboardModifier.MetaModifier)
+_WHEEL_CONTROLS = (QSlider, QAbstractSpinBox, QComboBox)
def is_navigation_key(key, modifiers) -> bool:
@@ -80,7 +84,8 @@ class _KeyboardNavigation(QObject):
"""The one app-wide answer to "is the user moving focus by keyboard": on for a navigation
key, off for any mouse press. The stylesheet's :focus rings match only a widget whose
`keyboard_ring` property is true, which is kept in step on the focused widget alone, so a
- change repolishes one widget rather than the window."""
+ change repolishes one widget rather than the window. Scrollable settings require focus
+ before their controls can take the wheel."""
def __init__(self, app) -> None:
super().__init__(app)
@@ -89,6 +94,8 @@ class _KeyboardNavigation(QObject):
def eventFilter(self, watched, event) -> bool:
kind = event.type()
+ if kind in (QEvent.Type.Polish, QEvent.Type.Wheel):
+ return self._scroll_wheel(watched, event)
if kind not in (QEvent.Type.KeyPress, QEvent.Type.MouseButtonPress,
QEvent.Type.MouseButtonDblClick, QEvent.Type.FocusIn):
return False
@@ -100,6 +107,44 @@ class _KeyboardNavigation(QObject):
self._mark(watched)
return False
+ def _scroll_wheel(self, watched, event) -> bool:
+ control = watched
+ if not isinstance(control, QWidget):
+ return False
+ if event.type() == QEvent.Type.Polish and not isinstance(control, _WHEEL_CONTROLS):
+ return False
+ while not isinstance(control, _WHEEL_CONTROLS):
+ if control.isWindow() or isinstance(control, QScrollArea):
+ return False
+ control = control.parentWidget()
+ if control is None:
+ return False
+ area = control.parentWidget()
+ while area is not None and not isinstance(area, QScrollArea):
+ if area.isWindow():
+ return False
+ area = area.parentWidget()
+ if area is None:
+ return False
+ if event.type() == QEvent.Type.Polish:
+ # WheelFocus acquires focus before application filters see a real wheel event.
+ if control.focusPolicy() == Qt.FocusPolicy.WheelFocus:
+ control.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
+ return False
+ if control.hasFocus():
+ return False
+ viewport = area.viewport()
+ forwarded = QWheelEvent(
+ QPointF(viewport.mapFromGlobal(event.globalPosition().toPoint())),
+ event.globalPosition(), event.pixelDelta(), event.angleDelta(),
+ event.buttons(), event.modifiers(), event.phase(), event.inverted(),
+ event.source(), event.pointingDevice())
+ forwarded.setTimestamp(event.timestamp())
+ # Explicit forwarding also handles synthetic wheels, which Qt does not propagate.
+ QApplication.sendEvent(viewport, forwarded)
+ event.setAccepted(forwarded.isAccepted())
+ return True
+
def set(self, active: bool) -> None:
if active == self.active:
return