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

タグ: 12.0savvy

macOS 12.4beta1で「GUIなしツールから起動したAppleScriptでUTIを取得できない」バグ?

Posted on 4月 18, 2022 by Takaaki Naganoya

スクリプトメニューやService Stationなど、「メニューやウィンドウを持たないGUIなしツール」がたくさんmacOS環境にありますが、macOS 12.4上ではこれらのAppleScript起動ツールから起動したAppleScriptから、UniformtypeIdentifiers.frameworkを用いたUTIの取得をブロックされているようです。

スクリプトメニューで実行を確認した(途中までで実行がブロックされてしまった)AppleScriptを、スクリプトエディタ上で実行したところ、問題なく実行されます。ちなみに、内容は選択した画像ファイルをPixelmator Proで超解像処理してクリップボードに設定する(コピーする)という「おかわいらしい」内容のものです。

Service Stationは、コンテクストメニューからのAppleScript実行を可能にするAppleScript実行ツールですが、これについてもしかるべきハンドラを書いて同じAppleScriptを実行させるようにしてみたものの、UTIの取得をブロックされるようです。

→ 追試で、Terminal.app上からosascript経由で実行してみたところ、UniformtypeIdentifiers.frameworkの呼び出しに失敗することが判明

明示的にMain threadで実行しないとダメ???>UniformtypeIdentifiers.framework

AppleScript名:🟧選択中の画像を超解像💝処理してコピー.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/03/25
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8" — Yosemite (10.10) or later
use framework "Foundation"
use framework "UniformtypeIdentifiers"
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 acceptUTI to "public.image"

set aFile to choose file
(*
tell application "Finder"
  set aFile to first item of (selection as alias list)
end tell
*)

–set aUTI to getUTIFromFile(aFile) of me –選択ファイルからUTIを
–display dialog aUTI
–if aUTI is equal to missing value then return

–set uRes to filterUTIList({aUTI}, acceptUTI) of me –選択ファイルのUTIが、受付可能UTIに含まれるかどうかチェック
–if uRes is equal to {} then return –選択したファイルが画像ではなかった

–掃除
tell application "Pixelmator Pro" to close every document without saving

–取得した画像を超解像処理してコピー
tell application "Pixelmator Pro"
  try
    open aFile
  on error
    close every document without saving
    
return
  end try
  
  
tell front document
    with timeout of 3000 seconds
      super resolution
    end timeout
  end tell
end tell

tell application "Pixelmator Pro"
  tell front document
    select all
    
copy
    
close without saving
  end tell
end tell

on getUTIFromFile(aFile)
  set aPath to POSIX path of aFile
  
  
set aWS to current application’s NSWorkspace’s sharedWorkspace()
  
set pRes to (aWS’s isFilePackageAtPath:aPath) as boolean
  
if pRes = false then
    set superType to (current application’s UTTypeData)
  else
    set superType to (current application’s UTTypePackage)
  end if
  
  
set pathString to current application’s NSString’s stringWithString:aPath
  
set aExt to (pathString’s pathExtension()) as string
  
  
set aUTType to current application’s UTType’s typeWithFilenameExtension:aExt conformingToType:(superType)
  
  
set aUTIstr to aUTType’s identifier() as string
  
return aUTIstr
end getUTIFromFile

–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 Bug news UTI | Tagged 12.0savvy Pixelmator Pro Service Station | Leave a comment

Keynoteで選択中のtext itemとshapeをもとにtext itemを敷き詰める

Posted on 4月 15, 2022 by Takaaki Naganoya

Keynote v12で正常化した「selection」を用いて、選択中のshapeオブジェクトの範囲に、選択中のtext itemを指定数敷き詰めるAppleScriptです。

–> Watch Demo Movie

Keynote書類上に、敷き詰める領域を示すshapeオブジェクトを1つ、敷き詰める内容を示すtext itemオブジェクトを1つ配置し、これら2つを選択して本Scriptを実行。

選択状態で実行。

指定の最小文字サイズから最大文字サイズ(Keynote書類上で選択したtext item中の文字サイズ)までの間で乱数選択しつつ、指定個数を指定エリア中に作成します。

AppleScript名:選択中のtext itemとshapeをもとにtext itemを敷き詰める.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/04/15
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

property textItem : missing value
property shapeItem : missing value

property objMax : 200 –生成するオブジェクト(text item)の個数
property fontSizeMin : 12 –生成するオブジェクト内のobject textのフォントサイズ(これ以下のサイズは生成しない)

tell application "Keynote"
  set aVer to (version as real)
  
if aVer < 12 then return
  
  
tell front document
    –書類上で選択中のオブジェクトを種別に抽出する
    
set aaSel to selection
    
if length of aaSel is not equal to 2 then error "You have to select one text item and one shape."
    
    
repeat with i in aaSel
      set j to contents of i
      
set tmpClass to class of j
      
      
if tmpClass = text item and textItem = missing value then
        set textItem to j
      else if tmpClass = shape and shapeItem = missing value then
        set shapeItem to j
      end if
    end repeat
    
    
if {textItem, shapeItem} contains missing value then error "Selected objects are not suitable"
    
    
    
–選択されたshapeオブジェクトから情報を取得
    
set aPos to (position of shapeItem)
    
set minX to item 1 of aPos
    
set maxX to minX + (width of shapeItem)
    
set minY to item 2 of aPos
    
set maxY to minY + (height of shapeItem)
    
    
–選択されたtext itemオブジェクトから情報を取得
    
set maxFSize to size of object text of textItem
    
set oText to object text of textItem
    
set tWidth to width of textItem
    
set tHeight to height of textItem
    
    
    
–shapeオブジェクトで指定された領域に、text itemを生成
    
repeat objMax times
      –座標を乱数で指定
      
set randomX to random number from minX to (maxX – tWidth)
      
set randomY to random number from minY to (maxY – tHeight)
      
–文字サイズを乱数で指定
      
set randomCSize to random number from fontSizeMin to maxFSize
      
      
tell current slide
        set tmpT to make new text item with properties {object text:oText, position:{randomX, randomY}, width:tWidth, height:tHeight} at the end
        
ignoring application responses
          set size of every character of object text of tmpT to randomCSize
        end ignoring
      end tell
      
    end repeat
  end tell
end tell

★Click Here to Open This Script 

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

SF Symbolsを名称で指定してPNG画像化

Posted on 4月 15, 2022 by Takaaki Naganoya

SF Symbolsに収録されている文字を、名称で指定してデスクトップにPNG画像で書き出すAppleScriptです。

同フォントは、アプリ上のアイコン素材3,300個以上をフォント化し、再利用しやすくすることで、アイコンで何かの意図を示すことを規格化したいという、現代における象形文字の再発明みたいな存在です。

文化や人種を超えた、非言語コミュニケーションを促進するための基盤としてAppleが整備を行なっているものなんでしょう。文化を縦断したインフラみたいな。

アイコン素材を自分で作るのはつらいので、正直助かっています。Appleが配布しているSF Symbols 3アプリケーションを使って画面上でいろいろ探して、文字を指定できます。

一応、SF Symbols.app自体にも指定フォントを画像化する機能はついているのですが、レンダリング時の指定解像度が低すぎて、プレゼン資料や本のイラストとして利用するには不便すぎます(本来の利用目的である、タブバーのアイコンに指定するのには向いている解像度なんでしょうけれども)。

そこで、指定のフォントの文字を名称で指定するとPNG画像にレンダリングするAppleScriptを作成してみました。

文字を指定するのはできているのですが、フォントのファミリーとかマルチカラーとかの指定の方法がよくわかりません。

