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

タグ: 14.0savvy

指定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

Numbersで選択中の2列のセルを比較して並べ直して書き戻す v2

Posted on 10月 14, 2024 by Takaaki Naganoya

Numbers上でデータを整理しているときに、必要になって組んでみたものです。少し大きいAppleScriptですが、ありもののルーチンをつなぎ合わせて書いたので、とくに画期的な何かを書いたということはありません。

もともと、Numbers上にまとめたデータ(2列分)があって、それらを同じものは同じ行に並べ、削除されたものは空欄、追加されたものは下に列挙するという整理を行なっていました。


▲処理前の状態。2列x処理を行う分の行を選択した状態で本AppleScriptを実行する(スクリプトメニューなどを推奨)


▲処理後の状態。このように整理を行う

この作業をまとめて行うものです。そんなに高速化に配慮しているわけではないので、巨大なデータを扱うのには(このままでは)向いていないかもしれません。ただ、高速化の余地はいろいろあります。

もう、これは分かりきっていた話ですが、Numbers向けに凝ったAppleScriptを書くと、Numbersの機能はほとんど使わずに、AppleScriptの配列やらNSObjectのNSArrayやらを使いまくった「Cocoaの機能のオンパレード」みたいなAppleScriptになります。これは、Numbersに絶望的に何も機能がないためで、データの入出力しか行う余地がありません。

AppleScript名:選択中の2列のセルを比較して並べ直して書き戻す v2
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/10/14
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set curTable to getCurTable() of me
if curTable = "" then return

set {s1Row, s1Column, e1Row, e1Column} to getSelectionRange(curTable) of me
–> {73, 3, 86, 4}

set colWidth to e1Column – s1Column + 1
–> 2

if colWidth is not equal to 2 then
  display dialog "Numbers上の表の選択幅が2ではないので、処理終了します" buttons {"OK"} default button 1
  
return
end if

set rowHeight to e1Row – s1Row + 1
–> 15

–縦方向に列のセルの値を取得(左側)
set v1List to getValueByRange(curTable, s1Column, s1Row, e1Row) of me

–スイープ(空白セルのmissing valueを除去)
set v1aList to sweepList(v1List, missing value) of me
–> {"com.apple.eloquence.fr-CA.Grandpa", "com.apple.eloquence.fi-FI.Grandpa", " com.apple.eloquence.de-DE.Grandpa", " com.apple.eloquence.pt-BR.Grandpa", "com.apple.eloquence.en-US.Grandpa", "com.apple.eloquence.es-ES.Grandpa", " com.apple.eloquence.en-GB.Grandpa", " com.apple.eloquence.it-IT.Grandpa", " com.apple.eloquence.es-MX.Grandpa"}

–縦方向に列のセルの値を取得(右側)
set v2List to getValueByRange(curTable, e1Column, s1Row, e1Row) of me

–スイープ(空白セルのmissing valueを除去)
set v2aList to sweepList(v2List, missing value) of me
–> {"com.apple.eloquence.de-DE.Grandpa", "com.apple.eloquence.en-GB.Grandpa", "com.apple.eloquence.en-US.Grandpa", "com.apple.eloquence.es-ES.Grandpa", "com.apple.eloquence.es-MX.Grandpa", "com.apple.eloquence.fi-FI.Grandpa", "com.apple.eloquence.fr-CA.Grandpa", "com.apple.eloquence.fr-FR.Grandpa", "com.apple.eloquence.it-IT.Grandpa", "com.apple.eloquence.pt-BR.Grandpa", "com.apple.eloquence.ja-JP.Grandpa", "com.apple.eloquence.ko-KR.Grandpa", "com.apple.eloquence.zh-CN.Grandpa", "com.apple.eloquence.zh-TW.Grandpa"}

set dList to getDiffBetweenLists(v1aList, v2aList) of me
–> {addItems:{"com.apple.eloquence.zh-TW.Grandpa", "com.apple.eloquence.ko-KR.Grandpa", "com.apple.eloquence.ja-JP.Grandpa", "com.apple.eloquence.zh-CN.Grandpa"}, minusItems:{}}

set newList to {}
set minusList to minusItems of dList

repeat with i in v1aList
  set j to contents of i
  
if j is not in minusList then
    if j is in v2aList then
      set the end of newList to j
    else
      set the end of newList to ""
    end if
  else
    set the end of newList to ""
  end if
end repeat

set addList to addItems of dList
set addList to sort1DNumList(addList, true) of me –昇順ソート

set new2List to newList & addList

set newLen to length of new2List
if newLen > rowHeight then
  display dialog "新規データが大きいため(" & (rowHeight as string) & "行に対して、データが" & (newLen as string) & "件)データをNumbersに描き戻せません"
  
return –元のデータ範囲よりも、新規データ範囲(行)が多かったら処理を打ち切る(将来アップデート予定。行挿入などで対処)
end if

repeat (rowHeight – newLen + 1) times
  set the end of new2List to ""
end repeat

setValueByRange(curTable, e1Column, s1Row, e1Row, new2List) of me

on setValueByRange(curTable, s1Column, s1Row, e1Row, vList)
  tell application "Numbers"
    tell curTable
      tell column s1Column
        set cList to cells s1Row thru e1Row
      end tell
      
      
set aCount to 1
      
repeat with i in cList
        set aVal to item aCount of vList
        
set value of i to aVal
        
set aCount to aCount + 1
      end repeat
      
    end tell
  end tell
end setValueByRange

on getValueByRange(curTable, s1Column, s1Row, e1Row)
  tell application "Numbers"
    tell curTable
      tell column s1Column
        set vList to value of cells s1Row thru e1Row
        
return vList
      end tell
    end tell
  end tell
end getValueByRange

on getCurTable()
  tell application "Numbers"
    tell front document
      tell active sheet
        try
          set theTable to first table whose class of selection range is range
        on error
          return "" –何も選択されてなかった場合
        end try
        
        
return theTable
      end tell
    end tell
  end tell
end getCurTable

on getSelectionRange(theTable)
  tell application "Numbers"
    tell theTable
      set aSel to properties of selection range
      
set selName to name of aSel
      
set {s1, s2} to parseByDelim(selName, ":") of me
      
      
–始点の情報を取得する
      
set s1Row to (address of row of range s1) as integer
      
set s1Column to (address of column of range s1) as integer
      
      
–終点の情報を取得する
      
set e1Row to (address of row of range s2) as integer
      
set e1Column to (address of column of range s2) as integer
      
      
return {s1Row, s1Column, e1Row, e1Column}
    end tell
  end tell
end getSelectionRange

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 sweepList(aList, sweepItem)
  set bList to {}
  
repeat with i in aList
    if contents of i is not equal to sweepItem then
      set the end of bList to contents of i
    end if
  end repeat
  
return bList
end sweepList

–リストの差分を取得_v2
on getDiffBetweenLists(aArray as list, bArray as list)
  set allSet to current application’s NSMutableSet’s setWithArray:aArray
  
allSet’s addObjectsFromArray:bArray
  
  
–重複する要素のみ抜き出す
  
set duplicateSet to current application’s NSMutableSet’s setWithArray:aArray
  
duplicateSet’s intersectSet:(current application’s NSSet’s setWithArray:bArray)
  
  
–重複部分を削除する
  
allSet’s minusSet:duplicateSet
  
set resArray to (allSet’s allObjects()) as list
  
  
set aSet to current application’s NSMutableSet’s setWithArray:aArray
  
set bSet to current application’s NSMutableSet’s setWithArray:resArray
  
aSet’s intersectSet:bSet –積集合
  
set addRes to aSet’s allObjects() as list
  
  
set cSet to current application’s NSMutableSet’s setWithArray:bArray
  
cSet’s intersectSet:bSet –積集合
  
set minusRes to cSet’s allObjects() as list
  
  
return {addItems:minusRes, minusItems:addRes}
end getDiffBetweenLists

