Skip to content

Commit ed889a6

Browse files
larsbrubakerclaude
andcommitted
Deliver letter and digit keys on macOS so Command shortcuts work, and stop the beep
TranslateKeyCode only named special keys, so every letter and digit arrived as Keys.None and no Command (or Control) shortcut ever matched: ⌘S, ⌘Z, ⌘Y, ⌘A, ⌘C/V/X, ⌘+/⌘- and text-field copy/paste were all dead. Resolve the key from charactersIgnoringModifiers when the key-code table has no entry. Command chords were deliberately left unhandled so menu key equivalents could run, but the app installs no NSMenu, so they fell through to NSBeep. Swallow them like every other key down (still skipping OnKeyPress so ⌘S does not type an "s"); noted in DispatchEvent for whenever a main menu is added. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 0ea311a commit ed889a6

2 files changed

Lines changed: 244 additions & 14 deletions

File tree

PlatformMac/mac/MacSystemWindow.cs

Lines changed: 98 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1478,11 +1478,15 @@ private static void PumpEvents()
14781478
/// Hands an event to the agg window it belongs to.
14791479
/// </summary>
14801480
/// <returns>
1481-
/// True when AppKit must <em>not</em> also see the event. Only unmodified key events are swallowed:
1482-
/// the content view is a plain NSView with no key handling, so letting a keystroke walk the
1483-
/// responder chain ends at NSBeep. Command-modified keys are passed on so menu equivalents and
1484-
/// Cmd-Q keep working, and every mouse event is passed on because title-bar dragging, live resize
1485-
/// and the close button are all AppKit's to handle.
1481+
/// True when AppKit must <em>not</em> also see the event. Every key event is swallowed: the content
1482+
/// view is a plain NSView with no key handling, so letting a keystroke walk the responder chain
1483+
/// ends at NSBeep. That includes Command chords, which used to be passed on for menu key
1484+
/// equivalents - the application installs no NSMenu, so there were no equivalents to reach and
1485+
/// every Cmd-shortcut the application itself handled beeped on top of doing its work. If a main
1486+
/// menu is ever installed, unhandled Command chords will need forwarding again.
1487+
/// <para/>
1488+
/// Every mouse event is passed on because title-bar dragging, live resize and the close button are
1489+
/// all AppKit's to handle.
14861490
/// </returns>
14871491
private static bool DispatchEvent(IntPtr nsEvent)
14881492
{
@@ -1760,18 +1764,17 @@ internal static ulong ReleaseAppliedModifierKeys(IReadOnlySet<Keys> appliedModif
17601764
private bool HandleKeyDown(IntPtr nsEvent)
17611765
{
17621766
ulong flags = Send_Q(nsEvent, Sel("modifierFlags"));
1763-
Keys modifiers = TranslateModifiers(flags);
1764-
Keys keyCode = TranslateKeyCode(Send_u(nsEvent, Sel("keyCode")));
1767+
var keyEvent = MakeKeyEventArgs(nsEvent, flags);
17651768

1766-
var keyEvent = new KeyEventArgs(keyCode | modifiers);
17671769
this.aggSystemWindow.OnKeyDown(keyEvent);
17681770
Keyboard.SetKeyDownState(keyEvent.KeyCode, true);
17691771

1770-
// Command-modified keys are menu equivalents; agg gets a look but AppKit must still see them.
1772+
// A Command chord is a shortcut, never text, so it stops at the key down - typing Cmd-S must
1773+
// not also insert an "s" into whatever has focus.
17711774
bool commandHeld = (flags & NSEventModifierFlagCommand) != 0;
17721775
if (commandHeld)
17731776
{
1774-
return false;
1777+
return true;
17751778
}
17761779

17771780
if (!keyEvent.SuppressKeyPress)
@@ -1801,9 +1804,7 @@ private bool HandleKeyDown(IntPtr nsEvent)
18011804

18021805
private bool HandleKeyUp(IntPtr nsEvent)
18031806
{
1804-
Keys modifiers = TranslateModifiers(Send_Q(nsEvent, Sel("modifierFlags")));
1805-
Keys keyCode = TranslateKeyCode(Send_u(nsEvent, Sel("keyCode")));
1806-
var keyEvent = new KeyEventArgs(keyCode | modifiers);
1807+
var keyEvent = MakeKeyEventArgs(nsEvent, Send_Q(nsEvent, Sel("modifierFlags")));
18071808

18081809
// Only process the key up if we saw the key down, matching the Windows sink.
18091810
if (Keyboard.IsKeyDown(keyEvent.KeyCode))
@@ -1812,7 +1813,90 @@ private bool HandleKeyUp(IntPtr nsEvent)
18121813
Keyboard.SetKeyDownState(keyEvent.KeyCode, false);
18131814
}
18141815

1815-
return (Send_Q(nsEvent, Sel("modifierFlags")) & NSEventModifierFlagCommand) == 0;
1816+
// Swallowed for the same reason a key down is, Command chords included.
1817+
return true;
1818+
}
1819+
1820+
/// <summary>
1821+
/// Reads the parts of a key NSEvent that decide which agg key it is, and composes the event args.
1822+
/// </summary>
1823+
private KeyEventArgs MakeKeyEventArgs(IntPtr nsEvent, ulong flags)
1824+
{
1825+
return MakeKeyEventArgs(
1826+
Send_u(nsEvent, Sel("keyCode")),
1827+
FromNSString(Send_r(nsEvent, Sel("charactersIgnoringModifiers"))),
1828+
flags);
1829+
}
1830+
1831+
/// <summary>
1832+
/// Composes the agg key event a keyDown or keyUp carries, from the three parts of the NSEvent that
1833+
/// determine it.
1834+
/// </summary>
1835+
/// <remarks>
1836+
/// Pure - no ObjC calls, no state - so the whole key translation can be exercised without a window,
1837+
/// in the same spirit as <see cref="ModifierDownStateKeys"/>.
1838+
/// </remarks>
1839+
internal static KeyEventArgs MakeKeyEventArgs(ushort virtualKey, string charactersIgnoringModifiers, ulong flags)
1840+
{
1841+
Keys keyCode = TranslateKeyCode(virtualKey);
1842+
1843+
if (keyCode == Keys.None)
1844+
{
1845+
keyCode = TranslateCharacterKey(charactersIgnoringModifiers);
1846+
}
1847+
1848+
return new KeyEventArgs(keyCode | TranslateModifiers(flags));
1849+
}
1850+
1851+
/// <summary>
1852+
/// Maps the layout-resolved text of a key onto agg's <see cref="Keys"/>, for the letters and digits
1853+
/// <see cref="TranslateKeyCode"/> deliberately does not name.
1854+
/// </summary>
1855+
/// <remarks>
1856+
/// A virtual key code is a hardware position - 0x01 is "where S sits on a US layout" and is a
1857+
/// different letter on an AZERTY one - so the key code table cannot answer "which letter is this".
1858+
/// Shortcuts are all spelled as key codes (Ctrl+S, Ctrl+Z, Ctrl+A), so without this every one of
1859+
/// them arrived as a bare Control modifier with <see cref="Keys.None"/> attached and matched
1860+
/// nothing: Cmd-S did not save, it only beeped.
1861+
/// <para/>
1862+
/// <c>-[NSEvent charactersIgnoringModifiers]</c> is the source because it resolves the layout while
1863+
/// factoring Command and Option back out - Option-S is "s" here and the dead-key text only in
1864+
/// <c>characters</c>. Shift is <em>not</em> factored out, so each shifted spelling has to be mapped
1865+
/// onto the same key its unshifted spelling gives, which is what WinForms reports either way.
1866+
/// </remarks>
1867+
internal static Keys TranslateCharacterKey(string charactersIgnoringModifiers)
1868+
{
1869+
if (string.IsNullOrEmpty(charactersIgnoringModifiers))
1870+
{
1871+
return Keys.None;
1872+
}
1873+
1874+
char character = char.ToUpperInvariant(charactersIgnoringModifiers[0]);
1875+
1876+
if (character >= 'A' && character <= 'Z')
1877+
{
1878+
return Keys.A + (character - 'A');
1879+
}
1880+
1881+
if (character >= '0' && character <= '9')
1882+
{
1883+
return Keys.D0 + (character - '0');
1884+
}
1885+
1886+
switch (character)
1887+
{
1888+
// The zoom shortcuts, with the shifted spelling of each key alongside the unshifted one.
1889+
case '=':
1890+
case '+':
1891+
return Keys.Oemplus;
1892+
1893+
case '-':
1894+
case '_':
1895+
return Keys.OemMinus;
1896+
1897+
default:
1898+
return Keys.None;
1899+
}
18161900
}
18171901

18181902
/// <summary>
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
/*
2+
Copyright (c) 2026, Lars Brubaker
3+
All rights reserved.
4+
5+
Redistribution and use in source and binary forms, with or without
6+
modification, are permitted provided that the following conditions are met:
7+
8+
1. Redistributions of source code must retain the above copyright notice, this
9+
list of conditions and the following disclaimer.
10+
2. Redistributions in binary form must reproduce the above copyright notice,
11+
this list of conditions and the following disclaimer in the documentation
12+
and/or other materials provided with the distribution.
13+
14+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
18+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
23+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24+
25+
The views and conclusions contained in the software and documentation are those
26+
of the authors and should not be interpreted as representing official policies,
27+
either expressed or implied, of the FreeBSD Project.
28+
*/
29+
30+
using System.Threading.Tasks;
31+
using MatterHackers.Agg.Platform.Mac;
32+
using TUnit.Assertions;
33+
using TUnit.Assertions.Extensions;
34+
using TUnit.Core;
35+
36+
using static MatterHackers.Agg.Platform.Mac.AppKitConstants;
37+
38+
namespace MatterHackers.Agg.UI.Tests
39+
{
40+
/// <summary>
41+
/// A keyDown carries a hardware key position, not a letter, so every letter and digit shortcut has to
42+
/// be resolved from the layout-resolved characters instead. Without that, Cmd+S arrived as a bare
43+
/// Control modifier with no key attached and no shortcut in the application could ever match it.
44+
/// </summary>
45+
public class MacKeyTranslationTests
46+
{
47+
/// <summary>The US-layout hardware position of S; on another layout it is another letter, which is
48+
/// exactly why a key code cannot be what a letter shortcut is matched on.</summary>
49+
private const ushort VkSOnUsLayout = 0x01;
50+
51+
[Test]
52+
public async Task CommandSIsControlS()
53+
{
54+
KeyEventArgs keyEvent = MacSystemWindow.MakeKeyEventArgs(VkSOnUsLayout, "s", NSEventModifierFlagCommand);
55+
56+
await Assert.That(keyEvent.KeyCode).IsEqualTo(Keys.S);
57+
await Assert.That(keyEvent.Control).IsTrue();
58+
}
59+
60+
[Test]
61+
public async Task PhysicalControlSIsAlsoControlS()
62+
{
63+
KeyEventArgs keyEvent = MacSystemWindow.MakeKeyEventArgs(VkSOnUsLayout, "s", NSEventModifierFlagControl);
64+
65+
await Assert.That(keyEvent.KeyCode).IsEqualTo(Keys.S);
66+
await Assert.That(keyEvent.Control).IsTrue();
67+
}
68+
69+
/// <summary>The everyday shortcuts, each of which was equally dead before the letters resolved.</summary>
70+
[Test]
71+
[Arguments("z", Keys.Z)]
72+
[Arguments("y", Keys.Y)]
73+
[Arguments("a", Keys.A)]
74+
[Arguments("c", Keys.C)]
75+
[Arguments("v", Keys.V)]
76+
[Arguments("x", Keys.X)]
77+
public async Task CommandLetterShortcutsResolve(string characters, Keys expected)
78+
{
79+
KeyEventArgs keyEvent = MacSystemWindow.MakeKeyEventArgs(0, characters, NSEventModifierFlagCommand);
80+
81+
await Assert.That(keyEvent.KeyCode).IsEqualTo(expected);
82+
await Assert.That(keyEvent.Control).IsTrue();
83+
}
84+
85+
/// <summary>
86+
/// charactersIgnoringModifiers drops Command and Option but keeps Shift, so a shifted key arrives
87+
/// spelled differently while WinForms reports the same key code either way.
88+
/// </summary>
89+
[Test]
90+
public async Task ShiftedSpellingsShareTheirKeyCode()
91+
{
92+
KeyEventArgs shiftedZ = MacSystemWindow.MakeKeyEventArgs(
93+
0,
94+
"Z",
95+
NSEventModifierFlagCommand | NSEventModifierFlagShift);
96+
97+
await Assert.That(shiftedZ.KeyCode).IsEqualTo(Keys.Z);
98+
await Assert.That(shiftedZ.Control).IsTrue();
99+
await Assert.That(shiftedZ.Shift).IsTrue();
100+
101+
// The 3D view's zoom shortcuts: Cmd+= and Cmd++ are one key, as are Cmd+- and Cmd+_.
102+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, "=", NSEventModifierFlagCommand).KeyCode)
103+
.IsEqualTo(Keys.Oemplus);
104+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, "+", NSEventModifierFlagCommand).KeyCode)
105+
.IsEqualTo(Keys.Oemplus);
106+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, "-", NSEventModifierFlagCommand).KeyCode)
107+
.IsEqualTo(Keys.OemMinus);
108+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, "_", NSEventModifierFlagCommand).KeyCode)
109+
.IsEqualTo(Keys.OemMinus);
110+
}
111+
112+
[Test]
113+
public async Task DigitsResolve()
114+
{
115+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, "1", 0).KeyCode).IsEqualTo(Keys.D1);
116+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, "0", 0).KeyCode).IsEqualTo(Keys.D0);
117+
}
118+
119+
/// <summary>
120+
/// The named keys have to keep winning: their characters are private-use-area codes that are not
121+
/// text and must never be mistaken for one.
122+
/// </summary>
123+
[Test]
124+
public async Task NamedKeysBeatTheirCharacters()
125+
{
126+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(VkForwardDelete, "", 0).KeyCode)
127+
.IsEqualTo(Keys.Delete);
128+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(VkReturn, "\r", 0).KeyCode).IsEqualTo(Keys.Enter);
129+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(VkEscape, "", 0).KeyCode).IsEqualTo(Keys.Escape);
130+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(VkDelete, "", 0).KeyCode).IsEqualTo(Keys.Back);
131+
}
132+
133+
/// <summary>A dead key, or a character agg has no key for, still has to carry its modifiers.</summary>
134+
[Test]
135+
public async Task UnknownCharactersAreNoKeyButKeepTheirModifiers()
136+
{
137+
KeyEventArgs keyEvent = MacSystemWindow.MakeKeyEventArgs(0, "é", NSEventModifierFlagCommand);
138+
139+
await Assert.That(keyEvent.KeyCode).IsEqualTo(Keys.None);
140+
await Assert.That(keyEvent.Control).IsTrue();
141+
142+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, null, 0).KeyCode).IsEqualTo(Keys.None);
143+
await Assert.That(MacSystemWindow.MakeKeyEventArgs(0, string.Empty, 0).KeyCode).IsEqualTo(Keys.None);
144+
}
145+
}
146+
}

0 commit comments

Comments
 (0)