AppleScript名:SF Symbolsを名称で指定してPNG画像化 v1a.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/04/14
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.8" — Monterey (12) or later
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"
use scripting additions

set aName to "paperplane.circle.fill"
set anImage to current application’s NSImage’s imageWithSystemSymbolName:(aName) accessibilityDescription:(missing value)
set resImg to resizeNSImage(anImage, 50.0) of me

set aDesktopPath to current application’s NSString’s stringWithString:(POSIX path of (path to desktop))
set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingPathExtension:"png")

set fRes to saveNSImageAtPathAsPNG(resImg, savePath) of me

on resizeNSImage(aSourceImg, aScale)
  set aSize to aSourceImg’s |size|()
  
set newWidth to (width of aSize) * aScale
  
set newheight to (height of aSize) * aScale
  
  
set targFrame to current application’s NSMakeRect(0, 0, newWidth, newheight)
  
set targImage to current application’s NSImage’s alloc()’s initWithSize:{newWidth, newheight}
  
  
set aKey to {current application’s NSImageHintInterpolation}
  
set aObj to current application’s NSNumber’s numberWithInt:(current application’s NSImageInterpolationLow)
  
set hintRec to current application’s NSDictionary’s dictionaryWithObject:aObj forKey:aKey
  
  
targImage’s lockFocus()
  
aSourceImg’s drawInRect:targFrame fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeCopy) fraction:1.0 respectFlipped:true hints:hintRec
  
targImage’s unlockFocus()
  
  
return targImage
end resizeNSImage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in Font Image | Tagged 11.0savvy 12.0savvy SF Symbols | Leave a comment

Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加

Posted on 4月 14, 2022 by Takaaki Naganoya

いまひとつ、「こういう表現を行いたいんだけど、どう操作していいのかわからない」感のあるPixelmator Pro。毎回、メニューを漁っては「これ、どう作るんだろうーなー」という手探り感があります。

Photoshopで育って、どっぷりPhotoshopで画像処理を理解した人がPixelmator Proを理解するのに、敷居の高さを感じます。これ、絶対に「こういう完成物を作りたい」という人向けに「こういう手順で操作すればいい」というマニュアル的なものが必要です。

さて、Pixelmator Proの新バージョンv2.4.1が登場。機械学習を利用した人物写真の自動切り抜き機能が目玉のようです。



Student with laptop photo created by freepic.diller – www.freepik.com

おお!まつげの箇所だけちょっと切れてしまったけど、これはいい感じ!



Lookstudio – jp.freepik.com によって作成された people 写真

上半身はほぼ完璧! こーれーはすごい。

いろんなスナップ写真を切り抜かせてみましたが、人物の全身が写っているとヒット率が高いようです。つまり、おかしな箇所を切り抜かれる危険性が低くなるということです。白いTシャツが抜ける危険性が高いようで、、、

Pixelmator 2.4.1 AppleScript用語辞書変更内容

export formatに「Motion」(Motion project.)が追加された
コマンド「select subject」追加。
コマンド「smart refine selection」追加。
コマンド「remove background」追加。
エレメント「color adjustments layer」「effects layer」追加。

クラス「image layer」がコマンド「remove background」と「decontaminate colors」に応答するようになった。
クラス「group laye」に要素「color adjustments layer」「effects layer」を追加
クラス「color adjustments layer」「effects layer」を追加

コマンド「draw elliptical selection」の同義語(draw oval selection)を廃止
コマンド「resize image」の同義語(adjust size、image size)を廃止
コマンド「resize canvas」の同義語(adjust canvas、canvas size)を廃止

冒頭の人物自動切り抜きを行うAppleScriptを書いてみると、こんな感じです。Pixelmator ProのAppleScript用語辞書にもサンプルScriptが掲載されています。

AppleScript名:人物自動切り抜き.scpt
tell application "Pixelmator Pro"
  tell front document
    remove background –v2.4.1 or later
  end tell
end tell

★Click Here to Open This Script 

Posted in Image | Tagged 10.15savvy 11.0savvy 12.0savvy Pixelmator Pro | Leave a comment

新発売:AppleScript基礎テクニック集(4)〜AppleScript用語辞書の読み方

Posted on 4月 13, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第4巻、「AppleScript用語辞書の読み方」です。PDF 39ページ、掲載Scriptアーカイブつき。

→ 販売ページ

AppleScript用語辞書の読み方については、業務の一環として記述していても理解していない人も多いので、理解できると大きな力になる内容です。普段使っていないアプリケーションでも、AppleScriptが書きやすくなるはずです。

用語辞書の構成要素

AppleScript用語辞書ってなに?
AppleScript用語辞書を読む前に
AppleScript用語辞書を読むために必要なもの
AppleScript用語辞書の確認方法
参考資料:えせスクリプタブルなアプリケーション一覧
AppleScript用語辞書の表示内容
AppleScript用語辞書掲載のサンプルScript
AppleScript用語辞書の生ファイルを表示
参考資料:用語辞書の生ファイルを得る意義
AppleScript用語辞書の構成要素
えせスクリプタブルな用語辞書の具体例

用語辞書の読み方

GUIアプリケーション操作のAppleScript記述例
アプリケーションのオブジェクト構造を調べる
document
へたくそなサンプルScriptをわかりやすく清書
より高機能なツールによる用語辞書の確認

画面上の機能とAppleScript的な属性値の付け合わせ

オブジェクトのプロパティを取得して調査
オブジェクトの選択状態による結果の変化
オブジェクトのプロパティを取得して調査
複数クラスの属性を継承している場合に
オブジェクトのプロパティを変更するテスト

Posted in Books news | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

新発売:AppleScript基礎テクニック集(3)〜ファイル・パス処理

Posted on 4月 10, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第3巻、「ファイル・パス処理」です。PDF 38ページ、掲載Scriptアーカイブつき。

→ 販売ページ

本書は、まさに「基礎」中の「基礎」ともいえる「パス操作」の基礎的なサンプルを提示して段階的に紹介。最近はCocoaの機能ばかり使っているので、逆にFinderやSystem Events相手に苦労しました。

ファイル・パス処理

ファイル・パス関連オブジェクトの全体像
ファイルパス各形式の特徴や用途
ファイル・パス形式
ホームディレクトリのパスを取得
参考資料:path to で指定できるパラメータ
参考資料:path to temporary items
各種パス形式の変換
パスの組み立て
指定ファイルの親フォルダ(上位フォルダ)を求める
指定パスのファイル名だけを求める
指定パスの拡張子を求める
指定パスの拡張子だけを置換
指定フォルダの存在確認
指定フォルダに指定名称のファイルが存在するか確認
指定ファイルのリネーム(名称変更)
指定フォルダのリネーム(名称変更)
指定ファイルがパッケージかどうかを求める
指定パスからUTIを求める
指定パスがフォルダかどうかを求める
POSIX pathのチルダ(「~」)を展開
フルパスからチルダ(「~」)つきPOSIX pathを計算
特定パスのローカライズ名称を求める
特定パスが所属するドライブ名を求める

Posted in Books news | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

Keynoteで選択中のオブジェクトを取得して座標でソート

Posted on 4月 10, 2022 by Takaaki Naganoya

Keynote 12.0でまともになった「selection」を使って、選択状態にあるKeynote書類上のオブジェクト(text item)をX座標、Y座標でソートするAppleScriptです。

--> {{objID:2, positionY:219, myCon:"①①①①①", positionX:184}, {objID:4, positionY:492, myCon:"❷❷❷❷❷", positionX:184}, {objID:1, positionY:219, myCon:"③③③③③", positionX:1047}, {objID:3, positionY:492, myCon:"❹❹❹❹❹", positionX:1047}}