–1D List(数値)をsort / ascOrderがtrueだと昇順ソート、falseだと降順ソート
on sort1DNumList(theList as list, aBool as boolean)
  tell current application’s NSSet to set theSet to setWithArray_(theList)
  
tell current application’s NSSortDescriptor to set theDescriptor to sortDescriptorWithKey_ascending_(missing value, aBool)
  
set sortedList to theSet’s sortedArrayUsingDescriptors:{theDescriptor}
  
return (sortedList) as list
end sort1DNumList

★Click Here to Open This Script 

Posted in diff list | Tagged 13.0savvy 14.0savvy 15.0savvy Numbers | Leave a comment

Numbersで選択範囲のセルの前後の空白を削除

Posted on 10月 14, 2024 by Takaaki Naganoya

コピペで作ったNumbersの表に空白文字(ゴミ)が入っている場合のクリーニング用AppleScriptです。Numbers v14.2用に作成しましたが、バージョンが異なっても動作に変化はないでしょう。

ExcelやNumbersなどの表計算アプリでは、前のセルに入力されたフォーマットを維持する機能がついているため、前のセルが空白文字ではじまる(=ゴミが入っている)と、次のセルにも同様にゴミが入ることになります。

そこで、クリーニング用に本Scriptを作成しました。


▲こんな風に、セルの先頭にスペースが入ってしまっている場合のクリーニング用Script。対象セルを選択して本Scriptを実行


▲本Script実行後の様子。各セルの冒頭に入っていたスペースが削除される

ただ、大量のセルを処理するような配慮は一切行っていないので、広範囲のセルを処理する場合には、もっと真剣に高速化を行う必要があることでしょう。

macOS標準装備のスクリプトメニューに入れて呼び出すことを想定しています。

AppleScript名:選択範囲のセルの前後の空白を削除して書き戻す
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/10/14
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSCharacterSet : a reference to current application’s NSCharacterSet

set curTable to getCurTable() of me
if curTable = "" then return

tell application "Numbers"
  tell curTable
    set cList to every cell of selection range
    
repeat with i in cList
      set j to contents of i
      
set tmpVal to value of j
      
if tmpVal is not equal to missing value then
        set tmpVal to trimWhiteSpaceFromHeadAndTail(tmpVal) of me
        
ignoring application responses
          set value of j to tmpVal
        end ignoring
      end if
    end repeat
  end tell
end tell

on getCurTable()
  tell application "Numbers"
    tell front document
      tell active sheet
        try
          set theTable to first table whose class of selection range is range
        on error
          return "" –何も選択されてなかった場合
        end try
        
        
return theTable
      end tell
    end tell
  end tell
end getCurTable

on trimWhiteSpaceFromHeadAndTail(aStr as string)
  set aString to NSString’s stringWithString:aStr
  
set bString to aString’s stringByTrimmingCharactersInSet:(NSCharacterSet’s whitespaceAndNewlineCharacterSet)
  
return bString as anything –as anything
end trimWhiteSpaceFromHeadAndTail

★Click Here to Open This Script 

Posted in Text | Tagged 13.0savvy 14.0savvy 15.0savvy Numbers | Leave a comment

Pages書類の内容を伏せ字に v2

Posted on 10月 5, 2024 by Takaaki Naganoya

現在オープン中の最前面のPages書類の内容を伏せ字に置き換えるAppleScriptの改良版です。電子書籍「Pages+AppleScriptで本をつくろう!」のために作成したScriptの改良版です。

–> Download Script Bundle With library

実行にはライブラリ「dynamicClicker」が必要なため、上記リンクからAppleScriptバンドル書類をダウンロードして実行してください。

Pagesの書類上のオブジェクトは、

のようになっており(iWork Scripting Book with AppleScriptより引用)、shapeとtext itemの区別ができないという「頭のおかしな仕様」になっていますが、オブジェクトのclassを求めれば、だいたいは区別できる状況です。

group itemについてはメニューを強制操作して(なくなるまで永久ループで)グループ解除を行い、そののちにshapeとtableについては伏せ字処理を行います。

image、chart、movieなどのオブジェクトについては伏せ字処理を行いませんが、そのあたりは処理したいユーザーの趣味次第でしょう。

AppleScript名:全ページを伏せ字に v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/10/02
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

tell application "Pages"
  tell front document
    set pCount to count every page
    
repeat with p from 1 to pCount
      tell page p
        –ひたすらグループ化されたアイテムを解除する。多重にグループ化が可能なので、ひたすら繰り返す
        
repeat
          set gList to every group
          
if gList = {} then exit repeat
          
set gRes to ungroupPagesItems(gList) of me
        end repeat
        
        
–通常処理
        
set aList to every iWork item
        
        
repeat with i in aList
          set j to contents of i
          
set tmpClass to class of j
          
          
if tmpClass = shape then
            set aText to object text of j
            
set mText to maskStrings(aText) of me
            
set object text of j to mText
            
          else if tmpClass = table then
            tell j
              set tmpW to width
              
set tmpH to height
              
set tumeF to false
              
set cColumn to count every column
              
              
if tmpW = 0 or tmpH = 0 then
                —
              else
                set aRatio to tmpW / tmpH
                
                
if aRatio < 0.125 then set tumeF to true
                
if cColumn = 1 then set tumeF to true
              end if
            end tell
            
            
–表がツメでない場合にのみ処理
            
if tumeF = false then
              tell j
                set aTitle to ""
                
try
                  set aTitle to name of it
                  
set mText to maskStrings(aTitle) of me
                  
set name of it to mText
                end try
                
                
set cellList to every cell
                
repeat with ii in cellList
                  set jj to contents of ii
                  
set aValue to (value of jj) as string
                  
set mText to maskStrings(aValue) of me
                  
set value of jj to mText
                end repeat
                
              end tell
              
            end if
          end if
          
        end repeat
        
      end tell
    end repeat
  end tell
end tell

–Pagesで選択中のアイテムをグループ解除する
on ungroupPagesItems(gList as list)
  set appName to "Pages" –Application Name
  
set aList to {"配置", "グループ解除"} –Localized Menu Titles (menu title structure to "Ungroup")
  
  
tell application "Pages"
    tell front document
      set selection to gList
    end tell
  end tell
  
  
set aRes to clickSpecifiedMenuElement(appName, aList) of dLib
  
return aRes
end ungroupPagesItems

–指定したルールのとおりの文字種の並びになっているか?
on maskStrings(aStr)
  set aList to characters of aStr
  
  
set chkList to {}
  
repeat with i from 1 to (length of aList)
    set j1 to contents of item i of aList
    
    
set tmpStr to j1
    
    
set j2 to (my chkNumeric:j1)
    
set j3 to (my chkAlphabetCapt:j1)
    
set j4 to (my chkAlphabetSmall:j1)
    
    
if j2 = true then
      set tmpStr to "9"
    else if j3 = true then
      set tmpStr to "Z"
    else if j4 = true then
      set tmpStr to "z"
    else
      set tmpStr to "あ"
    end if
    
    
set the end of chkList to tmpStr
  end repeat
  
return chkList as string
end maskStrings

— アルファベット大文字か
on chkAlphabetCapt:checkString
  set aStr to current application’s NSString’s stringWithString:checkString
  
set allCharSet to current application’s NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabetCapt:

— アルファベット小文字か
on chkAlphabetSmall:checkString
  set aStr to current application’s NSString’s stringWithString:checkString
  
set allCharSet to current application’s NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabetSmall:

–数字のみか
on chkNumeric:checkString
  set digitCharSet to current application’s NSCharacterSet’s characterSetWithCharactersInString:"0123456789"
  
set ret to my chkCompareString:checkString baseString:digitCharSet
  
return ret as boolean
end chkNumeric:

–アルファベットと数字のみか
on chkAlphaNumeric:checkString
  set alnumCharSet to current application’s NSCharacterSet’s alphanumericCharacterSet()
  
set ret to my chkCompareString:checkString baseString:alnumCharSet
  
return ret as boolean
end chkAlphaNumeric:

–アルファベットと数字と記号のみか
on chkAlphaNumericSymbol:checkString
  set muCharSet to current application’s NSCharacterSet’s alphanumericCharacterSet()’s mutableCopy()
  
muCharSet’s addCharactersInString:"$\"!~&=#[]._-+`|{}?%^*/’@-/:;(),"
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkAlphaNumericSymbol:

–記号のみか
on chkSymbol:checkString
  set muCharSet to current application’s NSCharacterSet’s alloc()’s init()
  
muCharSet’s addCharactersInString:"$\"!~&=#[]._-+`|{}?%^*/’@-/:;(),"
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkSymbol:

–全角文字が存在するか
on chkMultiByteChar:checkString
  set aStr to current application’s NSString’s stringWithString:checkString
  
set aRes to aStr’s canBeConvertedToEncoding:(current application’s NSASCIIStringEncoding)
  
return (aRes as boolean)
end chkMultiByteChar:

on chkCompareString:checkString baseString:baseString
  set aScanner to current application’s NSScanner’s localizedScannerWithString:checkString
  
aScanner’s setCharactersToBeSkipped:(missing value)
  
aScanner’s scanCharactersFromSet:baseString intoString:(missing value)
  
return (aScanner’s isAtEnd()) as boolean
end chkCompareString:baseString:

on chkCompareString:checkString characterSet:baseSet
  set anNSString to current application’s NSString’s stringWithString:checkString
  
set theRange to anNSString’s rangeOfCharacterFromSet:baseSet
  
return (|length| of theRange = 0) as boolean
end chkCompareString:characterSet:

★Click Here to Open This Script 

Posted in Object control | Tagged 13.0savvy 14.0savvy 15.0savvy Pages | Leave a comment

Pages書類の内容を伏せ字に

Posted on 10月 3, 2024 by Takaaki Naganoya

現在オープン中の最前面のPages書類の内容を伏せ字に置き換えるAppleScriptです。

新刊「Pages+AppleScriptで本をつくろう!」の作成のために書いたものです。Pages書類を付録として電子書籍に添付する場合に、あくまでデザインテンプレートとしての利用を見込んでいるため、本文がそのまま入っていると困るわけです、私が。

そんなわけで、せっかく作ったPages書類の内容を伏せ字にして、ダミー書類化するためのAppleScriptが必要になったわけです。

一応、テキストを伏せ字にするAppleScriptは作ってあったので、これをPages書類相手に処理するよう書き換えたものがこれです。


▲処理前


▲処理後

ただし、すべてのPages書類内のオブジェクトに対応していません。groupオブジェクトについては、メニュー操作を行えばグループ解除を行えなくもないですが、未着手です。

ちょっと気をつけて処理したのが「表」の内部セルに入っている値です。空欄だと値(value)がmissing valueになるので、そこは触らないほうがよかったかもしれません。

自分だけの事情になりますが、ページ左右端に「ツメ」と呼ばれるマークを「表」オブジェクトを用いて記入しているため、この「ツメ」に相当する「表」については無視するようにしています。

AppleScript名:全ページを伏せ字に.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/10/02
—
–  Copyright © 2024 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 pCount to count every page
    
repeat with p from 1 to pCount
      tell page p
        set aList to every iWork item
        
        
repeat with i in aList
          set j to contents of i
          
set tmpClass to class of j
          
          
if tmpClass = shape then
            set aText to object text of j
            
set mText to maskStrings(aText) of me
            
set object text of j to mText
            
          else if tmpClass = group then
            
            
            
          else if tmpClass = table then
            tell j
              set tmpW to width
              
set tmpH to height
              
set tumeF to false
              
set cColumn to count every column
              
              
if tmpW = 0 or tmpH = 0 then
                —
              else
                set aRatio to tmpW / tmpH
                
                
if aRatio < 0.125 then set tumeF to true
                
if cColumn = 1 then set tumeF to true
              end if
            end tell
            
            
–表がツメでない場合にのみ処理
            
if tumeF = false then
              tell j
                set aTitle to ""
                
try
                  set aTitle to name of it
                  
set mText to maskStrings(aTitle) of me
                  
set name of it to mText
                end try
                
                
set cellList to every cell
                
repeat with ii in cellList
                  set jj to contents of ii
                  
set aValue to (value of jj) as string
                  
set mText to maskStrings(aValue) of me
                  
set value of jj to mText
                end repeat
                
              end tell
              
            end if
          end if
          
        end repeat
        
      end tell
    end repeat
  end tell
end tell

–指定したルールのとおりの文字種の並びになっているか?
on maskStrings(aStr)
  set aList to characters of aStr
  
  
set chkList to {}
  
repeat with i from 1 to (length of aList)
    set j1 to contents of item i of aList
    
    
set tmpStr to j1
    
    
set j2 to (my chkNumeric:j1)
    
set j3 to (my chkAlphabetCapt:j1)
    
set j4 to (my chkAlphabetSmall:j1)
    
    
if j2 = true then
      set tmpStr to "9"
    else if j3 = true then
      set tmpStr to "Z"
    else if j4 = true then
      set tmpStr to "z"
    else
      set tmpStr to "あ"
    end if
    
    
set the end of chkList to tmpStr
  end repeat
  
return chkList as string
end maskStrings

— アルファベット大文字か
on chkAlphabetCapt:checkString
  set aStr to current application’s NSString’s stringWithString:checkString
  
set allCharSet to current application’s NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabetCapt:

— アルファベット小文字か
on chkAlphabetSmall:checkString
  set aStr to current application’s NSString’s stringWithString:checkString
  
set allCharSet to current application’s NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabetSmall:

–数字のみか
on chkNumeric:checkString
  set digitCharSet to current application’s NSCharacterSet’s characterSetWithCharactersInString:"0123456789"
  
set ret to my chkCompareString:checkString baseString:digitCharSet
  
return ret as boolean
end chkNumeric:

–アルファベットと数字のみか
on chkAlphaNumeric:checkString
  set alnumCharSet to current application’s NSCharacterSet’s alphanumericCharacterSet()
  
set ret to my chkCompareString:checkString baseString:alnumCharSet
  
return ret as boolean
end chkAlphaNumeric:

–アルファベットと数字と記号のみか
on chkAlphaNumericSymbol:checkString
  set muCharSet to current application’s NSCharacterSet’s alphanumericCharacterSet()’s mutableCopy()
  
muCharSet’s addCharactersInString:"$\"!~&=#[]._-+`|{}?%^*/’@-/:;(),"
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkAlphaNumericSymbol:

–記号のみか
on chkSymbol:checkString
  set muCharSet to current application’s NSCharacterSet’s alloc()’s init()
  
muCharSet’s addCharactersInString:"$\"!~&=#[]._-+`|{}?%^*/’@-/:;(),"
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkSymbol:

–全角文字が存在するか
on chkMultiByteChar:checkString
  set aStr to current application’s NSString’s stringWithString:checkString
  
set aRes to aStr’s canBeConvertedToEncoding:(current application’s NSASCIIStringEncoding)
  
return (aRes as boolean)
end chkMultiByteChar:

on chkCompareString:checkString baseString:baseString
  set aScanner to current application’s NSScanner’s localizedScannerWithString:checkString
  
aScanner’s setCharactersToBeSkipped:(missing value)
  
aScanner’s scanCharactersFromSet:baseString intoString:(missing value)
  
return (aScanner’s isAtEnd()) as boolean
end chkCompareString:baseString:

on chkCompareString:checkString characterSet:baseSet
  set anNSString to current application’s NSString’s stringWithString:checkString
  
set theRange to anNSString’s rangeOfCharacterFromSet:baseSet
  
return (|length| of theRange = 0) as boolean
end chkCompareString:characterSet:

★Click Here to Open This Script 

Posted in Object control Text | Tagged 13.0savvy 14.0savvy 15.0savvy Pages | Leave a comment

新刊電子書籍「Pages+AppleScriptで本をつくろう!」を刊行

Posted on 10月 3, 2024 by Takaaki Naganoya

