Files
osr-mono/packages/osr-code-bot/kbot-extensions/docs/shell-ext/osx.md
T
2025-02-01 14:25:34 +01:00

2.5 KiB

Custom Context Menus (Open With) in macOS

There are several ways to register custom context menus ("Open With" options) in macOS.

Method 1: Using Launch Services

This method uses macOS's built-in Launch Services feature:

  1. Open System Preferences
  2. Go to Keyboard > Shortcuts > Services
  3. Create a new service in Automator

Method 2: Using an Application Bundle

To register a custom application in the "Open With" menu, you need to create a proper application bundle with an Info.plist file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>txt</string>
                <string>md</string>
            </array>
            <key>CFBundleTypeName</key>
            <string>Text Document</string>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
        </dict>
    </array>
    <key>CFBundleIdentifier</key>
    <string>com.yourcompany.yourapp</string>
    <key>CFBundleName</key>
    <string>YourApp</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
</dict>
</plist>

Method 3: Using UTIs (Uniform Type Identifiers)

You can also register UTIs for your application to handle specific file types. Here's an example in Swift:

import UniformTypeIdentifiers

class DocumentHandler: NSObject, UTIDocumentProvider {
    func document(withContentsOfURL url: URL,
                  typeUti: String) throws -> AnyObject {
        // Handle the document here
        return NSString()
    }
}

Method 4: Using defaults Command

You can use the defaults command-line tool to associate file types with applications:

# Associate .txt files with your app
defaults write com.apple.TextEdit LSHandlers -txt
your.app.bundle.identifier

Best Practices

  1. Always provide clear file type associations in your Info.plist
  2. Use unique bundle identifiers
  3. Provide appropriate icons for your file types
  4. Implement proper error handling
  5. Test your implementation thoroughly

Useful Tools

  1. Xcode - For creating application bundles
  2. Automator - For creating simple services
  3. lstype command - For inspecting UTIs
  4. defaults command - For managing file associations