選択したtext itemを座標で並べ替え、内容を個別に評価してファイル書き出しするAppleScriptを別途用意して書籍作成用のツールとして、使っています。

書籍の作成作業用に作ったので、アホみたいに高機能です。text itemの内容をAppleScriptとして構文確認して、AppleScriptのオブジェクトを生成し、中間言語コードに解釈ずみの.scptファイルとして書き出しています(書籍のサンプルScript生成用)。こういうツールを作ってすぐに実戦投入できるのも、Keynoteのselectionがまともになったおかげです。

–> Watch Demo Movie

AppleScript名:選択中のオブジェクトを座標をもとにソート.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/04/09
—
–  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 "Keynote"
  tell front document
    set aaSel to selection
    
set posList to {}
    
set aCount to 1
    
    
repeat with i in aaSel
      set j to contents of i
      
set mySource to object text of j
      
      
tell j
        set {posX, posY} to position
      end tell
      
      
set the end of posList to {positionX:posX, positionY:posY, objID:aCount, myCon:mySource}
      
      
set aCount to aCount + 1
    end repeat
    
  end tell
end tell

set zList to sortRecListByLabel(posList, {"positionX", "positionY"}, {true, true}) of me

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as list, ascendF as list)
  set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
set aCount to length of aLabelStr
  
set sortDescArray to current application’s NSMutableArray’s new()
  
repeat with i from 1 to aCount
    set aLabel to (item i of aLabelStr)
    
set aKey to (item i of ascendF)
    
set sortDesc to (current application’s NSSortDescriptor’s alloc()’s initWithKey:aLabel ascending:aKey)
    (
sortDescArray’s addObject:sortDesc)
  end repeat
  
  
return (aArray’s sortedArrayUsingDescriptors:sortDescArray) as list
end sortRecListByLabel

★Click Here to Open This Script 

Posted in list Sort | Tagged 11.0savvy 12.0savvy Keynote | Leave a comment

iWork Appsがバージョン12.0にアップデートでselection動作正常化

Posted on 4月 9, 2022 by Takaaki Naganoya

昨日、iWork Apps(Keynote、Pages、Numbers)がVer.12.0にバージョンアップしていました。

AppleScript系ではgetコマンドが追加(Keynote、Pages)されたぐらいですが、これによって「selection」の動作がまともになりました。

前バージョンのアップデートで「スライド単位の選択」がselectionで取れなくなったことで、「何か変更しようとしている最中なんだろう」とは思っていました。予想どおりです。selection動作の空白期間を置かず、前バージョンの段階で実装されていたらもっとよかったのですが。

AppleScript対応アプリケーション、スクリプタブルなアプリケーションの世界観は、小さい世界観のものから大きい世界観のものまでいろいろです。

小さい世界観1(一番小さい):
アプリケーション起動、バージョン確認、書類のオープン、書類の印刷、アプリケーションの設定情報の確認

小さい世界観2:
小さい世界観1+アプリケーション固有のコマンドの実行

小さい世界観3:
小さい世界観2+書類やデータ作成のための機能、選択中のデータをおおまかに取得する機能
Keynote v11.xはここ

小さい世界観4:
小さい世界観3+書類上のオブジェクト作成/改変機能、選択中のデータやオブジェクトへの参照を取得する機能
Keynote v12.xはここ? まだ、Chart作成などで未サポートのグラフ形式などもあり、不完全

大きい世界観:
小さい世界観4+書類上のオブジェクトの多数を作成/改変する機能
Adobe InDesign、Word、Excel、PowerPoint、Pixelmator Proなど。かつての(v5ぐらいの)Pagesはここにいた

Keynoteでselectionを試してみたところ、何か書類上のオブジェクトを選択してselectionを実行すると、オブジェクトへの参照を(複数、リスト形式で)取れます。オブジェクトを選択した状態でなければ、書類上のどのスライドを表示中かというスライドへの参照が取得できるようです。

Keynoteにおける処理の自由度は大幅に上がりました。選択中のテキストボックスを取得できれば、その中に含まれるテキストなり書式つきテキストを取得して、書き直し、元のテキストボックスに書き戻すことができます。

選択中のイメージを取得できれば、その画像のパスを求めるかあるいはファイル名を求めて、オリジナルの画像ファイル(書類内に格納された画像、外部に存在する画像かはやってみないと)を画像フィルタ処理などを行って書き戻すといった処理が行いやすくなります。以前までのバージョンでは、選択した画像をいったんコピーしてクリップボードに格納し、そのクリップボード内の画像に対して画像処理していました。

Pagesでも、さまざまなオブジェクトへの参照がselectionによって取得できますが、あいかわらず「ページ」という概念があるんだかないんだか不明で、アプリケーションの根幹にかかわる部分なのでいまひとつ気軽に言えないところではあります。

Posted in news | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote Numbers Pages | Leave a comment

新発売:AppleScript基礎テクニック集(2)〜tellブロックの整理

Posted on 4月 8, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第2巻、「tellブロックの整理」です。PDF 36ページ、掲載Scriptアーカイブつき。

→ 販売ページ

本書は、AppleScriptのプログラムの7割以上を占めると言われている、tellブロックの記述や整理方法についてまとめています。tellブロックの書き方が楽になれば、すなわちプログラムの7割以上の部分を楽に書けるともいえます。

tellブロックの記述は、AppleScriptのプログラミングにおいて、決して避けては通れない基礎テクニックなのです。

tellブロック

tellブロックの基本構造
省略表記が可能
省略表記の自動判別+自動展開
1行にまとめることも可能
変数, propertyに入れて指定
tellブロックにof itを補う必要があるケースも
it, me, AppleScript
tellブロックの分割
オブジェクト階層をサブルーチンに渡す
ちょっと凝ったtellブロック

GUI Scriptingにおけるtellブロック

画面上のGUI部品を強引に操作するGUI Scripting
手軽,遅い,tell文が深いGUI Scripting
tell文のネスティングを浅く書く工夫

同一アプリケーションの異なるバージョンへのtell

対象アプリケーションの指定方法
アプリケーションの存在確認
アプリケーションのバージョンを検出
Spotlightでアプリケーションを検索
ご参考:Spotlight検索ライブラリをインストール
Spotlightで同じ名前のアプリケーション情報を取得
対象アプリケーションを名前以外で指定

Posted in Books news | Tagged 12.0savvy | Leave a comment

新発売:AppleScript基礎テクニック集(1)〜間接指定

Posted on 4月 6, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第1巻、「間接指定」です。PDF 36ページ、掲載Scriptアーカイブつき。

1年に15冊も書いていると、割とPiyomaru Softwareの電子書籍も数が増えてきまして……何がどういう人向けのものなのか、おおまかなマップを示してほしいという話を聞くようになりました。

「基礎」とはいっても、入門者が読むような内容ではなく、脱・初心者とか中級者(とりあえず、目的のScriptを組めるレベル)向けといったところでしょうか。

目次:

間接指定

直接指定と間接指定
処理データの間接指定(配列から指定)
Unicode文字の間接指定
date(日付)オブジェクトの間接指定
ファイルパスの間接指定
参考資料:path to で指定できるパラメータ
音声読み上げキャラクタの間接指定
実行Scriptの間接指定
コマンドの間接指定
実行ハンドラ(サブルーチン)の間接指定

間接指定の導入実例