電子書籍新刊「Pages+AppleScriptで本をつくろう!」を刊行しました。全370ページ、サンプルAppleScriptアーカイブつき。
→ 販売ページ

本書は、Appleのかんたんワープロ「Pages」の使い方を「本づくり」という観点からわかりやすくまとめたものです。

本という「お約束の塊」について、それぞれの部品をどのように作っているか、実例にもとづいてご紹介しています。本書を作ったときのPages書類を含め、用例をオマケとして添付しています。

Pagesはシンプルで強力な機能を備えていますが、シンプルであるがゆえに手間が増えてしまうケースがままあります。

これに対して、macOSのスクリプト言語である「AppleScript」を利用することで、手間のかかる作業を省ける構造になっています。

本書では、筆者がPagesを使って本を作るなかで、「どうしてもこれが必要」と感じた内容をまとめたAppleScriptを付録としてご提供しています。

本書をお買い求めいただくことで、どなたも同じ道具を使って手軽に電子書籍コンテンツを作る環境とノウハウを得られる、と自負するものです。

目次

準備編

1章

電子書籍の筆者になろう!

2章

本を作るために、Pagesになれよう!
Pagesで作る「本」とは?
Pagesのツールバー設定
Pagesの参考書
AppleScriptでパワーアップ

3章

Pagesの基本操作
テキスト
表
写真
図形
欄外の表記

実践編

4章

「本」を作る作業に慣れよう!
本を作る「作業」の流れ
Pages、4つのオキテ
PDF書き出し
Skim PDF Viewerの使い方

5章

本の部品を作る作業に慣れよう!
表紙
記事一覧でもある「目次」
読者へのあいさつ「まえがき」
仁義のための登録商標表記
記事本文ページ
記事を区切る「章トビラ」
本の名刺「奥付」
本の余韻を生む「裏表紙」
ページの左右を調整する「空白」

6章

Pagesのレイアウトに翻訳

7章

本は「顔」(表紙)が命
応用編

8章

頒布/配布方法を選ぼう

9章

作成した電子書籍を各種Book Storeへ
電子書籍をクリエーター天国のBOOTHで販売
電子書籍をAmazon Kindleで販売!
各電子書籍ストアの「検閲」

10章

Mac App Storeから取得
ユーザー辞書の作り方
表情豊かな、フォントをそろえよう!
フリーで利用できるイラスト/画像素材を活用しよう!
本の構造を知ろう!
プリンタで両面印刷してホチキス製本
コンビニのコピー機で出力してホチキス製本
付録AppleScriptについて
①PDF書き出し+結合
②ツメ操作
③パーソナル面付け
④PDFへのTOC追加
⑤テキストボックス操作
⑥表の列幅、行高さ調整
⑦フォント情報収集
⑧ファイル名(章)修正
⑨ファイル名(仮想ノンブル)修正
⑩PDF操作
筆者が刊行した電子書籍の仕様
Pagesのバージョン履歴

Posted in Books news | Tagged 13.0savvy 14.0savvy 15.0savvy Pages | Leave a comment

Safari v18のtabのpidを取得

Posted on 9月 21, 2024 by Takaaki Naganoya

新たにリリースされたSafari v18(macOS 13/14/15用)で、各Tabに「pid」属性が新設されました。

各Webコンテンツのブラウズを行う処理プロセスを、独立したプロセスで行うことで、メモリの食いすぎでプロセスが止まったような場合にでも他のWebブラウジングに影響を与えない、というあたりにメリットがあったとか。


▲Safari v17とv18のAppleScript用語辞書(sdef)を比較したところ


▲SafariでYouTube上のムービーを再生しているところ


▲アクティビティモニタ上で該当するpidのプロセスを確認

pidがわかると、どういう「いいこと」があるのかが問題です。メモリの使用状況などを確認することはできますし、個別にプロセスをkillすることもできるわけですが、そこまでやるんだろうかと。そういうニーズがあって新設したのか、ちょっとわからないところです。

それはともかく、Safari(≒WebKit)系はゴミプロセスがメモリ上に残りまくるので(Mail.appもメッセージを表示するだけでゴミプロセスが残るし)、その点がちょっとどうなのかという点と、Webコンテンツ上の画像ボタンを文字認識しておかしな動作をしまくるので、そのあたりは勘弁してほしいところです。

AppleScript名:Safariのtabのpidを取得.scpt
tell application "Safari"
  tell window 1
    set aList to pid of every tab
    
–> {33892}
  end tell
end tell

★Click Here to Open This Script 

Posted in news Object control | Tagged 13.0savvy 14.0savvy 15.0savvy Safari | Leave a comment

iCalendarファイルの作成

Posted on 9月 20, 2024 by Takaaki Naganoya

オープンソースのプロジェクト「iCal4ObjC」をFramework化してAppleScriptから呼び出し、iCalendarファイル(.ics)をデスクトップに作成するテストコードです。実行には、iCalendarKit.framework(macOS 10.15以降用にUniversal Binaryでビルド)を必要とします。また、macOS標準搭載のスクリプトエディタ上では動作せず、Script DebuggerないしSDから書き出したEnhanced Appletとして動かす必要があります。

–> DownloadiCalendarKit.framework (To ~/Library/Frameworks)

本Scriptの実行結果です。

AppleScript名:iCal4ObjCのじっけん(iCalendarファイルの作成).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/09/20
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use framework "iCalendarKit" –https://github.com/cybergarage/iCal4ObjC
use scripting additions

set ical to current application’s CGICalendar’s alloc()’s init()

–Add an object
set icalObj to current application’s CGICalendarObject’s alloc()’s initWithProdid:"//CyberGarage//iCal4ObjC//EN"

–Add a component
set icalComp to current application’s CGICalendarComponent’s alloc()’s initWithType:"VTODO"
icalObj’s addComponent:icalComp

ical’s addObject:icalObj

— Add a property
set icalProp to current application’s CGICalendarProperty’s alloc()’s init()
icalProp’s setName:"SUMMARY"
icalProp’s setValue:"Write report"
icalComp’s addComponent:icalProp

set outPath to POSIX path of (path to desktop) & (do shell script "uuidgen") & ".ics"

ical’s writeToFile:outPath

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.15savvy 11.0savvy 12.0savvy 13.0savvy 14.0savvy 15.0savvy | Leave a comment

Script DebuggerがmacOS 15.x上で起動せず→起動

Posted on 9月 18, 2024 by Takaaki Naganoya

Script DebuggerがmacOS 15上で起動しない状況が続いています。

日本語ユーザー環境、英語ユーザー環境にかかわらずmacOS 15/macOS 15.1上でScript Debuggerが起動しません。

ちなみに、macOS 14.7ではユーザーディレクトリ下のFrameworkを実行できない問題も発生しており、macOS 14/15を信用せずにメイン環境をmacOS 13.7のままにとどめていますが、この判断が大正解のようです。

続報:
rm ~/Library/Preferences/.2xbG4@@Ght01%!020#u

rm ~/Library/Preferences/.2xbZ4@@Ght01%!010#u

rm ~/Library/Application\ Support/.1@xX4D@yyt02"!2&0#a

rm ~/Library/Application\ Support/.1@xX4D@yytT2"!2&1#a

とすることで、macOS 15.x上でもScript Debuggerが起動できました。実際には、Terminal上でこれをそのまま実行しても削除できなかったので、当該フォルダに移動してTerminal上でファイルを確認したうえで削除しました。

SDが起動できないと、Framework呼び出しを行なっているAppleScriptの実行や書き出しに支障が出るため、実に困ります。

ただ、SDのアップデートやメンテナンスが数少ない開発者によって支えられている以上、代替策も用意しておきたいところです。

Posted in Bug | Tagged 13.0savvy 14.0savvy 15.0savvy Script Debugger | Leave a comment

Finderのfileのkind(種類)の日本語ローカライズ内容がmacOS 14以降で変更されている件(続報)

Posted on 9月 17, 2024 by Takaaki Naganoya

