AppleScript名:指定ファイルに指定アイコン画像をつける |
— Created 2015-10-19 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aPath to POSIX path of (choose file of type {"com.apple.icns", "public.tiff"} with prompt "Choose Icon File") –アイコンファイル set aFile to POSIX path of (choose file with prompt "Choose Target File") –設定対象のファイル set aURL to current application’s |NSURL|’s fileURLWithPath:aPath set aImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL set aSW to current application’s NSWorkspace’s sharedWorkspace() aSW’s setIcon:aImage forFile:aFile options:0 |
タグ: 10.11savvy
指定フォルダからカスタムアイコンを削除する v3
指定のフォルダに指定されていたアイコン画像を削除するAppleScriptです。
特定のフォルダを監視して、ファイルが追加されたり削除されたりすると、指定のAppleScriptを実行する仕組み「フォルダアクション」がmacOSに標準装備されています。
フォルダアクションはフォルダアクションでいいのですが、あまり融通が効かないので、フォルダアクションを使わずにAppleScript独自でフォルダを監視することはよくあります。
そして、監視対象に指定したフォルダのアイコンを変更し、わかりやすく「監視対象である」ことをユーザーに伝えることも、よくある話です。そして、監視処理が終了したあとでフォルダのアイコンをOS標準の元のものに戻しておく必要があります。本Scriptはそういう処理に用いるものです。
AppleScript名:指定フォルダからカスタムアイコンを削除する v3 |
— Created 2015-10-21by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aFolder to POSIX path of (choose folder with prompt "Choose Target Folder") –カスタムアイコン削除対象のフォルダ removeCustomIcon(aFolder) of me on removeCustomIcon(aFolder) set aSW to current application’s NSWorkspace’s sharedWorkspace() aSW’s setIcon:(missing value) forFile:aFolder options:0 –Erase tell application "Finder" update ((POSIX file aFolder) as alias) –Refresh State end tell end removeCustomIcon |
指定フォルダに指定アイコン画像をつける v3
指定のフォルダに指定アイコン画像をつけるAppleScriptです。
特定のフォルダを監視して、ファイルが追加されたり削除されたりすると、指定のAppleScriptを実行する仕組み「フォルダアクション」がmacOSに標準装備されています。
フォルダアクションはフォルダアクションでいいのですが、あまり融通が効かないので、フォルダアクションを使わずにAppleScript独自でフォルダを監視することはよくあります。
そして、監視対象に指定したフォルダのアイコンを変更し、わかりやすく「監視対象である」ことをユーザーに伝えることも、よくある話です。本Scriptはそういう処理に用いるものです。
もちろん、処理が終了したあとは監視対象フォルダのアイコンは元に戻しておくべきで、「指定フォルダからカスタムアイコンを削除する v3」とペアで使っています。
AppleScript名:指定フォルダに指定アイコン画像をつける v3 |
— Created 2015-10-21 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set anIconPath to POSIX path of (choose file of type {"com.apple.icns", "public.tiff"} with prompt "Choose Icon File") set aFolder to POSIX path of (choose folder with prompt "Choose Folder") setCustomIcon(anIconPath, aFolder) of me on setCustomIcon(aPath, aFolder) set aFolderPath to current application’s NSString’s stringWithString:aFolder set aURL to current application’s |NSURL|’s fileURLWithPath:aPath set aImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL set aSW to current application’s NSWorkspace’s sharedWorkspace() aSW’s setIcon:(missing value) forFile:aFolder options:0 –Erase tell application "Finder" update ((POSIX file aFolder) as alias) –Refresh State end tell aSW’s setIcon:aImage forFile:aFolderPath options:0 –Write tell application "Finder" update ((POSIX file aFolder) as alias) –Refresh State end tell end setCustomIcon |
指定ファイルのxattrの削除(ダウンロードしたファイルが開けないときに)
AppleScript名:指定ファイルのxattrの削除(ダウンロードしたファイルが開けないときに) |
use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "XAttribute" –https://github.com/rylio/OTMXAttribute set dlFullPath to POSIX path of (choose file) set xRes to removeXAttrFromFile(dlFullPath, "com.apple.quarantine") on removeXAttrFromFile(aFile, anXattr) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute = missing value then return true –There is no use to remove xattr –Remove Xattr set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end removeXAttrFromFile |
指定EnumがどのFrameworkに所属しているか検索 v2
AppleScript名:指定EnumがどのFrameworkに所属しているか検索 v2 |
— 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 NSFileManager : a reference to current application’s NSFileManager property NSString : a reference to current application’s NSString property NSPredicate : a reference to current application’s NSPredicate property NSMutableArray : a reference to current application’s NSMutableArray property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding set a1Res to searchEnumFromHeaderFiles("NSUTF8StringEncoding") of me –> {"DiscRecording.framework", "Foundation.framework", "SpriteKit.framework"} set a2Res to searchEnumFromHeaderFiles("NSNumberFormatterRoundUp") of me –> {"Foundation.framework"} set a3Res to searchEnumFromHeaderFiles("NSParagraphStyleAttributeName") of me –> {"AppKit.framework"} on searchEnumFromHeaderFiles(targString) set aClass to current application’s NSClassFromString(targString) if aClass is not equal to missing value then return false set dPath to POSIX path of (path to application id "com.apple.dt.Xcode") set aFol to dPath & "Contents/Developer/Platforms/MacOSX.platform/" & "Developer/SDKs/MacOSX.sdk/System/Library/Frameworks" set bList to retFullPathWithinAFolderWithRecursiveFilterByExt(aFol, "h") of me set matchedList to {} repeat with i in bList set j to contents of i set aStr to (NSString’s stringWithContentsOfFile:j encoding:NSUTF8StringEncoding |error|:(missing value)) if aStr ≠ missing value then set aRange to (aStr’s rangeOfString:targString) if aRange’s location() ≠ current application’s NSNotFound and (aRange’s location()) < 9.99999999E+8 then set tmpStr to (current application’s NSString’s stringWithString:j) set pathList to tmpStr’s pathComponents() set thePred to (current application’s NSPredicate’s predicateWithFormat:"pathExtension == ’framework’") set aRes to (pathList’s filteredArrayUsingPredicate:thePred)’s firstObject() as text set the end of matchedList to aRes end if end if end repeat set aArray to current application’s NSArray’s arrayWithArray:matchedList set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self" return bArray as list end searchEnumFromHeaderFiles –指定フォルダ以下のすべてのファイルを再帰で取得(拡張子で絞り込み) on retFullPathWithinAFolderWithRecursiveFilterByExt(aFol, aExt) set anArray to NSMutableArray’s array() set aPath to NSString’s stringWithString:aFol set dirEnum to NSFileManager’s defaultManager()’s enumeratorAtPath:aPath repeat set aName to (dirEnum’s nextObject()) if aName = missing value then exit repeat set aFullPath to aPath’s stringByAppendingPathComponent:aName anArray’s addObject:aFullPath end repeat set thePred to NSPredicate’s predicateWithFormat:"pathExtension == [c]%@" argumentArray:{aExt} set bArray to anArray’s filteredArrayUsingPredicate:thePred return bArray as list end retFullPathWithinAFolderWithRecursiveFilterByExt |
指定クラスがどのFrameworkに所属しているか検索 v3
AppleScript名:指定クラスがどのFrameworkに所属しているか検索 v3 |
— Created 2017-10-14 by Shane Stanley — Modified 2017-10-14 by Takaaki Naganoya use AppleScript version "2.4" use scripting additions use framework "Foundation" set fRes1 to searchClassInFrameworks("JSContext") of me –> "JavaScriptCore.framework" set fRes2 to searchClassInFrameworks("NSApplication") of me –> "AppKit.framework" set fRes3 to searchClassInFrameworks("NSRect") of me –> false set fRes4 to searchClassInFrameworks("PDFPage") of me –> "Quartz.framework" set fRes5 to searchClassInFrameworks("NSUTF8StringEncoding") of me –> false set fRes6 to searchClassInFrameworks("CIColor") of me –> "CoreImage.framework" on searchClassInFrameworks(aTarget) set aClass to current application’s NSClassFromString(aTarget) if aClass = missing value then return false set theComponenents to (current application’s NSBundle’s bundleForClass:aClass)’s bundleURL’s pathComponents() set thePred to current application’s NSPredicate’s predicateWithFormat:"pathExtension == ’framework’" set aRes to (theComponenents’s filteredArrayUsingPredicate:thePred)’s firstObject() as text return aRes end searchClassInFrameworks |
指定スクリプト書類の記述OSA言語を取得する v2
AppleScript名:指定スクリプト書類の記述OSA言語を取得する v2 |
— Created 2017-06-04 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "OSAKit" set anAlias to choose file of type {"com.apple.applescript.script", "com.apple.applescript.script-bundle"} set sRes to getOSALangKindFromScriptFile(anAlias) of me –> {osaName:"AppleScript", osaDesc:"AppleScript.", osaVer:"2.5"} –> {osaName:"JavaScript", osaDesc:"JavaScript", osaVer:"1.1"} on getOSALangKindFromScriptFile(anAlias) set aURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of anAlias) set theScript to current application’s OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value) set scriptName to theScript’s |language|()’s |name|() as string set scriptDesc to theScript’s |language|()’s info() as string set scriptVer to theScript’s |language|()’s |version|() as string return {osaName:scriptName, osaDesc:scriptDesc, osaVer:scriptVer} end getOSALangKindFromScriptFile |
データのClassを求める
データのclassを求めるAppleScriptです。
AppleScriptではもともと、
class of 変数
で、変数に入っているデータのclassが求められます。ただ、CocoaのオブジェクトのClassは求められないので、このようなScriptを書いてみた次第です。
AppleScript名:データのClassを求める |
use AppleScript version "2.4" use scripting additions use framework "Foundation" set theValue to "10" set aClass to getClassFromData(theValue) of me –> "text" set cRes to getClassFromData(current application’s NSArray’s arrayWithArray:{1, 2, 3}) of me –> "NSArray" tell application "System Events" set a to process "Finder" end tell set dClass to getClassFromData(a) of me –> "application process" tell application "Safari" if running then if (count of every document) > 0 then set a to front document set eClass to getClassFromData(a) of me –> "document" end if end if end tell on getClassFromData(aData) set aRes to (count {aData} each reference) if aRes = 0 then –Pure AppleScript Object try return (class of aData) as string on error return false end try else –NSObject set nsObjRes to getClassNameStringFromObject(aData) of me if nsObjRes = false then –Maybe application Object return (class of aData) as string else return nsObjRes –NSObject end if end if end getClassFromData on getClassNameStringFromObject(aObject) set classList to {"AddressBook", "AVAsset", "AVAssetExportSession", "AVAudioPlayer", "CGPointZero", "CGPostMouseEvent", "CIColor", "CIFilter", "CIImage", "CIVector", "CLLocation", "CLLocationManager", "CWInterface", "EKAlarm", "EKEventStore", "EKStructuredLocation", "FSEvent", "IOBluetoothDevice", "IOBluetoothHostController", "ITLibrary", "JSContext", "MKMapView", "Myriad Helpers", "NSAffineTransform", "NSAlert", "NSAnimationContext", "NSApp", "NSApplication", "NSArray", "NSAttributedString", "NSAutoreleasePool", "NSBezierPath", "NSBitmapImageRep", "NSBox", "NSBundle", "NSButton", "NSByteCountFormatter", "NSCalendar", "NSCharacterSet", "NSClassFromString", "NSColor", "NSColorList", "NSColorSpace", "NSColorWell", "NSComboBox", "NSCompoundPredicate", "NSCountedSet", "NSData", "NSDataDetector", "NSDate", "NSDateComponents", "NSDateFormatter", "NSDateIntervalFormatter", "NSDatePicker", "NSDecimalNumber", "NSDictionary", "NSEnergyFormatter", "NSError", "NSEvent", "NSFileManager", "NSFileSystemFreeSize", "NSFont", "NSFontCollection", "NSFontManager", "NSGraphicsContext", "NSHelpManager", "NSHomeDirectory", "NSHost", "NSImage", "NSImageView", "NSIndexSet", "NSIntersectionRect", "NSInvocationOperation", "NSJSONSerialization", "NSLengthFormatter", "NSLinguisticTagger", "NSLocale", "NSLocaleIdentifier", "NSLog", "NSMakePoint", "NSMakeRange", "NSMakeRect", "NSMapTable", "NSMassFormatter", "NSMatrix", "NSMenuItem", "NSMetadataQuery", "NSMutableArray", "NSMutableAttributedString", "NSMutableCharacterSet", "NSMutableData", "NSMutableDictionary", "NSMutableIndexSet", "NSMutableSet", "NSMutableString", "NSMutableURLRequest", "NSNetServiceBrowser", "NSNotificationCenter", "NSNumber", "NSNumberFormatter", "NSNumberFormatterRoundDown", "NSNumberFormatterRoundUp", "NSOpenPanel", "NSOperationQueue", "NSOrderedSet", "NSPasteboard", "NSPasteboardItem", "NSPipe", "NSPNGFileType", "NSPointInRect", "NSPopUpButton", "NSPredicate", "NSPrinter", "NSPrintInfo", "NSPrintOperation", "NSProcessInfo", "NSPropertyListFormat", "NSPropertyListImmutable", "NSPropertyListSerialization", "NSRange", "NSRect", "NSRegularExpression", "NSRegularExpressionAnchorsMatchLines", "NSRegularExpressionDotMatchesLineSeparators", "NSRegularExpressionSearch", "NSRunningApplication", "NSSavePanel", "NSScanner", "NSScreen", "NSScriptCommand", "NSSegmentedControl", "NSSet", "NSShadow", "NSSharingService", "NSSlider", "NSSortDescriptor", "NSSound", "NSSpeechRecognizer", "NSSpeechSynthesizer", "NSSpellChecker", "NSSplitView", "NSStatusBar", "NSString", "NSTableColumn", "NSTableView", "NSTask", "NSTextField", "NSTextView", "NSThread", "NSTimeInterval", "NSTimer", "NSTimeZone", "NSUnarchiver", "NSUnionRect", "NSURL", "NSURLComponents", "NSURLConnection", "NSURLDownload", "NSURLQueryItem", "NSURLRequest", "NSURLRequestReloadIgnoringLocalCacheData", "NSUserDefaults", "NSUTF8StringEncoding", "NSUUID", "NSView", "NSWeekCalendarUnit", "NSWindow", "NSWindowController", "NSWorkspace", "NSXMLParser", "NSZeroRect", "NSZeroSize", "ODNode", "ODQuery", "ODSession", "OSAScript", "OSAScriptController", "OSAScriptView", "PDFAnnotation", "PDFDestination", "PDFDocument", "PDFOutline", "PDFPage", "PDFThumbnailView", "PDFView", "QCView", "SBApplication", "WebView", "WKWebView"} repeat with i in classList set j to contents of i set aClass to current application’s NSClassFromString(j) try set aRes to (aObject’s isKindOfClass:aClass) as boolean on error –May be an Application Object return false end try if aRes = true then return j end repeat return false end getClassNameStringFromObject |
asHTMLexportLib v2
指定のAppleScript書類をスクリプトエディタでオープンし、書式情報を読み取ってURLリンク付きのHTML(テキスト)を生成するAppleScriptです。AppleScript Librariesとして他のScriptから呼び出して利用しています。
オリジナルは2006年ごろに作成したもので、「秘伝のタレ」よろしくその時々のOSの変更を反映させて使い続けています。
AppleScriptの書式(とくに色情報)をHTML書き出し時にどのように反映させるかについては、いろいろと「流派」があり、
・スクリプトエディタ上の色情報を読み取ってそのままカラータグで展開する派
・CSSなどで構文要素ごとにスタイルを指定する派
で、本Scriptは前者の方式で書かれた最古のScriptの末裔です。書き出しHTMLが長くなるというデメリットはあるものの、構造の単純さが幸いしてわずかな修正でメンテナンスを継続できています。
当初、AppleScriptからスクリプトエディタをコントロールすると不具合が多く、他のAppleScript開発環境(Script Debugger)からの実行を余儀なくされていました。macOS 10.6あたりでずいぶん安定して利用できるようになってきた記憶があります(10.3とか10.4はいま思い出しても辛かった)。
HTMLに埋め込むURLスキーム「applescript:」からは、AppleScriptの新規作成、作成中のAppleScript書類のカーソル位置へのペースト、書類末尾へのペーストなどの動作を指定できますが、結局Blogに10年前からつけているURLリンクもそれほど認識されておらず(なぜ??)、新規作成のリンクのみ付加するように変更しました。
また、「applescript:」のURLリンクでは生成するAppleScript書類のファイル名をあらかじめ指定できるようになっているものの、古いバージョンのmacOS(Mac OS X)ではこの名称指定が仇となってURLリンクが認識されないという問題が発生するため、名称も指定していません。
一応、書き出し対象ファイルがAppleScriptかJavaScriptかを判定して、書き出し時のカラーリングを変更するようになっています。OSAScriptフレームワーク経由で書類から直接OSA言語の種別は取得できるものの、スクリプトエディタ自体から情報を取得しても手間はたいして変わらないので現状のようになっています。
AppleScript名:asHTMLexportLib |
use AppleScript version "2.4" use scripting additions use framework "Foundation" property quotChar : string id 34 property headerCol : "0000CC" –"0000CC" –ヘッダー部分(濃い色) property bodyBackCol : "EEFFFF" –"EEFFFF" –Script本文下地(薄い色) property footerCol : "66FFFF" –"66FFFF" –スクリプトリンク部分 property repMark : "_replacepoint_" on run set aPath to choose file of type {"com.apple.applescript.script", "com.apple.applescript.script-bundle"} set aRes to retScriptHTML(aPath) of me end run on retScriptHTML(aPath) –parameter is alias script spd property TIDsList : {} property dataOut : {} property textList : {} property colorList : {} end script set pName to "com.apple.ScriptEditor2" tell application id pName set asDoc to open aPath tell asDoc –front document set aInfo to properties set curLang to name of language of aInfo –現在のOSA言語の名称を取得する end tell –OSA Language名称をもとに色セットを変更する changeColor(curLang) of me set c to name of asDoc –front document set aF to aPath as string –retMacOSpathList(aPath) of me set contText to getContentsOfFile(asDoc) of me –front document set encText to makeEncodedScript(contText) of me set newLinkText to "applescript://com.apple.scripteditor?action=new&script=" & encText –set insLinkText to "applescript://com.apple.scripteditor?action=insert&script=" & encText –set apndLinkText to "applescript://com.apple.scripteditor?action=append&script=" & encText set comText to description of asDoc –front document set (textList of spd) to getAttributeRunOfFile(asDoc) of me —every attribute run of asDoc –front document set (colorList of spd) to getColorOfAttributeRunOfFile(asDoc) of me —color of every attribute run of asDoc –front document end tell set tabChar to string id 9 set (TIDsList of spd) to {{"\\", "\"}, {"’", "’"}, {"&", "&"}, {">", ">"}, {"<", "<"}, {" ", " "}, {string id 13, "<br>"}, {string id 10, "<br>"}, {"\"", """}} set (dataOut of spd) to {} set iCounter to 1 repeat with i in (textList of spd) set j to contents of i set curDelim to AppleScript’s text item delimiters repeat with eachItem in (TIDsList of spd) set AppleScript’s text item delimiters to contents of item 1 of eachItem set j to every text item of j set AppleScript’s text item delimiters to contents of item 2 of eachItem set j to j as string end repeat set AppleScript’s text item delimiters to curDelim set cText to RBG2HTML(item iCounter of (colorList of spd)) of me set the end of (dataOut of spd) to "<font color=" & cText & ">" & j & "</font>" set iCounter to iCounter + 1 end repeat set htmlHeader to "<table width=" & quotChar & "100%" & quotChar & " border=" & quotChar & "0" & quotChar & "cellspacing=" & quotChar & "2" & quotChar & " cellpadding=" & quotChar & "2" & quotChar & "> <tr> <td bgcolor=\"#" & headerCol & "\"><font color=" & quotChar & "#FFFFFF" & quotChar & ">" & curLang & "名:" & c if comText is not equal to "" then set comText to "<br><font size=" & quotChar & "2" & quotChar & ">【Comment】 " & comText & "</font><br>" end if set htmlHeader2 to "</font></td> </tr> <tr> <td bgcolor=\"#" & bodyBackCol & "\"><font size=\"3\">" set htmlFooter1 to "</font></td> </tr> <tr> <td bgcolor=\"#" & footerCol & "\"><p><font size=\"2\"><a href=\"" & newLinkText & "\">★Click Here to Open This Script</a> </font></p> </td> </tr> </table> " set dataText to htmlHeader & comText & htmlHeader2 & ((dataOut of spd) as text) & htmlFooter1 set dataText to dataText as Unicode text tell application id pName close asDoc without saving –close front document without saving end tell return dataText end retScriptHTML on makeEncodedScript(contText) set aList to every paragraph of contText set aClass to class of aList if aClass = list then set aLen to length of aList else set aLen to 1 end if set aaList to {} set delim to AppleScript’s text item delimiters set AppleScript’s text item delimiters to repMark set bList to aList as text set AppleScript’s text item delimiters to delim set aaList to (retURLencodedStrings(bList) of me) as text set search_string to retURLencodedStrings(repMark) of me –"%5Freplacepoint%5F" as text set replacement_string to "%0D" as text set bList to replace_chars(aaList, search_string, replacement_string) of me return bList end makeEncodedScript –RGB値からHTMLの色指定に変換 on RBG2HTML(RGB_values) — NOTE: this sub-routine expects the RBG values to be from 0 to 65536 set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"} set the the hex_value to "" repeat with i from 1 to the count of the RGB_values set this_value to (item i of the RGB_values) div 256 if this_value is 256 then set this_value to 255 set x to item ((this_value div 16) + 1) of the hex_list set y to item (((this_value / 16 mod 1) * 16) + 1) of the hex_list set the hex_value to (the hex_value & x & y) as string end repeat return ("#" & the hex_value) as string end RBG2HTML on replace_chars(this_text, search_string, replacement_string) set AppleScript’s text item delimiters to the search_string set the item_list to every text item of this_text set AppleScript’s text item delimiters to the replacement_string set this_text to the item_list as string set AppleScript’s text item delimiters to "" return this_text end replace_chars on retURLencodedStrings(aText) set aStr to current application’s NSString’s stringWithString:aText set encodedStr to aStr’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s alphanumericCharacterSet()) return encodedStr as text end retURLencodedStrings on changeColor(aLang) if aLang = "AppleScript" then set headerCol to "0000CC" –"0000CC" –ヘッダー部分(濃い色) set bodyBackCol to "EEFFFF" –"EEFFFF" –Script本文下地(薄い色) set footerCol to "66FFFF" –"66FFFF" –スクリプトリンク部分 else if aLang = "JavaScript" then set headerCol to "804000" –"0000CC" –ヘッダー部分(濃い色) set bodyBackCol to "E2D3D3" –"EEFFFF" –Script本文下地(薄い色) set footerCol to "E7AC53" –"66FFFF" –スクリプトリンク部分 end if end changeColor on getContentsOfFile(asDoc) tell application id "com.apple.ScriptEditor2" set aCon to (properties of asDoc) end tell return contents of aCon end getContentsOfFile on getAttributeRunOfFile(asDoc) tell application id "com.apple.ScriptEditor2" set aCon to (every attribute run of asDoc) end tell return aCon end getAttributeRunOfFile on getColorOfAttributeRunOfFile(asDoc) tell application id "com.apple.ScriptEditor2" set aCon to color of (every attribute run of asDoc) end tell return aCon end getColorOfAttributeRunOfFile |
WordPress XML-RPC Frameworkのじっけん
WordPress XML-RPC Frameworkを呼び出して、指定のWordPressとXML-RPCによる通信を行うテスト用のAppleScriptです。
# 本BlogではAppleScriptからの自動更新時以外はWordPressのXML-RPC通信機能をプラグイン「Disable XML-RPC」によって止めているので、本Scriptを実行してもエラーになる可能性があります。他のWordPressのサイトでお試しください
本Blogがホスティング業者との行き違いでデータベースをシャットダウンされて、やむなく再構築を行おうと決意してから迅速に再構築を進めて来られたのは、手元にAppleScriptの元コードがすべて無傷で残っていたことと、これまで半自動だった記事の投稿をすべてAppleScriptから自動化できる目処が立っていたためでした。
・指定のAppleScriptをHTML化(URLリンク付き)するAppleScriptライブラリ
・指定内容のHTMLをWordPressにXML-RPC経由で投稿するAppleScript
といった「飛び道具」を整備することで、指定のAppleScript書類をWordPressに投稿できるようになりました。
とくに、XML-RPCについてはAppleScriptの標準搭載命令「call xmlrpc」がとことん使い物にならず、WordPressへの通信を行うとクラッシュすることを(ずいぶん昔に)確認してあったため、、、かわりになる部品を地道に探してありました。
WordPressとのXML-RPCによる通信を行うmacOS用フレームワーク「wpxmlrpc」を見つけ、Xcode上でビルドしてAppleScriptから呼び出す実験を行い、このように実際の投稿に利用しています。Github上のドキュメントはたいへんに素っ気なく、そのままObjective-CのコードをAppleScriptに置き換えても動作しない程度の素朴すぎる内容でしたが、REST APIの呼び出しAppleScriptを参考に内容を類推してひととおり動作できるところまでこぎつけました。
AppleScript名:WordPress XML-RPC Frameworkのじっけん |
— Created 2018-02-08 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "wpxmlrpc" –https://github.com/wordpress-mobile/wpxmlrpc set aRes to callXMLRPC("http://piyocast.com/as/xmlrpc.php", "demo.addTwoNumbers", {2, 3}) of me –> 5 set aRes to callXMLRPC("http://piyocast.com/as/xmlrpc.php", "mt.supportedMethods", {}) of me –> {"wp.getUsersBlogs", "wp.newPost", "wp.editPost", "wp.deletePost", "wp.getPost", "wp.getPosts", "wp.newTerm", "wp.editTerm", "wp.deleteTerm", "wp.getTerm", "wp.getTerms", "wp.getTaxonomy", "wp.getTaxonomies", "wp.getUser", "wp.getUsers", "wp.getProfile", "wp.editProfile", "wp.getPage", "wp.getPages", "wp.newPage", "wp.deletePage", "wp.editPage", "wp.getPageList", "wp.getAuthors", "wp.getCategories", "wp.getTags", "wp.newCategory", "wp.deleteCategory", "wp.suggestCategories", "wp.uploadFile", "wp.deleteFile", "wp.getCommentCount", "wp.getPostStatusList", "wp.getPageStatusList", "wp.getPageTemplates", "wp.getOptions", "wp.setOptions", "wp.getComment", "wp.getComments", "wp.deleteComment", "wp.editComment", "wp.newComment", "wp.getCommentStatusList", "wp.getMediaItem", "wp.getMediaLibrary", "wp.getPostFormats", "wp.getPostType", "wp.getPostTypes", "wp.getRevisions", "wp.restoreRevision", "blogger.getUsersBlogs", "blogger.getUserInfo", "blogger.getPost", "blogger.getRecentPosts", "blogger.newPost", "blogger.editPost", "blogger.deletePost", "metaWeblog.newPost", "metaWeblog.editPost", "metaWeblog.getPost", "metaWeblog.getRecentPosts", "metaWeblog.getCategories", "metaWeblog.newMediaObject", "metaWeblog.deletePost", "metaWeblog.getUsersBlogs", "mt.getCategoryList", "mt.getRecentPostTitles", "mt.getPostCategories", "mt.setPostCategories", "mt.supportedMethods", "mt.supportedTextFilters", "mt.getTrackbackPings", "mt.publishPost", "pingback.ping", "pingback.extensions.getPingbacks", "demo.sayHello", "demo.addTwoNumbers"} on callXMLRPC(paramURL, aMethod, aParamList) set aURL to current application’s |NSURL|’s URLWithString:paramURL set aReq to current application’s NSMutableURLRequest’s alloc()’s initWithURL:aURL aReq’s setHTTPMethod:"POST" set encoder to current application’s WPXMLRPCEncoder’s alloc()’s initWithMethod:aMethod andParameters:aParamList (aReq’s setHTTPBody:(encoder’s dataEncodedWithError:(missing value))) set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aReq returningResponse:(reference) |error|:(missing value) set resList to aRes as list set bRes to contents of (first item of resList) set cRes to second item of resList (* (NSHTTPURLResponse) <NSHTTPURLResponse: 0x6000000289a0> { URL: http://piyocast.com/as/xmlrpc.php } { status code: 200, headers { Connection = close; "Content-Type" = "text/xml; charset=UTF-8"; Date = "Wed, 07 Feb 2018 16:10:49 GMT"; Server = Apache; "Transfer-Encoding" = Identity; } } *) set decoder to current application’s WPXMLRPCDecoder’s alloc()’s initWithData:bRes set errF to (decoder’s isFault()) as boolean if errF = true then —Error set xmlRPCres to faultCode of resStr set xmlRPCbody to faultString of resStr return false else –Success? set xmlRPCres to (decoder’s object()) as list of string or string –Error if xmlRPCres = missing value then return false end if return xmlRPCres end callXMLRPC |
指定URLをロードして1枚ものの大きなPNGにレンダリング v2.1
指定URLのWebコンテンツをWebViewに読み込んでレンダリングし、1枚ものの大きなPNG画像に保存するAppleScriptです。
資料作成時にWebサイトの内容を利用する場合、こうした1枚ものの大きな画像にレンダリングすることがよくあります(Webサイトのデザインや構成変更の提案時など)。PDFとしてレンダリングする場合が多いですが、サイズ軽減のためにPNGなどの画像でレンダリングすることもあり、その場合のために作成したものです。
ただ、実際に作っておいてナニですが、PDFで保存する場合のほうが多く、PNGでレンダリングするケースはまれです。
# そのままではmacOS 10.13以降の環境で動かなくなっていたので、一部修正しました。ただ、今後のことを考えるとWebViewではなくWkWebViewを使って動作するものがあったほうがよいでしょう
AppleScript名:指定URLをロードして1枚ものの大きなPNGにレンダリング v2a |
— Created 2015-09-15 by Takaaki Naganoya — Modified 2019-11-09 by Takaaki Naganoya — 2019 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "WebKit" use framework "Quartz" use framework "AppKit" property loadDone : false property theWebView : missing value property userAgentName : "Version/9.0 Safari/601.1.56" set aOutPath to "~/Desktop/outIMG_1.png" set aURL to "http://www.apple.com/jp/shop/browse/home/specialdeals/mac" –set aURL to "http://piyocast.com/as" –Check If this script runs in foreground if not (current application’s NSThread’s isMainThread()) as boolean then display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical error number -128 end if set aPath to current application’s NSString’s stringWithString:aOutPath set bPath to aPath’s stringByExpandingTildeInPath() –URL Validation check set aRes to validateURL(aURL) if aRes = false then return set aTitle to getURLandRender(aURL) –Specify Render to image view (HTML world) set aTargetView to (my theWebView)’s mainFrame()’s frameView()’s documentView() –Get Web Contents Size set targRect to aTargetView’s |bounds|() –Make Window begin–????? Really Needed ???? Very doubtful if class of targRect = record then set aWidth to width of |size| of targRect set aHeight to height of |size| of targRect else if class of targRect = list then set aWidth to item 1 of item 2 of targRect set aHeight to item 2 of item 2 of targRect end if set aWin to current application’s NSWindow’s alloc()’s init() aWin’s setContentSize:{aWidth + 40, aHeight + 20} aWin’s setContentView:(my theWebView) aWin’s setOpaque:false aWin’s |center|() –Make Window end set aData to aTargetView’s dataWithPDFInsideRect:targRect set aImage to current application’s NSImage’s alloc()’s initWithData:aData set bData to aImage’s TIFFRepresentation() set aBitmap to current application’s NSBitmapImageRep’s imageRepWithData:bData –Write To File set myNewImageData to (aBitmap’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:bPath atomically:true) as boolean return aRes –Download the URL page to WebView and get page title on getURLandRender(aURL) set my loadDone to false set my theWebView to missing value openURL(aURL) set waitLoop to 1000 * 60 –60 seconds set hitF to false repeat waitLoop times if my loadDone = true then set hitF to true exit repeat end if current application’s NSThread’s sleepForTimeInterval:("0.001" as real) –delay 0.001 end repeat if hitF = false then return set jsText to "document.title" set x to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsText) as text return x end getURLandRender –Down Load URL contents to WebView on openURL(aURL) set noter1 to current application’s NSNotificationCenter’s defaultCenter() set (my theWebView) to current application’s WebView’s alloc()’s init() (my theWebView)’s setApplicationNameForUserAgent:userAgentName (my theWebView)’s setMediaStyle:"screen" (my theWebView)’s setDrawsBackground:true –THIS SEEMS NOT TO WORK –(my theWebView)’s backGroundColor:(current application’s NSColor’s whiteColor())–Mistake –(my theWebView)’s setShouldUpdateWhileOffscreen:true noter1’s addObserver:me selector:"webLoaded:" |name|:(current application’s WebViewProgressFinishedNotification) object:(my theWebView) (my theWebView)’s setMainFrameURL:aURL end openURL –Web View’s Event Handler:load finished on webLoaded:aNotification set my loadDone to true end webLoaded: –URL Validation Check on validateURL(anURL as text) set regEx1 to current application’s NSString’s stringWithString:"((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+" set predicate1 to current application’s NSPredicate’s predicateWithFormat_("SELF MATCHES %@", regEx1) set aPredRes1 to (predicate1’s evaluateWithObject:anURL) as boolean return aPredRes1 end validateURL |
簡易形態素解析してスーパー大辞林で辞書検索
「words of」によるAppleScriptビルトインの超簡易形態素解析を実行して、日本語の文を単語(形態素)ごとに分解し、macOS標準搭載の辞書.appの「スーパー大辞林」で全単語を検索するAppleScriptです。
実行にあたっては、上記Frameworkを~/Library/Frameworksにインストールしたうえで、macOS 10.14以降ではScript Debuggerを用いるか、お使いのMacをSIP解除してScript Editor上で呼び出して実行する必要があります。
処理対象:”大きな栗の木の下で”
実行結果:
–> {{dictName:”スーパー大辞林”, keywordName:”で”, dictContents:”で 「て」の濁音の仮名。歯茎破裂音の有声子音と前舌の半狭母音とから成る音節。”}….}}
AppleScript名:簡易形態素解析してスーパー大辞林で辞書検索 |
— Created 2015-10-25 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set aText to "大きな栗の木の下で" set wList to words of aText repeat with i in wList set dRes to getWordDifinitionInJapaneseDictionary(i as string) of me end repeat on getWordDifinitionInJapaneseDictionary(aTerm as string) set localNameList to getNameOfLocalDictionaries() of me set dNameList to {"スーパー大辞林"} set aSet to current application’s NSMutableSet’s setWithArray:localNameList set bSet to current application’s NSMutableSet’s setWithArray:dNameList aSet’s intersectSet:bSet set dList to aSet’s allObjects() as list if dList = {} then return false set aResList to {} repeat with i in dNameList set aDictionary to (current application’s TTTDictionary’s dictionaryNamed:i) set hitEntryList to (aDictionary’s entriesForSearchTerm:aTerm) as list if hitEntryList is not equal to {missing value} then repeat with ii in hitEntryList set j to contents of ii set headW to (j’s headword) set headW to headW as text try set aText to (j’s |text|) set aText to aText as text on error set aText to (j’s HTML) set aText to decodeCharacterReference(aText) of me end try set the end of aResList to {dictName:(i as text), keywordName:headW, dictContents:aText} end repeat end if end repeat aResList end getWordDifinitionInJapaneseDictionary on decodeCharacterReference(aStr) set anNSString to current application’s NSString’s stringWithString:aStr set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF16StringEncoding) set styledString to current application’s NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value) set plainText to (styledString’s |string|()) as string return plainText end decodeCharacterReference on getNameOfLocalDictionaries() set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set the end of dNameList to (i’s |name|()) as text end repeat return dNameList end getNameOfLocalDictionaries |
Dictionary.appの辞書名を言語で抽出
AppleScript名:DIctionary.appの辞書名を言語で抽出 |
— Created 2015-10-25 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit –Dictionary.appのすべての辞書名を出力 set d1Res to getEveryLocalDictionaryInformation() of me –> {{dictName:"뉴에이스 영한사전 / 뉴에이스 한영사전", dictLang:"韓国語 – 英語"}, {dictName:"Multidictionnaire de la langue française", dictLang:"フランス語"}, {dictName:"राजपाल हिन्दी शब्दकोश", dictLang:"ヒンディー語"}, ….} –DIctionary.appの辞書のうち言語ラベル(shortName)が「日本語」ではじまるものを抽出(和英辞典など) set d2Res to getLocalDictionaryInformationByFromLang("日本語") of me –> {{dictName:"スーパー大辞林", dictLang:"日本語"}, {dictName:"ウィズダム英和辞典 / ウィズダム和英辞典", dictLang:"日本語 – 英語"}} –Dictionary.appの辞書のうち言語ラベル(shortName)が「日本語」で終わるものを抽出(英和辞典、日本語辞典) set d3Res to getLocalDictionaryInformationByToLang("日本語") of me –> {{dictName:"スーパー大辞林", dictLang:"日本語"}} –Dictionary.appの辞書のうち言語ラベル(shortName)が「日本語」ではじまり「英語」で終わるもの(和英辞典)を抽出 set d4Res to getLocalDictionaryInformationByFromToLang("日本語", "英語") of me –> {{dictName:"ウィズダム英和辞典 / ウィズダム和英辞典", dictLang:"日本語 – 英語"}} on getEveryLocalDictionaryInformation() set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set aName to (|name|() of i) as string set sName to (shortName() of i) as string set the end of dNameList to {dictName:aName, dictLang:sName} end repeat return dNameList end getEveryLocalDictionaryInformation on getLocalDictionaryInformationByFromLang(aFromLang) set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set aName to (|name|() of i) as string set sName to (shortName() of i) as string if sName begins with aFromLang then set the end of dNameList to {dictName:aName, dictLang:sName} end if end repeat return dNameList end getLocalDictionaryInformationByFromLang on getLocalDictionaryInformationByToLang(aToLang) set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set aName to (|name|() of i) as string set sName to (shortName() of i) as string if sName ends with aToLang then set the end of dNameList to {dictName:aName, dictLang:sName} end if end repeat return dNameList end getLocalDictionaryInformationByToLang on getLocalDictionaryInformationByFromToLang(aFromLang, aToLang) set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set aName to (|name|() of i) as string set sName to (shortName() of i) as string if sName starts with aFromLang and sName ends with aToLang then set the end of dNameList to {dictName:aName, dictLang:sName} end if end repeat return dNameList end getLocalDictionaryInformationByFromToLang |
指定辞書で指定キーワードを串刺し検索
AppleScript名:指定辞書で指定キーワードを串刺し検索 |
— Created 2015-10-25 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set dRes to getWordDifinitionInDictionaries("青い", {"スーパー大辞林"}) of me on getWordDifinitionInDictionaries(aTerm as string, dNameList as list) set localNameList to getNameOfLocalDictionaries() of me –指定辞書がローカル環境に存在しているかどうかチェック set aSet to current application’s NSMutableSet’s setWithArray:localNameList set bSet to current application’s NSMutableSet’s setWithArray:dNameList aSet’s intersectSet:bSet set dList to aSet’s allObjects() as list if dList = {} then return false set aResList to {} repeat with i in dNameList set aDictionary to (current application’s TTTDictionary’s dictionaryNamed:i) set hitEntryList to (aDictionary’s entriesForSearchTerm:aTerm) as list if hitEntryList is not equal to {missing value} then repeat with ii in hitEntryList set j to contents of ii set headW to (j’s headword) set headW to headW as text try set aText to (j’s |text|) set aText to aText as text on error set aText to (j’s HTML) set aText to decodeCharacterReference(aText) of me end try set the end of aResList to {dictName:(i as text), keywordName:headW, dictContents:aText} end repeat end if end repeat aResList end getWordDifinitionInDictionaries on decodeCharacterReference(aStr) set anNSString to current application’s NSString’s stringWithString:aStr set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF16StringEncoding) set styledString to current application’s NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value) set plainText to (styledString’s |string|()) as string return plainText end decodeCharacterReference on getNameOfLocalDictionaries() set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set the end of dNameList to (i’s |name|()) as text end repeat return dNameList end getNameOfLocalDictionaries |
ASOCでOS内蔵辞書を串刺し検索するじっけん3
AppleScript名:ASOCでOS内蔵辞書を串刺し検索するじっけん3 |
— Created 2015-10-25 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit –Japanese & English Dictionaries set dNameList to {"Apple用語辞典", "Oxford Thesaurus of English", "スーパー大辞林", "Oxford Dictionary of English", "Oxford American Writer’s Thesaurus", "Wikipedia", "New Oxford American Dictionary", "ウィズダム英和辞典 / ウィズダム和英辞典", "Wikipedia"} –English Dictionaries set dNameList to {"Oxford American Writer’s Thesaurus", "New Oxford American Dictionary"} –Wikipedia set dNameList to {"Wikipedia"} set aTerm to "set" set aResList to {} repeat with i in dNameList set aDictionary to (current application’s TTTDictionary’s dictionaryNamed:i) set hitEntryList to (aDictionary’s entriesForSearchTerm:aTerm) as list if hitEntryList is not equal to {missing value} then repeat with ii in hitEntryList set j to contents of ii set headW to (j’s headword) set headW to headW as text try set aText to (j’s |text|) set aText to aText as text on error set aText to (j’s HTML) set aText to decodeCharacterReference(aText) of me end try set the end of aResList to {dictName:(i as text), keywordName:headW, dictContents:aText} end repeat end if end repeat aResList on decodeCharacterReference(aStr) set anNSString to current application’s NSString’s stringWithString:aStr set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF16StringEncoding) set styledString to current application’s NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value) set plainText to (styledString’s |string|()) as string return plainText end decodeCharacterReference |
指定辞書でキーワード検索
AppleScript名:指定辞書でキーワード検索 |
— Created 2017-12-30 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set aRes to findKeywordWithDictionaryApp("rake", "ウィズダム英和辞典 / ウィズダム和英辞典") of me on findKeywordWithDictionaryApp(aKeyword, aDictName) set aDictionary to (current application’s TTTDictionary’s dictionaryNamed:aDictName) set hitEntryList to (aDictionary’s entriesForSearchTerm:aKeyword) as list if hitEntryList is not equal to {missing value} then repeat with ii in hitEntryList set j to contents of ii set headW to (j’s headword) set headW to headW as text try set aText to (j’s |text|) set aText to aText as text on error set aText to (j’s HTML) set aText to decodeCharacterReference(aText) of me end try return aText end repeat return {} end if end findKeywordWithDictionaryApp on decodeCharacterReference(aStr) set anNSString to current application’s NSString’s stringWithString:aStr set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF16StringEncoding) set styledString to current application’s NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value) set plainText to (styledString’s |string|()) as string return plainText end decodeCharacterReference |
日本語の慣用句を検索する
辞書.app内の辞書「スーパー大辞林」を対象に、慣用句のキーワード検索(部分一致検索)を行うAppleScriptです。
–> dictKit.framework (To ~/Library/Frameworks/)
掲載時はmacOS 10.12上で作成、検証を行っていましたが、その後macOS 10.14でホームディレクトリ下のFrameworkへのアクセスが禁止されたため、実行にはScript Debugger上、およびScript Debuggerから書き出したEnhanced AppleScript Applet上で書き出して実行する必要があります。
# あるいは、SIPを解除すればスクリプトエディタ上でも実行可能です
AppleScript名:日本語の慣用句を検索する |
— Created 2017-12-30 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set aRes to retJapaneseIdionFromKanjiChar("血") of me –> {"血が通う", "血が騒ぐ", "血が繫がる", "血が上る", "血が引く", "血で血を洗う", "血と汗", "血となり肉となる", "血に飢える", "血の出るよう", "血の滲むよう", "血は争えない", "血は水よりも濃い", "血も涙もない", "血湧き肉躍る", "血を受ける", "血を歃る", "血を吐く思い", "血を引く", "血を見る", "血を分ける"} set aRes to retJapaneseIdionFromKanjiChar("家") of me –> {"家給し人足る", "家高し", "家に杖つく", "家貧しくして孝子顕わる", "家をあける", "家を出ず", "家を外にする"} set aRes to retJapaneseIdionFromKanjiChar("水") of me –> {"水到りて渠成る", "水が合わない", "水が漬く", "水が入る", "水が引く", "水涸る", "水清ければ魚棲まず", "水澄む", "水で割る", "水と油", "水にする", "水に流す", "水になる", "水に馴れる", "水温む", "水の滴るよう", "水の流れと身のゆくえ", "水の低きに就く如し", "水は方円の器に随う", "水も漏らさぬ", "水をあける", "水を打ったよう", "水を得た魚のよう", "水を掛ける", "水をさす", "水を向ける"} set aRes to retJapaneseIdionFromKanjiChar("木") of me –> {"木から落ちた猿", "樹静かならんと欲すれども風止まず", "木で鼻を括る", "木に竹を接ぐ", "木にも草にも心を置く", "木に餅がなる", "木に縁りて魚を求む", "木の股から生まれる", "木六竹八塀十郎", "木を見て森を見ず"} on retJapaneseIdionFromKanjiChar(aKanji) set aDictionary to (current application’s TTTDictionary’s dictionaryNamed:"スーパー大辞林") set hitEntryList to (aDictionary’s entriesForSearchTerm:aKanji) as list if hitEntryList is not equal to {missing value} then repeat with ii in hitEntryList set j to contents of ii set headW to (j’s headword) set headW to headW as text try set aText to (j’s |text|) set aText to aText as text on error set aText to (j’s HTML) set aText to decodeCharacterReference(aText) of me end try if aText contains "〈句項目〉" then set aCount to 1 set tmpList to paragraphs of aText set aLen to length of tmpList repeat with i in tmpList set j to contents of i if j contains "〈句項目〉" then set outList to items (aCount + 1) thru -1 of tmpList exit repeat end if set aCount to aCount + 1 end repeat repeat with ii from (aCount + 1) to aLen set jj to contents of ii if jj = "" then exit repeat end repeat set outList to contents of items (aCount + 1) thru (ii – 1) of tmpList return outList end if end repeat return {} end if end retJapaneseIdionFromKanjiChar on decodeCharacterReference(aStr) set anNSString to current application’s NSString’s stringWithString:aStr set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF16StringEncoding) set styledString to current application’s NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value) set plainText to (styledString’s |string|()) as string return plainText end decodeCharacterReference |
ASOCでOS内蔵辞書を串刺し検索するじっけん1
AppleScript名:ASOCでOS内蔵辞書を串刺し検索するじっけん1 |
— Created 2015-10-22 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set aTerm to "Apple" set aResList to {} repeat with ii in dList set hitEntryList to (ii’s entriesForSearchTerm:aTerm) as list if hitEntryList is not equal to {missing value} then set aDname to ii’s |name|() as text repeat with i in hitEntryList set j to contents of i set headW to (j’s headword) set headW to headW as text set aText to (j’s |text|) set aText to aText as text set the end of aResList to {aDname, headW, aText} end repeat end if end repeat aResList |
ASOCで辞書.appで検索可能な辞書名称一覧を取得する v13
AppleScript名:ASOCで辞書.appで検索可能な辞書名称一覧を取得する v13 |
— Created 2015-10-22 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set dSet to current application’s TTTDictionary’s availableDictionaries() set dList to dSet’s allObjects() set dNameList to {} repeat with i in dList set the end of dNameList to (i’s |name|()) as text end repeat dNameList –OS X 10.10 (27 dict) –> {"뉴에이스 영한사전 / 뉴에이스 한영사전", "Apple 用語辞典", "Multidictionnaire de la langue française", "राजपाल हिन्दी शब्दकोश", "Dizionario italiano da un affiliato di Oxford University Press", "Oxford-Hachette French Dictionary", "NE Ordbok", "牛津英汉汉英词典", "Oxford Thesaurus of English", "スーパー大辞林", "Oxford Dictionary of English", "Oxford American Writer’s Thesaurus", "Norsk Ordbok", "Gran Diccionario Oxford – Español-Inglés • Inglés-Español", "Wikipedia", "Duden-Wissensnetz deutsche Sprache", "Толковый словарь русского языка", "뉴에이스 국어사전", "Prisma woordenboek Nederlands", "New Oxford American Dictionary", "Dicionário de Português licenciado para Oxford University Press", "Oxford German Dictionary", "Diccionario General de la Lengua Española Vox", "ウィズダム英和辞典 / ウィズダム和英辞典", "Arkadaş Türkçe Sözlük", "พจนานุกรมไทย ฉบับทันสมัยและสมบูรณ์", "现代汉语规范词典"} –macOS 10.12 (32 dict) –> {"뉴에이스 영한사전 / 뉴에이스 한영사전", "Multidictionnaire de la langue française", "राजपाल हिन्दी शब्दकोश", "Dizionario italiano da un affiliato di Oxford University Press", "Oxford-Hachette French Dictionary", "NE Ordbok", "Apple用語辞典", "牛津英汉汉英词典", "スーパー大辞林", "Oxford Dictionary of English", "Oxford American Writer’s Thesaurus", "Gran Diccionario Oxford – Español-Inglés • Inglés-Español", "Norsk Ordbok", "Wikipedia", "Oxford Paravia Il Dizionario inglese – italiano/italiano – inglese", "Duden-Wissensnetz deutsche Sprache", "Толковый словарь русского языка", "Oxford Thesaurus of English", "TTY Dictionary", "Dicionário de Português licenciado para Oxford University Press", "New Oxford American Dictionary", "Prisma woordenboek Nederlands", "뉴에이스 국어사전", "Oxford German Dictionary", "五南國語活用辭典", "Diccionario General de la Lengua Española Vox", "ウィズダム英和辞典 / ウィズダム和英辞典", "Arkadaş Türkçe Sözlük", "พจนานุกรมไทย ฉบับทันสมัยและสมบูรณ์", "现代汉语规范词典", "Politikens Nudansk Ordbog", "Prisma Handwoordenboek Engels"} –macOS 10.13 (34 dict) –> {"Gran Diccionario Oxford – Español-Inglés • Inglés-Español", "Norsk Ordbok", "Arkadaş Türkçe Sözlük", "五南國語活用辭典", "Oxford Thesaurus of English", "Oxford Dictionary of English", "พจนานุกรมไทย ฉบับทันสมัยและสมบูรณ์", "スーパー大辞林", "राजपाल हिन्दी शब्दकोश", "Duden-Wissensnetz deutsche Sprache", "Multidictionnaire de la langue française", "现代汉语规范词典", "Prisma woordenboek Nederlands", "Dicionário de Português licenciado para Oxford University Press", "New Oxford American Dictionary", "ウィズダム英和辞典 / ウィズダム和英辞典", "NE Ordbok", "Толковый словарь русского языка", "Apple用語辞典", "Diccionario General de la Lengua Española Vox", "뉴에이스 국어사전", "Politikens Nudansk Ordbog", "TTY Dictionary", "Prisma Handwoordenboek Engels", "Dizionario italiano da un affiliato di Oxford University Press", "Wikipedia", "Oxford Paravia Il Dizionario inglese – italiano/italiano – inglese", "Oxford German Dictionary", "Oxford-Hachette French Dictionary", "Oxford Russian Dictionary – Русско-Английский • Англо-Русский", "Oxford American Writer’s Thesaurus", "Oxford Portuguese Dictionary – Português-Inglês • Inglês-Português", "牛津英汉汉英词典", "뉴에이스 영한사전 / 뉴에이스 한영사전"} |
ASOCで辞書検索じっけん
AppleScript名:ASOCで辞書検索じっけん |
— Created 2015-10-22 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "dictKit" –https://github.com/mattt/DictionaryKit set aDictionary to current application’s TTTDictionary’s dictionaryNamed:"Apple用語辞典" –macOS 10.12で"Apple 用語辞典"から"Apple用語辞典"に名称が変更された set dRes to aDictionary’s |name|() set dRes to dRes as text –> "Apple 用語辞典" set aTerm to "AppleScript" set hitEntryList to (aDictionary’s entriesForSearchTerm:aTerm) as list if hitEntryList = {missing value} then return "" –ヒットしなかった場合 repeat with i in hitEntryList set j to contents of i set headW to (j’s headword) set headW to headW as text –> "AppleScript" set aText to (j’s |text|) set aText to aText as text (*) –> "AppleScript OS X に内蔵されたスクリプト言語です。AppleScript 言語のコマンドを使用すれば、“メール”、Safari、“カレンダー”など、さまざまなアプリケーションで繰り返しの作業や複雑な作業を自動化できます。 *) end repeat |