間接的に表同士の重なりを検出
間接的に表同士の重なりを検出
間接的にチェック範囲を検出
直接指定から間接指定に書き換えた結果
実際のScript

Posted in Books news | Tagged 12.0savvy | Leave a comment

Keynoteの最前面の書類の現在のスライド上の表オブジェクトの重なり合い(2つ以上対応)を検出 v3

Posted on 4月 5, 2022 by Takaaki Naganoya

Keynote書類の現在のスライド(ページ)上に存在する表オブジェクトの重なり合いを検出するAppleScriptです。

前バージョンでは、複数の表オブジェクトが配置されていると、表オブジェクトの位置情報と大きさから生成したNSRect同士の重なりチェックを行なった際に、同じ表同士の重なりチェックも行なっていたので、

複数の表が存在していると、もれなく「重なっている」という警告が出てくるものでした。

本バージョンでは、同じ表同士を重なりチェックしないようにとか、1×3と3×1という「同じオブジェクト同士の重なりチェックを2度行っている」ようなものを排除しています。

今度の順列組み合わせパターン生成ルーチン「retPairPermutationsWithoutSelfCollision」では、これらのパターンを除去しています。

{{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5}}

↑余計な組み合わせパターンは生成されなくなりました。

実際に本Scriptを用いて(複数ページ対応板)、121ページ分の表の重なり合わせチェックを行なってみたところ、M1 Mac miniで3.4秒程度です。

–> Watch Demo Movie


▲重なり合わせ判定:なし


▲重なり合わせ判定:あり


▲重なり合わせ判定:なし


▲重なり合わせ判定:あり(400%拡大表示)


▲重なり合わせ判定:あり(75%拡大表示)

本Scriptの完全版を「AppleScript基礎テクニック集(1)〜間接指定」に収録しています。

AppleScript名:現在のスライド上の表オブジェクトの重なり合い(2つ以上対応)を検出 v3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/04/03
—
–  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 "Keynote"
  tell front document
    set docHeight to height
    
    
tell current slide
      set tList to every table
      
      
if length of tList < 2 then return false –複数の「表」がなかったら衝突は発生していない
      
      
–表の座標とサイズによりNSRectangleを作成する
      
set bList to {}
      
      
repeat with i in tList
        set j to contents of i
        
        
tell j
          set {xPos, yPos} to position
          
set aWidth to width
          
set aHeight to height
          
          
set aRect to makeRect(xPos, yPos, aWidth, aHeight) of me
        end tell
        
        
set the end of bList to aRect
      end repeat
      
      
–作成したNSRectangleの順列組み合わせペア・パターンを作成して、NSRectangle同士の衝突判定を順次行う
      
set aLen to length of bList
      
set permuList to retPairPermutationsWithoutSelfCollision(aLen) of me
      
set corruptList to {}
      
      
repeat with i in permuList
        copy i to {i1, i2}
        
set rectRes to detectRectanglesCollision(item i1 of bList, item i2 of bList) of me
        
if rectRes = true then return true –表同士の衝突が発生している
      end repeat
      
      
return false –表同士の衝突は発生していない
    end tell
  end tell
end tell

on makeRect(xPos, yPos, aWidth, aHeight)
  return current application’s NSMakeRect(xPos, yPos, aWidth, aHeight)
end makeRect

–NSRect同士の衝突判定
on detectRectanglesCollision(aRect, bRect)
  set a1Res to (current application’s NSIntersectionRect(aRect, bRect)) as {record, list}
  
set tmpClass to class of a1Res
  
  
if tmpClass = record then
    –macOS 10.10, 10.11, 10.12
    
return not (a1Res = {origin:{x:0.0, y:0.0}, |size|:{width:0.0, height:0.0}})
  else if tmpClass = list then
    –macOS 10.13 or later
    
return not (a1Res = {{0.0, 0.0}, {0.0, 0.0}})
  end if
end detectRectanglesCollision

–1から任意の数までのアイテムで、2個ずつの組み合わせのすべての順列組み合わせパターンを計算して返す
–ただし、1×1とか2×2などの同一アイテム同士の掛け合わせを除去するものとする
on retPairPermutationsWithoutSelfCollision(aMax)
  set aList to {}
  
  
repeat with x from 1 to aMax
    repeat with xx from 1 to aMax
      if x is not equal to xx then
        
        
set tmpItem to {x, xx}
        
set a2List to sort1DNumList(tmpItem, true) of me
        
        
if {a2List} is not in aList then
          set the end of aList to a2List
        end if
      end if
      
    end repeat
  end repeat
  
  
return aList
end retPairPermutationsWithoutSelfCollision

–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 list | Tagged 12.0savvy Keynote NSRect | 1 Comment

Keynoteの最前面の書類の現在のスライドで、表オブジェクトの重なり合い(2つ以上対応)を検出 v2

Posted on 4月 3, 2022 by Takaaki Naganoya

Keynote書類の現在のスライド(ページ)上に存在する表オブジェクトの重なり合いを検出するAppleScriptです。

Cocoa Scripting Course #4のチェックを行なっていたら、表オブジェクトが重なり合っていたページがあってヘコみました(再チェック中です)。

これを自動でチェックするためのAppleScriptを書いてみました。とりあえず、現在表示しているスライド(ページ)を対象に。最終的には、開始と終了のスライドの番号を与えておくと、その間のスライドをすべてチェックできるとよいでしょう。

CocoaのNSRect同士であれば、重なり合いを検出できるので大変便利です。Keynote上の表オブジェクトから、位置情報と大きさの情報を取得すれば、簡単に目的のデータ(配列に入れたNSRect)を作れることでしょう。

ただし、NSIntersectionRectでNSRect同士の衝突検出を行えるとしても、1対1でしかチェックできないようなので、検出された表同士のすべての衝突チェック組み合わせを行うべく、順列組み合わせペア・パターンを計算する部品を急遽作って(以前作った、Permutation計算とは仕様が違うので)、2つずつ表(から作ったNSRect)を取り出して矩形座標の衝突判定を行なっています。

Keynoteの座標系は「左上」が原点座標で、Cocoaの座標系は左下のはずで….macOS 12で左上になったという話もありますが、実戦投入してみたら衝突が発生していないスライドでも衝突が検出されていたので、このあたり修正する必要があるかもしれません。

Keynoteのスライド上の表の配置状況をCocoaのNSRectで表現し、デバッグ用に画像で表示させてみました。重なりをシミュレーションするだけなら、とくに問題はなさそうです。

→ 原因がわかりました。表の座標とサイズから作ったNSRect同士を重なり合い計算するための、順列組み合わせパターン計算ルーチンで1×1とか2×2とかの「同じNSRect同士」の重なりを計算するようなパターンまで出力していたのが原因です。

つまり、現状では「複数の表オブジェクトが入っているスライド」を検出するだけの計算を行なってしまっているようです。

--> {{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 1}, {2, 2}, {2, 3}, {2, 4}, {2, 5}, {3, 1}, {3, 2}, {3, 3}, {3, 4}, {3, 5}, {4, 1}, {4, 2}, {4, 3}, {4, 4}, {4, 5}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}}

と計算してしまうところを、

--> {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 1}, {2, 3}, {2, 4}, {2, 5}, {3, 1}, {3, 2}, {3, 4}, {3, 5}, {4, 1}, {4, 2}, {4, 3}, {4, 5}, {5, 1}, {5, 2}, {5, 3}, {5, 4}}

のように、同じアイテム同士の組み合わせになるパターンだけを除外してあげればよかったわけです。自分で資料を作ってみてわかりました。