FinderやSystem Eventsで扱っているファイルの種別(kind)属性情報が、macOS 14以降で変更になっていて困っている件、その後の続報です。

おそらく、多言語ローカライズを行なっている下請け業者(いろんなメーカーのローカライズを担当している多言語ローカライザー企業)へのApple側からの指示内容に何か変化があって、不必要な部分までローカライズ内容の統一(≒修正)が行われてしまったのだろう、と見立てていました。

実際に身の回りのマシンで調査したところ、おおよそその見立てで間違っていないようです。

もとになっている英語版の表記については割と一貫性があって、コロコロ方針が変わっているようには見えません。

しかし、日本語ローカライズされた属性値については不可解というか「これを指示した人間の知性を疑う」という変わりっぷりであり、そこまで想定していなかったUS Apple側の指示内容がいいかげんだった、という想像を裏付けるものとなっています。

ローカライズにおいては変更しても意味がないし、変更することで悪影響が出る部分もあるわけですが、そこまで細かくチェックしていないということなんでしょう。

Posted in Bug Localize | Tagged 14.0savvy 15.0savvy | Leave a comment

Script Debugger v8.0.8 ホームディレクトリ以下のFrameworkを実行できない障害が発生

Posted on 9月 16, 2024 by Takaaki Naganoya

# 訂正:Script Debugger自体を再起動したら動くようになりました。何をやってもmissing valueしか返らなくなってビビりました。

ユーザーディレクトリ下のCocoa FrameworkをロードしてAppleScriptから実行可能なScript DebuggerおよびそのEnhancesd Applet。最新版のv8.0.8で、ホームディレクトリ下に配置したこれらCocoa Frameworkの実行ができないことを確認しています。

ちょっと凝ったAppleScriptでバンドル内にFrameworkを入れて呼び出しているものについては、目下実行できない状況にあります。自分が確認したのはmacOS 14.7環境。呼び出したはいいものの結果にmissing valueが返ってきて、首をひねっていたところ、原因がScript Debuggerにあることを確認。

自分でビルドした野良Cocoa Frameworkや、Bridge Plusの内蔵Frameworkまで、みんな呼び出せない状況です(日本語ユーザー環境)。

画像の余白トリミングから2D Arrayの高速ソーティングなど、Framework呼び出しは日常的なAppleScriptの実行に欠かせないものです。

Posted in Bug | Tagged 14.0savvy Script Debugger | 3 Comments

iWork Appsでオブジェクトの削除を安全に

Posted on 9月 14, 2024 by Takaaki Naganoya

iWork Apps(Keynote、Pages、Numbers)にはAppleScript系の機能でいろいろ勘弁してほしい仕様がありますが、その中でも最大のものが、書類内の各オブジェクトがIndexで管理されていることです。

Indexというのは、1からはじまる連番の数値です。

iWork Apps(Keynote、Pages、Numbers)のドキュメント上でオブジェクトの削除を行おうとすると、「地獄」を見ることになります。

iWork Appsの書類上でオブジェクトの削除を行うと、このIndex値が振り直されてしまうために、正しく「対象」を指し示すことが(途中から)できなくなってしまうのです。あるいは、まったく関係のない別のオブジェクトが削除されるとか。

これが、idで管理されていれば、何かのオブジェクトを削除されても影響はありません。何かUUID的な重複しないidが割り振られて、最初から最後まで(アプリケーションが起動してから終了するまで、あるいは書類がオープンされてからクローズされるまで)個別に識別されます。

対策

各オブジェクトを識別する場合に、それ専用の属性値を持たせることがあります。

Adobe InDesign:script label AppleScriptから設定・確認が可能なラベル(文字列)を設定できる

もともとある仕組みを本来の目的以外の用途に使うことができるケースもあります。

OmniGraffle:URL urlとかいいつつ、文字列だったらだいたいなんでも入った記憶が

そして、iWork Apps(Keynote、Pages、Numbers)。普段ほとんど使わなくて、AppleScriptから操作できて害のない属性値なんて便利なものがあるわけが……ありました。

Keynoteで使っている例は見かけましたが、他で使ったことのない「reflectin value」。つまり、「反射」属性。

PagesでもNumbersでも使ったことがありません。個人的には、Keynoteでも使ったことがないと思います。

選択状態にあるオブジェクトをもとに何らかの処理を行なって、選択していたオブジェクトを削除する場合に、普通に処理すると(オブジェクトがIndexで管理されているので)、地獄を見ます。

なので、削除対象のオブジェクトのreflection valueに100とか(1〜100のうち、0でないお好きな値を)を設定しておいて、ひととおり処理し終わったら、reflection valueが指定値になっているオブジェクトだけをフィルタ参照で削除する、といった対策が有効です。

実際のAppleScript

前処理Scriptで、最初にreflection valueが何か設定されているオブジェクトが存在しないことを確認したうえで、選択中のオブジェクトのreflection valueに100を設定し……

AppleScript名:削除_前処理.scptd
tell application "Pages"
  tell front document
    set reList to every iWork item whose reflection value is 100
    
if length of reList is not equal to 0 then return
    
    
set aSel to selection
    
repeat with i in aSel
      set j to contents of i
      
set reflection value of j to 100
    end repeat
  end tell
end tell

★Click Here to Open This Script 

処理を行なったあとで、reflection valueに100と設定されているオブジェクトを削除します。

AppleScript名:削除_後処理.scptd
tell application "Pages"
  tell front document
    tell current page
      set aSel to delete (every iWork item whose reflection value = 100)
    end tell
  end tell
end tell

★Click Here to Open This Script 

Posted in Object control | Tagged 13.0savvy 14.0savvy 15.0savvy Keynote Numbers Pages | Leave a comment

Pixelmator Proがv3.6.8でHDR画像をサポート

Posted on 9月 1, 2024 by Takaaki Naganoya

Pixelmator Proがv3.6.8でHDR画像のサポートを追加しました。

Pixelmator Pro 3.3.13–> 3.6.8

AppleScript用語辞書の比較で確認された変化は以下のとおりです。

・予約語「JPEG」の類義語として「JPG」を追加定義
・HDR画像の予約語を追加(OpenExr、HDR JPEG、HDR HEIC、HDR AVIF、HDR PNG)
・applicationのプロパティとして「load hdr content」を新設
・documentのプロパティとして「display hdr content」を新設

HDR対応について

Appleの公式資料によれば、現行機種はHDRに対応しているとのこと。

ただし、接続しているディスプレイによって、

「このディスプレイはHDRコンテンツをサポートしていません」(Mac mini M1+Apple Cinema Display)
「このディスプレイはHDRコンテンツのサポートが制限されています」(MacBook Air M2)

といったように、非対応/対応(不完全対応を含む)と状態が分かれるようです。

対応環境でPixelmator ProのHDRサポート状態を変更してHDR画像をオープンする実験は行なってみました。


▲Pixelmator Proの設定ウィンドウ HDRコンテンツのサポートが制限されている(MacBook Air M2)と表示


▲Pixelmator ProでサンプルのHDR JPEGをオープンしたところ

AppleScript名:HDR画像をオープン
tell application "Pixelmator Pro"
  set load hdr content to true
  
set aHDR2 to load hdr content
  
–> true
  
if aHDR2 = false then return
  
  
set aHDRfile to choose file
  
  
open aHDRfile
  
end tell

★Click Here to Open This Script 

HDR画像をオープンしても、HDR表示が行われるかどうかは別の管理になっている(documentのプロパティ)ので、そこも設定する必要があるようです。変更すると画面上でわずかに階調表現に変化が見られました(ちょっとだけ)。

AppleScript名:オープン中のHDR画像をHDR表示する
tell application "Pixelmator Pro"
  –環境チェック
  
set appHDR to load hdr content
  
if appHDR = false then return
  
  
–HDR画像の表示状態を変更
  
tell front document
    set display hdr content to true
    
set docHDR to display hdr content
  end tell
end tell

★Click Here to Open This Script 

