Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions source/_magnifier/magnifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@
MagnifierParameters,
MagnifierAction,
MagnifiedView,
MagnifierTrackingType,
Direction,
Filter,
Coordinates,
)
from .config import (
getFollowState,
getZoomLevel,
getPanStep,
getFilter,
Expand All @@ -35,6 +37,7 @@
_isDebug,
)
from .utils.focusManager import FocusManager
from .utils.mouseHook import MagnifierMouseHook


class Magnifier:
Expand All @@ -57,6 +60,7 @@ def __init__(self):
self._isManualPanning: bool = False
self._consecutiveErrors: int = 0
self._recoveryAttempts: int = 0
self._mouseHook: MagnifierMouseHook | None = None
# Register for display changes
_displayTracking.displayChanged.register(self._onDisplayChanged)
self._screenCurtainIsActive: bool = False
Expand Down Expand Up @@ -184,6 +188,8 @@ def _startMagnifier(self) -> None:

self._isActive = True
self.currentCoordinates = self._focusManager.getCurrentFocusCoordinates()
self._mouseHook = MagnifierMouseHook(self._onMouseMove)
self._mouseHook.start()
Comment thread
Boumtchack marked this conversation as resolved.

def _updateMagnifier(self) -> None:
"""
Expand Down Expand Up @@ -246,12 +252,31 @@ def _attemptRecovery(self) -> None:
self._consecutiveErrors = 0
self._startTimer(self._updateMagnifier)

def _onMouseMove(self, x: int, y: int) -> None:
"""
Called from the hook thread on every WM_MOUSEMOVE.
Updates the magnified view immediately, bypassing the wx timer loop.
Only acts when mouse tracking is enabled and the magnifier is active.
"""
if not self._isActive or self._isManualPanning:
return
if not getFollowState(MagnifierTrackingType.MOUSE):
return
try:
self.currentCoordinates = Coordinates(x, y)
self._doUpdate()
except OSError:
pass

def _stopMagnifier(self) -> None:
"""
Stop the magnifier
"""
if not self._isActive:
return
if self._mouseHook:
self._mouseHook.stop()
self._mouseHook = None
self._stopTimer()
self._isActive = False
# Unregister from display changes
Expand Down
69 changes: 69 additions & 0 deletions source/_magnifier/utils/mouseHook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2026 NV Access Limited, Antoine Haffreingue
# This file may be used under the terms of the GNU General Public License, version 2 or later, as modified by the NVDA license.
# For full terms and any additional permissions, see the NVDA license file: https://github.com/nvaccess/nvda/blob/master/copying.txt

"""Dedicated low-level mouse hook for the magnifier.