あとは、3×5と5×3は計算としては同じ意味なので、こういう重複パターンを除去してあげる必要があるのですが…重なりの「個数」を数えるのであるのであればともかく、重なりを「検出」するだけなら重複除去まではする必要がないでしょう。

AppleScript名:現在のスライド上の表オブジェクトの重なり合い(2つ以上対応)を検出 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/04/03
—
–  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 "Keynote"
  tell front document
    tell current slide
      set tList to every table
      
      
if length of tList < 2 then return false –複数の「表」がなかったら衝突は発生していない
      
      
–表の座標とサイズによりNSRectangleを作成する
      
set bList to {}
      
      
repeat with i in tList
        set j to contents of i
        
        
tell j
          set {xPos, yPos} to position
          
set aWidth to width
          
set aHeight to height
          
set aRect to makeRect(xPos, yPos, aWidth, aHeight) of me
        end tell
        
        
set the end of bList to aRect
      end repeat
      
      
–作成したNSRectangleの順列組み合わせペア・パターンを作成して、NSRectangle同士の衝突判定を順次行う
      
set aLen to length of bList
      
set permuList to retPairPermutations(aLen) of me
      
set corruptList to {}
      
      
repeat with i in permuList
        copy i to {i1, i2}
        
set rectRes to detectRectanglesCollision(item i1 of bList, item i2 of bList) of me
        
if rectRes = true then return true –表同士の衝突が発生している
      end repeat
      
      
return false –表同士の衝突は発生していない
    end tell
  end tell
end tell

on makeRect(xPos, yPos, aWidth, aHeight)
  return current application’s NSMakeRect(xPos, yPos, aWidth, aHeight)
end makeRect

–NSRect同士の衝突判定
on detectRectanglesCollision(aRect, bRect)
  set a1Res to (current application’s NSIntersectionRect(aRect, bRect)) as {record, list}
  
set tmpClass to class of a1Res
  
  
if tmpClass = record then
    –macOS 10.10, 10.11, 10.12
    
return not (a1Res = {origin:{x:0.0, y:0.0}, |size|:{width:0.0, height:0.0}})
  else if tmpClass = list then
    –macOS 10.13 or later
    
return not (a1Res = {{0.0, 0.0}, {0.0, 0.0}})
  end if
end detectRectanglesCollision

–1から任意の数までのアイテムで、2個ずつの組み合わせのすべての順列組み合わせパターンを計算して返す
on retPairPermutations(aMax)
  set aList to {}
  
  
repeat with x from 1 to aMax
    repeat with xx from 1 to aMax
      set tmpItem to {x, xx}
      
if tmpItem is not in aList then
        set the end of aList to tmpItem
      end if
    end repeat
  end repeat
  
  
return aList
end retPairPermutations

★Click Here to Open This Script 

Posted in list | Tagged 12.0savvy Keynote NSRect | 1 Comment

基礎テクニック集を編纂中

Posted on 4月 3, 2022 by Takaaki Naganoya

AppleScriptの日常的かつ基礎的なテクニックをまとめた 、小規模でお求めやすい価格の電子書籍シリーズ「AppleScript基礎テクニック集」を刊行する予定です。

表紙をとりあえず作ってみましたが、この表紙を1シリーズ分作る瞬間が一番楽しいですね。


Racool_studio – jp.freepik.com によって作成された business 写真

→ AppleScript基礎テクニック集①間接指定


Technology photo created by drobotdean – www.freepik.com

→ AppleScript基礎テクニック集②tellブロック


Lookstudio – jp.freepik.com によって作成された people 写真

→ AppleScript基礎テクニック③ファイルパス処理


Student with laptop photo created by freepic.diller – www.freepik.com

→ AppleScript基礎テクニック集④AppleScript用語辞書の読み方

(以下省略)

Posted in Books news | Tagged 12.0savvy | Leave a comment

NSCharacterSetの使い方を間違えた

Posted on 3月 30, 2022 by Takaaki Naganoya

これまでに、NSMutableCharacterSetを使うべきところにNSCharacterSetを指定していたAppleScriptがあって、これは自分のミスだったのですが……これまで、この書き方で動いてしまって気が付かなかったものでした(Thanks Shane!)

このところ、AppleScriptの処理系やmacOS自体のバグが続いたので、不可思議な問題を見つけると「これどーなの?」と関係筋に確認をとっています。Appleにレポートする前に複数のScripterに確認をとって、「本当にそうなのか?」「再現性のあるトラブルか?」という話をしています。そんな中で、これは自分のミスでした。

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

それが、macOS 12.3で急に厳密に動かなくなり….逆にいえば、「なんでこれまでは動いていたんだろう?」というところではあるのですが、割と文字種別の判定はいろんなScriptで行なっているので影響が大きいところです。

on chkSymbol:checkString
	set muCharSet to NSMutableCharacterSet's alloc()'s init()
	muCharSet's addCharactersInString:"$\"!~&=#[]._-+`|{}<>?%^*/'@-/:;(),"
	set ret to my chkCompareString:checkString baseString:muCharSet
	return ret as boolean
end chkSymbol:

Cocoa Scripting Course #1 NSStringの付録サンプルScriptに該当するものがあるため、バグ情報を掲載しています。
また、差し替えたものをダウンロードできるように購入ページ上のアーカイブを更新いたします。

Posted in Text | Tagged 12.0savvy NSCharacterSet NSMutableCharacterSet | Leave a comment

macOS 12.3上でFinder上で選択中のファイルをそのままオープンできない件

Posted on 3月 28, 2022 by Takaaki Naganoya

macOS 12.xはAppleScriptの処理系に対して、主にセキュリティ面でいろいろ修正が加わっています。

この修正は、セキュリテイを「高める」という名目のもとに行われているのですが、セキュリティ面での課題さえ片付けられれば、その他に悪影響を及ぼしていたとしても「知ったことではない」というのがAppleの態度です。そして、その問題に対してユーザー側から文句が出てこなければ、そのままです。

–> View Demo Movie

とくに、深謀遠慮な考えとか、素晴らしい見通しとかはなく、「上から言われたからやっている」というやっつけ仕事感を感じます。

AppleはSteve Jobsが作り上げた秘密警察みたいな組織になっていて、チーム間の権限の切り分けが病的なまでに行われており、チームが違うと会社が違うぐらいの隔たりが発生しています。それは、Steve Jobsという「垣根を無視して横断して歩く異物」がいたから成立する組織であって、官僚化、硬直化が絶賛進行中といったところです。

話を戻しますが….たしかに、そうした機能的なアップを伴わない修正で何も問題(副作用)が起こらなければ「セキュリティが高まったのでよかったね」という美談になるわけですが、たいていの場合にはそうなりません。意図していなかった箇所に副作用が生じます。

あるいは、セキュリティのポリシー同士が実は矛盾を生んでいる、という状況になっていて、Aという問題とBという問題を解決した結果、あらたにCというもっと巨大な問題が発生する、とかいった状況は容易にあり得るわけです。それでも、各担当者は誠意をもってその仕事に取り組んでいるわけで、こうした「人間的に尊敬できて素晴らしい能力を持ったスタッフ」による「熱心かつ誠意あふれる真摯な仕事」が合成された結果、「見たことも聞いたこともない間抜けな理由から生じる猛毒にまみれた悪意」が合成されてしまうことが、現在のTim CookのAppleの下ではあり得るのです。

「Finder上で選択中のファイルをそのままオープンする」

というのは、ここ数年というよりもAppleScriptを覚えたてのころにちょろっと書いて実行したぐらいであり、実際のところ「それがどうした?」というレベルの処理です。