Posted in Image Object control | Tagged 13.0savvy 14.0savvy 15.0savvy Pixelmator Pro | Leave a comment

新刊電子書籍「AppleScriptでたのしむ レトロ・グラフィック プログラム集」を刊行

Posted on 8月 31, 2024 by Takaaki Naganoya

電子書籍新刊「AppleScriptでたのしむ レトロ・グラフィック プログラム集」を刊行しました。全154ページ、サンプルAppleScriptアーカイブつき。
→ 販売ページ

1980年代や90年代の8/16ビットPCのBASICで描かせていた、三角関数による各種グラフィックスをAppleScriptで再現。ダイアログで表示するだけでなく、各種GUIアプリ(Keynote、Numbers、Pages、Excel、PowerPoint、Word、Pixelmator Pro)を操作して描画したり、画像書き出ししてAirDropでiOSデバイスに転送するようなサンプルを収録しています。

目次

1章 レトロ・グラフィックスの世界

懐かしのレトロCGの世界を再現
時代を経て感じる郷愁とも異なるテイスト
その昔、十数分かけて描いた三角関数グラフ
1秒以下で終了 vs 6分で終了
最新環境で動くAppleScriptにBASICのプログラムを移植
アップルスクリプトは、構文色分け必須の、色で要素を見分ける環境
最低限の知識でAppleScriptによるグラフィックを
AppleScript書類内に、実行に必要なライブラリを同梱
筆者の関数計算ライブラリ「calcLibAS」内蔵関数
コラム ポケコンエミュレータ“pockemul”

2章 早足で紹介するAppleScriptの世界

1994年から採用され続けている言語
GUIアプリを操作するために存在。搭載実行環境がとても多い
書き方は、アプリ内に存在する用語辞書を参照
本来の機能を利用するためにはシステム設定で許可する必要が
10.10以降でCocoaを直接呼べるようになったインタプリタ言語
GUI部品を直接操作してアプリを操作する強制操作機能が人気?
Web上のAPIを呼んでクラウド系の機能も利用
AS自体で予約語と機能を記述するライブラリ機能
コラム AppleScriptの世界の全体像 OS機能の最深部からGUIそのものの操作まで

3章 AppleScriptでグラフィックスを扱う

Cocoaの機能を呼び出してメモリ上で画像を作成
NSAlertの上にNSImageViewを作成しグラフィック表示
Cocoaのグラフィックス座標系”
主要なアプリケーションの座標系”
画像ファイルに書き出せば”
他のアプリにコピー&ペースト”
当時は存在していなかった透過画像”
パラメータを変えると動作が変わる”
コラム GUIアプリごとの応答速度の違い

4章 レトロ・グラフィックスプログラム集

スクリプトエディタでオープンして実行するだけ
必要なライブラリはバンドル内にすべて格納
掲載リストはグラフィックス描画にかかわる箇所のみ
How to use/ダイアログ表示AppleScript
How to use/ファイル出力AppleScript
How to use/ファイル出力+AirDrop AppleScript
How to use/クリップボード転送AppleScript
How to use/各種GUIアプリ操作AppleScript
OS標準搭載の13の実行環境およびサードパーティの数十の実行環境

線画テスト
円画テスト①
円画テスト②
サイクロイド曲線
バラ曲線
パスカルの蝸牛形
リサージュ曲線
ダイヤモンドパターン
アルキメデスの螺旋
メキシカンハット①
メキシカンハット②
メキシカンハット③
メキシカンハット④
コラム マシンごとの実行速度の違い

Posted in Books news | Tagged 13.0savvy 14.0savvy 15.0savvy Excel Keynote Numbers Pages Pixelmator Pro PowerPoint Word | Leave a comment

macOS 14で変更になったOSバージョン取得APIの返り値

Posted on 8月 24, 2024 by Takaaki Naganoya

macOSのバージョンを求める機能については、かならず複数の方法で取得できるように調査しています。

それは、Appleがバグを作る可能性が一番高い機能だからです(なんで懲りないんだろ?)。

OSバージョンを求めるのに、

・AppleScriptの標準装備コマンド「system info」で求める
–> {AppleScript version:”2.8″, AppleScript Studio version:”1.5.3″, system version:”13.6.9″, short user name:”XXXX”, long user name:”XXXXX XXXXX”, user ID:504, user locale:”ja_JP”, home directory:alias “Macintosh HD:Users:XXXX:”, boot volume:”Macintosh HD:”, computer name:”M1 mini”, host name:”m1mini.local”, IPv4 address:”192.168.0.99″, primary Ethernet address:”99:99:99:99:ZZ:99″, CPU type:”ARM64E”, CPU speed:missing value, physical memory:16384}

・AppleScriptの環境プロパティ「system attribute」を求める
set v1 to system attribute “sys1” –> 10
set v2 to system attribute “sys2” –> 4
set v3 to system attribute “sys3” –> 11

・shell commandで求める
–> sw_vers
–> sw_vers -productVersion

などに加えて、NSProcessInfos processInfo()’s operatingSystemVersion() を呼び出すという方法も加わりました。

ただ、これが最近おかしな挙動をするようになったのに気づいていろいろ調査してみたら、macOS 14になって返り値のフォーマットを変えたことが判明しました。ラベルつきの値(NSDictionary)で返してきたのが、ラベルなしの配列(NSArray)で返すように変わっています。macOS 10.13で座標系のデータをラベルなしで返すように変更してきたのと同様の変更が加えられています。

macOS 14.xの初期バージョンでは従来タイプの値を返してきたように記憶していますが、いつ変更したのやら。

AppleScript名:OSバージョンを求める.scpt
use AppleScript
use framework "Foundation"
use scripting additions

set pInfo to (current application’s NSProcessInfo’s processInfo()’s operatingSystemVersion())
–> {majorVersion:10, minorVersion:14, patchVersion:6}–10.14
–> {majorVersion:13, minorVersion:6, patchVersion:9}–13.6.9
–> {14, 6, 1}–14.6.1
–> {15, 1, 0}–15.0.1

★Click Here to Open This Script 

こういう基本的な情報を提供するAPIの仕様を変更することに、どういうインセンティブがあるのか不明です。変える価値があると判断したから変えたんでしょう。自分にはどういう理由なのか、さっぱり分かりません。

安全のためには、AppleScriptのビルトイン機能を使うか、OS内のplistを読み取って自分で処理するとかいった「対策」が必要なのでしょう。

Posted in System | Tagged 14.0savvy 15.0savvy | Leave a comment

デフォルトインストールされたフォント名を取得するAppleScript

Posted on 8月 3, 2024 by Takaaki Naganoya

macOSにインストールされているフォントの情報をsystem_profiler経由で取得し、各フォントのパス情報をもとに、/System/Library/Fonts以下に入っているものだけを抽出して、フォント名をリストアップするAppleScriptです。

Pages書類に含まれているフォントのうち、デフォルトインストールされたものではないものを抽出するために、OSにデフォルトインストールされたものだけを取得すべく、基礎情報を得るために書いてみたものです(現在執筆中の電子書籍「Pages+AppleScriptで本をつくろう!」の付録Scriptとして用意しました)。

事前に何か設定するといった必要はありません。スクリプトエディタやScript Debuggerで実行するだけです。

AppleScriptからフォントの存在するパス情報はなかなか取得しにくい、FontBook.appがAppleScript非対応になったので、ほぼ無理なのですが、system_profilerから取得すれば、それほど難しくありません。

実行所要時間は、

  M1 Mac mini (macOS 13.6):6秒
  M2 Mac mini(macOS 14.6):10秒
  M2 MacBook Air(macOS 14.6):15秒

ぐらいで、M1 Mac miniの速さが光ります。OSの違いから、macOS 13.6環境ではallFontsが1168、macOS 14.6環境では1603とフォント数がどうやら異なっているのですが(M2 miniも同じ)、フォント数を考慮してもM1 Mac miniの処理の速さが光ります。

