Getting screen dimensions while accounting the menu bar, dock and multiple displays

While improving my cascade windows shortcut, I wondered if I could do better than hard-code the height of the menu bar, in case my shortcut was useful for someone with a fancy new MacBook Pro, which has a taller menu bar to envelop the notch.

Shortcuts only provides the screen dimensions of the current display:

The usual AppleScript solution doesn’t handle multiple displays and I couldn’t find an easy way to get the menu bar window, without spelunking into System Events.

However, there’s a lot of attributes available via AppKit. Many solutions I found used third-party utilities that retrieve these attributes but we can use the AppleScript/JavaScript Objective-C bridge to get them directly:

function run(input, parameters) {
	ObjC.import("Cocoa")
	const frame = $.NSScreen.mainScreen.frame
	const visible = $.NSScreen.mainScreen.visibleFrame
	return frame.size.height - (visible.size.height + visible.origin.y)
}

The main screen is the one containing the window with keyboard focus. The frame has its origin and size attributes, while the visible frame excludes the area occupied by the menu bar and dock. Because I wanted the offset from the top left to start placing windows, I calculated the menu bar height by subtracting the visible height (adding the vertical visible origin, which gives the dock height, if any) from the frame height.

This gives 25 points on my MacBook Air and (I think) 38 on a new MacBook Pro. Yes, hard-coding or using Shortcut import questions would be easier, but I learned a lot in the process of working this out. I hope there’s something useful here for others!