AppleScript名:アプリケーションバンドル内のファイルパスを取得する |
use AppleScript version "2.4" use scripting additions use framework "Foundation" property |NSURL| : a reference to current application’s |NSURL| property NSFileManager : a reference to current application’s NSFileManager set aRes to getPathsIn_maxfiles_("/Applications/Safari.app", 4096) –> {"/Applications/Safari.app/Contents", "/Applications/Safari.app/Contents/_CodeSignature", "/Applications/Safari.app/Contents/_CodeSignature/CodeResources", …. — Example of file manager directory enumeration on getPathsIn:folderPath maxfiles:MaxNum script spd property aList : {} end script set aList of spd to {} set theNSURL to |NSURL|’s fileURLWithPath:folderPath set theNSFileManager to NSFileManager’s new() — get URL enumerator set theNSFileEnumerator to theNSFileManager’s enumeratorAtURL:theNSURL includingPropertiesForKeys:{} options:0 errorHandler:(missing value) repeat with i from 1 to MaxNum — arbitrary number — get next URL in enumerator set anNSURL to theNSFileEnumerator’s nextObject() if anNSURL is missing value then exit repeat — missing value means there are no more set the end of (aList of spd) to (anNSURL’s |path|() as text) end repeat return (aList of spd) end getPathsIn:maxfiles: |
月: 2018年2月
指定のアプリケーションのInfo.plistの任意の属性値を取得する
AppleScript名:指定のアプリケーションのInfo.plistの任意の属性値を取得する |
— Created 2017-07-23 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use BridgePlus : script "BridgePlus" –http://piyocast.com/as/archives/4759 load framework set aP to choose file set aURLrec to getAppPropertyFromInfoPlist(aP, "NSAppleScriptEnabled") of me –> {appName:"Photos", appBundleID:"com.apple.Photos", urlScheme:{"photos"}} on getAppPropertyFromInfoPlist(aP, aPropertyLabel) set aURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of aP) set aBundle to current application’s NSBundle’s bundleWithURL:aURL set aDict to aBundle’s infoDictionary() set appNameDat to (aDict’s valueForKey:"CFBundleName") as string set bundleIDat to (aDict’s valueForKey:"CFBundleIdentifier") as string set aRes to aDict’s valueForKey:aPropertyLabel if aRes is not equal to missing value then set aRes to aRes as string end if set aRec to {appName:appNameDat, appBundleID:bundleIDat, propRes:aRes} return aRec end getAppPropertyFromInfoPlist |
指定のアプリケーションのInfo.plistのすべての属性値を取得する
AppleScript名:指定のアプリケーションのInfo.plistのすべての属性値を取得する |
— Created 2017-07-23 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aP to choose file set aURLrec to getAppAllPropertyFromInfoPlist(aP) of me –> (NSDictionary) {DTCompiler:"com.apple.compilers.llvm.clang.1_0", NSAppleScriptEnabled:"YES", CFBundleInfoDictionaryVersion:"6.0", DTPlatformVersion:"GM", CFBundleIconFile:"Automator.icns", CFBundleName:"Automator", DTSDKName:"macosx10.12internal", NSServices:{{NSMenuItem:{default:"Create Service"}, NSSendTypes:{"NSStringPboardType", "NSFilenamesPboardType"}, … on getAppAllPropertyFromInfoPlist(aP) set aURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of aP) set aBundle to current application’s NSBundle’s bundleWithURL:aURL set aDict to aBundle’s infoDictionary() return aDict end getAppAllPropertyFromInfoPlist |
値を指定してCIColorを作成
AppleScript名:値を指定してCIColorを作成 |
— Created 2017-04-19 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" set redValue to 0 set greenValue to 0 set blueValue to 1 set alphaVlaue to 1.0 set aCIColor to current application’s CIColor’s alloc()’s initWithRed:redValue green:greenValue blue:blueValue alpha:alphaVlaue –> (CIColor) (0 0 1 1) |
NSColorからCIColorを作成
AppleScript名:NSColorからCIColorを作成 |
— Created 2017-04-19 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" use framework "AppKit" set redValue to 0 set greenValue to 0 set blueValue to 1 set alphaVlaue to 1.0 set aNSColor to current application’s NSColor’s colorWithCalibratedRed:redValue green:greenValue blue:blueValue alpha:alphaVlaue set aCIColor to current application’s CIColor’s alloc()’s initWithColor:aNSColor –> (CIColor) (0 0 1 1) |
GPUImageで指定画像が真っ白かどうか判定する
GPUImage Frameworkを用いて、指定画像が真っ白かどうかを判定するAppleScriptです。
–> GPUImage.framework(To ~/Library/Frameworks/)
指定画像のドットがすべて白いかどうかを判定する処理を真剣に行うと、かなり大変です。
いまでは大したことのない1,024 x 768のサイズの画像であっても、ピクセル数は786,432個。78万ピクセルのデータをRGBの各チャネルについてチェックを行う必要があります。78万×3=240万要素ぐらいの処理を行うわけで、メモリ8Gバイト搭載のMacでAppleScriptを用いて処理するのはつらいものがあります(AppleScriptの配列であるlist型変数はメモリ効率がそれほどよくないので)。
240万要素のList型変数(配列)をループで全要素チェックするだけでもけっこうな時間がかかります。こうした地道なアプローチで攻めるのは物理的に不可能です。実用的ではありません。
すべてのピクセルが白いかチェックするのに実用的な処理といえば、Adobe Photoshopで画像の明度ヒストグラムを求めて、ヒストグラムの配列をチェックするというものがあります(実戦に投入していました)。ただし、処理を行うのにAdobe Photoshopが必要になります。Photoshopがない環境では手も足も出ません。
そこで、GPUImage.frameworkをAppleScriptから呼び出してヒストグラムを計算する方法を見つけました。これであれば、AppleScriptと一緒に配布することも可能ですし、処理もPhotoshopより(起動時間を勘案すると)高速に行えます。
実際に、1024×768および1980×1200の真っ白い画像を作成し、それぞれ1ピクセルだけ黒く塗りつぶして空白検出を行なったところ「空白ではない」ことを検知できました(ただし、1×1の画像の判定をミスするという問題がありました)。
GPUImageのヒストグラム出力は、結果にArrayが返ってくるわけでもなく、ヒストグラム出力「画像」が出てくるだけです。その画像を256ピクセルほどスキャンして検出しています。
指定画像がすべて白いかチェックを行う演算は、PDFの空白ページの検出で利用しています。テキストだけではなく、グラフィック要素が指定ページに存在しているかどうかをチェックするために、GPUImage.frameworkのこのヒストグラム出力機能を利用しています。
GPUImage.framework自体は、Swiftで書き直されたGPUImage2に移行。さらにAppleから OpenGLとOpenGL ESが非推奨になりMetalが推奨になったためにGPUImage2も今度の動向がどうなるか不明。新たなGPUImage3に移行するのか、GPUImage2の機能のまましばらく行くのか動向が気になります(結局、Metal対応のGPUImage3に移行)。
各種の画像フィルター処理については代替手段があるものの、このヒストグラム計算による空白画像検出については現時点で代替手段がないため、調査しておきたいところです。ヒストグラム計算自体はありふれた演算なのですが、Objective-Cでラッピングされている例が少ないので、自分でプログラムを書かないといけないのかもしれません。
→ AppleScriptだけで本Scriptよりも高速に画像の空白判定を行えるようになりました(画像の空白判定 v4)。GPUImage.frameworkの機能はこの種類の処理にはもう使っていません。
AppleScript名:GPUImageで指定画像が真っ白かどうか判定する |
— Created 2017-02-12 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" use framework "GPUImage" use framework "Quartz" use framework "QuartzCore" use framework "CoreGraphics" set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select a image to check which is blank (or not) ") set aURL to current application’s |NSURL|’s fileURLWithPath:aFile set anNSImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL set wRes to my detectAllWhite:anNSImage –> true (Blank = White) –> false (Not Blank = Not White) –指定のNSImageが真っ白かどうかをチェック on detectAllWhite:anNSImage –グレースケールフィルタを通して色要素を削除 set grayImage to filterWithNSImage(anNSImage, "GPUImageGrayscaleFilter") of me –明度ヒストグラム画像を取得 set imgRes to getHistogramFromImage(grayImage, 4) of me –画像のサイズ(幅、高さ)をピクセル数で取得する(念のため) set aSize to imgRes’s |size|() set aWidth to aSize’s width() set aHeight to aSize’s height() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:(imgRes’s TIFFRepresentation()) –白い画像のデータパターン set aWhitePattern to current application’s NSMutableArray’s arrayWithArray:{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0} set resArray to current application’s NSMutableArray’s alloc()’s init() repeat with i from 0 to 255 set origColor to (aRawimg’s colorAtX:i y:1) set srgbColSpace to current application’s NSColorSpace’s genericGrayColorSpace set aColor to (origColor’s colorUsingColorSpace:srgbColSpace) set aWhite to aColor’s whiteComponent() (resArray’s addObject:aWhite) end repeat set aRes to (resArray’s isEqualTo:aWhitePattern) as boolean return aRes end detectAllWhite: –各種ヒストグラムの定数(From GPUImage.framework) –0:kGPUImageHistogramRed –1:kGPUImageHistogramGreen –2:kGPUImageHistogramBlue –3:kGPUImageHistogramRGB –4:kGPUImageHistogramLuminance –指定のNSImageを明度ヒストグラム化してNSImageで返す on getHistogramFromImage(aNSImage, histogramType) set aFilter to current application’s GPUImageHistogramFilter’s alloc()’s initWithHistogramType:histogramType set aProcImg to (aFilter’s imageByFilteringImage:aNSImage) return aProcImg end getHistogramFromImage –NSImageをGPUImage.frameworkの指定フィルタで処理してNSImageを返す on filterWithNSImage(aNSImage, filterName as string) set aClass to current application’s NSClassFromString(filterName) set aImageFilter to aClass’s alloc()’s init() set aProcImg to (aImageFilter’s imageByFilteringImage:aNSImage) return aProcImg end filterWithNSImage |
任意の2色の色差ΔEを求める
Coloursをフレームワーク化したcolorsKit.frameworkを呼び出して、指定の任意のRGB色2色の色差(ΔE)を計算するAppleScriptです。
色差を求めるためには、RGB色をXYZを経由してL*a*b*色に変換する必要があります。変換自体はColoursの内蔵機能で行っています。
ただし、色差を求める際にNSColor’s whiteColor()などと通常のメソッドで求めたNSColorとColoursの機能を用いて求めたNSColorとの間で計算をするとエラーになります。色差の計算はColoursの機能を用いて作成したNSColor同士で行う必要があるようです。
AppleScript名:任意の2色の色差ΔEを求める |
— Created 2017-12-29 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "colorsKit" –https://github.com/bennyguitar/Colours use framework "AppKit" property NSColor : a reference to current application’s NSColor set aASCol to choose color set bASCol to choose color set aCocoaList to retCocoaColorList(aASCol, 65535) of me set bCocoaList to retCocoaColorList(bASCol, 65535) of me set aCol to NSColor’s colorFromRGBAArray:aCocoaList set bCol to NSColor’s colorFromRGBAArray:bCocoaList set aDist to aCol’s distanceFromColor:bCol type:2 –ColorDistanceCIE2000 return aDist –Convert "choose color" RGB list (0-65535) to Cocoa color RGBA Array (0.0-1.0) on retCocoaColorList(aColorList, aMax) set cocoaColorList to {} repeat with i in aColorList set the end of cocoaColorList to i / aMax end repeat set the end of cocoaColorList to 1.0 return cocoaColorList end retCocoaColorList |
文字列のURLエンコード、URLデコード
AppleScript名:文字列のURLエンコード、URLデコード |
— Created 2017-09-19 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "あいうえお" set bStr to encodeURLencoding(aStr) of me –> "%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A" set cStr to decodeURLencoding(bStr) of me –> "あいうえお" on encodeURLencoding(origStr as string) set aStr to current application’s NSString’s stringWithString:origStr set encodedStr to aStr’s stringByAddingPercentEscapesUsingEncoding:(current application’s NSUTF8StringEncoding) return encodedStr as string end encodeURLencoding on decodeURLencoding(encodedStr) set aStr to current application’s NSString’s stringWithString:encodedStr set bStr to aStr’s stringByReplacingPercentEscapesUsingEncoding:(current application’s NSUTF8StringEncoding) return bStr as string end decodeURLencoding |
URLにリソースが存在するかチェック v4
AppleScript名:URLにリソースが存在するかチェック v4 |
— Created 2016-10-18 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "http://piyocast.com/as/wp-content/uploads/2018/02/map2-1024×796.png" set aURL to (current application’s |NSURL|’s URLWithString:aStr) set {exRes, headerRes, aData} to checkURLResourceExistence(aURL, 3) of me log exRes –> true / false return {exRes, headerRes as record} –> {true, {|content-type|:"image/png", |keep-alive|:"timeout=1, max=100", Server:"Apache", Expires:"Tue, 06 Feb 2018 09:52:20 GMT", |cache-control|:"max-age=300", |date|:"Tue, 06 Feb 2018 09:47:30 GMT", |content-length|:"323366", Connection:"Keep-Alive", |x-content-type-options|:"nosniff", Etag:"\"1f81fd7-4ef26-564871949b4c7\"", |accept-ranges|:"bytes", |last-modified|:"Tue, 06 Feb 2018 08:38:11 GMT"}} — 指定URLにファイル(画像など)が存在するかチェック –> {存在確認結果(boolean), レスポンスヘッダー(NSDictionary), データ(NSData)} on checkURLResourceExistence(aURL, timeOutSec as real) set aRequest to (current application’s NSURLRequest’s requestWithURL:aURL cachePolicy:(current application’s NSURLRequestUseProtocolCachePolicy) timeoutInterval:timeOutSec) set aRes to (current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)) set dRes to (first item of (aRes as list)) set bRes to (second item of (aRes as list)) if bRes is not equal to missing value then set hRes to (bRes’s allHeaderFields()) set aResCode to (bRes’s statusCode()) as integer else set hRes to {} set aResCode to -1 –error end if return {(aResCode = 200), hRes, dRes} end checkURLResourceExistence |
multi page tiffを読み込んで、PDFにする v2
AppleScript名:multi page tiffを読み込んで、PDFにする v2 |
— Created 2015-01-01 by Takaaki Naganoya — Modified 2016-04-18 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" use framework "Quartz" use framework "AppKit" property |NSURL| : a reference to current application’s |NSURL| property NSString : a reference to current application’s NSString property PDFPage : a reference to current application’s PDFPage property NSImage : a reference to current application’s NSImage property PDFDocument : a reference to current application’s PDFDocument property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep set a to choose file of type {"public.tiff"} with prompt "Select Multi-page tiff file" –tiff set aRes to convertMultiPageTiffToPDF(a) of me on convertMultiPageTiffToPDF(anAlias) –Make Output Path set b to POSIX path of anAlias set bb to changeExtensionInPath("pdf", b) –OutPath –Read Multi-Page TIFF set aURL to |NSURL|’s fileURLWithPath:b set aImage to NSImage’s alloc()’s initWithContentsOfURL:aURL set aRawimg to aImage’s TIFFRepresentation() set eachTiffPages to (NSBitmapImageRep’s imageRepsWithData:aRawimg) as list –Make Blank PDF set aPDFdoc to PDFDocument’s alloc()’s init() set pageNum to 0 repeat with curPage in eachTiffPages set thisImage to contents of curPage set aImg to (NSImage’s alloc()’s initWithSize:(thisImage’s |size|())) (aImg’s addRepresentation:thisImage) (aPDFdoc’s insertPage:(PDFPage’s alloc()’s initWithImage:aImg) atIndex:pageNum) set pageNum to pageNum + 1 end repeat return (aPDFdoc’s writeToFile:bb) as boolean end convertMultiPageTiffToPDF –ファイルパス(POSIX path)に対して、拡張子のみ付け替える on changeExtensionInPath(extStr as string, aPath as string) set pathString to NSString’s stringWithString:aPath set theExtension to pathString’s pathExtension() set thePathNoExt to pathString’s stringByDeletingPathExtension() set newPath to thePathNoExt’s stringByAppendingPathExtension:extStr return newPath as string end changeExtensionInPath |
ASOCでPDFを回転させて保存 v2
AppleScript名:ASOCでPDFを回転させて保存 v2 |
— Created 2015-10-20 by Takaaki Naganoya — Modified 2016-07-01 by Takaaki Naganoya–複数回PDFに回転処理を行った場合の挙動を改善 — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" set aPath to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Select PDF") set newFile to POSIX path of (choose file name) set pdfRes to rotatePDFandSaveAt(aPath, newFile, 90) of me –oldPath and newPath have to be a POSIX path, aDegree have to be in {0, 90, 180, 270, 360} on rotatePDFandSaveAt(oldPath as string, newPath as string, aDegree as integer) –Error Check if aDegree is not in {0, 90, 180, 270, 360} then error "Wrong Degree" set aURL to current application’s |NSURL|’s fileURLWithPath:oldPath set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() –count pages –Make Blank PDF set newPDFdoc to current application’s PDFDocument’s alloc()’s init() –Rotate Each Page repeat with i from 0 to (pCount – 1) set aPage to (aPDFdoc’s pageAtIndex:i) –Set Degree set curDegree to aPage’s |rotation|() –Get Current Degree (aPage’s setRotation:(aDegree + curDegree)) –Set New Degree (newPDFdoc’s insertPage:aPage atIndex:i) end repeat set aRes to newPDFdoc’s writeToFile:newPath return aRes as boolean end rotatePDFandSaveAt |
ASOCでPDFの各種情報を取得する
PDFの各種情報を取得するAppleScriptです。
これまで、GUIアプリケーションを呼び出してPDFの情報を取得していましたが、PDFKitの機能を利用してAppleScript単体で(GUIアプリケーションの機能を呼び出すことなく)処理できるようになりました。
PDF関連は、ほぼたいていの処理をAppleScriptだけで行えています。しいて(自分が)できていないのは、ウォーターマークを埋め込むような処理ぐらいでしょうか。それ以外であれば、たいてい行えます。
AppleScript名:ASOCでPDFの各種情報を取得する |
— Created 2015-10-20 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "QuartzCore" set aPath to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Select PDF") set aURL to current application’s |NSURL|’s fileURLWithPath:aPath set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() –ページ数 –> 1 set aMajorVersion to aPDFdoc’s majorVersion() –バージョン(メジャーバージョン) –> 1 set aMinorVersion to aPDFdoc’s minorVersion() –バージョン(マイナーバージョン) –> 3 set aRoot to aPDFdoc’s outlineRoot() –> missing value set anAttr to (aPDFdoc’s documentAttributes()) as record –> (NSDictionary) {Creator:"Pages", Producer:"Mac OS X 10.11.1 Quartz PDFContext", ModDate:(NSDate) 2015-10-20 07:45:55 +0000, Title:"testPDF", CreationDate:(NSDate) 2015-10-20 07:45:55 +0000} set aCreator to anAttr’s Creator() –> "Pages" set aProducer to anAttr’s Producer() –> "Mac OS X 10.11.1 Quartz PDFContext" set aTitle to anAttr’s Title() –> "testPDF" set aCreationDate to anAttr’s CreationDate() –PDF作成年月日 –> date "2015年10月20日火曜日 16:45:55" set aModDate to anAttr’s ModDate() –PDF変更年月日 –> date "2015年10月20日火曜日 16:45:55" set anEncF to aPDFdoc’s isEncrypted() –暗号化されている(パスワードが設定されている)か? –> false set anLockF to aPDFdoc’s isLocked() –ロックされているか? –> false set aCopyF to aPDFdoc’s allowsCopying() –テキストのコピーを許可されているか? –> true set aPrintF to aPDFdoc’s allowsPrinting() –印刷を許可されているか? –> true –PDFのサイズを取得する(単位:Point) set aPage to aPDFdoc’s pageAtIndex:0 set aBounds to aPage’s boundsForBox:(current application’s kPDFDisplayBoxMediaBox) set aSize to |size| of aBounds –> {width:595.28, height:841.89} |
連番JPEGファイルを読み込んで連結したPDFを作成(既存のPDFに追加)
AppleScript名:連番JPEGファイルを読み込んで連結したPDFを作成(既存のPDFに追加) |
— Created 2016-09-20 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" use framework "Quartz" use framework "AppKit" set aExt to ".jpg" set targAlias to retFrontFinderWindowsTargetIfExits(path to desktop) of me set aFol to choose folder with prompt "追記するJPEG画像ファイルが入っているフォルダを選択" default location targAlias set fList to getFilePathList(aFol, aExt) of me set f2List to my sort1DList:fList ascOrder:true –sort by ascending set newFile to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "既存のPDFファイルを選択(このPDF末尾に画像を追加)") set newFilePath to current application’s NSString’s stringWithString:newFile set newFileURL to current application’s |NSURL|’s fileURLWithPath:newFile –Get Exsisting PDF’s URL and Use it set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:newFileURL set pageNum to ((aPDFdoc’s pageCount()) as integer) repeat with i in f2List set j to contents of i set aURL to (current application’s |NSURL|’s fileURLWithPath:j) set bImg to (current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL) (aPDFdoc’s insertPage:(current application’s PDFPage’s alloc()’s initWithImage:bImg) atIndex:pageNum) set pageNum to pageNum + 1 end repeat aPDFdoc’s writeToFile:newFilePath –ASOCで指定フォルダのファイルパス一覧取得(拡張子指定つき) on getFilePathList(aFol, aExt) set aPath to current application’s NSString’s stringWithString:(POSIX path of aFol) set aFM to current application’s NSFileManager’s defaultManager() set nameList to (aFM’s contentsOfDirectoryAtPath:aPath |error|:(missing value)) as list set anArray to current application’s NSMutableArray’s alloc()’s init() repeat with i in nameList set j to i as text if (j ends with aExt) and (j does not start with ".") then –exclude invisible files set newPath to (aPath’s stringByAppendingString:j) (anArray’s addObject:newPath) end if end repeat return anArray as list end getFilePathList –1D List(文字)をsort / ascOrderがtrueだと昇順ソート、falseだと降順ソート on sort1DList:theList ascOrder:aBool set aDdesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:aBool selector:"localizedCaseInsensitiveCompare:" set theArray to current application’s NSArray’s arrayWithArray:theList return (theArray’s sortedArrayUsingDescriptors:{aDdesc}) as list end sort1DList:ascOrder: on retFrontFinderWindowsTargetIfExits(aDefaultLocation) tell application "Finder" set wCount to count every window if wCount ≥ 1 then tell front window set aTarg to target as alias end tell return aTarg else return aDefaultLocation end if end tell end retFrontFinderWindowsTargetIfExits |
連番JPEGファイルを読み込んで連結したPDFを作成(新規作成)
AppleScript名:連番JPEGファイルを読み込んで連結したPDFを作成(新規作成) |
— Created 2016-09-20 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "QuartzCore" use framework "Quartz" use framework "AppKit" set aExt to ".jpg" set aFol to choose folder set fList to getFilePathList(aFol, aExt) of me set f2List to my sort1DList:fList ascOrder:true –sort by ascending set newFile to POSIX path of (choose file name with prompt "新規PDFファイルの名称を選択") set newFilePath to current application’s NSString’s stringWithString:newFile –Make Blank PDF set aPDFdoc to current application’s PDFDocument’s alloc()’s init() set pageNum to 0 repeat with i in f2List set j to contents of i set aURL to (current application’s |NSURL|’s fileURLWithPath:j) set bImg to (current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL) (aPDFdoc’s insertPage:(current application’s PDFPage’s alloc()’s initWithImage:bImg) atIndex:pageNum) set pageNum to pageNum + 1 end repeat aPDFdoc’s writeToFile:newFilePath –ASOCで指定フォルダのファイルパス一覧取得(拡張子指定つき) on getFilePathList(aFol, aExt) set aPath to current application’s NSString’s stringWithString:(POSIX path of aFol) set aFM to current application’s NSFileManager’s defaultManager() set nameList to (aFM’s contentsOfDirectoryAtPath:aPath |error|:(missing value)) as list set anArray to current application’s NSMutableArray’s alloc()’s init() repeat with i in nameList set j to i as text if (j ends with aExt) and (j does not start with ".") then –exclude invisible files set newPath to (aPath’s stringByAppendingString:j) (anArray’s addObject:newPath) end if end repeat return anArray as list end getFilePathList –1D List(文字)をsort / ascOrderがtrueだと昇順ソート、falseだと降順ソート on sort1DList:theList ascOrder:aBool set aDdesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:aBool selector:"localizedCaseInsensitiveCompare:" set theArray to current application’s NSArray’s arrayWithArray:theList return (theArray’s sortedArrayUsingDescriptors:{aDdesc}) as list end sort1DList:ascOrder: |
PDFから本文テキストを抽出して配列にストアして文字列検索
AppleScript名:PDFから本文テキストを抽出して配列にストアして文字列検索 |
— Created 2017-06-18 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" property textCache : missing value property aList : {} –検索対象の語群 set sList to {"notification", "Cocoa"} –considering case set thePath to POSIX path of (choose file of type {"com.adobe.pdf"}) –PDFのテキスト内容をあらかじめページごとに読み取って、検索用のテキストキャッシュを作成 set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath) set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL set theCount to theDoc’s pageCount() as integer set textCache to current application’s NSMutableArray’s new() repeat with i from 0 to (theCount – 1) set aPage to (theDoc’s pageAtIndex:i) set tmpStr to (aPage’s |string|()) (textCache’s addObject:{pageIndex:i + 1, pageString:tmpStr}) end repeat –主にテキストキャッシュを対象にキーワード検索 repeat with s in sList –❶部分一致で抽出 set bRes to ((my filterRecListByLabel1(textCache, "pageString contains ’" & s & "’"))’s pageIndex) as list –❷、❶のページ単位のテキスト検索で見つからなかった場合(ページ間でまたがっている場合など) if bRes = {} then set bRes to {} set theSels to (theDoc’s findString:s withOptions:0) repeat with aSel in theSels set thePage to (aSel’s pages()’s objectAtIndex:0)’s label() set curPage to (thePage as integer) if curPage is not in bRes then set the end of bRes to curPage end if end repeat end if set the end of aList to bRes end repeat return aList –リストに入れたレコードを、指定の属性ラベルの値で抽出 on filterRecListByLabel1(aRecList as list, aPredicate as string) set aArray to current application’s NSArray’s arrayWithArray:aRecList set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate return filteredArray end filterRecListByLabel1 |
PDFの本文テキスト内容からリンクURLを抽出する
AppleScript名:本文テキスト内容からリンクURLを抽出する |
— Created 2017-08-12 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "Quartz" use BPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus property NSString : a reference to current application’s NSString property NSCharacterSet : a reference to current application’s NSCharacterSet property NSRegularExpression : a reference to current application’s NSRegularExpression property NSRegularExpressionAnchorsMatchLines : a reference to current application’s NSRegularExpressionAnchorsMatchLines property NSRegularExpressionDotMatchesLineSeparators : a reference to current application’s NSRegularExpressionDotMatchesLineSeparators script spdPDF property foundURLs : {} property aList : {} property outList : {} end script load framework set (foundURLs of spdPDF) to {} set theFile to POSIX path of (choose file of type "com.adobe.pdf") set (aList of spdPDF) to textInPDFinEachPage(theFile) of me set pCounter to 1 repeat with i in (aList of spdPDF) set aURL1 to extractLinksFromNaturalText(i as string) of me set aURL2 to (current application’s SMSForder’s arrayByDeletingBlanksIn:((aURL1) as list)) set tmpOut to {} repeat with ii in aURL2 set aURL to (ii’s absoluteString()) as string if aURL begins with "http://piyocast.com/as/" then set the end of tmpOut to aURL end if end repeat if tmpOut is not equal to {} then set (outList of spdPDF) to (outList of spdPDF) & tmpOut end if end repeat set outStr to retArrowText(outList of spdPDF, return) of me on textInPDFinEachPage(thePath) script textStorage property aList : {} end script set (aList of textStorage) to {} set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath) set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL set theCount to theDoc’s pageCount() as integer repeat with i from 1 to theCount set thePage to (theDoc’s pageAtIndex:(i – 1)) set curStr to (thePage’s |string|()) set curStr2 to curStr’s decomposedStringWithCanonicalMapping() –Normalize Text with NFC set targString to string id 13 & string id 10 & string id 32 & string id 65532 –Object Replacement Character set bStr to (curStr2’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s characterSetWithCharactersInString:targString)) set the end of (aList of textStorage) to (bStr as string) end repeat return contents of (aList of textStorage) end textInPDFinEachPage on extractLinksFromNaturalText(aString) set anNSString to current application’s NSString’s stringWithString:aString set {theDetector, theError} to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeLink) |error|:(reference) set theMatches to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()} set theResults to theMatches’s valueForKey:"URL" return theResults as list end extractLinksFromNaturalText –リストを指定デリミタをはさんでテキスト化 on retStrFromArrayWithDelimiter(aList, aDelim) set anArray to current application’s NSArray’s arrayWithArray:aList set aRes to anArray’s componentsJoinedByString:aDelim return aRes as text end retStrFromArrayWithDelimiter on retArrowText(aList, aDelim) –自分のASでよく使うハンドラ名称なので、同じものを用意 return my retStrFromArrayWithDelimiter(aList, aDelim) end retArrowText |
ASOCでPDFをページごとに分解する v3
AppleScript名:ASOCでPDFをページごとに分解する v3 |
— Created 2014-12-26 by Takaaki Naganoya — Modified 2015-09-26 by Takaaki Naganoya — Modified 2015-10-01 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" –use framework "Quartz" use framework "QuartzCore" 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() –PDFをページごとに分割してファイル書き出し repeat with i from 0 to (pCount – 1) set thisPage to (aPDFdoc’s pageAtIndex:(i)) set thisDoc to (current application’s PDFDocument’s alloc()’s initWithData:(thisPage’s dataRepresentation())) set outPath to addString_beforeExtensionIn_("_" & (i + 1) as string, aPOSIXpath) (thisDoc’s writeToFile:outPath) –書き出し end repeat –ファイルパス(POSIX path)に対して、文字列(枝番)を追加。拡張子はそのまま on addString:extraString beforeExtensionIn:aPath 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:theExtension return newPath as string end addString:beforeExtensionIn: |
ASOCでPDFをページごとに分解してJPEGで保存する v3
AppleScript名:ASOCで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 # http://piyocast.com/as/archives/4176 use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" use framework "QuartzCore" 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 |
ASOCで指定PDFのページ数をかぞえる v2
AppleScript名:ASOCで指定PDFのページ数をかぞえる v2 |
use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" use framework "QuartzCore" set aFile to choose file of type {"com.adobe.pdf"} set pCount to my pdfPageCount:aFile –指定PDFのページ数をかぞえる(10.9対応。普通にPDFpageから取得) –返り値:PDFファイルのページ数(整数値) on pdfPageCount:aFile set aFile to POSIX path of aFile set theURL to current application’s |NSURL|’s fileURLWithPath:aFile set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:theURL set aRes to aPDFdoc’s pageCount() return aRes as integer end pdfPageCount: |
迷路をRTFで作成して脱出経路を赤く着色する v3
AppleScript名:迷路をRTFで作成して脱出経路を赤く着色する v3 |
— Created 2017-09-19 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" use framework "MazeFinder" –https://github.com/tcjennings/MazeFinder property NSFont : a reference to current application’s NSFont property NSUUID : a reference to current application’s NSUUID property NSColor : a reference to current application’s NSColor property NSString : a reference to current application’s NSString property Board2D : a reference to current application’s Board2D property Pathfinder : a reference to current application’s Pathfinder property NSDictionary : a reference to current application’s NSDictionary property NSLiteralSearch : a reference to current application’s NSLiteralSearch property NSMutableArray : a reference to current application’s NSMutableArray property NSFontAttributeName : a reference to current application’s NSFontAttributeName property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName property NSDocumentTypeDocumentAttribute : a reference to current application’s NSDocumentTypeDocumentAttribute –NSNotFoundはプロパティに代入しても認識されなかった set targFontName to "Courier-Bold" –PostScript Name set targFontSize to 13 –Point –迷路テキストデータ作成→Attributed Stringに set aStr to create2DMazeAndSolveIt(30, 30, 1, 1, 28, 28) of me –Plain Text set anAttr to changeAttrStrsFontAttribute(aStr, targFontName, targFontSize) of me –Attributed String –迷路データに着色(参照呼び出し, Call by reference) markCharOfAttributedString(anAttr, aStr, "!", (NSColor’s redColor())) of me –結果のRTFをデスクトップ上に書き出す。ファイル名はUUID.rtf set targFol to current application’s NSHomeDirectory()’s stringByAppendingPathComponent:"Desktop" set aRes to my saveStyledTextAsRTF(targFol, anAttr) –指定のAttributed String内で指定文字列が含まれる箇所に指定の色をつける(結果はメイン側に参照渡し) on markCharOfAttributedString(anAttr, origStr, aTargStr, aColor) set rList to searchWordWithRange(origStr, aTargStr) of me repeat with ii in rList (anAttr’s addAttribute:(NSForegroundColorAttributeName) value:aColor range:ii) end repeat end markCharOfAttributedString –指定の文字列をAttributed Stringに変換して任意のフォントを一括指定 on changeAttrStrsFontAttribute(aStr, aFontPSName, aFontSize) set tmpAttr to NSMutableAttributedString’s alloc()’s initWithString:aStr set aRange to current application’s NSMakeRange(0, tmpAttr’s |length|()) set aVal1 to NSFont’s fontWithName:aFontPSName |size|:aFontSize tmpAttr’s beginEditing() tmpAttr’s addAttribute:(NSFontAttributeName) value:aVal1 range:aRange tmpAttr’s endEditing() return tmpAttr end changeAttrStrsFontAttribute –指定テキストデータ(atargText)内に、指定文字列(aSearchStr)が含まれる範囲情報(NSRange)をすべて取得する on searchWordWithRange(aTargText, aSearchStr) set aStr to NSString’s stringWithString:aTargText set bStr to NSString’s stringWithString:aSearchStr set hitArray to NSMutableArray’s alloc()’s init() set cNum to (aStr’s |length|()) as integer set aRange to current application’s NSMakeRange(0, cNum) repeat set detectedRange to aStr’s rangeOfString:bStr options:NSLiteralSearch range:aRange set aLoc to (detectedRange’s location) –CAUTION !!!! Sometimes aLoc returns not NSNotFound (-1) but a Very large number if (aLoc > 9.999999999E+9) or (aLoc = (current application’s NSNotFound)) then exit repeat hitArray’s addObject:detectedRange set aNum to aLoc as integer set bNum to (detectedRange’s |length|) as integer set aRange to current application’s NSMakeRange(aNum + bNum, cNum – (aNum + bNum)) end repeat return hitArray end searchWordWithRange –スタイル付きテキストを指定フォルダ(POSIX path)にRTFで書き出し on saveStyledTextAsRTF(targFol, aStyledString) set bstyledLength to aStyledString’s |string|()’s |length|() set bDict to NSDictionary’s dictionaryWithObject:"NSRTFTextDocumentType" forKey:(NSDocumentTypeDocumentAttribute) set bRTF to aStyledString’s RTFFromRange:(current application’s NSMakeRange(0, bstyledLength)) documentAttributes:bDict set theName to (NSUUID’s UUID()’s UUIDString()) set thePath to NSString’s stringWithString:targFol set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:"rtf" return (bRTF’s writeToFile:thePath atomically:true) as boolean end saveStyledTextAsRTF –2D迷路を作成して脱出経路を検索して文字列で迷路データを出力する –迷路サイズ x,y スタート座標 x, y ゴール座標 x,y on create2DMazeAndSolveIt(xMax, yMax, xStart, yStart, xGoal, yGoal) set myBoard to Board2D’s alloc()’s init() myBoard’s setupBoardWithRows:xMax WithColumns:yMax –60×60ぐらいが上限。正方形でないとダメ myBoard’s createMazeFromBoard() set myPathfinder to Pathfinder’s alloc()’s init() set myPath to myPathfinder’s findPathThroughMaze:myBoard fromX:xStart fromY:yStart toX:xGoal toY:yGoal set aCount to myPath’s |count|() if aCount > 0 then set aRes to myBoard’s drawPathThroughMaze:myPath return aRes as string else return false end if end create2DMazeAndSolveIt |