もしくは、macOSのバージョンの違いにより、system_profilerの実行速度が大きく異なるとか? macOS 13.6環境と14.6環境にそれほど差があるものなんでしょうか。

無駄な処理も入っていますが、いろいろチェックしながら作ったもので、ベンチマーク用に作ったものではありません。

# M2 Airってなんでこんなに時間がかかるんだろう? 放熱台に乗せて処理しているのに。処理のほとんどの時間がsystem_profilerの実行で消費しています

AppleScript名:OSデフォルトインストールされたフォント名を取得.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/08/03
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSMutableArray : a reference to current application’s NSMutableArray
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSPropertyListFormat : a reference to current application’s NSPropertyListFormat
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSPropertyListImmutable : a reference to current application’s NSPropertyListImmutable
property NSPropertyListSerialization : a reference to current application’s NSPropertyListSerialization

script spd
  property sRes : missing value
  
property aSource : missing value
  
property bRes : missing value
  
property fontNames : {}
  
property fontPath : {}
  
property outList : {}
end script

–システムにインストールされているフォントの情報を全抽出
set sRes of spd to do shell script "system_profiler -xml SPFontsDataType"
set aSource of spd to first item of (readPlistFromStr(sRes of spd) of me)

–全フォント情報から、名称とパス情報を抽出
set bRes of spd to (((aSource of spd)’s valueForKeyPath:"_items"))
set fontNames of spd to ((bRes of spd)’s valueForKeyPath:"_name") as list
set fontPath of spd to ((bRes of spd)’s valueForKeyPath:"path") as list

–ループでOSデフォルトインストールされているフォントを抽出
set outList of spd to {}
set aCount to 1

repeat with i in (fontPath of spd)
  set j to contents of i
  
  
if j begins with "/System/Library/Fonts/" then
    –指定のフォントに複数のTypefaceが含まれていることを考慮し、情報を取り出す
    
set outItem to (((item aCount of (bRes of spd)))’s valueForKeyPath:"typefaces._name") as list
    
set the end of (outList of spd) to outItem
  end if
  
  
set aCount to aCount + 1
end repeat

–すべてのTypefaceを入れた入れ子の2D Listから1D Listに変換
set allFonts to FlattenList((outList of spd)) of me

–ドット(.)ではじまるフォントを除外
set outList to {}
repeat with i in allFonts
  set j to contents of i
  
if j does not start with "." then
    set the end of outList to j
  end if
end repeat

return outList

–stringのplistを読み込んでRecordに
on readPlistFromStr(theString)
  set aSource to NSString’s stringWithString:theString
  
set pListData to aSource’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aPlist to NSPropertyListSerialization’s propertyListFromData:pListData mutabilityOption:(NSPropertyListImmutable) format:(NSPropertyListFormat) errorDescription:(missing value)
  
return aPlist
end readPlistFromStr

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel(aRecList as list, aPredicate as string)
  set aArray to NSArray’s arrayWithArray:aRecList
  
  
set aPredicate to NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
  
set bList to filteredArray as list
  
