iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐰

Hacks and Official Methods for Disabling NSToolbar Display Mode

に公開
2024/11/28

The NSToolbar Display Mode is a mechanism that allows users to switch between three currently available modes: "Icon and Label," "Icon Only," and "Text Only."

In short, up until macOS 14 Sonoma, no official method was provided to disable changes to the Display Mode. You had to use hacks, such as digging into the UI structure as introduced in this article. However, starting from macOS 15 Sequoia, a dedicated API has been added, allowing you to safely disable Display Mode changes and related UI without relying on hacks.


Context menu


macOS Sonoma version of Finder's toolbar palette


Old Mac OS X toolbar palette / Source: https://book.mynavi.jp/macfan/detail_summary/id=26650

As a side note, in older versions of macOS / Mac OS X, there was a mechanism to change the icon size (Size Mode) in addition to the Display Mode. At that time, the UI included a "Use Small Size" menu item and checkbox. In recent macOS versions, this feature is hidden by the system, and the API itself has been deprecated. Generally, there is no need to worry about the Size Mode.

2024-06-17 Update: Official method to be provided in macOS 15 Sequoia

The hacks mentioned in this article were necessary for macOS 14 Sonoma and earlier. Since a dedicated API is finally expected to be provided in macOS 15 Sequoia and later, you won't need to perform dangerous hacks.

var allowsDisplayModeCustomization: Bool { get set }

https://developer.apple.com/documentation/appkit/nstoolbar/4357348-allowsdisplaymodecustomization?changes=latest_minor

It seems hacks are the only way in macOS 14 Sonoma and earlier

It appears that NSToolbar Display Mode cannot be disabled officially in macOS 14 Sonoma and earlier. This is because no such public API is provided. However, looking at Safari's UI, these controls are disabled, so Apple seems to have some means of achieving this. I would love to know how, but unfortunately, it is not safely possible from a third-party developer's perspective.

On sites like Stack Overflow, the only methods I found were bluntly digging into NSView subviews and changing isHidden flags. I'll introduce the ones I tried that proved effective.


The Safari toolbar palette does not include a Display Mode pop-up button

Blocking Display Mode Changes

Simply override displayMode in an NSToolbar subclass and fix it to a specific mode. This is just a standard subclassing technique, so it isn't a hack and doesn't cause any issues.

This makes the Display Mode change itself non-functional. However, while the standard UI controls stop working, they remain visible in the UI. If that bothers you, you'll need further hacks.

MyToolbar
// Force fix to "Icon Only"
override var displayMode: NSToolbar.DisplayMode {
	get {
		.iconOnly
	}
	set {
		super.displayMode = .iconOnly
	}
}

Hiding the UI: Hiding Context Menu Items


Context menu

Disable certain items in the toolbar's context menu. This involves accessing a private property of NSToolbar using value(forKey:). First, get a reference to toolbarView using the key "_toolbarView", and then get a reference to the NSMenu object via the menu property.

Once you have the menu object, evaluate the action with NSSelectorFromString("changeToolbarDisplayMode:") and hide matching NSMenuItem objects by setting their isHidden flag.

This might not be allowed in apps submitted to the App Store, though some reports suggest it was fine. Either way, it's not a great approach, but it seems to be the most effective method for now.

MyToolbar
/// Disable menu items
func disableToolbarMenuActions() {
    // Get _toolbarView, then get the context menu
	if let toolbarView = value(forKey: "_toolbarView") as? NSView,
	   let contextMenu = toolbarView.menu {
		for item in contextMenu.items {
            // Hide target menu items
			if item.action == NSSelectorFromString("changeToolbarDisplayMode:") {
				item.isHidden = true
			}
		}
	}
}

Hiding the UI: Hiding the Toolbar Palette UI


macOS Sonoma version of Finder's toolbar palette

I want to hide the pop-up button on the toolbar palette (the palette used during customization) and the label that says "Show" (in Japanese environments).

runCustomizationPalette(_ sender: Any?) can be overridden to dig into the subviews immediately after the palette sheet is displayed to identify the target and hide it using isHidden.

Since this must be done immediately after display, there is an unavoidable issue where the pop-up button remains visible for a split second.

While the method of overriding runCustomizationPalette() mentioned above sometimes allowed the buttons to be visible for a moment, the following method using NSWindowDelegate can avoid this phenomenon by intercepting right before the palette is displayed.

The NSWindowDelegate method window(_:willPositionSheet:using:) allows you to detect the timing just before a sheet is displayed, so implement this in the main window's delegate. Next, obtain the contentView of the window corresponding to the palette sheet and proceed to dig through the subviews. As for identifying subviews, it seems that in recent versions of macOS (tested only on Sonoma 14.4.1), views are layered using NSStackView and NSBox, which requires some extra effort.

Reference: https://stackoverflow.com/questions/8351346/customize-nstoolbar-disable-use-small-size

NSWindowDelegate
func window(_ window: NSWindow, willPositionSheet sheet: NSWindow, using rect: NSRect) -> NSRect {
	if let sheetView = sheet.contentView {
		var needsRedraw = false
		// Array of all subviews flattened
		let allSubviews = sheetView.allSubviews()
		
		var labels = [NSTextField]()
		
		for view in allSubviews {
			// Identify and hide pop-up buttons
			if let button = view as? NSPopUpButton {
				button.isHidden = true
				needsRedraw = true
			}
			if let label = view as? NSTextField {
				labels.append(label)
			}
		}
		
		// Hide the "Show" label
		// Since it's hard to identify, treat the one at the very bottom of the sheetView coordinates as "it"
		targetLabel = labels.sorted { l0, l1 in
			var f0: NSRect {
				if let s0 = l0.superview, s0 != sheetView {
					return s0.convert(l0.frame, to: sheetView)
				}
				else {
					return l0.frame
				}
			}
			var f1: NSRect {
				if let s1 = l1.superview, s1 != sheetView {
					return s1.convert(l1.frame, to: sheetView)
				}
				else {
					return l1.frame
				}
			}
			
			return f0.minY < f1.minY
		}.first
						   
		if let targetLabel {
			targetLabel.isHidden = true
			needsRedraw = true
		}
		
		// Execute redraw
		if needsRedraw {
			sheetView.display()
		}
	}
	
	return rect
}
NSView+allSubviews
extension NSView {	
	func allSubviews() -> [NSView] {
		var allSubviews = [NSView]()
		for view in subviews {
			allSubviews.append(contentsOf: view.allSubviews())
		}
		return allSubviews
	}
}

Conclusion

As you might have guessed, the two methods other than "Blocking Display Mode Changes" are not very safe. They could break at any time with an OS update, and since they touch private areas, there is a concern that Apple might take issue with them if you are submitting the app to the App Store.

If you still want to disable toolbar Display Mode changes despite these risks, these methods seem to be your only options. However, since a safe API will be provided from macOS 15 Sequoia onwards, consider adopting that method for Sequoia and later while carefully weighing your approach for Sonoma and earlier.

Alternatively, you could simply disable the toolbar customization feature altogether. While this means users will no longer be able to freely rearrange the toolbar, it is very safe because it is controlled via a public API. In this case, none of the three methods introduced in this article are necessary.

allowsUserCustomization

Discussion