Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: File path

XcodeのWorkspace Documentをクローズ後、再オープン

Posted on 2月 21 by Takaaki Naganoya

XcodeでオープンしているWorkspace Document(.xcodeproj)のパスを取得してクローズし、再度オープンするAppleScriptです。macOS 15.3上のXcode 16.2で動作をテストしました。

Xcodeでオープン中の.applescriptファイルの構文確認を行うために、いろいろ試行錯誤してみたものの、Xcodeでオープン中にはファイルへの書き込み権限を取得できない雰囲気が濃厚。Xcodeのエディタで表示中のコンテンツ(.applescript)の本文に文字列を突っ込んでみても、Xcodeに蹴られます。

# AppleScriptからの制御が封じられているので、まっとうな手口が使えません

これに対策するために、Xcode Projectをいったんクローズして、構文確認を行うとよさそうだったので、試作品を作ってみたものです。

AppleScript名:XcodeのWorkspace Documentをクローズ後、再オープン.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2025/02/21
—
–  Copyright © 2025 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "Xcode"
  set xcVer to version
  
  
tell workspace document 1
    set xWSprojPath to path
    
close
  end tell
end tell

–delay 1

tell application "Xcode"
  open ((POSIX file xWSprojPath) as alias)
end tell

★Click Here to Open This Script 

Posted in file File path Object control | Tagged 13.0savvy 14.0savvy 15.0savvy Xcode | Leave a comment

Xcodeでオープン中のAppleScriptのフルパスを返す

Posted on 2月 14 by Takaaki Naganoya

Xcodeでオープン中のXcode Projectで表示中のファイルのフルパスを返すAppleScriptです。Xcodeで表示中のAppleScript書類(テキストベースの.applescript)をコンパイルして、省略表記した部分をすべて展開して元ファイルに書き戻すAppleScriptを書こうとして作ったものです。

Xcode.appのAppleScript用語辞書は、実用性がないというべきなのか、編集中のファイルに対する補助機能を作ろうとしても編集中のファイルのファイル名が取得できないとか、selectionの取得もできないとか、いまひとつ「使えない」という印象です(仕事をしているフリでもしてるんだろうか?>担当者)。

XcodeのAppleScript用語辞書には、日常的な作業を便利にするために必要とされる基礎的な機能が何もないので、「これでどうしろと?」と、途方に暮れてしまう出来です。

ただ、強引にファイル名の情報を取得しつつ(Windowのnameから取得)、Xcode Projectのルートフォルダからファイル検索することで、どうにかファイルのフルパスを取得してみました。取得したファイル名のファイルがProject内に複数存在する可能性もあるため、そのような場合にはどのファイルかを選択するように書いてみました(実にナンセンスな処理です)。

本Scriptでは、AppleScriptのプロジェクトに対して利用することを前提にしているため「.applescript」ファイルを取得する仕様になっていますが、別に「.m」でも「.swift」でも抽出できるように変更するのは容易です。

AppleScript名:Xcodeでオープン中のAppleScriptのフルパスを返す.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2025/02/14
—
–  Copyright © 2025 Piyomaru Software, All Rights Reserved
—

use AppleScript
use scripting additions
use framework "Foundation"

set targString to " " & string id 8212 & " " –コピペやURL Events経由で受け渡すと壊れる

tell application "Xcode"
  set xcVer to version
  
  
—オープン中のファイル名(余計な文字列つき)を取得
  
tell window 1
    set aStr to name
  end tell
  
  
–Xcode Project書類のパスを取得
  
tell document 1
    set aPrjPath to path of it
  end tell
end tell

set a1Str to parseFileNameFromXCodeWindowName(aStr, targString) of me
if a1Str does not end with ".applescript" then return

set pathString to current application’s NSString’s stringWithString:(aPrjPath)
set parentFol to (pathString’s stringByDeletingLastPathComponent()) as string

set aList to retFullPathUnderAFolderWithRecursiveFilterByFileName(parentFol, a1Str) of me
if length of aList > 1 then
  set aRes to first item of (choose from list aList)
else
  set aRes to first item of aList
end if

return aRes
–> "/Users/me/Documents/testXC162/testXC162/AppDelegate.applescript"

on parseFileNameFromXCodeWindowName(aStr, aDelim)
  set aCount to retFrequency(aStr, aDelim) of me
  
set aRes to parseByDelim(aStr, aDelim) of me
  
return item 2 of aRes
end parseFileNameFromXCodeWindowName

–指定文字列内の指定キーワードの出現回数を取得する
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

on retFullPathUnderAFolderWithRecursiveFilterByFileName(aFol, aFileName)
  set anArray to current application’s NSMutableArray’s array()
  
set aPath to current application’s NSString’s stringWithString:aFol
  
set dirEnum to current application’s 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 current application’s NSPredicate’s predicateWithFormat_("lastPathComponent == %@", aFileName)
  
set bArray to anArray’s filteredArrayUsingPredicate:thePred
  
  
return bArray as list
end retFullPathUnderAFolderWithRecursiveFilterByFileName

★Click Here to Open This Script 

Posted in file File path Text | Tagged 13.0savvy 14.0savvy 15.0savvy Xcode | Leave a comment

choose fileで指定したsdefを読み込み、sdef中のサンプル(用例)を個別にHTML書き出しする

Posted on 12月 30, 2024 by Takaaki Naganoya

スクリプトエディタから書き出したsdefファイルを選択すると、指定の書き出し先フォルダにsdef内のAppleScriptサンプルをHTML形式で書き出すAppleScriptです(最初のバージョンでHTMLの実体参照デコード処理をハードコーディングしていたのを、Cocoaの機能を利用するよう書き換えました)。

スクリプトエディタでAppleScript用語辞書を表示させた状態で、ファイル書き出しすると個別のsdefファイルとして保存できます。この状態のsdefにアプリのバージョン番号を付加して、バージョン履歴として保存しています。

こうして保存しておいたsdef内のサンプルAppleScriptをHTMLとして書き出します。Pixelmator Proに58本のサンプルScriptが入っていたので、けっこうな分量になります。それを手作業で取り出すのは手間なので、Scriptで取り出すことにしました。

それを収集するために作ったのが本Scriptです。

本来、スクリプトエディタで表示(xinclude解消+レンダリング)させたsdefを処理させるAppleScriptで、いちいちxincludeの展開を行わせるのは無意味なのですが、本Scriptはもともと「アプリのBundle IDを指定してsdefのパスを求めて処理する」ようになっていたため、仕様がとがりすぎて汎用性がいまひとつだったので、「スクリプトエディタで書き出したsdefを処理」するように書き換えたという経緯があるためです。説明したら余計にわからなくなったような、、、、

AppleScript名:choose fileで指定したsdefを読み込み、sdef中のサンプル(用例)を個別にHTML書き出しする v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/31
—
–  Copyright © 2022-2024 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use framework "AppKit"
use scripting additions

set sdefAlias to (choose file of type {"com.apple.scripting-definition"} with prompt "書き出したSDEFを選択")
set sdefFullPath to (POSIX path of sdefAlias)

–SDEF読み込み(Xincludeの展開が必要な状態)
tell current application
  set theXML to read sdefAlias as «class utf8»
end tell

–NSXMLDocumentの生成、Xincludeを有効に
set {theXMLDoc, theError} to current application’s NSXMLDocument’s alloc()’s initWithXMLString:theXML options:(current application’s NSXMLDocumentXInclude) |error|:(reference)

set aDocStr to (theXMLDoc’s XMLData)
set aDocStr2 to (current application’s NSString’s alloc()’s initWithData:(aDocStr) encoding:(current application’s NSUTF8StringEncoding)) as string

set sampleList to (extractStrFromTo(aDocStr2, "<html>", "</html>") of me)
set sampleCount to length of sampleList
if sampleCount = 0 then return

set outFol to POSIX path of (choose folder with prompt "Select Output Folder")

set aCount to 1

repeat with i in sampleList
  set j to (contents of i)
  
  
if j is not equal to "" then
    set j1 to decodeCharacterReference(j) of me
    
set j2 to "<!DOCTYPE html><html><meta charset=utf-8><title>" & (aCount as string) & "</title><body>" & j1 & "</body></html>"
    
    
set wPath to outFol & (aCount as string) & ".html"
    
set fRes to writeToFileAsUTF8(j2, wPath) of me
    
if fRes = false then error
    
    
set aCount to aCount + 1
  end if
end repeat