return bList
end filterRecListByLabel

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel1(aRecList, 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

–By Paul Berkowitz
–2009年1月27日 2:24:08:JST
–Re: Flattening Nested Lists
on FlattenList(aList)
  set oldDelims to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {"????"}
  
set aString to aList as text
  
set aList to text items of aString
  
set AppleScript’s text item delimiters to oldDelims
  
return aList
end FlattenList

★Click Here to Open This Script 

Posted in Font | Tagged 12.0savvy 13.0savvy 14.0savvy 15.0savvy | Leave a comment

AppleScriptでMyriad Tables Libが使えないケース

Posted on 7月 28, 2024 by Takaaki Naganoya

Myriad Tables Lib(最新版はv1.13)はShane StanleyによるAppleScriptライブラリで、かつてのClassic MacOSに存在していたGUI記述系のOSAX(名前は忘れた)を思わせるほど柔軟性が高いAppleScriptライブラリの逸品です。

自分としては、これを用いる場合でも過度な作り込みを行わず、編集可能なデータビューワー的な機能を手軽に追加するのがよいと感じています。

自分でもさらに機能を簡略化した「display table by list」ライブラリを用意しています。

macOS自体のセキュリティ制限により使えないケースも

ところが、本ライブラリが機能しないケースが確認されました。

特定の呼び方を行うと、ダイアログ+表の表示そのものが封じられるという、macOS側の新たな制限によるもののようです。

そのため、自分がmacOS 10.12用にAppleScriptで開発したシステムが、現在のmacOS 14.xで部分的に動かなくなってしまいました。目下、システムを改修中です。Myriad Tables Libを使って手抜きをしていた箇所を、すべて自力で表UI(NSTableView)を使って表示・編集する必要があるようです(けっこう大変)。

ステータスメニューから呼び出した場合にブロック

同システムはステータスメニューからタイマー機能を呼び出すようなシステムだったのですが、このメニューからMyriad Tables Libを呼び出すと、Xcode上で作成したAppleScriptアプリであっても、Script Debugger上で実行したAppleScriptであっても、表示がブロックされてしまいます。

ランタイム環境がどれであっても、ステータスメニューから呼び出してMyriad Tables Libによるテーブル表示は行えませんでした。

macOS 10.12:可能
macOS 10.13:不可
macOS 10.14:(未検証)
macOS 10.15:(未検証)
macOS 11.x:(未検証)
macOS 12.x:(未検証)
macOS 13.6:不可
macOS 14.6:不可
macOS 15β:(未検証)

これは、Script Debugger上で実行したAppleScriptから、ステータスメニュー上に動的に項目を作成し、そこにメニューを追加した場合でも、Xcode上で作成した場合でも同様の挙動が見られます。

Shaneに聞いてみた

その後、Shaneに実際に聞いてみたところ、ダイアログ表示をメインスレッド実行しないとできないらしい(意訳)ことが明らかになってきました。

ダメ元で表UIつきダイアログ表示を明示的にメインスレッド指定して実行してみたところ、ハネられました。

自作の「display table by list」ライブラリを同様に呼び出してみたところ、これも表示できませんでした。このライブラリは自分が作ったのでソースコードをすべて自分が管理しており、アラートダイアログの表示ハンドラをメインスレッド指定で呼び出しています。どの時点でメインスレッド指定実行しないとダメなのかは明確ではありませんが、割と八方ふさがりな状況です。

Posted in GUI Script Libraries Security | Tagged 13.0savvy 14.0savvy | Leave a comment

メキシカンハット v3a

Posted on 7月 28, 2024 by Takaaki Naganoya

メキシカンハットの描画AppleScriptのedama2さんバージョンで、さらに多色対応したものです。

–> Download mexicanHatv3a

AppleScript名:メキシカンハット v3a.scptd
— Created 2024-06-28 by Takaaki Naganoya
— Modified 2024-07-09 by Edama2
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use mLib : script "calcLibAS"
use imgDispLib : script "imageDisplayLib"

on run
  my main()
end run

on main()
  (*
  set userReply to display dialog "拡大率を入力してください(1-8)" default answer "3"
  set aScale to userReply’s text returned as number
  if aScale < 1 or 8 < aScale then return beep
  *)

  
set aScale to 3
  
  
–描画
  
set listBezierPaths to {}
  
repeat 3 times
    set listBezierPaths’s end to current application’s NSBezierPath’s bezierPath()
  end repeat
  
  
–https://x.com/yone/status/1805552100400939161
  
set D to {}
  
set dR to pi / 180
  
  
repeat 255 times
    set end of D to 192
  end repeat
  
  
repeat with y from -120 to 120 by 4
    
    
if y < 0 then
      set rY to -60
    else
      set rY to 60
    end if
    
    
repeat with x from -180 to 180 by 4
      
      
if (x < -60) then
        set rX to -120
      else if (x < 60) then
        set rX to 0
      else
        set rX to 120
      end if
      
      
set rR to (x – rX) ^ 2 + (y – rY) ^ 2
      
set z to 180 * (exp (rR / -800))
      
set sX to floor (128 + x / 2 – y / 4)
      
set sY to floor (128 – y / 4 – z / 2)
      
      
if not (sX < 0 or 256 ≤ sX) then
        if not ((D’s item (sX + 1)) ≤ sY) then
          
          
set zz to (floor (z * 0.0389)) + 1
          
log result
          
set idRect to current application’s NSMakeRect(sX * aScale, sY * aScale, aScale, aScale)
          
          
if ((zz = 1) or (zz = 3) or (zz = 5) or (zz = 7)) then
            (listBezierPaths’s item 1’s appendBezierPathWithRect:idRect)
          end if
          
if ((zz = 2) or (zz = 3) or (zz ≥ 6)) then
            (listBezierPaths’s item 2’s appendBezierPathWithRect:idRect)
          end if
          
if (zz ≥ 4) then
            (listBezierPaths’s item 3’s appendBezierPathWithRect:idRect)
          end if
          
          
set (D’s item (sX + 1)) to sY
        end if
      end if
    end repeat
  end repeat
  
  
#
  
set srcWidth to 0
  
set srcHeight to 0
  
repeat with idBezierPath in listBezierPaths
    set tmpWidth to current application’s NSMaxX(idBezierPath’s |bounds|())
    
set tmpHeight to current application’s NSMaxY(idBezierPath’s |bounds|())
    
if srcWidth < tmpWidth then set srcWidth to tmpWidth
    
if srcHeight < tmpHeight then set srcHeight to tmpHeight
  end repeat
  
  
#
  
set srcSize to current application’s NSMakeSize(srcWidth, srcHeight)
  
log result
  
set srcImage to current application’s NSImage’s alloc()’s initWithSize:srcSize
  
  
set operation to current application’s NSCompositingOperationScreen
  
–>set operation to current application’s NSCompositingOperationSourceOver
  
  
repeat with num from 1 to count listBezierPaths
    
    
if num is 1 then
      set idColor to current application’s NSColor’s blueColor()
    else if num is 2 then
      set idColor to current application’s NSColor’s redColor()
    else if num is 3 then
      set idColor to current application’s NSColor’s greenColor()
    end if
    
    
tell srcImage
      lockFocus()
      
      
tell current application’s NSImage’s alloc()
        tell initWithSize_(srcSize)
          lockFocus()
          
idColor’s setFill()
          
listBezierPaths’s item num’s fill()
          
unlockFocus()
          (
its drawAtPoint:(current application’s NSZeroPoint) fromRect:(current application’s NSZeroRect) operation:operation fraction:1.0)
        end tell
      end tell
      
      
unlockFocus()
    end tell
  end repeat
  
  
  
# 反転して合成
  
set dstImage to current application’s NSImage’s alloc()’s initWithSize:srcSize
  
tell dstImage
    lockFocus()
    
    
current application’s NSColor’s blackColor()’s setFill()
    
current application’s NSRectFill(current application’s NSMakeRect(0, 0, its |size|()’s width, its |size|()’s height))
    
    
set xform to current application’s NSAffineTransform’s transform()
    
xform’s translateXBy:0.0 yBy:(its |size|()’s height)
    
xform’s scaleXBy:1.0 yBy:-1.0
    
xform’s concat()
    
    
srcImage’s drawInRect:(current application’s NSMakeRect(0, 0, its |size|()’s width, its |size|()’s height))
    
unlockFocus()
  end tell
  
  
–結果表示
  
dispImage(dstImage, "Mexican Hat") of imgDispLib
end main

★Click Here to Open This Script 

Posted in GUI | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

メキシカンハット v3

Posted on 7月 28, 2024 by Takaaki Naganoya

メキシカンハットの描画AppleScriptの、edama2さんバージョンです。

–> Download mexicanHatv3

AppleScript名:メキシカンハット v3.scptd
— Created 2024-06-28 by Takaaki Naganoya
— Modified 2024-07-09 by Edama2
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use mLib : script "calcLibAS"
use imgDispLib : script "imageDisplayLib"

on run
  my main()
end run

on main()
  (*
  set userReply to display dialog "拡大率を入力してください(1-8)" default answer "3"
  set aScale to userReply’s text returned as number
  if aScale < 1 or 8 < aScale then return beep
  *)

  
set aScale to 3
  
  
  
–描画
  
set idBezierPath to current application’s NSBezierPath’s bezierPath()
  
  
–https://x.com/Stosstruppe/status/1279774386396880897
  
set dT to {}
  
set dB to {}
  
  
repeat 256 times
    set dT’s end to 192
  end repeat
  
repeat 256 times
    set dB’s end to -1
  end repeat
  
  
repeat with y from -120 to 120 by 4
    
    
if y < 0 then
      set rY to -60
    else
      set rY to 60
    end if
    
    
repeat with x from -180 to 180 by 4
      
      
if (x < -60) then
        set rX to -120
      else if (x < 60) then
        set rX to 0
      else
        set rX to 120
      end if
      
      
set rR to (x – rX) ^ 2 + (y – rY) ^ 2
      
set z to 180 * (exp (rR / -800))
      
set cX to floor (128 + x / 2 – y / 4)
      
set cY to floor (128 – y / 4 – z / 2)
      
      
if not (cX < 0 or 256 ≤ cX) then
        set pSet to false
        
        
if ((dT’s item (cX + 1)) > cY) then
          set (dT’s item (cX + 1)) to cY
          
set pSet to true
        end if
        
if ((dB’s item (cX + 1)) < cY) then
          set dB’s item (cX + 1) to cY
          
set pSet to true
        end if
        
        
if pSet then
          set idRect to current application’s NSMakeRect(cX * aScale, cY * aScale, aScale, aScale)
          (
idBezierPath’s appendBezierPathWithRect:idRect)
        end if
        
      end if
    end repeat
  end repeat
  
  
log idBezierPath’s |bounds|()
  
set srcWidth to current application’s NSMaxX(idBezierPath’s |bounds|())
  
set srcHeight to current application’s NSMaxY(idBezierPath’s |bounds|())
  
set srcSize to current application’s NSMakeSize(srcWidth, srcHeight)
  
log result
  
  
–set idColor to current application’s NSColor’s blueColor()
  
–set idColor to current application’s NSColor’s redColor()
  
set idColor to current application’s NSColor’s greenColor()
  
  
tell current application’s NSImage’s alloc()
    tell initWithSize_(srcSize)
      lockFocus()
      
idColor’s setFill()
      
idBezierPath’s fill()
      
unlockFocus()
      
set srcImage to it
    end tell
  end tell
  
  
# 反転して合成
  
set dstImage to current application’s NSImage’s alloc()’s initWithSize:srcSize
  
tell dstImage
    lockFocus()
    
    
current application’s NSColor’s blackColor()’s setFill()
    
current application’s NSRectFill(current application’s NSMakeRect(0, 0, its |size|()’s width, its |size|()’s height))
    
    
set xform to current application’s NSAffineTransform’s transform()
    
xform’s translateXBy:0.0 yBy:(its |size|()’s height)
    
xform’s scaleXBy:1.0 yBy:-1.0
    
xform’s concat()
    
    
srcImage’s drawInRect:(current application’s NSMakeRect(0, 0, its |size|()’s width, its |size|()’s height))
    
unlockFocus()
  end tell
  
  
–結果表示
  
dispImage(dstImage, "Mexican Hat") of imgDispLib
end main

★Click Here to Open This Script 

Posted in GUI | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • AppleScriptによる並列処理
  • Cocoa Scripting Course 続刊計画
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • Keynote、Pages、Numbers Ver.14.0が登場
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • AppleScript入門① AppleScriptってなんだろう?
  • Numbersで最前面の書類のすべてのシート上の表の行数を合計
  • macOS 14で変更になったOSバージョン取得APIの返り値

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (130) CotEditor (66) Finder (51) iTunes (19) Keynote (117) 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 (76) Pages (55) 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
  • date
  • 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年4月
  • 2025年3月
  • 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