#!/usr/bin/xcrun swift | |
import Cocoa | |
struct ProgramOption { | |
var list : Bool = false | |
var set : String? = nil | |
var help : Bool = false | |
} | |
func getInstalledBrowsers () -> [ NSBundle ] { | |
var browsers = [ NSBundle ]() | |
let array = LSCopyAllHandlersForURLScheme("http").takeRetainedValue() | |
for var i = 0, len = CFArrayGetCount(array); i < len; i++ { | |
let bundleId = unsafeBitCast(CFArrayGetValueAtIndex(array, i), CFString.self) as String | |
if let path = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier(bundleId) { | |
if let bundle = NSBundle(path: path) { | |
// let name: String = bundle.infoDictionary!["CFBundleName"] as String | |
browsers.append(bundle) | |
} | |
} | |
} | |
return browsers | |
} | |
func setDefaultBrowser (bundleId : String) -> Bool { | |
let httpResult = LSSetDefaultHandlerForURLScheme("http", bundleId) | |
let httpsResult = LSSetDefaultHandlerForURLScheme("https", bundleId) | |
if httpResult == noErr && httpsResult == noErr { | |
return true | |
} else { | |
return false | |
} | |
} | |
var option = ProgramOption() | |
for var i = 0, len = Process.arguments.count; i < len; i++ { | |
let arg = Process.arguments[i] | |
switch arg { | |
case "-h", "--help": | |
option.help = true | |
case "-l", "--list": | |
option.list = true | |
case "-s", "--set": | |
option.set = Process.arguments[++i] | |
default: | |
break | |
} | |
} | |
if option.help { | |
println("-h, --help: Show help (this)") | |
println("-l, --list: Show installed browser list") | |
println("-s [bundleId], --set [bundleId]: Set default browser to specified browser") | |
exit(0) | |
} | |
if option.list { | |
let browsers = getInstalledBrowsers() | |
for browser in browsers { | |
let bundleId = browser.bundleIdentifier! | |
let path = browser.bundlePath | |
println("\(bundleId)") | |
println("\t\(path)") | |
} | |
} | |
if let bundleId = option.set { | |
if setDefaultBrowser(bundleId) { | |
exit(0) | |
} else { | |
exit(1) | |
} | |
} | |
exit(0) | |
peco る
set_default_browser.swift --set $( set_default_browser.swift -l | grep -v "\t" | peco )
雑にpecoれる