–指定パスからアプリケーションのScriptabilityをbooleanで返す
on retAppSdefNameFromBundleIPath(appPath as string)
  set aDict to (current application’s NSBundle’s bundleWithPath:appPath)’s infoDictionary()
  
set aRes to aDict’s valueForKey:"OSAScriptingDefinition"
  
if aRes = missing value then return false
  
set asRes to aRes as string
  
  
return asRes as string
end retAppSdefNameFromBundleIPath

–指定文字と終了文字に囲まれた内容を抽出
on extractStrFromTo(aParamStr, fromStr, toStr)
  set theScanner to current application’s NSScanner’s scannerWithString:aParamStr
  
set anArray to current application’s NSMutableArray’s array()
  
  
repeat until (theScanner’s isAtEnd as boolean)
    set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
theScanner’s scanString:fromStr intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to "" –>追加
    
theScanner’s scanString:toStr intoString:(missing value)
    
anArray’s addObject:theValue
  end repeat
  
  
return (anArray as list)
end extractStrFromTo

on writeToFileAsUTF8(aStr, aPath)
  set cStr to current application’s NSString’s stringWithString:aStr
  
set thePath to POSIX path of aPath
  
set aRes to cStr’s writeToFile:thePath atomically:false encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
  
return aRes as boolean
end writeToFileAsUTF8

–文字置換
on repChar(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

–実体参照をデコード
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

★Click Here to Open This Script 

Posted in file File path sdef XML | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

指定Bundle IDのアプリの各言語のローカライズ名称を取得して出力

Posted on 10月 17, 2024 by Takaaki Naganoya

指定アプリの各ローカライズ言語における名称(CFBundleName)を取得するAppleScriptです。

まだテスト実装レベルのため、無駄な処理が入っています。

もともと本Scriptは、電子書籍に掲載する表を作成するために書いたものです。


▲電子書籍「AppleScriptによるWebブラウザ自動操縦ガイド」より

こうした資料を掲載する際に、手で調査するのは大変なので、AppleScriptを書いて資料を作成しています。ただ、macOS 13以降で(正確にいえばXcode 15以降で)はローカライズの方法が変更されたため、新たに作られた.loctableデータにアクセスしています。

従来のローカライズ方式と、新方式が混在している状況なので、旧方式でアクセスして値が得られなかった場合には、このScriptを使うとよいのでしょう。

AppleScript名:指定Bundle IDのアプリの各言語のローカライズ名称を取得して出力.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/10/16
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use scripting additions
use framework "Foundation"

property NSArray : a reference to current application’s NSArray
property NSPredicate : a reference to current application’s NSPredicate

set targAppBundleID to "com.apple.ScriptEditor2"
set targKey to "CFBundleName"
set aLocale to (current application’s NSLocale’s currentLocale())

set locResList to getAppInfoPlistValueInEveryLocalizedLangs(targAppBundleID, targKey, aLocale) of me
–> {{"ヘブライ語", "עורך התסריטים"}, {"韓国語", "스크립트 편집기"}, {"インドネシア語", "Editor Skrip"}, {"オランダ語", "Scripteditor"}, {"トルコ語", "Betik Düzenleyici"}, {"フィンランド語", "Skriptieditori"}, {"ハンガリー語", "Szkriptszerkesztő"}, {"ロシア語", "Редактор скриптов"}, {"イタリア語", "Script Editor"}, {"スペイン語(ラテンアメリカ)", "Editor de Scripts"}, {"ギリシャ語", "Επεξεργασία σκριπτ"}, {"カタロニア語", "Editor de Scripts"}, {"フランス語(カナダ)", "Éditeur de script"}, {"中国語(台湾)", "工序指令編寫程式"}, {"中国語(香港)", "程式碼編寫程式"}, {"ポーランド語", "Edytor skryptów"}, {"スウェーデン語", "Skriptredigerare"}, {"ノルウェー語", "Prosedyreredigering"}, {"アラビア語", "محرر البرامج النصية"}, {"英語", "Script Editor"}, {"デンマーク語", "Instruksværktøj"}, {"ヒンディー語", "स्क्रिप्ट संपादक"}, {"タイ語", "ตัวแก้ไขสคริปต์"}, {"中国語(中国本土)", "脚本编辑器"}, {"英語(イギリス)", "Script Editor"}, {"マレー語", "Editor Skrip"}, {"チェコ語", "Editor skriptů"}, {"スロバキア語", "Script Editor"}, {"英語(オーストラリア)", "Script Editor"}, {"スロベニア語", "Skriptni urejevalnik"}, {"ドイツ語", "Skripteditor"}, {"ベトナム語", "Trình soạn thảo tập lệnh"}, {"ポルトガル語(ブラジル)", "Editor de Scripts"}, {"スペイン語", "Editor de Scripts"}, {"ウクライナ語", "Редактор скриптів"}, {"ルーマニア語", "Editor scripturi"}, {"フランス語", "Éditeur de script"}, {"クロアチア語", "Urednik skripte"}, {"ポルトガル語(ポルトガル)", "Editor de Scripts"}, {"日本語", "スクリプトエディタ"}}

on getAppInfoPlistValueInEveryLocalizedLangs(targAppBundleID, targKey, aLocale)
  script spd
    property urlList : {}
  end script
  
  
–macOS 13以降がターゲット
  
set v1 to system attribute "sys1" –> 10, 11, 12, 13, 14, 15….
  
if v1 < 13 then error "This Script require macOS 13 or later"
  
  
–指定アプリのバンドル内のResourceから「InfoPlist.loctable」で終わるファイル名のパスを抽出
  
tell application "Finder"
    set defPath to application file id targAppBundleID
  end tell
  
  
set defPath to (POSIX path of (defPath as alias)) & "Contents/Resources" –Cocoa流のPOSIX path
  
set fList to getFilesIn(defPath) of me
  
  
set anArray to NSArray’s arrayWithArray:fList
  
set aPred to NSPredicate’s predicateWithFormat:"SELF ENDSWITH ’InfoPlist.loctable’"
  
set locRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
  
set resList to {}
  
  
  
–.loctableファイルでループ(1つだけだが)
  
repeat with i in locRes
    set j to contents of i
    
set (urlList of spd) to (my readPlistAt:(j))
    
set langKeys to ((urlList of spd)’s allKeys()) as list
    
    
–Language Codeでループ
    
repeat with ii in langKeys
      set jj to contents of ii
      
set aLangDat to ((urlList of spd)’s valueForKey:jj)
      
      
—plist(=loctable)のlabelでループ
      
set allLangKeys to (aLangDat’s allKeys()) as list
      
repeat with iii in allLangKeys
        set jjj to contents of iii
        
set aVal to (aLangDat’s valueForKey:(jjj))
        
        
if jjj = targKey then
          set locLangName to getLangNameWithLocale(jj, aLocale) of me
          
set the end of resList to {locLangName, aVal as string}
          
exit repeat
        end if
      end repeat
    end repeat
  end repeat
  
  
return resList
end getAppInfoPlistValueInEveryLocalizedLangs

–Read Plist
on readPlistAt:thePath
  set thePath to current application’s NSString’s stringWithString:thePath
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theDict to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
  
return theDict
end readPlistAt:

–指定フォルダ内のファイルのフルパス一覧を返す
on getFilesIn(posixPath)
  script spd
    property allItems : {}
  end script
  
  
set allItems of spd to {}
  
  
— make URL
  
set theNSURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
  
— make file manager
  
set theNSFileManager to current application’s NSFileManager’s new()
  
  
— get URL enumerator
  
set theNSFileEnumerator to theNSFileManager’s enumeratorAtURL:theNSURL includingPropertiesForKeys:{current application’s NSURLIsDirectoryKey, current application’s NSURLIsPackageKey} options:((current application’s NSDirectoryEnumerationSkipsPackageDescendants) + (current application’s NSDirectoryEnumerationSkipsHiddenFiles as integer)) errorHandler:(missing value)
  
  
— get all items from enumerator
  
set (allItems of spd) to theNSFileEnumerator’s allObjects()
  
set theFolders to {} — to store folders
  
  
— loop through
  
repeat with i from 1 to count of (allItems of spd)
    — is it a directory?
    
set {theResult, isDirectory} to ((item i of (allItems of spd))’s getResourceValue:(reference) forKey:(current application’s NSURLIsDirectoryKey) |error|:(missing value))
    
if isDirectory as boolean = false then
      set {theResult, isPackage} to ((item i of (allItems of spd))’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value))
      
      
