Skip to content

Commit 9213406

Browse files
sergiiopmclaude
andcommitted
perf: make the recordable lens smooth and keep the pointer responsive
With "Show lens in recordings" on, zooming and moving stuttered and the pointer itself lagged. Profiling showed every magnifier call waits for the next composition, and the UI thread doing that work was also the one serving the low-level mouse hook, so all system input queued behind rendering. - Move the mouse and keyboard hooks to a dedicated thread; wheel events are marshalled to the UI thread - Replace the 15 ms timer with an idle render loop paced by the compositor (DwmFlush or the magnifier's own wait), one frame per display refresh - Make the zoom easing time-based so it runs at the same speed at any frame rate - Recordable lens: set the transform only when the zoom changes, drop the extra InvalidateRect (it cost a second composition per frame), fade instead of resize on appear/disappear, move lens and shadow in a single DeferWindowPos batch, re-send shadow pixels only while fading - Build both lenses' chrome at startup so the first zoom has no hitch Measured on a 144 Hz display during zoom and movement: recordable lens from ~43 fps with 50 ms stalls to ~124 fps (max 31 ms); first frame from 230 ms to 25 ms; default lens from ~64 to ~81 fps. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4223de5 commit 9213406

7 files changed

Lines changed: 323 additions & 146 deletions

File tree

‎src/DibSurface.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,15 @@ public DibSurface(int width, int height)
4242

4343
/// <summary>
4444
/// Shows this surface in a per-pixel-alpha layered window at <paramref name="position"/>,
45-
/// scaled around its centre and faded according to the animation's appearance.
45+
/// scaled around its centre and faded by <paramref name="opacity"/>.
4646
/// </summary>
47-
public void Present(IntPtr hwnd, Point position, float appearance)
47+
public void Present(IntPtr hwnd, Point position, float opacity, float scale)
4848
{
4949
IntPtr source = DC;
50-
if (appearance < 0.999f)
50+
if (scale < 0.999f)
5151
{
5252
if (scratch == null) scratch = new DibSurface(Width, Height);
53-
DrawScaled(scratch, LensAnimation.ScaleFor(appearance));
53+
DrawScaled(scratch, scale);
5454
source = scratch.DC;
5555
}
5656

@@ -60,7 +60,7 @@ public void Present(IntPtr hwnd, Point position, float appearance)
6060
var blend = new Native.BLENDFUNCTION
6161
{
6262
BlendOp = Native.AC_SRC_OVER,
63-
SourceConstantAlpha = (byte)Math.Round(255 * Math.Max(0f, Math.Min(1f, appearance))),
63+
SourceConstantAlpha = (byte)Math.Round(255 * Math.Max(0f, Math.Min(1f, opacity))),
6464
AlphaFormat = Native.AC_SRC_ALPHA,
6565
};
6666
Native.UpdateLayeredWindow(hwnd, IntPtr.Zero, ref dst, ref size, source, ref origin, 0,

‎src/ILens.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,12 @@ interface ILens : IDisposable
1212
/// <summary>
1313
/// Draws one frame. <paramref name="show"/> is where the lens is heading: it animates in or out
1414
/// towards that state, and hides itself once the exit animation finishes.
15+
/// Returns true if drawing already waited for the next composition, so the caller needn't.
1516
/// </summary>
16-
void Update(Point cursor, double zoom, Settings settings, bool show);
17+
bool Update(Point cursor, double zoom, Settings settings, bool show);
18+
19+
/// <summary>Does the one-off setup for the current size and DPI ahead of time, so opening is instant.</summary>
20+
void Prepare(Point cursor, Settings settings);
1721

1822
/// <summary>Hides the lens immediately, without animating.</summary>
1923
void HideLens();

‎src/InputHooks.cs‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
using System;
2+
using System.Runtime.InteropServices;
3+
using System.Threading;
4+
5+
namespace Loupe
6+
{
7+
/// <summary>
8+
/// Low-level mouse and keyboard hooks running on their own thread.
9+
///
10+
/// Windows calls low-level hooks on the thread that installed them, and every mouse and key event
11+
/// in the system waits for the callback. Keeping them away from the rendering thread means a slow
12+
/// frame can never make the pointer itself lag.
13+
/// </summary>
14+
sealed class InputHooks : IDisposable
15+
{
16+
readonly Func<int, bool> onWheel;
17+
readonly Action onEscape;
18+
readonly ManualResetEvent ready = new ManualResetEvent(false);
19+
readonly Thread thread;
20+
21+
// Delegates are kept in fields so they stay alive while the hooks are installed.
22+
Native.LowLevelHookProc mouseProc, keyboardProc;
23+
IntPtr mouseHook, keyboardHook;
24+
uint threadId;
25+
26+
/// <param name="onWheel">
27+
/// Called on the hook thread for every wheel notch with its delta; return true to swallow it.
28+
/// Must be quick: the whole system's input waits for it.
29+
/// </param>
30+
/// <param name="onEscape">Called on the hook thread when Esc is pressed. The key is never swallowed.</param>
31+
public InputHooks(Func<int, bool> onWheel, Action onEscape)
32+
{
33+
this.onWheel = onWheel;
34+
this.onEscape = onEscape;
35+
36+
thread = new Thread(Run) { Name = "Loupe input hooks", IsBackground = true, Priority = ThreadPriority.AboveNormal };
37+
thread.Start();
38+
ready.WaitOne();
39+
}
40+
41+
public bool IsInstalled
42+
{
43+
get { return mouseHook != IntPtr.Zero; }
44+
}
45+
46+
void Run()
47+
{
48+
threadId = Native.GetCurrentThreadId();
49+
mouseProc = MouseCallback;
50+
keyboardProc = KeyboardCallback;
51+
IntPtr module = Native.GetModuleHandle(null);
52+
mouseHook = Native.SetWindowsHookEx(Native.WH_MOUSE_LL, mouseProc, module, 0);
53+
keyboardHook = Native.SetWindowsHookEx(Native.WH_KEYBOARD_LL, keyboardProc, module, 0);
54+
ready.Set();
55+
56+
// Hooks are delivered through this thread's message loop.
57+
Native.MSG msg;
58+
while (Native.GetMessage(out msg, IntPtr.Zero, 0, 0) > 0)
59+
{
60+
Native.TranslateMessage(ref msg);
61+
Native.DispatchMessage(ref msg);
62+
}
63+
64+
if (mouseHook != IntPtr.Zero) Native.UnhookWindowsHookEx(mouseHook);
65+
if (keyboardHook != IntPtr.Zero) Native.UnhookWindowsHookEx(keyboardHook);
66+
}
67+
68+
IntPtr MouseCallback(int nCode, IntPtr wParam, IntPtr lParam)
69+
{
70+
if (nCode >= 0 && wParam.ToInt32() == Native.WM_MOUSEWHEEL)
71+
{
72+
var data = (Native.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.MSLLHOOKSTRUCT));
73+
int delta = unchecked((short)(data.mouseData >> 16));
74+
if (onWheel(delta))
75+
return new IntPtr(1); // swallow the scroll so the app underneath doesn't see it
76+
}
77+
return Native.CallNextHookEx(mouseHook, nCode, wParam, lParam);
78+
}
79+
80+
IntPtr KeyboardCallback(int nCode, IntPtr wParam, IntPtr lParam)
81+
{
82+
if (nCode >= 0 && wParam.ToInt32() == Native.WM_KEYDOWN && Marshal.ReadInt32(lParam) == Native.VK_ESCAPE)
83+
onEscape();
84+
return Native.CallNextHookEx(keyboardHook, nCode, wParam, lParam);
85+
}
86+
87+
public void Dispose()
88+
{
89+
Native.PostThreadMessage(threadId, Native.WM_QUIT, IntPtr.Zero, IntPtr.Zero);
90+
thread.Join(1000);
91+
ready.Close();
92+
}
93+
}
94+
}

‎src/LensWindow.cs‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -51,24 +51,17 @@ public bool IsShown
5151
get { return visible; }
5252
}
5353

54-
public void Update(Point cursor, double zoom, Settings settings, bool show)
54+
public bool Update(Point cursor, double zoom, Settings settings, bool show)
5555
{
5656
float appearance;
5757
if (!animation.Step(show, out appearance))
5858
{
5959
HideLens();
60-
return;
60+
return false;
6161
}
6262

63-
float scale = Native.GetScaleAt(cursor);
64-
int width = (int)Math.Round(settings.LensWidth * scale);
65-
int height = (int)Math.Round(settings.LensHeight * scale);
66-
if (chrome == null || !chrome.Matches(width, height, scale))
67-
{
68-
chrome = new LensChrome(width, height, scale);
69-
if (surface != null) surface.Dispose();
70-
surface = new DibSurface(chrome.Width, chrome.Height);
71-
}
63+
EnsureChrome(cursor, settings);
64+
int width = chrome.LensWidth, height = chrome.LensHeight;
7265

7366
// Source area: centred on the pointer, kept inside the desktop.
7467
zoom = Math.Max(1.0, zoom);
@@ -95,7 +88,7 @@ public void Update(Point cursor, double zoom, Settings settings, bool show)
9588

9689
Composite();
9790
surface.Present(Handle, new Point(cursor.X - width / 2 - chrome.Margin, cursor.Y - height / 2 - chrome.Margin),
98-
appearance);
91+
appearance, LensAnimation.ScaleFor(appearance));
9992

10093
if (!visible)
10194
{
@@ -104,6 +97,24 @@ public void Update(Point cursor, double zoom, Settings settings, bool show)
10497
}
10598
Native.SetWindowPos(Handle, Native.HWND_TOPMOST, 0, 0, 0, 0,
10699
Native.SWP_NOMOVE | Native.SWP_NOSIZE | Native.SWP_NOACTIVATE);
100+
return false;
101+
}
102+
103+
public void Prepare(Point cursor, Settings settings)
104+
{
105+
EnsureChrome(cursor, settings);
106+
}
107+
108+
void EnsureChrome(Point cursor, Settings settings)
109+
{
110+
float scale = Native.GetScaleAt(cursor);
111+
int width = (int)Math.Round(settings.LensWidth * scale);
112+
int height = (int)Math.Round(settings.LensHeight * scale);
113+
if (chrome != null && chrome.Matches(width, height, scale)) return;
114+
115+
chrome = new LensChrome(width, height, scale);
116+
if (surface != null) surface.Dispose();
117+
surface = new DibSurface(chrome.Width, chrome.Height);
107118
}
108119

109120
public void HideLens()

0 commit comments

Comments
 (0)