AppleScript名:Finder上で選択中のファイルをオープン.scpt
–macOS 12.3でエラーになる処理
tell application "Finder"
  open selection
end tell

★Click Here to Open This Script 

Finder上で選択したファイルに対する処理は、きょうび何かのアプリケーションに渡さなくてもAppleScriptだけで処理できてしまうことが多いということもありますし(画像とか)、選択されたファイルをそのままオープンするという「1=1」みたいな処理はやりません。

選択したフォルダの中をすべてSpotlight経由で走査して、指定の形式のファイルだけをリストアップして、順次処理するようなものになっています。

ただ、10年たっても20年たっても「1=1」みたいな処理しかしていない人がけっこういて驚かされると同時に、意外なところで(Adobeのアプリケーションでアプリケーション間の連携に)使っていたりして、修正されないと困るケースは多いようです。

Shane StanleyがLateNight Softwareのフォーラムに投稿した、こうした処理への迂回Scriptがありました。さすがです。

Finder経由で書類のオープンと、その書類を作成したアプリケーションの起動を促すという、macOS 12.3で問題が起こっている処理を、Cocoaの機能を用いることで迂回してしまおうというものです。

ただ、そのままではFinder上で指定したファイルを1つオープンするという実証コードのレベルのものだったので、複数のファイルが選択されたものをオープンするように書き足してみました。

AppleScript名:macOS 12.3でFinder上の選択中のファイルをオープン.scpt
—
–  Created by: Shane Stanley
–  Created on: 2022/03/24

–  Modified by: Takaaki Naganoya
–  Modified on: 2022/03/27
—
— macOS 12.3でFinder上のselectionをただopenすると、作成したアプリケーションは起動するが、書類はオープンされないバグ
– に対処したもの。複数ファイルの選択状態を処理する場合がほとんどなので、若干追記
– ただ、漫然と選択したファイルをオープンするという処理はやっていないので(なにがしかの処理を自前でやるので)

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

tell application "Finder"
  set aSel to selection as alias list
  
if aSel = {} then return
end tell

openFiles(aSel) of me

on openFiles(pathList as list)
  repeat with i in pathList
    set j to contents of i
    
openFile(POSIX path of j) of me
  end repeat
end openFiles

on openFile(thePath as string) — POSIX path
  set ws to current application’s NSWorkspace’s sharedWorkspace()
  
set theURL to current application’s |NSURL|’s fileURLWithPath:thePath
  
ws’s openURL:theURL
end openFile

★Click Here to Open This Script 

Posted in Bug file news URL | Tagged 12.0savvy Finder | Leave a comment

macOS 12.x上のAppleScriptのトラブルまとめ

Posted on 3月 20, 2022 by Takaaki Naganoya

現在進行形で発生しているAppleScript系のトラブルについてまとめておきます。macOS 12になって、AppleScriptの処理系の根幹部分にいろいろ手が加わっており(だったら機能追加してほしい気がする)、不具合なのかセキュリティポリシーとの不整合なのか(そんなもん、社内で調整してほしい)よくわからない問題がいろいろ生じています。

Apple自身が機能ごとのリリースノートを出さないようになり、こういうときに困ります。macOS 12.xで見られた不具合の中には、かなりApple自身の邪悪なポリシー運用の結果として顕在化したものもあるので、明文化できないのでしょうか。何をやった結果として発生した問題である、と書いてしまうと「なんでAppleはそんな邪悪なことをやっているの?」と世界中からツッコミを受けるに違いありません。

問題1:Scriptを実行すると「表があふれました」と謎のエラーが表示される(解決したか不明)

macOS 12.3で解消されるか? と見ていましたが、完全に対処できている感じではない様子。
→ 関連情報:SkimのAppleScriptサポート機能にバグ
→ その後、この「表があふれました」エラーには遭遇していないので、問題は解決されたのでしょう。ただし、油断しているとmacOSのマイナーアップデート時に何かやらかす可能性があります。

問題2:12.3betaで発生した「AppleScript書類をオープンできない」問題(解決)

これについては、12.3Release版では発生していないもよう。息が止まるかと思うほど焦りました。電子書籍1つ作るにしても、手間のかかる作業の多くをAppleScriptで自動化。そうでなければ、そんなにポンポン書けません。

問題3:インストールされていないアプリケーションを操作するScriptをオープンできない(未解決)

ただし、そのMacにインストールされていないアプリケーションを操作するScriptをオープンしようとすると、これまでは「どのアプリケーションですか?」とユーザーに問い合わせしていましたが、これが一律にエラーになるようです。
→ macOS 12.5 beta5において、インストールされていないアプリケーションに対するAppleScriptをオープンした場合には、オリジナルのままオープンされ、コンパイル(構文確認)すると書き換えられるといった動作を行うことを確認しています

問題4:悪意を持って作られたAppleScriptバイナリ(アプレット?)のセキュリティ上の問題(CVE-2022-22626)(解決)

悪意を持って作成したAppleScriptバイナリは予期しない強制終了、ないしはプロセスが確保していたメモリを暴露(他のプロセスから読み書き&実行できてしまう?)する問題があったとのこと。

悪意を持って作ったことがないのと、ランタイムプログラムのメモリ処理の問題のようなので(???)、Scriptを書いている側には「そんなのあったの?」という話です。

個人的には、AppleScriptをアプレット化して動かすことは少なく、Script DebuggerかScript Menuで動かしている場合がほとんどです。

問題5:Finder上のselection itemsをオープンした際に、作成したアプリは起動されるがファイルはオープンされない問題

Finder上で選択したファイルを、指定のアプリケーションや、各ファイルを作成したアプリケーションで開かせようとした場合に、アプリケーションのプロセスは起動するものの、指定の書類はオープンされないという問題。macOS 12.3上で発生した新たな問題の様子。

先に対象のアプリケーションを起動しておくとファイルオープンの処理は通るというケースもあれば、そうではないというケースも。
→ macOS 12.3.1/12.4beta1で解消

問題6:macOS 12のスクリプトエディタで、Context Menu機能にバグ(未解決)


macOS 12のスクリプトエディタで、Script Assistantとして/Library/Scriptsに入れているAppleScriptをコンテクストメニューから呼び出せるようになっていますが、そこにカスタムScriptを入れて呼び出すと(絵文字入りファイル名)コンテクストメニュー上に重複した項目が表示されるというバグです。
→ 途中で「直った」という連絡をもらったのですが、まったく直っていませんでした。Appleのエンジニアは字が読めないか、目が見えないのでしょう。最低限、字が読めないとバグは取れないですよね?
→ macOS 14で解決

問題7:アプリケーション同士のイベントのやりとりが2回以上発生するとエラー-609になるバグ

macOS 12.5 beta 5で発生した前代未聞のバグ(?)。

現在のTim Cook体制下で狙っていると見られる「セキュリティ確保のためには動かないコンピュータが最高!」の思想を体現する機能の実現のためか、こうしたアプリケーション同士のイベントの送信をカウントしているようです。これがバグなのか意図したものなのかは不明ですが、カウントして準備を始めたということだけは言えるでしょう。

ただ、Dockに登録したアプリケーションに書類をドラッグ&ドロップすると3回目からはエラーになりますし、FinderのToolbarに登録したアプリケーションのアイコンを3回クリックしてもエラー-609になります。とうてい、まともな状態とは言えません。

macOS 12.5でこの機能がオンになるものとは思っていませんが、Apple側が何かよからぬ企みを行っていることだけは明らかです。