— is it not a package?
      
if not isPackage as boolean then
        set end of theFolders to (item i of (allItems of spd))’s |path|() as string –«class furl»
      end if
    end if
  end repeat
  
  
return theFolders
end getFilesIn

on getLangNameWithLocale(langCode, aLocale)
  set aLangName to (aLocale’s displayNameForKey:(current application’s NSLocaleIdentifier) value:langCode) as string
  
return aLangName
end getLangNameWithLocale

★Click Here to Open This Script 

Posted in File path Localize System | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

マウントしたディスクイメージから元のdmgファイルのパスを取得

Posted on 10月 16, 2024 by Takaaki Naganoya

マウント中のディスクイメージ(.dmg)ファイルのパスを求めるAppleScriptです。

macOS 13.7.1上で作成し、15.1上でも動作確認していますが、それほど込み入った機能は使っていないので、OSバージョン依存はないことでしょう。

実際に、オープンソースのPDFビューワー「Skim」の各バージョンのdmgファイルをダウンロードして、sdef(AppleScript用語説明)ファイルを収集してバージョンごとの変化を追う作業を行なったときに、バージョン判定を行うために元のdmgファイルのパスを求める処理を行なったものです。


▲マウントしたディスクイメージ(Skim)


▲マウント元のディスクイメージファイル


▲マウントしたディスクイメージからパス情報を取得することで、一部ファイルを取り出してコピーする際にバージョン情報を反映させた

AppleScript名:マウントしたディスクイメージから元のdmgファイルのパスを取得.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/10/16
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use scripting additions

set dName to "Skim"

–Disk Imageのマウントを確認
tell application "Finder"
  set dexRes to (get exists of disk dName)
end tell
if dexRes = false then error "指定のディスクイメージ「" & dName & "」はマウントされていません。" –マウントされていなかった

set aRes to getMountedDiskImageInfo("image-path : ") of me
–> "/Users/me/Downloads/Skim-1.4.6.dmg"

on getMountedDiskImageInfo(targMark)
  try
    set aRes to do shell script "hdiutil info"
  on error
    return false
  end try
  
  
set aResList to paragraphs of aRes
  
repeat with i in aResList
    set j to contents of i
    
if j begins with targMark then
      set aOff to offset of targMark in j
      
set aLen to length of targMark
      
set aRes to text (aLen + 1) thru -1 of j
      
return aRes
    end if
  end repeat
  
return false
end getMountedDiskImageInfo

★Click Here to Open This Script 

Posted in drive File path shell script | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

Cocoa Scripting Course #8, File path Processingを刊行

Posted on 4月 26, 2024 by Takaaki Naganoya

電子書籍「Cocoa Scripting Course」の第8巻、File path Processingを刊行しました。PDF 446ページです。

→ 販売ページ

本書は、Cocoa Scripting本の第8弾。ファイルパスの処理を基礎から応用まで幅広く扱っています。Cocoaの機能を使って圧倒的に高度なファイル処理を行いたいScripterには必携の1冊です。8巻と9巻は続巻になっており、並行して同時に企画しています(ファイル処理は9巻で扱います)。

「Cocoa経由で高速にファイル操作を行いたい」と思っても、意外なほど参考文献が少ないことに気づきます。単独で成立しているものは皆無でしょう。

以前は、AppleScriptでファイルパスの処理を行う際に、いろいろ困らされる話がありました。さまざまな注意すべきポイントはありつつも、Cocoaの機能を用いてファイルパスの処理を行えることは、FinderやSystem Eventsだけでファイル処理を行なっていた時代を思えば、隔世の感があります。

なんといっても、UTI系の演算が行えて、指定のUTIに所属するファイルだけを抽出するといった(拡張子だとJPEGとJPGの両方を指定)、スマートな処理ができるのは素晴らしいことです。高度な処理をお手軽に。圧倒的に高速に。

目次

1章 入門編

2章 実践編

3章 ファイルパス操作編

 ファイルパスの基礎知識
 ファイルパス操作の基礎
 ファイルパス計算
 ファイル名の操作
 ファイル名の抽出
 ファイル/フォルダのローカライズ名を取得
 指定パスの種別チェック
 特定のフォルダへのパスを求める
 ファイルパスの高度な処理

4章 ファイル情報操作編

 ファイルそのものの情報+メタ情報について
 ファイル情報の取得
 Spotlightメタデータ情報の取得
 xattr拡張ファイル情報の操作
 EXIF情報の取得
 MIME情報の取得
 Finderで選択中のファイルの取得/設定

5章 UTIによるファイルアクセス編

 拡張子/UTI/MIMEの位置付けについての基礎知識
 UTIについての基礎知識
 UTI同士の計算
 UTI利用サンプル
 Dynamic UTIについて
 UTIについての資料

6章 ドライブ情報編

 ドライブ情報を取得
 ドライブのマウント/アンマウント

添付サンプルScript紹介

資料編
 Cocoa Scripting関連のAppleScript命令
 Cocoa ScriptingとScript Object
 AppleScript Droplet
 サードパーティ製FrameworkやAppleScript Librariesを呼ぶ
 AppleScript mini reference
 AppleScript 各種ランタイム環境および関連ツール
 AppleScript予約語一覧
 エラーコード表

理解度確認テスト
あとがき、奥付

Posted in Books File path news | Tagged 12.0savvy 13.0savvy 14.0savvy | Leave a comment

display drop dialogライブラリをv1.5にアップデート

Posted on 11月 4, 2023 by Takaaki Naganoya

電子書籍「AppleScript最新リファレンスv2.8対応」の添付Scriptの中にこのAppleScriptライブラリを呼び出しているものがあったので、macOS 11以降のUIに応じて各種サイズを変更した「display drop dialog」のバージョン1.5をリリースしました。

複数のUTIを指定して、複数タイプの書類のドラッグ&ドロップを受け付けるようにしました。.scptと.scptdのドラッグ&ドロップを受け付けるとか。

また、本ライブラリではダイアログ上でのファイルの並び順もドラッグ&ドロップで変更できるため、複数のPDFをドラッグ&ドロップで指定して、処理順をダイアログ上で変更するといった用途に用いることを想定しています。

AppleScriptをmacOS標準搭載のスクリプトメニューから呼び出したような場合に、処理対象のファイルをドラッグ&ドロップで指定する場合のファイル受け付けのインタフェースとして用意したものです。

–> Download displayDropDialog15(Install to ~/Libraries/Script Libraries/ folder)

AppleScript名:accept AppleScript documents.scpt
use dropLib : script "display drop dialog" version "1.5"

set aMainMes to "Drop AppleScript"
set aSubMes to "Drag and Drop AppleScript files to Table (.scpt & .scptd)"
set aUTI to {"com.apple.applescript.script-bundle", "com.apple.applescript.script"}
set execButtonTitle to "Execute"

set aRes to (display drop dialog aUTI main message aMainMes sub message aSubMes with initial folder "" OK button title execButtonTitle)

★Click Here to Open This Script 

Posted in dialog file File path GUI Library | Tagged 11.0savvy 12.0savvy 13.0savvy 14.0savvy | Leave a comment

Finder上で選択中のASバンドル書類をオープンしてscpt形式で再保存

Posted on 10月 20, 2023 by Takaaki Naganoya

Finder上で選択中のAppleScriptバンドル形式書類をスクリプトエディタでオープンして、scpt形式で保存し直すAppleScriptです。

スクリプトエディタのコンテクストメニューが.scpt形式しか認識しないので、バンドル形式のScriptを変換するために作ったものです。

Finderの選択中のファイルをフィルタするのに、フィルタ参照ではなくUTIを求めて判定しています。

「AppleScript最新リファレンスv2.8対応」の付録Scriptの加工用に作ったものです。バンドル形式への変換は書いてあったものの、scpt形式に変換するものは書いていなかったので急遽、用意しました。

AppleScript名:Finder上で選択中のASバンドル書類をオープンしてscpt形式で再保存.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/10/20
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSPredicate : a reference to current application’s NSPredicate
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

on run
  set aResList to main("com.apple.applescript.script-bundle") of me
  
  
set ngList to {}
  
  
repeat with i in aResList
    set anAlias to contents of i
    
set aRes to saveAppleScriptAsScript(anAlias) of me
    
    
if aRes = false then
      set the end of ngList to contents of i
    end if
  end repeat
  
  
return ngList
end run

