From 1c207ae1c512f360b70d452df829c00bdda1f0eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Mon, 13 Nov 2023 20:02:11 +0100 Subject: [PATCH] macOS: Work around [NSApplication setWindowsMenu:] out of bound access The implementation of [NSApplication setWindowsMenu:] seems to look for the last item in the menu, but doesn't guard the check for the menu having items. Instead it guards on another array being non-empty, and in some situation this array has items of type NSWindowMenuItem while our window menu is empty (FB13369198). To work around this we insert a hidden dummy item into the menu. Fixes: PYSIDE-2525 Pick-to: 6.5 Change-Id: Iaa9dbc9454249f4eb34f8a338d0cc23685f0025a Reviewed-by: Friedemann Kleint Reviewed-by: Timur Pocheptsov (cherry picked from commit 0a0f7b864b0902fcedcc8cd26dd28779d36242ff) Reviewed-by: Qt Cherry-pick Bot --- src/plugins/platforms/cocoa/qcocoamenubar.mm | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/plugins/platforms/cocoa/qcocoamenubar.mm b/src/plugins/platforms/cocoa/qcocoamenubar.mm index 6dce096556e..72bbd9498dc 100644 --- a/src/plugins/platforms/cocoa/qcocoamenubar.mm +++ b/src/plugins/platforms/cocoa/qcocoamenubar.mm @@ -362,6 +362,15 @@ void QCocoaMenuBar::insertWindowMenu() winMenuItem.hidden = YES; winMenuItem.submenu = [[[NSMenu alloc] initWithTitle:@"QtWindowMenu"] autorelease]; + + // AppKit has a bug in [NSApplication setWindowsMenu:] where it will resolve + // the last item of the window menu's itemArray, but not account for the array + // being empty, resulting in a lookup of itemAtIndex:-1. To work around this, + // we insert a hidden dummy item into the menu. See FB13369198. + auto *dummyItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; + dummyItem.hidden = YES; + [winMenuItem.submenu addItem:[dummyItem autorelease]]; + [mainMenu insertItem:winMenuItem atIndex:mainMenu.itemArray.count]; app.windowsMenu = winMenuItem.submenu;