AppleScript名:considering numeric strings |
set aVer to "10.10.1" set bVer to "10.9.5" –OS X 10.4で導入されたconsidering numeric strings considering numeric strings if aVer > bVer then display dialog "Yosemite is newer than Mavericks" else display dialog "Whoa!" end if end considering if aVer > bVer then display dialog "Yosemite is newer than Mavericks" else display dialog "Whoa!" end if |
タグ: 10.13savvy
NSStringによりバージョン文字列比較
AppleScript名:NSStringによりバージョン文字列比較 |
— Created 2015-07-27 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aVer to "10.10.0" set bVer to "10.10" set aVerStr to current application’s NSString’s stringWithString:aVer set bVerStr to current application’s NSString’s stringWithString:bVer set aRes to aVerStr’s compare:bVer options:(current application’s NSNumericSearch) –> 1 –1:aVer > bVer, 0:aVer = bVer, -1:bVer > aVer |
バージョン番号文字列の正確な比較
AppleScript名:バージョン番号文字列の正確な比較 |
— Created 2015-07-27 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set a to "10.10" set b to "10.10.0" set aRes to compareVersionNumericStrings(a, b) of me –> "A=B" set a to "10.10" set b to "10.10.0.1" set aRes to compareVersionNumericStrings(a, b) of me –> "B>A" set a to "10.10.1" set b to "10.10.0.1" set aRes to compareVersionNumericStrings(a, b) of me –> "A>B" set a to "10.10.1" set b to "10.9.1.1" set aRes to compareVersionNumericStrings(a, b) of me –> "A>B" –バージョン番号文字列の正確な比較 on compareVersionNumericStrings(a, b) set aList to parseVersionNumber(a) of me –> {"10", "10"} set bList to parseVersionNumber(b) of me –> {"10", "10", "0"} set aLen to length of aList set bLen to length of bList if aLen = bLen then –何もしない set buryTimes to 0 else if aLen > bLen then set buryTimes to (aLen – bLen) set bList to addNullItems(bList, "0", buryTimes) of me else if bLen > aLen then set buryTimes to (bLen – aLen) set aList to addNullItems(aList, "0", buryTimes) of me end if set cLen to length of aList –aListもbListも同じ長さなのでこれでいい repeat with i from 1 to cLen set aItem to contents of item i of aList set bItem to contents of item i of bList considering numeric strings if aItem > bItem then return "A>B" else if aItem < bItem then return "B>A" end if end considering end repeat return "A=B" end compareVersionNumericStrings –バージョン番号文字列からメジャーバージョンを取り出し数値として返す on parseVersionNumber(a) set aStr to current application’s NSString’s stringWithString:a set aRes to (aStr’s componentsSeparatedByString:".") set bRes to aRes’s allObjects() return bRes as list end parseVersionNumber –指定リストの末尾に指定個数、埋め草を追加する on addNullItems(aList, anItem, aTimes) copy aList to bList repeat aTimes times set the end of bList to anItem end repeat return bList end addNullItems |
NFKC Casefoldの影響を除外した文字列比較
AppleScript名:NFKC Casefoldの影響を除外した文字列比較 |
use AppleScript version "2.4" use framework "Foundation" use scripting additions set a to "㍑" set b to "リットル" log (a = b) –AppleScriptネイティブの文字列比較だとこれらが混同されることに注意 –> true set c to compStrA_B_(a, b) –> false set a to "バビブベボ" set b to "ハヒフヘホ" log (a = b) –> false set c to compStrA_B_(a, b) –> false set a to "あいうえお" set b to "アイウエオ" log (a = b) –AppleScriptネイティブの文字列比較だとこれらが混同されることに注意 –> true set c to compStrA_B_(a, b) –> false –文字列比較をASOC(Cocoa)とAppleScriptで実施するテストルーチン on compStrA:a b:b set aStr to current application’s NSString’s stringWithString:a set bStr to current application’s NSString’s stringWithString:b return (aStr’s isEqualToString:bStr) as boolean end compStrA:b: |
Umlautを無視した文字列比較(NSDiacriticInsensitiveSearch)
AppleScript名:Umlautを無視した文字列比較(NSDiacriticInsensitiveSearch) |
— Created 2015-03-28 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" set aRes to compareIgnoringDiacriticals("AbC", "ÂbC") –> true set aRes to compareIgnoringDiacriticals("Abc", "Ábc") –> true set aRes to compareIgnoringDiacriticals("abc", "åbc") –> true –Strings Compare with ignoring Umlaut on compareIgnoringDiacriticals(aText as text, bText as text) set aStr to current application’s NSString’s stringWithString:aText return (aStr’s compare:bText options:((current application’s NSCaseInsensitiveSearch) + (current application’s NSDiacriticInsensitiveSearch as integer))) = current application’s NSOrderedSame end compareIgnoringDiacriticals |
テキストからリガチャーを削除する v2
AppleScript名:テキストからリガチャーを削除する v2 |
— Created 2017-01-17 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set inputStringWithLigatures to "ꜲꜳÆæꜴꜵꜶꜷꜸꜹꜺꜻꜼꜽffffifflfiflŒœꝎstꜨꜩᵫꝠꝡ" & "LJLjNJNjnjDZDzdzIJij" set aRes to removeLigaturesFromString(inputStringWithLigatures) of me –> "AAaaAEaeAOaoAUauAVavAVavAYayffffifflfiflOEoeOOstTZtzueVYvyLJLjNJNjnjDZDzdzIJij" on removeLigaturesFromString(inputStringWithLigatures) set theString to current application’s NSString’s stringWithString:inputStringWithLigatures # Convert what may be done applying transform "ÆæffffifflfiflŒœᵫ" & "LJLjNJNjnjDZDzdzIJij" set inputStringWithLigatures to (theString’s stringByApplyingTransform:"Latin-ASCII" |reverse|:false) as text # Treat the remaining ligatures set searchStrings to {"Ꜳ", "ꜳ", "Ꜵ", "ꜵ", "Ꜷ", "ꜷ", "Ꜹ", "ꜹ", "Ꜻ", "ꜻ", "Ꜽ", "ꜽ", "Ꝏ", "Ꜩ", "ꜩ", "Ꝡ", "ꝡ"} — if you find others, add them here set replaceStrings to {"AA", "aa", "AO", "ao", "AU", "au", "AV", "av", "AV", "av", "AY", "ay", "OO", "TZ", "tz", "VY", "vy"} — if you find others, add them here set saveTID to AppleScript’s text item delimiters considering case set i to 0 repeat with lig in searchStrings set i to i + 1 set AppleScript’s text item delimiters to {lig} set inputStringWithLigatures to text items of inputStringWithLigatures set AppleScript’s text item delimiters to {item i of replaceStrings} set inputStringWithLigatures to inputStringWithLigatures as text end repeat end considering set AppleScript’s text item delimiters to saveTID return inputStringWithLigatures end removeLigaturesFromString |
指定キーワードの出現回数のカウント
AppleScript名:指定キーワードの出現回数のカウント |
set origText to "このテキストはいずれ何らかの指定キーワードが何回出現するかという見地から評価される運命にある。評価されるということは、何がしかの文法的評価体系によって分析されるということである(すんごい、いいかげんな日本語)。" set aKeyText to "何" set freqNum to retFrequency(origText, aKeyText) of me –指定文字列内の指定キーワードの出現回数を取得する on retFrequency(origText, aKeyText) set aRes to parseByDelim(origText, aKeyText) of me return ((count every item of aRes) – 1) end retFrequency on parseByDelim(aData, aDelim) set curDelim to AppleScript’s text item delimiters set AppleScript’s text item delimiters to aDelim set dList to text items of aData set AppleScript’s text item delimiters to curDelim return dList end parseByDelim |
ASOCで文字を逆順に v2(CJK文字などマルチバイト対応)
AppleScript名:ASOCで文字を逆順に v2(CJK文字などマルチバイト対応) |
— Created 2015-09-01 by Takaaki Naganoya — Modified 2015-09-01 by Shane Stanley –Consider CJK Characters & Emoji –http://stackoverflow.com/questions/6720191/reverse-nsstring-text use AppleScript version "2.4" use scripting additions use framework "Foundation" set aUUID to (current application’s NSUUID’s UUID()’s UUIDString()) as text –> "46EF17B7-CB3E-4DD9-BA8A-013D3B30A80A" set aUUID to "😀😐" & aUUID & "😀😐" –> "😀😐46EF17B7-CB3E-4DD9-BA8A-013D3B30A80A😀😐" set revUUID to reversedStr(aUUID) as text –> "😐😀A08A03B3D310-A8AB-9DD4-E3BC-7B71FE64😐😀" on reversedStr(paramStr as text) set aStr to current application’s NSString’s stringWithString:paramStr set strLength to aStr’s |length|() set revStr to current application’s NSMutableString’s stringWithCapacity:strLength set charIndex to strLength – 1 repeat while charIndex > -1 set subStrRange to aStr’s rangeOfComposedCharacterSequenceAtIndex:charIndex revStr’s appendString:(aStr’s substringWithRange:subStrRange) set charIndex to (location of subStrRange) – 1 end repeat return revStr end reversedStr |
バージョン番号文字列からメジャーバージョンを取り出し数値として返す v4
AppleScript名:バージョン番号文字列からメジャーバージョンを取り出し数値として返す v4 |
use AppleScript version "2.5" use scripting additions use framework "Foundation" set a to "10.0.1" set b to retMajorVersionNumber(a) of me –> 10 set a to "9.10" set b to retMajorVersionNumber(a) of me –> 9 –バージョン番号文字列からメジャーバージョンを取り出し数値として返す on retMajorVersionNumber(a) set aStr to current application’s NSString’s stringWithString:a –> "10.0.1" (NSString) set aRes to (aStr’s componentsSeparatedByString:".") –> {"10","0","1"} (NSArray) set bRes to aRes’s firstObject() –> "10" (NSString) set cRes to bRes’s integerValue() –> 10 return cRes as integer end retMajorVersionNumber |
指定フォルダ以下のすべてのファイルのうち指定UTIに該当するものを取得(spotlightで処理)
AppleScript名:指定フォルダ以下のすべてのファイルを再帰で取得(spotlightで処理).scpt |
use AppleScript version "2.4" 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 –set theFolder to choose folder set theFolder to (path to desktop folder) set theFiles to mdLib’s searchFolders:{theFolder} searchString:"kMDItemContentType IN[c] %@" searchArgs:{"com.apple.applescript.script", "com.apple.applescript.script-bundle"} |
指定フォルダ以下のすべてのファイルを再帰で取得 v2
指定フォルダ以下のすべてのファイルを再帰で取得するAppleScriptです。
「指定フォルダ以下のファイルを取得する」やりかたは、Spotlightを使うのがベストです。ベストではあるものの、各ユーザーのHDDなりSSDは「破損している」ケースもあって、Spotligtの検索が効かない場合もあります。
また、マウントしたLAN上のファイルサーバーに対してSpotlightが効くかどうかは実際にやってみないと分かりません。OSが異なる可能性がありますし、同じmacOSであっても効くかどうかは実際に試してみるまではっきりしません(開発時に真っ先に確認するポイントでもあります。ファイルサーバーを相手に処理するつもりかどうかの確認です)。
そこで、地道に再帰処理でファイルを取得すること「も」試してみることになるわけですが、ここでFinderを使うと遅くなります。
OS X 10.6以降の64ビット化されたいわゆる「Cocoa Finder」は処理速度が低下しているため、大量のファイル処理をFinder経由で行うことは「悪手」といえます。数百個ぐらいでけっこうな処理速度の低下がみられます。1,000を超えると露骨に速度が下がります。フィルタ参照で条件をつけて抽出するのも速度低下につながります。さらに複数のフィルタ条件を指定するとアホみたいに遅くなります。Cocoa Finderの性能低下はハンパではありません。
たまに、Classic Mac OSの環境しか知らない人が久しぶりに現代の(64ビット化された)macOS上で昔と同じようにFinderに対して膨大なファイルの処理を行わせて「遅い」と文句を言っているのを見かけますが、Finder経由でのファイル処理が現実的ではないという状況を知らなければそういう感想になってしまうかもしれません。
# Classic MacOS〜macOS 10.6ぐらいまではFinder経由で行っても、極端に時間がかかることはありませんでした。それ以降の環境のお話です。また、macOS 10.7以降でも、数個〜数十程度のすくないファイルを処理する場合には、あまり問題になりません
そこで、NSFileManagerを用いてファイル処理を行うことで、「Spotlightほど速くはないものの、Finderで処理するよりははるかに高速」な処理を行えます。
AppleScript名:指定フォルダ以下のすべてのファイルを再帰で取得 v2 |
— Created 2017-08-04 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" property NSString : a reference to current application’s NSString property NSPredicate : a reference to current application’s NSPredicate property NSFileManager : a reference to current application’s NSFileManager property NSMutableArray : a reference to current application’s NSMutableArray –set aFol to POSIX path of (choose folder) set aFol to POSIX path of (path to desktop folder) –set aList to retFullPathWithinAFolderWithRecursive(aFol) of me set bList to retFullPathWithinAFolderWithRecursiveFilterByExt(aFol, "scpt") of me –set cList to retFilenameWithinAFolderWithRecursiveFilterByExt(aFol, {"scpt", "scptd"}) of me –set dList to retFullPathWithinAFolderWithRecursiveFilterByExtAndFileNameString(aFol, "png", "スクリーン") of me –set eList to retFullPathWithinAFolderWithRecursiveFilterByExtAndFileNameString(aFol, {"scpt", "scptd"}, "並列") of me –指定フォルダ以下のすべてのファイルを再帰で取得 on retFilenamesWithinAFolderWithRecursive(aFol) 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’s lastPathComponent()’s stringByDeletingPathExtension() as string) end repeat return anArray as list end retFilenamesWithinAFolderWithRecursive –指定フォルダ以下のすべてのファイルを再帰で取得 on retFullPathWithinAFolderWithRecursive(aFol) 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’s lastPathComponent()’s stringByDeletingPathExtension() as string) end repeat return anArray as list end retFullPathWithinAFolderWithRecursive –指定フォルダ以下のすべてのファイルを再帰で取得(拡張子で絞り込み) on retFilenameWithinAFolderWithRecursiveFilterByExt(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 retFilenameWithinAFolderWithRecursiveFilterByExt –指定フォルダ以下のすべてのファイルを再帰で取得(拡張子で絞り込み) 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 –指定フォルダ以下のすべてのファイルを再帰で取得(拡張子リストで絞り込み) on retFullPathWithinAFolderWithRecursiveFilterByExtList(aFol, aExtList) 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 IN [c]%@" argumentArray:{aExtList} set bArray to anArray’s filteredArrayUsingPredicate:thePred return bArray as list end retFullPathWithinAFolderWithRecursiveFilterByExtList –指定フォルダ以下のすべてのファイルを再帰で取得(文字列と拡張子で絞り込み) on retFullPathWithinAFolderWithRecursiveFilterByExtListAndFileNameString(aFol, aExt, aNameString) 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]%@ && lastPathComponent CONTAINS %@" argumentArray:{aExt, aNameString} set bArray to anArray’s filteredArrayUsingPredicate:thePred return bArray as list end retFullPathWithinAFolderWithRecursiveFilterByExtListAndFileNameString –指定フォルダ以下のすべてのファイルを再帰で取得(文字列と拡張子リストで絞り込み) on retFullPathWithinAFolderWithRecursiveFilterByExtAndFileNameString(aFol, aExtList, aNameString) 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 IN [c]%@ && lastPathComponent CONTAINS %@" argumentArray:{aExtList, aNameString} set bArray to anArray’s filteredArrayUsingPredicate:thePred return bArray as list end retFullPathWithinAFolderWithRecursiveFilterByExtAndFileNameString |
指定ボリウムをマウント
AppleScript名:指定ボリウムをマウント |
— Created 2015-12-01 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aPath to current application’s |NSURL|’s URLWithString:"afp://MBA13.local/maro" set ws to current application’s NSWorkspace’s sharedWorkspace() ws’s openURL:aPath |
CocoaでDiskSpace(%)を求める
AppleScript名:CocoaでDiskSpace(%)を求める |
— Created 2015-04-01 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aPath to current application’s NSString’s stringWithString:"/" set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:aPath |error|:(missing value) set fRes to (fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize)) as string set aDecNum to current application’s NSDecimalNumber’s decimalNumberWithString:fRes set aFreeNum to aDecNum’s decimalNumberByDividingBy:(current application’s NSDecimalNumber’s decimalNumberWithString:"1000000000") –"G" Bytes for Storage set bFreeNum to aFreeNum as real –> 84.058387756348 |
CocoaでDiskSpace(Bytes)を求める
AppleScript名:CocoaでDiskSpace(Bytes)を求める |
— Created 2015-04-02 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" usedSpace("/") –> 8.4346003456E+10 usedSpace2("/") –> 8.4345450496E+10 usedSpaceString("/") –> "84.35 GB" usedSpaceLongString("/") –> "45.77 GB (45,772,857,344 bytes)"–English user environment –> "45.77 GB (45,772,857,344 バイト)"–Japanese user environment tell application "Finder" free space of startup disk end tell –> 4.5784592712E+10 on usedSpace(volumePath) set theNSURL to current application’s class "NSURL"’s fileURLWithPath:volumePath –considering "ASOC in Xcode" set {theResult, theSize} to theNSURL’s getResourceValue:(reference) forKey:(current application’s NSURLVolumeAvailableCapacityKey) |error|:(missing value) return theSize as real — integer may be too big for AS end usedSpace on usedSpace2(volumePath) set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value) return (fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize)) as real — integer may be too big for AS end usedSpace2 on usedSpaceString(volumePath) set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value) set fRes to fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize) –Formatting set sizeString to current application’s NSByteCountFormatter’s stringFromByteCount:fRes countStyle:(current application’s NSByteCountFormatterCountStyleDecimal) return sizeString as text end usedSpaceString on usedSpaceLongString(volumePath) set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value) set fRes to fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize) –Formatting set theFormatter to current application’s NSByteCountFormatter’s alloc()’s init() theFormatter’s setCountStyle:(current application’s NSByteCountFormatterCountStyleDecimal) theFormatter’s setIncludesActualByteCount:true set sizeString to theFormatter’s stringFromByteCount:fRes return sizeString as text end usedSpaceLongString |
指定フォルダが所属しているDiskの空き容量をGバイト単位で返す
AppleScript名:指定フォルダが所属しているDiskの空き容量をGバイト単位で返す |
— Created 2015-04-02 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" set aFol to choose folder set aFolPOSIX to POSIX path of aFol set fRes to freeStorageSpaceG(aFolPOSIX) –指定フォルダが所属しているDiskの空き容量をGバイト単位で返す on freeStorageSpaceG(volumePath) set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value) set fileFree to (fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize)) set sizeString to current application’s NSByteCountFormatter’s stringFromByteCount:fileFree countStyle:(current application’s NSByteCountFormatterCountStyleDecimal) return sizeString as text end freeStorageSpaceG |
指定ボリウム(サーバーボリウム)の空き容量を調べる
AppleScript名:指定ボリウム(サーバーボリウム)の空き容量を調べる |
— Created 2015-05-14 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" set serverName to "maro" set aRes to getVolumeFreeSpace(serverName) of me on getVolumeFreeSpace(serverName) set anNSURL to (current application’s |NSURL|’s fileURLWithPath:"/Volumes")’s URLByAppendingPathComponent:serverName set theResult to (anNSURL’s checkResourceIsReachableAndReturnError:(missing value)) as boolean if not theResult then — not mounted, so handle error return false end if set {theResult, theSpare} to anNSURL’s getResourceValue:(reference) forKey:(current application’s NSURLVolumeAvailableCapacityKey) |error|:(missing value) if theResult as boolean then set spareString to (current application’s NSByteCountFormatter’s stringFromByteCount:theSpare countStyle:(current application’s NSByteCountFormatterCountStyleFile)) as text else — couldn’t get the value, so handle error error end if end getVolumeFreeSpace |
SDカードを検出
マウントされたドライブのうちSDカードに相当するものを検出するAppleScriptです。
ただし、iMac Proで採用されたUHS‑II対応のSDカードスロット+UHS-II対応のSDカードがどのように見えるかは実機がないので確認できません。
exFATのことも考えると、「MSDOS format」を抽出条件に入れないほうがいいのかもしれません。
AppleScript名:SDカードを検出 |
— Created 2016-10-04 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" tell application "Finder" set driveList to every disk whose format is (MSDOS format) and ejectable is true and startup is false repeat with i in driveList set myDisk to disk of (first item of i) set myMountPoint to POSIX path of (myDisk as alias) –> "/Volumes/JVCCAM_SD/" –> "/Volumes/RICOHDCX/" set sdRes to detectSDCard(myMountPoint) of me –> true –SD Card, false –Not SD Card end repeat end tell on detectSDCard(myMountPoint as string) set resData to runCommandString("system_profiler -xml SPStorageDataType") of me set aaDict to (readPlistFromStr(resData) of me) as list set aDictList to (_items of first item of aaDict) repeat with i in aDictList set j to contents of i set aMountPoint to (mount_point of j) as string –> "/Volumes/JVCCAM_SD" –> "/Volumes/RICOHDCX" if aMountPoint is not equal to "/" then if ((aMountPoint & "/") is equal to myMountPoint) then set aDevName to words of (device_name of physical_drive of j) set aMediaName to words of (media_name of physical_drive of j) –SD/SDHC/SDXCのカード検出 set aDevF to ("SD" is in aDevName) or ("SDHC" is in aDevName) or ("SDXC" is in aDevName) set aMediaF to ("SD" is in aMediaName) or ("SDHC" is in aMediaName) or ("SDXC" is in aMediaName) if (aDevF and aMediaF) then return true end if end if end repeat return false end detectSDCard –文字列で与えたシェルコマンドを実行する 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)} 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 –stringのplistを読み込んでRecordに on readPlistFromStr(theString) set aSource to current application’s NSString’s stringWithString:theString set pListData to aSource’s dataUsingEncoding:(current application’s NSUTF8StringEncoding) set aPlist to current application’s NSPropertyListSerialization’s propertyListFromData:pListData mutabilityOption:(current application’s NSPropertyListImmutable) |format|:(current application’s NSPropertyListFormat) errorDescription:(missing value) return aPlist end readPlistFromStr |
指定容量の指定名称のRAMディスクを作成する
指定容量+指定名称のRAMディスクを作成するAppleScriptです。
SSDのアクセス速度が意外と処理のボトルネックになることがあるので(並列処理時とか)、ごくまれにRAMディスクを作って処理することがあります。
ただ、ベンチマーク値では最新機種の方がこれ(↑)よりも高速なSSDを搭載していたりするので、なかなか感慨深いものがあります。実際に処理を行わせてみるとベンチマーク値ほどには差が出なかったりもします。
AppleScript名:指定容量の指定名称のRAMディスクを作成する |
— Created 2017-01-24 by Takaaki Naganoya — 2017 Piyomaru Software –https://www.tekrevue.com/tip/how-to-create-a-4gbs-ram-disk-in-mac-os-x/ use AppleScript version "2.4" use scripting additions use framework "Foundation" set dName to "RAM Disk" set dCapacity to 512 * 2 * 1000 –512MB set aCmd to "diskutil erasevolume HFS+ ’" & dName & "’ `hdiutil attach -nomount ram://" & (dCapacity as string) & "`" try do shell script aCmd end try |
指定フォルダ内のPDFの1ページ目をすべて別のPDFにまとめる
AppleScript名:指定フォルダ内のPDFの1ページ目をすべて別のPDFにまとめる |
— Created 2017-09-12 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" property |NSURL| : a reference to current application’s |NSURL| property NSPredicate : a reference to current application’s NSPredicate property NSFileManager : a reference to current application’s NSFileManager property PDFDocument : a reference to current application’s PDFDocument property NSMutableArray : a reference to current application’s NSMutableArray property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants set aFol to POSIX path of (choose folder with prompt "Choose folder" default location (path to pictures folder)) set targPDF to POSIX path of (choose file name with prompt "Choose File Name" default location (path to desktop folder) default name ((do shell script "uuidgen") & ".pdf")) set pRes to gatherEachFirstPage(aFol, targPDF) of me on gatherEachFirstPage(aFol, targPDF) set aURL to (|NSURL|’s fileURLWithPath:targPDF) set outPDFdoc to PDFDocument’s alloc()’s init() set aList to my getFilesByExtension:{"pdf"} fromDirectory:(aFol) set outPDFPageCount to 0 repeat with i in aList –集めたPDFの1ページ目を取得 set bURL to (|NSURL|’s fileURLWithPath:(POSIX path of i)) set bPDFdoc to (PDFDocument’s alloc()’s initWithURL:bURL) set bPage to (bPDFdoc’s pageAtIndex:0) –first page –まとめ先のPDFに追記 (outPDFdoc’s insertPage:bPage atIndex:outPDFPageCount) set outPDFPageCount to outPDFPageCount + 1 end repeat return (outPDFdoc’s writeToURL:aURL) as boolean end gatherEachFirstPage –指定フォルダ内の指定拡張子のファイルを抽出する on getFilesByExtension:listOfExtensions fromDirectory:sourceFolder set fileManager to NSFileManager’s defaultManager() set aURL to |NSURL|’s fileURLWithPath:sourceFolder set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value) set foundItemList to NSPredicate’s predicateWithFormat_("pathExtension.lowercaseString IN %@", listOfExtensions) set foundItemList to directoryContents’s filteredArrayUsingPredicate:foundItemList # Return as a list POSIX Paths set foundItemList to (foundItemList’s valueForKey:"path") as list return foundItemList end getFilesByExtension:fromDirectory: |
PDFをページごとに分解してJPEGで保存する v3
AppleScript名:PDFをページごとに分解してJPEGで保存する v3 |
— Created 2014-12-26 by Takaaki Naganoya — Modified 2015-09-26 by Takaaki Naganoya — Modified 2015-10-01 by Takaaki Naganoya — Modified 2016-07-27 by Takaaki Naganoya–Save each PDF page as jpeg — Modified 2016-07-27 by Takaaki Naganoya–Zero padding function, Consider Retina Env — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" use framework "AppKit" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "ページごとに分解するPDFを指定してください") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPOSIXpath to POSIX path of aHFSPath —書き出し先パスをPOSIX pathで用意しておく(あとで加工) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set compFactor to 1.0 –1.0 — 0.0 = max jpeg compression, 1.0 = none –Detect Retina Environment set retinaF to current application’s NSScreen’s mainScreen()’s backingScaleFactor() if retinaF = 1.0 then set aScale to 2.0 –Non Retina Env else set aScale to 1.0 –Retina Env end if –PDFをページごとに分割してJPEGでファイル書き出し repeat with i from 0 to (pCount – 1) –Pick Up a PDF page as an image set thisPage to (aPDFdoc’s pageAtIndex:(i)) set thisDoc to (current application’s NSImage’s alloc()’s initWithData:(thisPage’s dataRepresentation())) if thisDoc = missing value then error "Error in getting imagerep from PDF in page:" & (i as string) –Resize Image set pointSize to thisDoc’s |size|() set newSize to current application’s NSMakeSize((pointSize’s width) * aScale, (pointSize’s height) * aScale) set newImage to (current application’s NSImage’s alloc()’s initWithSize:newSize) newImage’s lockFocus() (thisDoc’s setSize:newSize) (current application’s NSGraphicsContext’s currentContext()’s setImageInterpolation:(current application’s NSImageInterpolationHigh)) (thisDoc’s drawAtPoint:(current application’s NSZeroPoint) fromRect:(current application’s CGRectMake(0, 0, newSize’s width, newSize’s height)) operation:(current application’s NSCompositeCopy) fraction:1.0) newImage’s unlockFocus() –Save Image as JPEG set theData to newImage’s TIFFRepresentation() set newRep to (current application’s NSBitmapImageRep’s imageRepWithData:theData) set targData to (newRep’s representationUsingType:(current application’s NSJPEGFileType) |properties|:{NSImageCompressionFactor:compFactor, NSImageProgressive:false}) set zText to retZeroPaddingText((i + 1), 4) of me set outPath to addString_beforeExtensionIn_addingExtension_("_" & zText, aPOSIXpath, "jpg") (targData’s writeToFile:outPath atomically:true) –書き出し end repeat –ファイルパス(POSIX path)に対して、文字列(枝番)を追加。任意の拡張子を追加 on addString:extraString beforeExtensionIn:aPath addingExtension:aExt set pathString to current application’s NSString’s stringWithString:aPath set theExtension to pathString’s pathExtension() set thePathNoExt to pathString’s stringByDeletingPathExtension() set newPath to (thePathNoExt’s stringByAppendingString:extraString)’s stringByAppendingPathExtension:aExt return newPath as string end addString:beforeExtensionIn:addingExtension: on retZeroPaddingText(aNum as integer, aDigitNum as integer) if aNum > (((10 ^ aDigitNum) as integer) – 1) then return "" –Range Check set aFormatter to current application’s NSNumberFormatter’s alloc()’s init() aFormatter’s setUsesGroupingSeparator:false aFormatter’s setAllowsFloats:false aFormatter’s setMaximumIntegerDigits:aDigitNum aFormatter’s setMinimumIntegerDigits:aDigitNum aFormatter’s setPaddingCharacter:"0" set aStr to aFormatter’s stringFromNumber:(current application’s NSNumber’s numberWithFloat:aNum) return aStr as string end retZeroPaddingText |