–scptdファイルをaliasで渡すと、scptファイルで同じ場所に保存し直す
on saveAppleScriptAsScript(aFile)
  set dPOSIX to POSIX path of aFile
  
if dPOSIX ends with "/" then
    set dPOSIX to (strings 1 thru -2 of dPOSIX)
  end if
  
  
–フルパスから、拡張子を付け替える
  
set newPath to changeExtFromPath(dPOSIX, "scpt") of me
  
set newFile to POSIX file newPath
  
  
tell application id "com.apple.scripteditor2"
    try
      open aFile
      
      
tell front document
        check syntax
      end tell
      
      
save front document as "script" in file newFile
      
close front document without saving
      
return true
    on error
      return false
    end try
    
  end tell
end saveAppleScriptAsScript

–POSIX pathの拡張子を付け替える
on changeExtFromPath(aPath, newExt)
  set pathString to current application’s NSString’s stringWithString:aPath
  
set newPath to ((pathString’s stringByDeletingPathExtension())’s stringByAppendingPathExtension:newExt) as string
  
return newPath
end changeExtFromPath

on main(acceptUTI)
  tell application "Finder"
    set aSel to selection as alias list
  end tell
  
  
set aList to {}
  
  
repeat with i in aSel
    set anAlias to contents of i
    
set aUTI to getUTIfromPath(anAlias) of me
    
if aUTI is not equal to missing value then
      set uRes to filterUTIList({aUTI}, acceptUTI) of me
      
      
if uRes is not equal to {} then
        set the end of aList to contents of i
      end if
    end if
  end repeat
  
  
return aList
end main

–AliasからUTIを求める
on getUTIfromPath(anAlias)
  set aPOSIXpath to POSIX path of anAlias
  
set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIXpath
  
if aURL = missing value then return missing value
  
set aRes to aURL’s resourceValuesForKeys:{current application’s NSURLTypeIdentifierKey} |error|:(missing value)
  
if aRes = missing value then return missing value
  
return (aRes’s NSURLTypeIdentifierKey) as string
end getUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

Posted in file File path filter | Tagged 12.0savvy 13.0savvy 14.0savvy Finder Script Editor | Leave a comment

ファイルサイズの取得(symbolic link解消あり)

Posted on 9月 15, 2023 by Takaaki Naganoya

指定のPOSIX pathに存在するファイルの大きさ(ファイルサイズ)を取得するAppleScriptです。指定パスがSymbolic Linkである場合に備えて、パスの実体を求めるようにしています。

/System/Library/Frameworksフォルダ以下のFrameworkに対してbridgingsupportファイルの存在確認、およびファイルサイズの取得を行う、書籍の素材作成用のツールScriptを作ったときの、ファイルサイズ取得部分の部品です。

こういう資料は作るのに手間暇がかかるので、できるかぎりScriptから生成できるようにしています。この部分についていえば、OSのバージョンアップがあっても、作り直すのは簡単です。

AppleScript名:ファイルサイズの取得(symbolic link解消あり).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/09/14
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

set aPath to "/System/Library/Frameworks/WebKit.framework"
set bPath to current application’s NSString’s stringWithString:(aPath)
set cPath to bPath’s stringByResolvingSymlinksInPath() as string

set dPath to cPath & "/Versions/A/Resources/BridgeSupport/WebKit.arm64e.bridgesupport"
set aFM to current application’s NSFileManager’s defaultManager()
set anAttr to aFM’s attributesOfItemAtPath:(dPath) |error|:(missing value)
set sRes to anAttr’s fileSize()
–> 57225

★Click Here to Open This Script 

Posted in file File path | Tagged 12.0savvy 13.0savvy | Leave a comment

マンデルブロ集合を文字で描画してRTFとして組み立ててテキストエディットでオープン

Posted on 8月 6, 2023 by Takaaki Naganoya

マンデルブロ集合を文字で組み立てて、デスクトップフォルダにRTF形式で保存して、テキストエディットでオープンして表示するAppleScriptです。

Courier Newはどの環境にも入っているフォントだと思っていますが、ない場合には別の等幅フォントのPostScript名に変更してください。また、フォントサイズや描画色を変更してみるといいかもしれません。

ちなみに、実用性はまっっっっったくありません。昔は計算に数分かかったのに、いまだとインタプリタ型の言語で動かしても1秒以下なんだ、へーという納得ができる程度です。

AppleScript名:マンデルブロ集合を描画してRTFとして組み立ててテキストエディットでオープン.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/08/06
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—
use AppleScript
use framework "Foundation"
use framework "AppKit"
use scripting additions

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 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 NSMutableDictionary : a reference to current application’s NSMutableDictionary
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

set outStr to generateMandel() of me
set anAssrStr to makeRTFfromParameters(outStr, "CourierNewPSMT", 12) of me

–結果のRTFをデスクトップ上に書き出す。ファイル名はUUID.rtf
set thePath to (POSIX path of (path to desktop)) & (do shell script "uuidgen") & ".rtf"
set aRes to my saveStyledTextAsRTF(thePath, anAssrStr)

set targAlias to (POSIX file (thePath as string)) as alias

tell application "TextEdit"
  activate
  
open targAlias
end tell

–スタイル付きテキストを指定パス(POSIX path)にRTFで書き出し
on saveStyledTextAsRTF(targPath, aStyledString)
  set targPathNSString to NSString’s stringWithString:targPath
  
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
  
return (bRTF’s writeToFile:targPath atomically:true) as boolean
end saveStyledTextAsRTF

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, aFontName as string, aFontSize as real)
  set aVal1 to NSFont’s fontWithName:aFontName |size|:aFontSize
  
set aKey1 to (current application’s NSFontAttributeName)
  
  
set aVal2 to NSColor’s cyanColor()
  
set aKey2 to (current application’s NSForegroundColorAttributeName)
  
  
set aVal3 to 0.0
  
set akey3 to (current application’s NSKernAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3}
  
set valList to {aVal1, aVal2, aVal3}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

–マンデルブロ集合を文字で描画して返す
on generateMandel()
  set outStr to ""
  
  
repeat with y from -12 to 12 by 1
    
    
repeat with x from -39 to 39 by 1
      
      
set ca to x * 0.0458
      
set cb to y * 0.08333
      
      
set a to ca
      
set b to cb
      
      
repeat with i from 0 to 15 by 1
        set t to (a * a) – (b * b) + ca
        
set b to (2 * a * b) + cb
        
        
set a to t
        
        
if ((a * a) + (b * b)) > 4 then exit repeat
      end repeat
      
      
      
if ((a * a) + (b * b)) ≤ 4 then
        set outStr to outStr & " "
      else
        if i > 9 then set i to i + 7
        
set outStr to outStr & string id (48 + i)
      end if
      
    end repeat
    
    
set outStr to outStr & return
  end repeat
  
  
return outStr
end generateMandel

★Click Here to Open This Script 

Posted in File path RTF Text | Tagged 12.0savvy 13.0savvy TextEdit | Leave a comment

PowerPointが扱うファイルパス形式が支離滅裂な件

Posted on 8月 2, 2023 by Takaaki Naganoya

いろいろ調べてみたら、PowerPointが扱うファイルパス形式に整合性がまったくないことがわかりました。なんなんでしょう、これは。

ファイルのオープン時:alias(HFS path)

これは、とくに問題はありません。最低限のラインはクリアしているといってよいでしょう。

PDF書き出し時:HFS pathのテキスト

fileオブジェクトではなくHFS pathの文字列です。ここでかなり「おかしなプログラムだな」という感想を抱きます。こんなおかしなデータを要求するのはPowerPointぐらいだと思いますよ?

PPTX書類の新規保存時:HFS pathのテキスト

PDF書き出しもPPTX書類の保存も、同じく「save」コマンドで行うので、仕様が同じなのも納得ですが、通常書類のsaveにこれでは相当変わった仕様にしか見えません。

書類のフルパス情報:POSIX path

これは、致命的におかしな挙動であり、呆れるほどおかしな仕様です。担当者が正気なのか疑わしいレベルです。Office 2011のPowerPointでpresentation(書類)のfull name(フルパス情報)を取得してみたところ、HFS path文字列が返ってきたという調査結果が残っていました。

いま、バージョン16.75のPowerPointのpresentation(書類)のfull name(フルパス情報)を取得すると、POSIX pathが返ってきます。


▲Office 2011のPowerPointのパス情報の記述


▲バージョン16.75のPowerPointのパス情報の記述