Runs in its own thread so it stays responsive even when the wx main thread is
busy (e.g. at high Windows display scale factors), which is the root cause of
the DPI-related lag compared to the built-in Windows Magnifier.
"""

import ctypes
import threading
from ctypes import byref
from ctypes.wintypes import MSG
from logHandler import log
from winBindings import user32
from winInputHook import MSLLHOOKSTRUCT, HC_ACTION, WH_MOUSE_LL

WM_MOUSEMOVE: int = 0x0200
WM_QUIT: int = 0x0012


class MagnifierMouseHook:
"""Installs a WH_MOUSE_LL hook in a dedicated thread. Calls onMouseMove(x, y) on every mouse move."""

def __init__(self, onMouseMove):
Comment thread
Boumtchack marked this conversation as resolved.
Outdated
self._onMouseMove = onMouseMove
self._thread: threading.Thread | None = None
self._cCallback = None # kept alive to prevent GC of the ctypes callback
self._hookReady = threading.Event()
self._hookInstalled: bool = False

def start(self) -> None:
self._thread = threading.Thread(target=self._run, name="magnifierMouseHook", daemon=True)
self._thread.start()
self._hookReady.wait(timeout=1.0)

def stop(self) -> None:
if self._thread:
user32.PostThreadMessage(self._thread.ident, WM_QUIT, 0, 0)
self._thread.join(timeout=1.0)
self._thread = None
self._cCallback = None
Comment thread
Boumtchack marked this conversation as resolved.

def _run(self) -> None:
def _onRawMouseEvent(code, eventType, mouseDataPointer):
Comment thread
Boumtchack marked this conversation as resolved.
Outdated
if code == HC_ACTION and eventType == WM_MOUSEMOVE:
mouseData = MSLLHOOKSTRUCT.from_address(mouseDataPointer)
try:
self._onMouseMove(mouseData.pt.x, mouseData.pt.y)
except Exception:
log.exception("Error in magnifier mouse hook callback")
return user32.CallNextHookEx(0, code, eventType, mouseDataPointer)

self._cCallback = user32.HOOKPROC(_onRawMouseEvent)
hookHandle = user32.SetWindowsHookEx(WH_MOUSE_LL, self._cCallback, None, 0)
self._hookInstalled = bool(hookHandle)
self._hookReady.set()
if not hookHandle:
log.error(f"Failed to install magnifier mouse hook (error {ctypes.GetLastError()})")
return

windowsMessage = MSG()
while user32.GetMessage(byref(windowsMessage), None, 0, 0):
pass

user32.UnhookWindowsHookEx(hookHandle)
Comment thread
Boumtchack marked this conversation as resolved.
Outdated
64 changes: 64 additions & 0 deletions tests/unit/test_magnifier/test_mouseHook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2025-2026 NV Access Limited, Antoine Haffreingue
# This file may be used under the terms of the GNU General Public License, version 2 or later, as modified by the NVDA license.
# For full terms and any additional permissions, see the NVDA license file: https://github.com/nvaccess/nvda/blob/master/copying.txt

from unittest.mock import MagicMock, patch
from _magnifier.fullscreenMagnifier import FullScreenMagnifier
from _magnifier.utils.types import Coordinates
from tests.unit.test_magnifier.test_magnifier import _TestMagnifier


class _TestMagnifierWithHook(_TestMagnifier):
"""Extends _TestMagnifier with a mock for MagnifierMouseHook."""

def setUp(self):
super().setUp()
self.mouseHook_patcher = patch("_magnifier.magnifier.MagnifierMouseHook")
self.MockMouseHook = self.mouseHook_patcher.start()
self.mock_hook_instance = MagicMock()
self.MockMouseHook.return_value = self.mock_hook_instance

def tearDown(self):
self.mouseHook_patcher.stop()
super().tearDown()


class TestMouseHookLifecycle(_TestMagnifierWithHook):
"""Tests for the WH_MOUSE_LL hook lifecycle managed by the base Magnifier class."""

def testHookStartedWithMagnifier(self):
"""Mouse hook is started when the magnifier starts."""
magnifier = FullScreenMagnifier()
magnifier._startMagnifier()

self.MockMouseHook.assert_called_once_with(magnifier._onMouseMove)
self.mock_hook_instance.start.assert_called_once()

magnifier._stopMagnifier()

def testHookStoppedWithMagnifier(self):
"""Mouse hook is stopped and cleared when the magnifier stops."""
magnifier = FullScreenMagnifier()
magnifier._startMagnifier()
magnifier._stopMagnifier()

self.mock_hook_instance.stop.assert_called_once()
self.assertIsNone(magnifier._mouseHook)


class TestOnMouseMove(_TestMagnifierWithHook):
"""Tests for FullScreenMagnifier._onMouseMove — the hook callback."""

def testUpdatesMagnifier(self):
"""_onMouseMove updates currentCoordinates and calls _fullscreenMagnifier."""
magnifier = FullScreenMagnifier()
magnifier._startMagnifier()
magnifier._fullscreenMagnifier = MagicMock()

with patch("_magnifier.magnifier.getFollowState", return_value=True):
magnifier._onMouseMove(500, 400)

magnifier._fullscreenMagnifier.assert_called_once()
self.assertEqual(magnifier.currentCoordinates, Coordinates(500, 400))
magnifier._stopMagnifier()
Loading