AppleScript名:RFC822デコーダー v0 |
— Created 2016-02-07 by Takaaki Naganoya — 2016 Piyomaru Software –http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter use AppleScript version "2.4" use scripting additions use framework "Foundation" set dateString to "Sun, 19 May 2002 15:21:36 GMT" –set dateString to "Tue, 01 Dec 2009 08:48:25 +0000" set aRes to rfc822StrDecode(dateString) of me –> date "2002年5月20日月曜日 0:21:36" –http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter on rfc822StrDecode(dateString) set aTZ to "GMT" set en_US_POSIX to current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX" set dateFormatter to current application’s NSDateFormatter’s alloc()’s init() dateFormatter’s setLocale:en_US_POSIX dateFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(current application’s NSString’s stringWithString:aTZ)) set aDate to missing value set RFC822String to (current application’s NSString’s stringWithString:dateString)’s uppercaseString() if (RFC822String’s rangeOfString:",")’s location() is not equal to (current application’s NSNotFound) then if aDate is equal to missing value then — Sun, 19 May 2002 15:21:36 GMT dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm:ss zzz" set aDate to dateFormatter’s dateFromString:RFC822String end if if aDate is equal to missing value then — Sun, 19 May 2002 15:21 GMT dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm zzz" set aDate to dateFormatter’s dateFromString:RFC822String end if if aDate is equal to missing value then — Sun, 19 May 2002 15:21:36 dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm:ss" set aDate to dateFormatter’s dateFromString:RFC822String end if if aDate is equal to missing value then — Sun, 19 May 2002 15:21:36 dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm" set aDate to dateFormatter’s dateFromString:RFC822String end if else if aDate is equal to missing value then — 19 May 2002 15:21:36 GMT dateFormatter’s setDateFormat:"d MMM yyyy HH:mm:ss zzz" set aDate to dateFormatter’s dateFromString:RFC822String end if if aDate is equal to missing value then — 19 May 2002 15:21 GMT dateFormatter’s setDateFormat:"d MMM yyyy HH:mm zzz" set aDate to dateFormatter’s dateFromString:RFC822String end if if aDate is equal to missing value then — 19 May 2002 15:21:36 dateFormatter’s setDateFormat:"d MMM yyyy HH:mm:ss" set aDate to dateFormatter’s dateFromString:RFC822String end if if aDate is equal to missing value then — 19 May 2002 15:21 dateFormatter’s setDateFormat:"d MMM yyyy HH:mm" set aDate to dateFormatter’s dateFromString:RFC822String end if end if if aDate is equal to missing value then return false return aDate as date end rfc822StrDecode |
カテゴリー: System
今日のYYYY,MM,DDを取得する
AppleScript名:今日のYYYY,MM,DDを取得する |
— Created 2015-12-26 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aCalend to current application’s NSCalendar’s currentCalendar() set aDate to current application’s NSDate’s |date|() set aYear to aCalend’s component:(current application’s NSCalendarUnitYear) fromDate:aDate set aYearStr to numToZeroPaddingStr(aYear, 4, "0") of me set aMonth to aCalend’s component:(current application’s NSCalendarUnitMonth) fromDate:aDate set aMonthStr to numToZeroPaddingStr(aMonth, 2, "0") of me set aDay to aCalend’s component:(current application’s NSCalendarUnitDay) fromDate:aDate set aDayStr to numToZeroPaddingStr(aDay, 2, "0") of me set dStr to aYearStr & aMonthStr & aDayStr –> "20171219" –整数の値に指定桁数ゼロパディングして文字列で返す on numToZeroPaddingStr(aNum as integer, aDigit as integer, paddingChar as text) set aNumForm to current application’s NSNumberFormatter’s alloc()’s init() aNumForm’s setPaddingPosition:(current application’s NSNumberFormatterPadBeforePrefix) aNumForm’s setPaddingCharacter:paddingChar aNumForm’s setMinimumIntegerDigits:aDigit set bNum to current application’s NSNumber’s numberWithInt:aNum set aStr to aNumForm’s stringFromNumber:bNum return aStr as text end numToZeroPaddingStr |
epoch timeをdateに変換
AppleScript名:epoch timeをdateに変換 |
— Created 2017-12-19 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set epochTimeStr to current application’s NSString’s stringWithString:"1401325412" set aDate to (current application’s NSDate’s alloc()’s initWithTimeIntervalSince1970:(epochTimeStr’s doubleValue())) as date –> (NSDate) 2014-05-29 01:03:32 +0000 –> date "2014年5月29日木曜日 10:03:32" |
現在時刻のepoch timeを取得する
AppleScript名:現在時刻のepoch timeを取得する |
— Created 2017-12-19 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set curDate to current application’s NSDate’s |date|() set epochSeconds to (curDate’s timeIntervalSince1970()) |
iBooksライブラリ中のepubファイルから情報を取得 v3
AppleScript名:iBooksライブラリ中のepubファイルから情報を取得 v3 |
— Created 2017/02/26 by Christopher Stone — Modified 2017/11/01 by Takaaki Naganoya use framework "Foundation" use scripting additions use mdLib : script "Metadata Lib" version "1.0.0" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#Metadata_Lib property NSString : a reference to current application’s NSString property NSMutableArray : a reference to current application’s NSMutableArray property NSPropertyListFormat : a reference to current application’s NSPropertyListFormat property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding property NSPropertyListImmutable : a reference to current application’s NSPropertyListImmutable property NSPropertyListSerialization : a reference to current application’s NSPropertyListSerialization set aPath to POSIX path of (path to library folder from user domain) set sourceFolder to aPath & "Containers/com.apple.BKAgentService/Data/Documents/iBooks/Books/" set textFiles to mdLib’s searchFolders:{sourceFolder} searchString:"kMDItemContentType contains %@ || kMDItemContentType contains %@ " searchArgs:{"com.apple.ibooks-folder", "org.idpf.epub-container"} set outDicList to NSMutableArray’s new() repeat with i in textFiles set aFile to (i as string) if aFile ends with "/" then set aFullPath to aFile & "iTunesMetadata.plist" else set aFullPath to aFile & "/iTunesMetadata.plist" end if try set xmlData to read ((POSIX file aFullPath) as alias) as «class utf8» set xRes to readPlistFromStr(xmlData) of me log xRes as list of string or string –as anything (maybe record or missing value) (*cover-writing-mode:vertical, genre:教育, scroll-axis:default, sort-artist:あっぷる, BKITunesMigratedMetadata:PersistentID:6.68315366592803E+18, seriesTitle:Everyone Can Code, sort-name:Swiftによるあぷりけーしょん開発:入門編, itemId:1209648719, apple-id:xxxxxxxxxxxx@xxx.xxx, fileExtension:ibooks, year:2017, releaseDate:2017-03-19T07:00:00Z, BKInsertionDate:512115887, asset-info:flavor:pluspub, file-size:60642970, book-info:publication-version:162901775, PageProgression:default, asset-info:flavor:pluspub, file-size:60642970, package-file-hash:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX, BKAllocatedSize:82993152, longDescription:このコースでは、Swiftという言語を使って基本的なプログラミングの土台をしっかりと作り上げていきます。基本的なiOSアプリケーションを一から開発するために必要なツール、手法、概念を活用して、実践的な練習に取り組みます。さらに、プログラミングと優れたアプリケーション開発の土台となる、ユーザーインターフェイス設計の基本原則についても学習します。このコースを受講するにあたってプログラミングの経験は必要ありません。プログラミングの経験がある場合、レッスンの最初の方は簡単に読み進めていただくとよいでしょう。このブックではプログラミングの基礎にとどまらず、ソフトウェア開発ツールや概念、ベストプラクティスについても学習できます。, artistId:9.39801385E+8, artistName:Apple Education, isPreview:false, BKDisplayName:mzbf.eqmpijqw..d2.dlv.d2.dlv.ibooks, human-friendly-publication-version:1.1, shouldDisableTouchEmulation:true, vendorId:379015, drmVersionNumber:0, kind:ebook, s:143462, genreId:10037, explicit:2, seriesAdamId:1.118575554E+9, publisher:Apple Inc. – Education, versionRestrictions:16843008, BKGenerationCount:2, desktopSupportLevel:supported, primaryLanguage:ja, itemName:Swiftによるアプリケーション開発:入門編, purchaseDate:2017-03-25T06:21:26Z, shouldDisableOptimizeSpeed:true, obeyPageBreaks:1, pageCount:244*) if xRes is not equal to missing value then (outDicList’s addObject:xRes) end if end try end repeat return outDicList as list of string or string –as anything –stringのplistを読み込んでNSDictionaryに on readPlistFromStr(theString) set aSource to NSString’s stringWithString:theString set pListData to aSource’s dataUsingEncoding:(NSUTF8StringEncoding) set aPlist to NSPropertyListSerialization’s propertyListFromData:pListData mutabilityOption:(NSPropertyListImmutable) |format|:(NSPropertyListFormat) errorDescription:(missing value) return aPlist end readPlistFromStr |
文字列で与えたシェルコマンドを実行する v2
do shell scriptコマンドとほぼ等価な、Cocoaの機能を用いたshell script実行のAppleScriptです。
よく「Terminal.app上のshell scriptをそのままdo shell scriptコマンドで実行して動かない」という声を聞きますが、そもそも環境変数が全然違うのでそのまま動くはずがありません。
AppleScriptのdo shell scriptコマンドは、いまのmacOSのセキュリティ向上の流れで行けば確実に近い将来に「デフォルトで実行禁止」「環境設定でオンにしてはじめて実行可能に」という扱いになることでしょう。
Cocoaのshell command呼び出し機能についても同様の制限が加わるかどうかは不明ですが、Cocoa経由でのshell command呼び出しAppleScriptについて調べておきました。
AppleScript名:文字列で与えたシェルコマンドを実行する v2 |
— Created 2016-02-13 by Takaaki Naganoya — 2016 Piyomaru Software –以下を参照: –http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app use AppleScript version "2.4" use scripting additions use framework "Foundation" set aRes to (runCommandString("pwd") of me) as string –> "/" set bRes to (runCommandString("cd & ls -la") of me) as string –Lock Screen –runCommandAtPath("/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession", "-suspend") of me –文字列で与えたシェルコマンドを実行する on runCommandString(commandStr as string) set aPipe to current application’s NSPipe’s pipe() set aTask to current application’s NSTask’s alloc()’s init() aTask’s setLaunchPath:"/bin/sh" aTask’s setArguments:{"-c", current application’s NSString’s stringWithFormat_("%@", commandStr)} –stringWithFormatはASOCに書き換え時の要注意点 aTask’s setStandardOutput:aPipe set aFile to aPipe’s fileHandleForReading() aTask’s |launch|() return current application’s NSString’s alloc()’s initWithData:(aFile’s readDataToEndOfFile()) encoding:(current application’s NSUTF8StringEncoding) end runCommandString –指定したパスのシェルコマンドを実行する(結果などは取得しない) on runCommandAtPath(commandPath as string, anArgument as string) set aTask to current application’s NSTask’s alloc()’s init() aTask’s setLaunchPath:commandPath aTask’s setArguments:(current application’s NSArray’s arrayWithObject:anArgument) aTask’s |launch|() end runCommandAtPath |
ドメイン名からIPアドレスを取得
AppleScript名:ドメイン名からIPアドレスを取得 |
— Created 2016-04-03 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set anIP to ((current application’s NSHost’s hostWithName:"www.google.com")’s address()) as string –> "216.58.200.196" |
インターネット接続確認
AppleScript名:インターネット接続確認 |
— Created 2015-12-16 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aRes to hasInternetConnection() of me –> true on hasInternetConnection() set aURL to current application’s |NSURL|’s alloc()’s initWithString:"http://www.google.com" set aReq to current application’s NSURLRequest’s alloc()’s initWithURL:aURL cachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:5.0 set urlRes to (current application’s NSURLConnection’s sendSynchronousRequest:aReq returningResponse:(missing value) |error|:(missing value)) if urlRes = missing value then return false else return true end if end hasInternetConnection |
Twitter投稿
macOS 10.13まではTwitter投稿やFacebook連携などもOSに組み込まれていたので、手軽にこうした機能を利用でき、macOS 10.13までの環境ではこのように呼び出せるようになっていました。
macOS 10.14から方針が変わり、これらの機能はOSに組み込まれなくなりました。いまだと、REST API経由で投稿を行うことになるでしょうか。
AppleScript名:Twitter投稿 |
— Created 2015-01-24 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aString to "ぴよ〜" set twService to current application’s NSSharingService’s sharingServiceNamed:(current application’s NSSharingServiceNamePostOnTwitter) set twService’s delegate to me set shareItems to current application’s NSMutableArray’s alloc()’s initWithObjects:aString tell twService to performWithItems:shareItems |
AirDropでファイルを送信する
Sharing Utilitiesを用いてAirDrop経由のファイル送信を行うAppleScriptです。
さすがに、Sharing Utilitiesは仕様も古いので、最新の環境に合わせて書き換えた「AirSharingLib Script Library」を配布、そちらを用いて同様の機能を実現するAppleScriptも掲載しています。
AppleScript名:AirDropでファイルを送信する |
use AppleScript version "2.4" use scripting additions use framework "Foundation" use shareLib : script "Sharing Utilities" –https://macosxautomation.com/mavericks/libraries/examples.html set anItem to choose file with prompt "Select File to send via AirDrop" set aaList to {anItem} begin AirDrop with aaList |
LAN上のHDDをマウントする v2
AppleScript名:LAN上のHDDをマウントする v2 |
–SMB経由でマウント set userAccount to "maro" –ユーザー名(環境に応じて書き換え) set userPass to "xxxxxx" –パスワード(環境に応じて書き換え) set aMachine to "smb://MBA11._smb._tcp.local/Macintosh HD" –11インチMacBook Air (10.9.2)でSMBのみ有効にしてテスト mountVolume(aMachine, userAccount, userPass) of me –通常実行 –AFP経由でマウント set userAccount to "maro" –ユーザー名(環境に応じて書き換え) set userPass to "xxxxxx" –パスワード(環境に応じて書き換え) set aMachine to "afp://MBA13._afpovertcp._tcp.local/Macintosh SSD" –13インチMacBook Air (10.7.5)でAFPとSMBの両方を有効にしてテスト mountVolumeAsync(aMachine, userAccount, userPass) of me –非同期実行 –指定のネットワーク上のディスクをマウントする on mountVolume(aMachine, userAccount, userPass) try with timeout of 100 seconds mount volume aMachine as user name userAccount with password userPass end timeout on error return false end try return true end mountVolume –指定のネットワーク上のディスクをマウントする(非同期実行) on mountVolumeAsync(aMachine, userAccount, userPass) try ignoring application responses mount volume aMachine as user name userAccount with password userPass end ignoring on error — end try end mountVolumeAsync |
無線LANデバイスのMACアドレスを取得する
AppleScript名:無線LANデバイスのMACアドレスを取得する |
— Created 2015-08-18 by Takaaki Naganoya — Created 2015-08-18 by Shane Stanley — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "CoreWLAN" set aRes to retWiFiMACaddress() –> "XX:XX:XX:XX:XX:XX" –WiFi DeviceのMAC ADDRESSを返す on retWiFiMACaddress() –Get WLAN Device Name set allNames to current application’s CWInterface’s interfaceNames()’s allObjects() –> (NSArray) {"en0"} –@MacBook Pro Retina 2012 set hitF to false repeat with i from 1 to allNames’s |count|() set aInterface to (current application’s CWInterface’s interfaceWithName:(allNames’s objectAtIndex:(i – 1))) if aInterface’s serviceActive() as boolean then set hitF to true exit repeat end if end repeat if hitF = false then return false –There is No WiFi Device (Broken or illigal configuration or Hackintosh) set aHWAddress to aInterface’s hardwareAddress() as text –> "b8:xx:xx:xx:xx:xx"–MAC Address return aHWAddress end retWiFiMACaddress |
無線LANの各種情報を取得する v2.2
AppleScript名:無線LANの各種情報を取得する v2.2 |
— Created 2015-08-18 by Shane Stanley — Modified 2015-08-18 by Takaaki Naganoya use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "CoreWLAN" –Get WLAN Device Name set allNames to current application’s CWInterface’s interfaceNames()’s allObjects() log allNames as list of string or string –> (NSArray) {"en0"} –@MacBook Pro Retina 2012 set hitF to false repeat with i from 1 to allNames’s |count|() set aInterface to (current application’s CWInterface’s interfaceWithName:(allNames’s objectAtIndex:(i – 1))) if aInterface’s serviceActive() as boolean then set hitF to true exit repeat end if end repeat if hitF = false then return false –There is No WiFi Device –WiFi device is Power On ? repeat 10 times set aPower to (aInterface’s powerOn()) as boolean if aPower = false then –ActiveなWLANがない場合(WiFiをオフにしている)にはWiFiパワーオン set wRes to aInterface’s setPower:true |error|:(missing value) delay 1 else exit repeat end if end repeat if aPower = false then return false –I could not power on WiFi deveice set aChan to aInterface’s wlanChannel() –> (CWChannel) <CWChannel: 0x60000040cdd0> [channelNumber=1(2GHz), channelWidth={20MHz}] set chanNumber to aChan’s channelNumber() log chanNumber –> 52 set chanBand to aChan’s channelBand() — 0 = unknown, 1 = 2GHz, 2 = 5GHz log chanBand –> 2 set chanWidth to aChan’s channelWidth() — 0 = unknown, 1 = 20MHz, 2 = 40MHz log chanWidth –> 2 set aTransRate to aInterface’s transmitRate() log aTransRate –> 162.0 set aChannnels to aInterface’s supportedWLANChannels() –> (NSSet) {(CWChannel) <CWChannel: 0x60800020fad0> [channelNumber=1(2GHz), channelWidth={20MHz}, active], (CWChannel) <CWChannel: 0x60800020fb90> [channelNumber=2(2GHz), channelWidth={20MHz}, active], ……………(CWChannel) <CWChannel: 0x608000208410> [channelNumber=64(5GHz), channelWidth={20MHz}, DFS], (CWChannel) <CWChannel: 0x60800020f9e0> [channelNumber=136(5GHz), channelWidth={20MHz}, DFS]} set aSSIDdata to aInterface’s ssidData() –> (NSData) <45787472 xxxxxxxx xxxxxxxx xxxx> set aSSID to aInterface’s ssid() as text –> "Extreme net_5G" set aActive to aInterface’s serviceActive() –> true set aSecurity to aInterface’s security() –> 4 set aRSSIval to aInterface’s rssiValue() –> -72 set aPower to aInterface’s powerOn() –> true set aNoise to aInterface’s noiseMeasurement() –> -91 set aIFname to aInterface’s interfaceName() as text –> "en0" set aMode to aInterface’s interfaceMode() –> 1 set aHWAddress to aInterface’s hardwareAddress() as text –> "b8:xx:xx:xx:xx:xx"–MAC Address set aCountry to aInterface’s countryCode() as text –> "JP" set aConfig to aInterface’s configuration() –> (CWConfiguration) <CWConfiguration: 0x6100002348e0> set aCacheRes to aInterface’s cachedScanResults() –> (NSSet) {(CWNetwork) <CWNetwork: 0x618000402740> ……………… [channelNumber=11(2GHz), channelWidth={20MHz}], ibss=0]} set aBSSID to aInterface’s bssid() as text –> "10:XX:XX:XX:XX:XX" set aPhyMode to aInterface’s activePHYMode() –> 4 |
WiFiデバイスのパワーをオンに
AppleScript名:WiFiデバイスのパワーをオンに |
— Created 2015-08-18 by Shane Stanley — Modified 2015-08-18 by Takaaki Naganoya use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "CoreWLAN" set wRes to powerOnEveryWiFiDevices() of me on powerOnEveryWiFiDevices() set allNames to current application’s CWInterface’s interfaceNames()’s allObjects() as list if allNames = {} then return false set powerList to {} repeat with i in allNames set j to contents of i set aInterface to (current application’s CWInterface’s interfaceWithName:j) set wRes to (aInterface’s setPower:true |error|:(missing value)) set aPower to (aInterface’s powerOn()) as boolean if aPower = false then display notification "Error occured in enabling an Wifi deviece ( " & j & " )…." end if set the end of powerList to aPower end repeat return ({true} is in powerList) –return whether some WiFi interface is on end powerOnEveryWiFiDevices |
LAN上のファイルサーバー(smb)のホスト名を取得する
AppleScript名:LAN上のファイルサーバー(smb)のホスト名を取得する |
— Created 2015-12-24 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" property foundHosts : {} property myHostName : "" findHostsViaBonjour("_smb._tcp") of me –smb’s port:445 –> {"MBA13"} on findHostsViaBonjour(aType) set foundHosts to {} set myHostName to (current application’s NSHost’s currentHost()’s localizedName()) as string set aBrowser to current application’s NSNetServiceBrowser’s alloc()’s init() aBrowser’s setDelegate:me aBrowser’s searchForServicesOfType:aType inDomain:"" repeat 1000 times if foundHosts is not equal to {} then exit repeat delay 0.01 end repeat aBrowser’s setDelegate:(missing value) return foundHosts end findHostsViaBonjour on netServiceBrowser:aNetServiceBrowser didFindService:aNetService moreComing:aMoreComing set aDesc to aNetServiceBrowser’s |description|() set bDesc to aNetService’s |description|() set cDesc to (aNetService’s |name|()) as text if cDesc is not in foundHosts and cDesc is not equal to myHostName then set the end of foundHosts to cDesc end if end netServiceBrowser:didFindService:moreComing: |
LAN上のファイルサーバー(afp)のホスト名を取得する
AppleScript名:LAN上のファイルサーバー(afp)のホスト名を取得する |
— Created 2015-12-24 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" property foundHosts : {} property myHostName : "" findHostsViaBonjour("_afpovertcp._tcp") of me –AFP’s port:548 –> {"MBA13", "Mini_2", "MBA11"} on findHostsViaBonjour(aType) set foundHosts to {} set myHostName to (current application’s NSHost’s currentHost()’s localizedName()) as string set aBrowser to current application’s NSNetServiceBrowser’s alloc()’s init() aBrowser’s setDelegate:me aBrowser’s searchForServicesOfType:aType inDomain:"" repeat 1000 times if foundHosts is not equal to {} then exit repeat delay 0.01 end repeat aBrowser’s setDelegate:(missing value) return foundHosts end findHostsViaBonjour on netServiceBrowser:aNetServiceBrowser didFindService:aNetService moreComing:aMoreComing set aDesc to aNetServiceBrowser’s |description|() set bDesc to aNetService’s |description|() set cDesc to (aNetService’s |name|()) as text if cDesc is not in foundHosts and cDesc is not equal to myHostName then set the end of foundHosts to cDesc end if end netServiceBrowser:didFindService:moreComing: |
Notification
macOS 10.10より、標準のScripting環境(スクリプトエディタ)上でCocoa-bridgeが使えるようになったので、Cocoa系のevent(Notification)が使えるようになったことを利用したサンプルです。
AppleScriptは基本的に、アプリケーションの機能や設定値を呼び出すためのもので、ごく一部の限られたアプリケーション以外からは「アプリケーション側からAppleScript(の所定のハンドラ)を呼び出す」方向のイベント呼び出しは利用できませんでした。
しかし、Cocoaのnotificationが利用できるようになったことで、多彩なイベント受信が行えるようになりました。
iTunes(or Music.app)の再生曲変更のnotificationを受信してやたらとTwitterなどに流そうとする入門Scripterがいるのですが(どこかの伝統芸か何かなんだろうか?)、そこはそんなに楽しいとも思えないし、本来のパワーを発揮していないとは思うのですが、見かけたらそっと触れないようにしておくことにしています。
AppleScript名:Notification |
— Created 2017-10-13 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" property NSDistributedNotificationCenter : a reference to current application’s NSDistributedNotificationCenter on run NSDistributedNotificationCenter’s defaultCenter()’s addObserver:me selector:"statusChanged:" |name|:"com.apple.iTunes.playerInfo" object:(missing value) end run on statusChanged:sender tell application id "com.apple.iTunes" try tell current track set anAlbum to album set aName to name set anArtist to album artist set aRating to rating end tell on error return end try end tell display notification aName end statusChanged: |
指定Bundle IDのプロセス存在確認(ASOC)v3
AppleScript名:指定Bundle IDのプロセス存在確認(ASOC)v3 |
— Created 2015-02-08 by Takaaki Naganoya — Created 2017-02-26 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aRes to chkAppProcesByBundleID("com.apple.iWork.Keynote") –> true on chkAppProcesByBundleID(aBundleID as string) set procArray to current application’s NSWorkspace’s sharedWorkspace’s runningApplications()’s valueForKeyPath:"bundleIdentifier" return (procArray’s containsObject:aBundleID) as boolean end chkAppProcesByBundleID |
バンドルIDで指定したプロセスを強制終了(NSRunningApplication)
バンドルIDで指定したプロセスを強制終了させるAppleScriptです。
Finderを終了させてみると、あえて意図して起動しないとFinderが終了したままの状態で戻って来ません。
AppleScript名:バンドルIDで指定したプロセスを強制終了(NSRunningApplication) |
— Created 2017-09-17 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set pRes to forceQuitAProcessByBUndleID("com.apple.finder") of me –指定プロセスの強制終了 on forceQuitAProcessByBUndleID(aBundleID) set appArray to current application’s NSRunningApplication’s runningApplicationsWithBundleIdentifier:aBundleID if appArray’s |count|() > 0 then set appItem to appArray’s objectAtIndex:0 set aRes to (appItem’s terminate()) as boolean return aRes else return false end if end forceQuitAProcessByBUndleID |
他のアプリケーションを隠す
AppleScript名:他のアプリケーションを隠す |
— Created 2017-01-07 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" current application’s NSWorkspace’s sharedWorkspace()’s hideOtherApplications() |