AppleScript用語辞書上の記載内容にはたいして変化はないのですが、こんな頭のおかしな状態になっているとは思いませんでした。正直、PowerPointで何かまとまった処理を行おうとは思ったことが(それほど)なかったのですが、Keynoteで山のようにいろいろ強烈なScriptを書いているので、PowerPointでもいろいろできるのでは? と、冗談半分で試してこの通りです。

まさか、ExcelとWordもこの調子なのでは?(^ー^;

AppleScript名:オープン中の最前面のPowerPoint書類のフルパスの文字列を取得.scpt
set a to getPPTpath() of me
–> "Cherry:Users:me:Documents:2013-MacUDingCFUD.ppt"–Office 2011
–> "/Users/me/Documents/AppleScript 13/PowerPoint/TESTプレゼンテーション1 .pptx"–Office 2019

–オープン中の最前面のPowerPoint書類のフルパスの文字列を取得
on getPPTpath()
  tell application "Microsoft PowerPoint"
    set pCount to count every presentation
    
if pCount = 0 then return false
    
tell active presentation
      –Documentのフルパスを取得する
      
set aPath to full name
      
return aPath
    end tell
  end tell
end getPPTpath

★Click Here to Open This Script 

PowerPointの書類からTOCつきのPDFを書き出すAppleScriptを書いた際には、頭のおかしなPowerPoint 16.75が返してくるパス形式をサブルーチン側で吸収して処理するようにしました。ただ、将来的にこの頭のおかしな形式からまともな形式に戻してきたときに問題が発生するので、再変更に備えてもう少し準備しておいたほうがよいのかもしれません。

このPowerPointの担当者は、頭がおかしいです。

AppleScript名:オープン中のPowerPoint書類のパスをalias形式で取得.scpt
set pptPath to getPPTpath() of me
–> alias "Macintosh HD:Users:me:Documents:AppleScript 13:PowerPoint:TESTプレゼンテーション1 (Sectionなし).pptx"

–オープン中の最前面のPowerPoint書類のフルパスの文字列を取得
on getPPTpath()
  tell application "Microsoft PowerPoint"
    set pCount to count every presentation
    
if pCount = 0 then return false
    
    
tell active presentation
      –Documentのフルパスを取得する
      
set aPath to full name
    end tell
  end tell
  
  
set aFile to POSIX file aPath
  
set anAlias to aFile as alias
  
return anAlias
end getPPTpath

★Click Here to Open This Script 

Posted in File path Object control | Tagged 13.0savvy PowerPoint | Leave a comment

PowerPointで最前面の書類をPDF書き出し

Posted on 7月 29, 2023 by Takaaki Naganoya

よくある、Microsoft PowerPointで、オープン中の最前面の書類を指定のパスにPDFで書き出すAppleScriptです。M1 Mac mini+macOS 13.5上で動作するMicrosoft PowerPointバージョン16.75で確認しています。

スクリプトエディタ上で動かしてみましたが、デスクトップ上にファイルを書き込もうとしたときに、初回のみPowerPointがデスクトップフォルダにアクセスしてよいか、OSが確認ダイアログを表示してきました。こういう動作はScriptからのコントロール時には困ります。自動処理を行う前にクリアしておきたい(あらかじめダイアログ表示+認証を済ませておきたい)ところです。


▲PowerPointから書き出したPDF

Microsoft PowerPointのAppleScript用語辞書を確認してみたところ、「export」コマンドが存在しません。情報をいろいろ調べてみたところ「save as PDF」で指定パスにPDFを保存するようです。

さらに、こうした場合にsaveコマンドで指定するファイルパスは、fileオブジェクトで指し示しますが、PowerPointでは少々事情が異なるようでした。fileを指定すると、書き出されません。HFS形式のパスをテキストで指定する必要がありました。どうもこのあたり、ところどころバグめいた実装が散見されます。

Excelへの画像貼り込みScriptのように、POSIX pathでPDF書き出し先を指定してみましたが、こちらはPOSIX pathで指定しても書き出せませんでした。

AppleScript名:最前面の書類をPDF書き出し.scpt
set theOutputPath to ((path to desktop folder) as string) & (do shell script "uuidgen") & ".pdf"

tell application "Microsoft PowerPoint"
  tell active presentation
    save in theOutputPath as save as PDF
    
–保存先のファイルパスを文字列で指定する必要がある
    
–fileオブジェクトで指定すると書き出されない(バグのような挙動)
  end tell
end tell

★Click Here to Open This Script 

Posted in file File path PDF | Tagged 13.0savvy PowerPoint | Leave a comment

画像をExcelのワークシート上に配置

Posted on 4月 4, 2023 by Takaaki Naganoya

Microsoft 365のExcel v16.71、Windows版とmacOS版のソースコードが共通化されたというふれ込みではあるものの、実はけっこうフォーム部分が違うし、VBのマクロエディタで日本語が記入できないとか、互換性のない関数(Mac上で動作しないENCODEURL、Switch,IFS、FILTERXML、WEBSERVICEなどの関数)の存在など、いろいろ勘弁してほしい出来です。

しばらくはNumbersだけで用が済んでいたのですが、ここのところWindows版のExcelの講座なども行っていたので、併せてmacOS版のExcelについても追加調査。細かい点のチェックを行っていました。

そんなExcelでアドインのオンラインストアからQRコード作成用アドインを探してみたところ、フリーなものは存在していないようです。

Cocoaの機能を利用すれば、割とすぐにできてしまう程度のQRコード。わざわざアドインの力を利用する必要などなかったのです。AppleScriptでQRコードを生成して、Excelのワークシートに差し込めばよいだけです。

ところが、ひさしぶりにExcelのScriptを引っ張り出してきて、昔書いた「Excelに指定の画像を配置する」Scriptを実行してみたところ、エラーで動きません。

ワークシート上にshapeを作成できるのに、そのshapeに指定パスの画像を割り当てる処理でエラーになります。

そんな時、「出来の悪いプログラマは、POSIX pathで誤魔化して実装する」という経験則が思い出されました。

目を閉じると、AppleのKeynoteで一時期行われていた、画像配置コマンドにPOSIX pathを要求していたアレな実装であるとか(あれはひどかった)、いまだにアレであり続けているAdobe Acrobat DistillerのdistillコマンドがPOSIX pathを要求する件であるとか(file pathって書いてあるのに、aliasじゃなくてPOSIX pathを要求するという地雷仕様)、枚挙にいとまがありません。

そんなわけで、普通に書いても通らなかったのでパスをPOSIX pathで与えてみたところ、見事(?)配置されました。

AppleScript名:画像をワークシート上に配置.scpt
set anImagePath to choose file
set anImagePOSIX to POSIX path of anImagePath

tell application "Microsoft Excel"
  set cwb to workbook 1
  
tell cwb
    tell worksheet 1
      set aPicShape to make new shape at the beginning
      
set width of aPicShape to 312
      
set height of aPicShape to 312
      
user picture of aPicShape picture file anImagePOSIX
    end tell
  end tell
end tell

★Click Here to Open This Script 

Posted in Bug file File path | Tagged 11.0savvy 12.0savvy 13.0savvy Excel | Leave a comment

ファイル選択でiCloud Driveをデフォルトフォルダに指定

Posted on 9月 24, 2022 by Takaaki Naganoya

ファイル選択時にiCloud Driveをデフォルトのフォルダに指定するAppleScriptです。

macOS 10.9あたりでスクリプトエディタがiCloud DriveにAppleScriptを保存したり、iCloud Drive上のAppleScriptをオープンしたりできるようになりました。iCloud Drive上にAppleScriptライブラリを置いて参照することもできたはずですが、ちょっと情報が出てきません。

AppleScript名:ファイル選択でiCloud Driveをデフォルトフォルダに指定.scpt
set filePath to (path to library folder from user domain as text) & "Mobile Documents:"
set fRes to choose file default location (filePath as alias)

★Click Here to Open This Script 

Posted in dialog File path iCloud | Tagged 12.0savvy | Leave a comment

AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib

Posted on 8月 22, 2022 by Takaaki Naganoya

AS関連データの取り扱いを簡単にすることを目的に書き出した、privateDatatypeLibです。

プログラムとデータを分離して、データ記述部分を外部ファイル(設定ファイルなど)に追い出したときに、どのようなデータかを表現するための道具として試作してみました。

macOS上のデータ記述子は、

などのさまざまなデータ識別方法が存在していますが、どれも(自分の)用途には合わなかったので、検討・試作をはじめてみました。Predicatesが一番近いものの、不十分なのでいろんなデータ型や用途に拡張。あくまで自分用なので「public」などの宣言はとくに不必要と考え、縮小して処理を行なっています。

とくに、ファイルパスの処理なんて定型処理しかしないのに、わざわざ何かの表現を行う必要があるのはナンセンスですし、日付関連も割と余計な記述が多いように感じています。

また、緯度/経度のデータや座標データなども、もう少しなんとかならないかと思っています。

AppleScript名:privateDataTypeLib.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/08/22
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aData to "100"
set dType to "@number"
set bData to "" –不要なケース多数。不要な場合にはヌル文字を指定
set mePath to path to me –実際には、呼び出し側で取得して指定。ライブラリ自体のパスを求めているのはテスト実行時のみ
set aRes to getParameterAndCalc(aData, dType, bData, mePath) of me

on getParameterAndCalc(aData, dType, bData, mePath)
  if dType = "@string" then
    return normalizeByNFC(aData) of me
    
  else if dType = "@number" then
    set tmpA to zenToHan(aData) of charConvKit of me –全角→半角変換
    
set a to detectOutNumStr(tmpA) of me –数字+関連・意外の文字を除外
    
return normalizeByNFC(a) of me
    
  else if dType = "@filepath.sub.foldername" then
    set aClass to class of aData –aliasだったらPOSIX pathに変換。file…はどうなんだか
    
if aClass = alias then set aData to POSIX path of aData
    
return aData & bData & "/"
    
  else if dType = "@file.comment" then
    set aStr to getFinderComment(POSIX path of mePath) of me
    
return normalizeByNFC(aStr) of me
    
  else if dType = "@file.name" then
    set aClass to class of aData
    
if aClass = alias then set aData to POSIX path of aData
    
set aStr to (current application’s NSString’s stringWithString:aData)’s lastPathComponent()’s stringByDeletingPathExtension()
    
return normalizeByNFC(aStr as string) of me
    
  else if dType = "@date.month" then
    set curDate to current date
    
set curMonth to month of curDate as number
    
return curMonth as string
    
  else
    return aData
  end if
end getParameterAndCalc

on normalizeByNFC(aStr)
  set aNSStr to current application’s NSString’s stringWithString:aStr
  
set aNFC to aNSStr’s precomposedStringWithCanonicalMapping()
  
return aNFC as string
end normalizeByNFC

–ANK文字列以外のものをそぎ落とす
on detectOutNumStr(testStr)
  set sList to characters of testStr
  
set aStr to ""
  
  
repeat with i in sList
    if detectOutNumChar(i) of me then
      set aStr to aStr & (i as string)
    end if
  end repeat
  
  
return aStr
end detectOutNumStr

on detectOutNumChar(testText)
  –Numeric + Special char
  
set ankChar to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-", "+", "E", ","}
  
  
set _testChar to testText as Unicode text
  
  
ignoring case
    repeat with i in _testChar
      set j to contents of i
      
if j is not in ankChar then
        return false
      end if
    end repeat
  end ignoring
  
  
return true
end detectOutNumChar

–Finderコメントを取得
on getFinderComment(aPOSIX)
  set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIX
  
set aMetaInfo to current application’s NSMetadataItem’s alloc()’s initWithURL:aURL
  
set metaDict to (aMetaInfo’s valuesForAttributes:{"kMDItemFinderComment"}) as record
  
if metaDict = {} then return ""
  
set aComment to kMDItemFinderComment of (metaDict)
  
return aComment
end getFinderComment

script charConvKit
  — Created 2017-09-06 by Shane Stanley
  
— Modified 2017-09-06 by Takaaki Naganoya
  
use AppleScript
  
use framework "Foundation"
  
property parent : AppleScript
  
  
property NSString : a reference to current application’s NSString
  
property NSStringTransformFullwidthToHalfwidth : a reference to current application’s NSStringTransformFullwidthToHalfwidth
  
property NSStringTransformHiraganaToKatakana : a reference to current application’s NSStringTransformHiraganaToKatakana
  
property NSStringTransformLatinToHiragana : a reference to current application’s NSStringTransformLatinToHiragana
  
property NSStringTransformLatinToKatakana : a reference to current application’s NSStringTransformLatinToKatakana
  
property NSStringTransformToUnicodeName : a reference to current application’s NSStringTransformToUnicodeName
  
property NSStringTransformToXMLHex : a reference to current application’s NSStringTransformToXMLHex
  
  
–半角→全角変換
  
on hanToZen(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:true) as string
  end hanToZen
  
  
–全角→半角変換
  
on zenToHan(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:false) as string
  end zenToHan
  
  
–ひらがな→カタカナ変換
  
on hiraganaToKatakana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:false) as string
  end hiraganaToKatakana
  
  
