🍎

How to get applications that can open a file on macOS

2024/10/03に公開

I needed to get a list from the terminal of applications that could be selected with ‘Open with’ in Finder. This process is similar to what is described in the following link.

https://support.apple.com/guide/mac-help/choose-an-app-to-open-a-file-on-mac-mh35597/mac

By the way, all extensions can specify the application to be opened by default. and obtaining this was easy: just use the ‘mdls’ or ‘duti’ commands.

So, how can I achieve the process I’m aiming for?
For example, if you search the Internet, you will discover a technique that uses the “lsregister” command.
Although this was terribly redundant for me.

This is because the amount of stdout dumped at one time is approximately 20 MB. Do we use the grep command to extract the necessary information from it? The answer is no.

Therefore, I thought of another approach

From a Mac terminal, AppleScript can be executed using the "osascript" command. And AppleScript can use Swift excellent functions.

How about the LSCopyAllRoleHandlersForContentType function as a test?
However, this function is apparently obsolete since macOS 12.0.

https://developer.apple.com/documentation/coreservices/1448020-lscopyallrolehandlersforcontentt

I took further time to investigate, and as a result, I finally found the method I was looking for in AppKit: the URLsForApplicationsToOpenURL method.

https://developer.apple.com/documentation/appkit/nsworkspace/3753000-urlsforapplicationstoopenurl

Actually write an AppleScript based on this.

use AppleScript version "2.4" 
use scripting additions

use framework "AppKit"
set filePath to "file path"
set fileURL to current application's NSURL's fileURLWithPath:filePath

set workspace to current application's NSWorkspace's sharedWorkspace()
set appsArray to workspace's URLsForApplicationsToOpenURL:fileURL

set resultList to {}
repeat with appURL in appsArray
	set end of resultList to appURL's lastPathComponent() as text
end repeat
return resultList

I tried it with a PNG file and was able to get a list of applications that could open it with flying colors.

And this would be feasible from the terminal.

Discussion