「地獄への道は善意で敷き詰められている」(The road to hell is paved with good intentions)という言葉があります。セキュリティ強化の美名のもとにこれが実現したとき、コンピュータが役立たずの置物になってしまいます。Tim Cook CEOによる最悪の施策として記憶されることでしょう。頭が悪すぎです。
→ macOS 12.5(21G69)で解決???? Release Notesに記載されてもいないので不明

Posted in Bug news | Tagged 12.0savvy | Leave a comment

ドラッグ&ドロップ機能の未来?

Posted on 3月 17, 2022 by Takaaki Naganoya

目下、Tim Cook体制のもと「セキュリティ至上主義」が掲げられ、機能の有用性とセキュリティ(機能を制限、削除する)をてんびんにかけると、後者が重視されるようになっています。

そんな中、ドラッグ&ドロップの機能についてはいろいろ制約を受けたり、一部で使えなくなっていくのではないかという「懸念」を持っています。

実際、macOS 10.12以降、AppleScriptドロップレット(ファイルのドラッグ&ドロップを受信して動作するAppleScriptの実行プログラム)がOS側のセキュリティ機能による動作の影響(xattr)を受け、まっとうな処理方法では期待されるファイル処理ができなくなっています(回避策はあります)。

このため、macOS上でもFinder上でiOS並みのファイル操作、ドラッグ&ドロップでファイル/フォルダを移動させる程度の処理しか許可されず、アプリケーション側にまとめてファイルを渡すような処理ができなくなる「かも」しれません。

このドラッグ&ドロップによるファイルの一括指示の機能を維持するために、「display drop dialog Script Library」というライブラリをedama2氏との協力のもと(自分は要望を出したぐらいで作ったのはedama2氏)、配布しています。

アラートダイアログで指定のファイルタイプの書類のFinderからのドラッグ&ドロップを受け付けます。わざわざDropletを作らなくてもファイルのドラッグ&ドロップを受け付けるためには、こうしたインタフェースがないとまずいんじゃないか? という予測のもとに企画したものです。

目下、macOS 12.3でFinderに対してファイルのAppleScriptからオープン操作を行わせると、「creatorのアプリケーションは起動するもののファイルがオープンされない」という現象が発生しており(エラーダイアログが出る例があったり、出ない例があったり)、Apple社内でも整合性が取れていない状況のようです。

Appleとしては個別のテクノロジーについて発言したり、WWDCでも技術ではなくマーケティング的なセッションが増えて「見るべきものがない」状況になっていますが、こうした状況は好ましいものとは言えません。

Posted in Bug news | Tagged 12.0savvy | Leave a comment

クリップボードの画像を指定色でモノクロ化してクリップボードへ v3

Posted on 3月 13, 2022 by Takaaki Naganoya

クリップボードに入れた画像を、グレースケール化したあとに指定の色のベタ塗り画像とフィルタで合成し、単色の色付き画像に変換するAppleScriptです。

資料に掲載する画像の情報量を減らすために、単色画像に変換したいと考えました。Photoshopだと2つのレイヤーの重ね合わせで指定して処理するような内容です。ただ、もうPhotoshopにできるぐらいのことの大部分は、AppleScriptだけで単独でできてしまうのが2022年的な状況です。

アプリケーションを使わずに処理するためには、CIFilterを用いて画像処理して、単色画像にすることになります。

CIFilterにもいろいろな画像フィルタ機能が用意されているわけで、ここから「どのフィルタを使うか」選ぶことになります。

# フィルタが200種類ぐらいあるんですけど!!

このような場合のために、FileMaker Proで作った「FileMaker Pro PowerPack」だとひととおりのCIFilterをサンプルデータで処理できるようにしておきました。

FileMaker Proのデータベース上にサンプルデータをコピー&ペーストしておけば、DB上でフィルタ処理してどのような処理をしてくれるかがわかります。

いやーー、作っておいてよかったー。「なんでこんなにフィルタ処理ばっかりあるんだよ!」的な話がありましたが、こうして実際に役立つわけで。フィルタの名称、編集できるテストデータ、処理結果が表示されるところまで……「動かせる資料」的なものに仕上がっています>FileMaker Pro PowerPack

ひととおりAppleScriptを作ってみて、いろいろ調整してみたところ……調整し切れなかったので、edama2さんに相談して(送りつけて)こんな感じに仕上がりました。

これでなんとか動くはずなのに、なぜこうなるのか。。。CIFilterを実際に日常的に使うツールで使ったのは実はこれが最初だったので、意外な挙動に割と困りました。


▲画面上の指定範囲のスクリーンショットを撮ってクリップボードへ


▲ScriptをmacOS標準搭載のスクリプトメニューから呼び出すことを前提に作った。


▲クリップボードの内容をペーストすると、単色化された画像が出力される

AppleScript名:クリップボードの画像を指定色でモノクロ化してクリップボードへ v3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/03/11
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
–  v2 Takaaki Naganoya : マスクが1/4の大きさになったり2倍になったりしていた
–  v3 edama2:上記の問題に対処。クリーンナップ
—
use AppleScript version "2.7"
use framework "AppKit"
use framework "CoreImage"
use framework "Foundation"
use scripting additions

on run
  my main()
end run

on main()
  –クリップボード内のデータをNSImageとして取得
  
set sourceImg to my getClipboardASImage()
  
  
# 色指定
  
set aColor to my makeNSColorFromRGBA255val(252, 2, 128, 255)
  
  
  
# 同じ大きさの塗りつぶし画像を作成
  
tell current application’s NSImage’s alloc()
    tell initWithSize_(sourceImg’s |size|())
      lockFocus()
      
aColor’s |set|()
      
set aRect to current application’s NSMakeRect(0, 0, its |size|()’s width, its |size|()’s height)
      
current application’s NSBezierPath’s fillRect:aRect
      
unlockFocus()
      
set fillImg to it
    end tell
  end tell
  
  
# NSImage –> CIimage
  
set sourceImage to my convNSImageToCIimage(sourceImg)
  
set fillImage to my convNSImageToCIimage(fillImg)
  
  
set newImage to my filterImage2(fillImage, sourceImage)
  
  
my restoreClipboard({newImage})
end main

on filterImage2(fillImage, sourceImage)
  
  
set redValue to 0.295719844358
  
set greenValue to 0.295719844358
  
set blueValue to 0.295719844358
  
set alphaVlaue to 1.0
  
set aCIColor to current application’s CIColor’s alloc()’s initWithRed:redValue green:greenValue blue:blueValue alpha:alphaVlaue
  
  
tell current application’s CIFilter
    — CIFilter(モノクロ化)
    
tell filterWithName_("CIColorMonochrome")
      setDefaults()
      
setValue_forKey_(sourceImage, "inputImage")
      
setValue_forKey_(aCIColor, "inputColor")
      
set filteredImage to valueForKey_("outputImage")
    end tell
    
    
— CIFilter(モノクロ化)
    
tell filterWithName_("CIAdditionCompositing")
      setDefaults()
      
setValue_forKey_(fillImage, "inputImage")
      
setValue_forKey_(filteredImage, "inputBackgroundImage")
      
set theCIImage to valueForKey_(current application’s kCIOutputImageKey)
    end tell
  end tell
  
  
# CIImage –> NSImage
  
set imageRep to current application’s NSCIImageRep’s alloc()’s initWithCIImage:theCIImage
  
set rNSImage to current application’s NSImage’s alloc()’s initWithSize:(imageRep’s |size|())
  
rNSImage’s addRepresentation:imageRep
  
  
return rNSImage
end filterImage2

# NSImage –> CIimage
on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

— クリップボードの内容をNSImageとして取り出して返す
on getClipboardASImage()
  set thePasteboard to current application’s NSPasteboard’s generalPasteboard()
  
set theAttributedStringNSArray to thePasteboard’s readObjectsForClasses:({current application’s NSImage}) options:(missing value)
  
set theNSImage to theAttributedStringNSArray’s objectAtIndex:0
  
return theNSImage
end getClipboardASImage

on restoreClipboard(theArray as list)
  set thePasteboard to current application’s NSPasteboard’s generalPasteboard()
  
thePasteboard’s clearContents()
  
thePasteboard’s writeObjects:theArray
end restoreClipboard

on makeNSColorFromRGBA255val(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer)
  set aRedCocoa to (redValue / 255) as real
  
set aGreenCocoa to (greenValue / 255) as real
  
set aBlueCocoa to (blueValue / 255) as real
  
set aAlphaCocoa to (alphaValue / 255) as real
  
set aColor to current application’s NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBA255val

★Click Here to Open This Script 

Posted in filter Image | Tagged 12.0savvy CIColor CIImage NSBezierPath NSCIImageRep NSColor NSImage NSPasteboard | Leave a comment

指定のPDFの本文テキストの文字数をカウント

Posted on 3月 9, 2022 by Takaaki Naganoya

指定のPDFの本文テキストを取り出し、文字数をカウントするAppleScriptです。


▲「AppleScriptによるWebブラウザ自動操縦ガイド」の文字数をカウントしようとした

300ページを超える、わりと大きな本のPDFデータから文字を取り出したので、それなりの文字数になりました。つまり、Cocoaの有効活用を考えないとデータサイズ的につらそうなデータ量になることが予想されました。

当初、(文字処理については)Cocoaの機能をあまり活用しないv2を作ったものの、処理にM1 Mac miniで30秒ほどかかりました。すべてNSStringのまま(AppleScriptのstringに型変換せずに)処理してみたら、案の定、大幅に処理が高速化され6秒あまりで完了。

ただし、両者でカウントした文字数が1万文字ぐらい違っていたので、(PDFから取得した文字の)Unicode文字のNormalize方式を変更したところ、両者で同じ結果になりました。また、処理速度に改変前から大幅な変化はありませんでした。

文字数を数えるという処理だとさすがにデータ数が膨大になるため、NSStringで処理したほうがメリットが大きいようです。

# あれ? 5文字ぐらい違う、、、、絵文字の部分か?

AppleScript名:指定のPDFの本文テキストの文字数を数える v2
use AppleScript version "2.8" –macOS 12 or later
use framework "Foundation"
use framework "PDFKit" –Comment Out under macOS 11
–use framework "Quartz"–Uncomment under macOS 11
use scripting additions

script spd
  property cRes : ""
  
property cList : {}
end script

set (cRes of spd) to ""
set (cList of spd) to {}

set (cRes of spd) to getTextFromPDF(POSIX path of (choose file of type {"pdf"})) of me
set (cList of spd) to current application’s NSArray’s arrayWithArray:(characters of (cRes of spd))
set cLen to (cList of spd)’s |count|()
return cLen
–> 256137 (24.763sec)

on getTextFromPDF(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping()) as text
end getTextFromPDF

★Click Here to Open This Script 

AppleScript名:指定のPDFの本文テキストの文字数を数える v3
use AppleScript version "2.8" –macOS 12 or later
use framework "Foundation"
use framework "PDFKit" –Comment Out under macOS 11
–use framework "Quartz"–Uncomment under macOS 11
use scripting additions

script spd
  property cRes : ""
  
property cList : {}
end script

set (cRes of spd) to ""
set (cList of spd) to {}

set (cRes of spd) to getTextFromPDF(POSIX path of (choose file of type {"pdf"})) of me
set cLen to (cRes of spd)’s |length|
return cLen as anything
–> 256142 (6.28 sec)

on getTextFromPDF(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping())
end getTextFromPDF

★Click Here to Open This Script 

わずかとはいえ、違いが出ていることは確かなので、1つのPDFに対して2つの処理方法でテキストを取り出して、それを配列に入れて集合演算して差分をとってみました。M1でも処理に1分少々かかりました。こういう処理は、M1 MaxでもM1 Ultraでも所要時間は変わらないことでしょう(逆にM1の方が処理時間が短い可能性まである)。

どうやら改行コードの解釈で文字数カウント結果に違いが出たようです。

AppleScript名:テキストの抽出方法による文字数の相違チェック.scptd
use AppleScript version "2.8" –macOS 12 or later
use framework "Foundation"
use framework "PDFKit" –Comment Out under macOS 11
–use framework "Quartz"–Uncomment under macOS 11
use scripting additions

script spd
  property cRes : ""
  
property cList : {}
end script

set (cRes of spd) to ""
set (cList of spd) to {}

set docPath to POSIX path of (choose file of type {"pdf"})

set (cRes of spd) to getTextFromPDF1(docPath) of me
set (cList of spd) to characters of (cRes of spd)
set anArray to current application’s NSArray’s arrayWithArray:(cList of spd)

set bStr to getTextFromPDF2(docPath) of me
set bArray to current application’s NSMutableArray’s new()
set bLen to (bStr’s |length|) as anything
repeat with i from 0 to (bLen – 1)
  set tmpStr to (bStr’s substringWithRange:(current application’s NSMakeRange(i, 1)))
  (
bArray’s addObject:(tmpStr))
end repeat

set aRes to diffLists(anArray, bArray) of me
set bRes to diffLists(bArray, anArray) of me
return {aRes, bRes}

on getTextFromPDF1(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping()) as text
end getTextFromPDF1

on getTextFromPDF2(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping())
end getTextFromPDF2

–1D List同士のdiffを計算する
on diffLists(aList, bList)
  set aSet to current application’s NSMutableSet’s setWithArray:aList
  
set bSet to current application’s NSMutableSet’s setWithArray:bList
  
set aRes to calcSetDifference(aSet, bSet) of me
  
return aRes
end diffLists

–2つのNSMutableSetの補集合を求める
on calcSetDifference(aSet, bSet)
  aSet’s minusSet:bSet –補集合
  
set aRes to aSet’s allObjects() as list
  
return aRes
end calcSetDifference

★Click Here to Open This Script 

Posted in PDF Text | Tagged 12.0savvy NSURL PDFDocument | Leave a comment

macOS 12のスクリプトエディタで、Context Menu機能にバグ

Posted on 3月 4, 2022 by Takaaki Naganoya

「AppleScriptによるWebブラウザ自動操縦ガイド」に添付している「Piyomaru Context Menu Assistant」。

スクリプトエディタのコンテクストメニューからAppleScriptを呼び出せるスクリプトエディタの機能を利用して、macOS標準装備の貧相で使い物にならないScriptを全部捨てて、そのかわりに強力なものをインストールするものです。


▲macOS標準でインストールされている、Script Assistant。古い、使えない、役に立たないの3拍子


▲Piyomaru Softwareが書籍のオマケでご提供しているPiyomaru Script Assistant(macOS 10.14.6)


▲macOS 12.3 beta 5上で表示したPiyomaru Script Assistant。メニュー項目(≒ファイル名)が2重に表示されている(macOS 12.3 beta5)

このScript Assistantが、macOS 12.3 beta 5上でメニュー項目が重複して表示されてしまうという現象に遭遇しています。

これは、macOS側のAppleが作ったバグであります。

Posted in Bug | Tagged 12.0savvy | 1 Comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

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

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (189) 14.0savvy (141) 15.0savvy (119) CotEditor (66) 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 (76) 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年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