–カタカナ→ひらがな変換
  
on katakanaToHiraganaTo(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:true) as string
  end katakanaToHiraganaTo
  
  
–ローマ字→ひらがな変換
  
on alphabetToHiragana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:false) as string
  end alphabetToHiragana
  
  
–ひらがな→ローマ字変換
  
on hiraganaToalphabet(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:true) as string
  end hiraganaToalphabet
  
  
–ローマ字→カタカナ変換
  
on alphabetToKatakana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:false) as string
  end alphabetToKatakana
  
  
–カタカナ→ローマ字変換
  
on katakanaToAlphabet(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:true) as string
  end katakanaToAlphabet
  
  
–文字→Unicode Name変換
  
on characterToUnicodeName(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:false) as string
  end characterToUnicodeName
  
  
–Unicode Name→文字変換
  
on unicodeNameToCharacter(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:true) as string
  end unicodeNameToCharacter
  
  
–文字→XML Hex変換
  
on stringToXMLHex(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:false) as string
  end stringToXMLHex
  
  
–XML Hex→文字変換
  
on xmlHexTostring(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:true) as string
  end xmlHexTostring
end script

★Click Here to Open This Script 

Posted in Calendar file File path folder Library Number Text URL | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy | 1 Comment

xincludeを有効にしてXML(sdef)読み込み v2

Posted on 7月 26, 2022 by Takaaki Naganoya

指定のBundle IDのアプリケーションのInfo.plistの値からSDEF(AppleScript命令定義ファイル)のファイル情報を読み取って、実際にSDEFの実ファイルを読み取り、得られた文字列をXMLとして解釈する際にXincludeを展開して、再度文字列に戻すAppleScriptです。

もともと、SDEFを読み取って分析することは、アプリケーションのバージョン間の変更差分を検出する用途で試していました。これは、変化のみを検出することを目的としたもので、内容について仔細に認識することを目的としたものではありませんでした。

そこから1歩進んで、AppleScript側から実行環境情報を取得する試みをいろいろ続けてきました。

実行環境自体が何なのか、という判別はここ数年で一番大きな成果だったと感じます。地球にいながら「銀河系の中の、太陽系の中の第3惑星にいる」ということが観測できるようになったわけです。

さらに、それぞれのランタイム環境の識別が可能になったことにより、各実行環境の「差」を判定しやすくなった、という副産物もありました。

話を戻しましょう。

SDEFを読んで、当該アプリケーションが何を行えるかをAppleScript側からも認識できるはずで、そのための調査も開始していました。

System Eventsの「Scripting Definition Suite」はその名前と用語から、AppleScriptからSDEFの解析を行うための部品であることが推測され、いろいろ調べてきたものの…..Apple側がSystem Eventsそれ自体のチェックを行うために設けた「メンテナンス&デバッグのための機能(ただしSystem Events専用)」だという結論にいたっています。つまり、System Events以外にはまるっきり使えません。

これで、AppleScriptのプログラム側からアプリケーション側の仕様を自動判別&解析するためには、SDEFそのものを解析するしかないという話になりました。

ただ、SDEFの直接解析については1つの「ちょっと困った仕様」がありました。外部ファイルをincludeできる(Xinclude)ようになっており、そのファイルを元のSDEF上に展開するのは、まじめにXML上の情報を分析する必要があります。ファイル・システム上のどこの場所からどのファイルを読み込むのか、という話と……XMLのオブジェクトモデル上のどこに展開するのかという話の両方を処理する必要があります。まじめに組むと、それなりの時間がかかってしまいそうです。

少ない例から推測してScriptを書くことは不可能ではありませんが、「隠れ仕様」が存在していた場合には対処できません。OS側にその機能があれば、そのままそっくり利用できたほうがよいだろうと思われました。

このXincludeの展開を(他力本願で)行うには、どこのレイヤーのどの機能を用いるべきなのか?

matttのOno.frameworkなどもビルドして試してみたものの、Xincludeの展開はソースコードを全文検索しても見つけられず、もうちょっと物理層に近いレイヤーのlibxml2の機能にアクセスする必要があるようでした。

ほかにも、Unix Shell Commandに、「xsltproc」コマンドが存在しており、Xinclude展開を行ってくれるようでした(XSLTを書けば)。スクリプトエディタに任意のアプリケーションをオープンさせればAppleScript用語辞書を表示してくれるわけで、この表示中のSDEFについてはXincludeがすべて解決された状態になっているため、AppleScriptからスクリプトエディタを操作するという手段もないわけではないのですが、もっとスマートに(こっそり)処理したかったので、これは(機能することがわかっていながらも)使えません。

結局、NSXMLDocumentのNSXMLNodeOptionsでNSXMLDocumentXIncludeを指定すると、XMLテキストをオブジェクトに解釈する際に外部ファイルを展開してくれることが判明。

Mail.appのSDEFでいえば、Standard Suiteにinclude指定があり、

元ファイルを読み込んだだけでは完全体のSDEFを取得できません。これを、本AppleScriptを用いて読み込んで解釈すると、

のように、指定パスに存在している「CocoaStandard.sdef」を展開します。ほかにも、Microsoft系のアプリケーションでXincludeを使用しており、本AppleScriptのような処理を経た上でSDEFの分析を行う必要があることでしょう。

これが、今日明日の段階で何か「すごいこと」ができるような存在になることは決してありませんが、この部品が存在していることで異次元の処理ができるようになるような手応えはあります。

AppleScript名:xincludeを有効にしてXML(sdef)読み込み v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/07/26
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

set targAppBundleID to "com.apple.mail" –SDEFを取り出すターゲットのアプリケーションのBundle ID

set thePath to POSIX path of (path to application id targAppBundleID)

set aSDEFname to retAppSdefNameFromBundleIPath(thePath, "OSAScriptingDefinition") of me
if aSDEFname = false then return

if aSDEFname does not end with ".sdef" then set aSDEFname to aSDEFname & ".sdef"
set sdefFullPath to thePath & "Contents/Resources/" & aSDEFname
set sdefAlias to (POSIX file sdefFullPath) as alias –sdefのフルパスを求める

–SDEF読み込み(Xincludeの展開が必要な状態)
tell current application
  set theXML to read sdefAlias as «class utf8»
end tell

–NSXMLDocumentの生成、Xincludeを有効に
set {theXMLDoc, theError} to current application’s NSXMLDocument’s alloc()’s initWithXMLString:theXML options:(current application’s NSXMLDocumentXInclude) |error|:(reference)

–XMLを文字データ化
set aDocStr to (theXMLDoc’s XMLData)
set aDocStr2 to (current application’s NSString’s alloc()’s initWithData:(aDocStr) encoding:(current application’s NSUTF8StringEncoding)) as string

–指定パスからアプリケーションのScriptabilityをbooleanで返す
on retAppSdefNameFromBundleIPath(appPath as string, aKey as string)
  set aDict to (current application’s NSBundle’s bundleWithPath:appPath)’s infoDictionary()
  
set aRes to aDict’s valueForKey:(aKey)
  
if aRes = missing value then return false
  
set asRes to aRes as string
  
  
return asRes as string
end retAppSdefNameFromBundleIPath

★Click Here to Open This Script 

Posted in file File path sdef XML | Tagged 12.0savvy | Leave a comment

相対パスを計算で求める

Posted on 6月 14, 2022 by Takaaki Naganoya

指定のPOSIX pathを元に相対パスを計算するAppleScriptです。

Unix shellであれば、相対パスについては「../../../」などと表現できるわけですが、シェルを介さずに計算する方法が見つからなかったので、必要に迫られて作っておきました。

AppleScript名:上位パスを相対的に求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/06/14
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aFile to "/Users/me/Documents/1/2/3"

set aNum to 1
set bFile to getUpperDir(aFile, aNum) of me

–> "/Users/me/Documents/1/2"

set aNum to 2
set cFile to getUpperDir(aFile, aNum) of me
–>"/Users/me/Documents/1"

set aNum to 3
set dFile to getUpperDir(aFile, aNum) of me
–> "/Users/me/Documents"

–与えられたパスから指定階層「上」のパスを求める
on getUpperDir(aPOSIXpath as string, aNum as integer)
  if aNum < 1 then return aPOSIXpath
  
set pathString to current application’s NSString’s stringWithString:aPOSIXpath
  
repeat aNum times
    set pathString to pathString’s stringByDeletingLastPathComponent()
  end repeat
  
return pathString as string
end getUpperDir

★Click Here to Open This Script 

AppleScript名:下位パスを配列で追加して求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/06/14
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aPOSIXpath to "/Users/me/Documents/" –AppleScriptのPOSIX path表現(フォルダを表現するさい、末尾に「/」)
set catDirList to {"1", "2", "3"}
set bPath to getChildPathByAppendingDirsByArray(aPOSIXpath, catDirList) of me
–> /Users/me/Documents/1/2/3

set aPOSIXpath to "/Users/me/Documents" –CocoaのPOSIX path表現(フォルダを表現する場合でも、末尾に「/」入らず)
set catDirList to {"3", "2", "1"}
set cPath to getChildPathByAppendingDirsByArray(aPOSIXpath, catDirList) of me
–> "/Users/me/Documents/3/2/1"

on getChildPathByAppendingDirsByArray(aPOSIXpath, catDirList)
  set pathString to current application’s NSString’s stringWithString:aPOSIXpath
  
set aList to (pathString’s pathComponents()) as list
  
set aList to aList & catDirList
  
  
set bPath to current application’s NSString’s pathWithComponents:aList
  
return bPath as string
end getChildPathByAppendingDirsByArray

★Click Here to Open This Script 

Posted in File path list Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

Keynoteの現在の書類と同じ階層に没スライド入れを作成

Posted on 5月 29, 2022 by Takaaki Naganoya

Keynoteの最前面の書類(現在の書類)と同じ階層に没スライドを入れるゴミ箱用のスライドを、編集中の現在のスライドと同じサイズ(Normal/HD)で同じテーマで作成するAppleScriptです。

ふだん、Keynoteで作業をしているときに、不要になったスライド(ページ)を完全削除せず、別書類に移動させて復活させられるようにしているのですが、その作業が煩雑だったのでScriptで自動化したものです。

同階層にゴミ箱用のスライド書類が存在していたら、それをオープンします。存在していなければ、新規作成して指定ファイル名で保存….というところで、v12のバグに遭遇してしまったわけです。

AppleScript名:Keynoteの現在の書類と同じ階層に没スライド入れを作成.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/29
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property newFileName : "没.key" —"trash.key"

tell application "Keynote"
  tell front document
    set dName to getCurThemeName() of me
    
set curFile to (file of it) as alias
    
set myHeight to height of it
    
set myWidth to width of it
  end tell
end tell

–書類の親フォルダを取得(POSIX path)
set parentFol to getParentFol(curFile) of me
set newKeynoteFile to parentFol & "/" & newFileName

–ファイルの存在確認
set exRes to chkFileExistence(newKeynoteFile) of me
if exRes = true then
  –すでに存在している場合はそれをオープン
  
set newKeynoteFileAlias to (POSIX file newKeynoteFile) as alias
  
tell application "Keynote"
    open newKeynoteFileAlias
  end tell
  
return
else
  –まだ存在していない場合、最前面の書類と同じテーマ、縦横比(SD、HD)の新規書類を作成する
  
set parentFolAlias to (POSIX file parentFol) as alias as string –POSIX path to HFS path string
  
set saveFilePathStr to (parentFolAlias as string) & newFileName
  
  
tell application "Keynote"
    set newDoc to make new document with properties {document theme:theme dName, width:myWidth, height:myHeight}
    
–save newDoc in file saveFilePathStr as Keynote–Keynote v12のバグに遭遇したため機能オフに
  end tell
end if

–ファイルの存在確認
on chkFileExistence(aFilePathStr)
  set fileManager to current application’s NSFileManager’s defaultManager()
  
set aRes to fileManager’s fileExistsAtPath:aFilePathStr
  
return aRes as boolean
end chkFileExistence

on getParentFol(anAlias)
  set aPath to POSIX path of anAlias
  
set pathString to current application’s NSString’s stringWithString:aPath
  
set newPath to pathString’s stringByDeletingLastPathComponent()
  
return newPath as string
end getParentFol

on getCurThemeName()
  tell application "Keynote"
    set dCount to count every document
    
if dCount = 0 then error "No Document"
    
    
tell front document
      set aTheme to document theme
      
set atThemeName to name of aTheme
    end tell
  end tell
end getCurThemeName

★Click Here to Open This Script 

Posted in File path | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | Leave a comment

書籍フォルダの階層をさかのぼって、ツメに掲載する最大チャプターを推測 v2

Posted on 3月 4, 2022 by Takaaki Naganoya

電子書籍を作るのにPagesやKeynoteを使っており、「AppleScriptによるWebブラウザ自動操縦ガイド」(以下、Webブラウザガイド)も全ページPagesで作っています。

PagesやKeynoteでは書籍作成用としては機能が素朴すぎて、足りない点はAppleScriptでツールを作って、作業の手間を減らしています。それらの補助Scriptは、各種パラメータをその本に合わせて固定して使用しています。

Webブラウザガイドは全14章で構成されているため、ページの左右につけている「ツメ」(Index)は1から14までの数字が入っています。

今後もツメチェックAppleScript(座標、塗りつぶし色と非選択色の自動判別、ファイル名からの該当章の自動ピックアップ)を他の書籍用にも運用していくつもりですが、この「全14章」という仕様は固定なので、章構成が異なる他の本のプロジェクトでは、自動で章の数をかぞえてくれるとよさそうだと考えました。

だいたい電子書籍のファイルについては、フォルダ分けして2階層ぐらいで管理しているので、その階層数については決め打ちでDoc rootフォルダを計算(parent of parent of….)するようにしました。そして、全フォルダのフォルダ名称を取得。

ダイアログで最終章を選択させると、そこから章番号を自動抽出して(「XX章」と書かれていることが前提)、その番号を返します。

こういう用途を考えると、階層構造をそのまま選択できるNSOutlineViewを選択用の部品に使えると便利で……これまでにもedama2さんと意見交換しつつNSOutlineViewをNSAlertダイアログ上に表示するといった試作も何回か検討してきたのですが、スクリプトエディタ/Script Debugger上で記述するAppleScriptObjCではこの部品を扱うのがとても難しいんですね。

ならば、Xcode上で記述するAppleScriptObjCにAppleScript用語辞書を持たせて、階層ファイル構造を選択させる専用の補助アプリケーションを作ってもいいのかも? ただ、Xcode 13.x系が壊れて使えないままの環境であるため、いまXcodeでビルドするわけにもいかないのでした。

choose fileコマンドやchoose folderコマンドに「icon view」「list view」「column view」といった初期表示状態を指定できる機能があれば、それで済むような気もしますが、どうせAppleに要望出してもこういうのは通らないので、自分で作ったほうが確実で早いですわー。

にしても、この通常ウィンドウと見分けがつかないファイル選択ダイアログ、macOS 11で最初に見たときには「正気か?!」と、腰を抜かしました。あいかわらず、この決定を下した責任者は●●だと思いますが、せめてもう少し視覚的に見分けがつくようにできなかったもんでしょうか。

AppleScript名:書籍フォルダの階層をさかのぼって、ツメに掲載する最大チャプターを推測 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/02/26
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "Pages"
  tell front document
    set filePath to (file of it) as alias
  end tell
end tell

tell application "Finder"
  set parentFol to (parent of parent of filePath)
  
tell parentFol
    set fNames to name of every folder
  end tell
end tell

set folName to contents of (choose from list fNames with prompt "書籍のツメに載せる最終章のフォルダを選択")
set cNum to retChapter(folName as string) of me
–> 14

–ファイル名から「章」情報を抽出
on retChapter(aStr)
  set wList to words of aStr
  
set aCount to 1
  
repeat with ii in wList
    set jj to contents of ii
    
if jj = "章" then
      return contents of item (aCount – 1) of wList
    end if
    
set aCount to aCount + 1
  end repeat
  
return 0 –Illeagal file name
end retChapter

★Click Here to Open This Script 

Posted in Books file File path Text | Tagged 12.0savvy Finder Pages | 1 Comment

Pixelmator Proで指定の画像を複数の3D LUTを用いてカラー調整して画像書き出し

Posted on 5月 2, 2021 by Takaaki Naganoya

Pixelmator Pro v2.0.8で追加された3D LUT(Look Up Table)によるカラー調整機能。これを用いて、複数の3D LUTファイルによるカラー調整を行い、それぞれ3D LUTファイルのファイル名を反映させて書き出すAppleScriptです。

3D LUTファイルは、探してみるとあちこちで配布されており、割とありふれた存在のようです。実際にフリー配布されている3D LUTファイルをダウンロードしてきて、1つのフォルダに入れておき、指定画像に対してカラー調整を行わせてみました。

–> [全てフリー!] シネマティックなルックになる10のLUTsを紹介します!!

フォルダに入っている3D LUTファイルをすべてループで処理するので、3D LUTファイル100個でも1,000個でも処理できますし、ちょっと書き換えれば複数の画像に対してそれぞれすべての3D LUTファイルによる色調整を実行するようにもできます。

AppleScript名:指定の画像を複数の3D LUTでカラー調整して画像書き出し.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/02
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSPredicate : a reference to current application’s NSPredicate
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

–処理対象の画像を選択
set anImage to choose file of type {"public.image"} default location (path to pictures folder) with prompt "Select Proc Image"
set imgParent to getParentPathFromAlias(anImage) of me

–3D LUTファイルを入れてあるフォルダを選択
set lutFolder to choose folder with prompt "Select 3D LUT folder"

–Filter 3D LUT (.cube) files only
tell application "Finder"
  set fList to (every file of folder lutFolder) as alias list
end tell

set lutList to getFilesWithUTI("com.blackmagicdesign.cube", fList) of me

–指定の画像ファイルをオープン
tell application "Pixelmator Pro"
  close every document saving no
  
open anImage
end tell

–Main Loop
repeat with i in lutList
  set aLut to contents of i
  
  
–ファイルパスの加工処理
  
set newImgName to ((current application’s NSString’s stringWithString:(POSIX path of aLut))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".jpg") as string
  
set newImgFullPath to (imgParent as string) & "/" & newImgName
  
set newImgFile to POSIX file newImgFullPath
  
  
tell application "Pixelmator Pro"
    activate
    
tell front document
      tell color adjustments of first layer –ここだけ、ネスティングを分割するとエラーになる
        set its custom lut to aLut
      end tell
      
      
export to newImgFullPath as JPEG with properties {compression factor:0.5, bits per channel:8}
      
undo
    end tell
  end tell
end repeat

–後片付け
tell application "Pixelmator Pro"
  tell front document
    close without saving
  end tell
end tell

on getParentPathFromAlias(aliasPath)
  set aPath to POSIX path of aliasPath
  
set pathString to current application’s NSString’s stringWithString:aPath
  
set newPath to pathString’s stringByDeletingLastPathComponent()
  
return newPath
end getParentPathFromAlias

on getFilesWithUTI(acceptUTI, aliasList)
  set aList to {}
  
  
repeat with i in aliasList
    set anAlias to i as alias
    
set aUTI to getUTIfromPath(anAlias) of me
    
if aUTI is not equal to missing value then
      set uRes to filterUTIList({aUTI}, acceptUTI) of me
      
      
if uRes is not equal to {} then
        set the end of aList to contents of i
      end if
    end if
  end repeat
  
  
return aList
end getFilesWithUTI

–AliasからUTIを求める
on getUTIfromPath(anAlias)
  set aPOSIXpath to POSIX path of anAlias
  
set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIXpath
  
if aURL = missing value then return missing value
  
set aRes to aURL’s resourceValuesForKeys:{current application’s NSURLTypeIdentifierKey} |error|:(missing value)
  
if aRes = missing value then return missing value
  
return (aRes’s NSURLTypeIdentifierKey) as string
end getUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

Posted in Color file File path Image | Tagged 10.14savvy 10.15savvy 11.0savvy Pixelmator Pro | Leave a comment

Post navigation

  • Older posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 13.6.5 AS系のバグ、一切直らず
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • Numbersで選択範囲のセルの前後の空白を削除
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • AppleScriptによる並列処理
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (187) 14.0savvy (137) 15.0savvy (115) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (75) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC