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

タグ: 11.0savvy

新発売:AppleScript基礎テクニック集(15)フォルダアクション

Posted on 6月 13, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第15巻、「フォルダアクション」です。PDF 33ページ、サンプルAppleScriptのZipアーカイブを添付。

→ 販売ページ

フォルダアクションは、任意のフォルダにAppleScriptを添付して、ユーザーがファイルを入れたり削除したり、フォルダをオープンしたりクローズすると指定のAppleScriptが実行されます。

実際には、共有フォルダに対してフォルダアクションを設定、多くのユーザーが所定のファイルをフォルダに入れることで、提出処理を簡略化したり、時間のかかる処理を集約してサーバー機で行わせる、所定の処理を確実に所定のパラメータや手順で行わせるといったシステムが使われてきました。

本書では、Macの便利で強力な機能である本フォルダアクションについて、ローカルのMac上に設定する方法について、基礎的な内容をご説明しています。

目次:

■フォルダアクションの歴史と仕組み

フォルダアクションとは?
フォルダアクション運用例
Classic Mac OS時代から続く伝統の機能
フォルダアクション関連ツール、ファイル
フォルダアクションScript中で利用可能な技術

■フォルダアクションの設定方法

フォルダアクション設定の使い方①
フォルダアクション設定の使い方②
フォルダアクション設定の注意点①
フォルダアクション設定の注意点②

■フォルダアクション自体のAppleScriptからの操作

Script側から行えるフォルダアクション操作①
Script側から行えるフォルダアクション操作②
Script側から行えるフォルダアクション操作③
Script側から行えるフォルダアクション操作④

■フォルダアクションの種類と書き方

イベントハンドラのパラメータ内容①
イベントハンドラのパラメータ内容②
実例1:入ってきたフォルダ中のPDFを大きさで分類①
実例1:入ってきたフォルダ中のPDFを大きさで分類②
実例1:入ってきたフォルダ中のPDFを大きさで分類③
実例2:指定フォルダのウィンドウ操作を受信

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

新発売:AppleScript基礎テクニック集(14)ファイルサーバーのマウント

Posted on 6月 6, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第14巻、「ファイル処理」です。PDF 32ページ、サンプルAppleScriptのZipアーカイブを添付。

→ 販売ページ

サーバー上の任意のマウント対象フォルダの情報を確認する方法がそっけなくて(地味で)、知らないと手も足も出ないという状況でもあります。

サーバー上の特定のフォルダをドライブとしてマウントする、という些細な処理ではあるものの、知っておくべき要点が多いのでまとめてみました。

続刊として予定しているeppc(リモートAppleEvent)について、このファイルサーバーのマウントの延長線上にあるため、eppcを使いたい人にはマスターしておくべきテーマといえるでしょう。

目次:

■macOSのファイル共有の仕組み

ファイル・サーバーとクライアントの関係
macOSのバージョンとファイル共有機能の変化
資料:ファイル共有プロトコルの歴史
共有する側(サーバー)の共有設定
共有する側(サーバー)の共有設定
共有URLの確認①
共有URLの確認②
共有URLの確認③

■サーバー・マシン名の確認

サーバー名の確認
サーバーURLの表記方法

■LAN上のサーバーの存在確認

LAN内のサーバー・プロトコル
指定プロトコルのサーバー一覧の取得①
指定プロトコルのサーバー一覧の取得②
指定プロトコルのサーバー一覧の取得③
指定プロトコルのサーバー一覧の取得④

■AppleScriptのmount volumeコマンド

mount volumeコマンド
指定のサーバー/フォルダをマウント
ファイルサーバーちょっといいノウハウ

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

Keynote書類中のスライドのトビラページを推測する

Posted on 6月 5, 2022 by Takaaki Naganoya

Keynote書類中の各スライド(ページ)のベースレイアウト(テンプレート)の名称から、トビラのページを推測するAppleScriptです。

まずは、なんでトビラのページを特定する必要があるのかといえば、TOC(Table Of Contents)つきでPDFに書き出す際に必要だからです。

トビラのページとは、

こういうものです。記事の開始ページに入っており、記事と記事の区切りをわかりやすくするために入れるものです。

そして、TOCはこういうものです。

目下、このTOCにおける階層をベースレイアウト名から推測するロジックをAppleScriptで組んでいますが、ざっくり言って「ベースレイアウト名」から推測している状態です。

もともと、Keynote書類からAppleScriptで各スライドの階層(Level)を取得できるとか、そもそもKeynote自体にTOCつきPDFを書き出す機能がついていれば、外部からScriptで操作しなくても済むわけですが、バージョンアップを繰り返してもそんな便利な機能がつく気配すらありません。Appleに機能追加のリクエストを出して、それが実装されるまで気長に待つよりも、今日すぐにでもScriptから実装したほうがよほど建設的です。また余計なことをされて機能不全を起こされても迷惑ですし。

なので、非常に遠回りな方法ではあるものの、ベースレイアウト(テンプレート)の名称からレベルを推測せざるを得ないというのが現状です。

ただ、これにも限界があります。「だいたい扉のページにはこのベースレイアウト(テンプレート)を使うよね」という「お約束」をベースに、処理を組み立てることになります。

扉のページにつかいがちなベースレイアウト(テンプレート)をあらかじめリストアップしておいて、該当するものを一律に「扉」とみなしてもいいはずです。

ただ、これもいまひとつ信用できないので、もう1手間かけておきたいところです。

Keynote書類のすべてのスライドからベースレイアウト(テンプレート)名を取得し、出現頻度やスライドの傾向から扉ページを特定したいところでもあります。

まずは、ベースレイアウト名一覧を取得し、ユニーク化(重複削除)。それぞれのベースレイアウト名でループして、書類中における出現頻度を求めます。

出現頻度については、1回ということはないでしょうし(規模によってはあるかもしれない)、全ページが該当するものでもないでしょう。また、表紙(最初のページ)、裏表紙(最後のページ)も異なります。

さらに、扉ページについていえば、ページ内に存在する文字アイテム(text item)が少ないことが期待されます。少なくとも自分が作るようなコンテンツではそうした傾向があります。

とりあえず、AppleScriptでKeynote書類からさまざまな情報を取得し、統計的なデータを取得(ページ上に存在するtext item数の標準偏差)するなどして、全体的な傾向を把握して検討するところでしょう。

あまりやりたくはないものの、完全な一括処理(ユーザーにどれが扉ページかを問い合わせない)を行うのではなく、ユーザー(自分)に扉ページのベーススライド名を確認する処理を追加することになるでしょうか。

--> {{baseLayoutName:"タイトルのみ", itemNumList:{10, 3, 3, 7, 14, 16, 10, 8, 6, 17, 9, 11, 16, 17, 11, 3, 3, 3, 15, 7, 16, 7, 3, 8, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 12, 12, 10, 3, 3, 3, 13}, stdDev:4.939129779062}, {baseLayoutName:"タイトル(上)広告用", itemNumList:{56, 22}, stdDev:17.0}, {baseLayoutName:"セクション", itemNumList:{4, 3, 2, 2, 2, 2, 2}, stdDev:0.728431359085}}
AppleScript名:各ベースレイアウト出現頻度およびレイアウト上のアイテム数の分布から扉を推測するテスト.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/06/04
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

property NSExpression : a reference to current application’s NSExpression
property NSMutableArray : a reference to current application’s NSMutableArray

tell application "Keynote"
  tell front document
    set themeNames to name of base layout of every slide
    
set themeList to items 2 thru -2 of themeNames
    
–> {"タイトルのみ", "タイトル(上)_飾りなし", "タイトル(上)広告用", "タイトル(上)広告用", "セクション", "タイトルのみ", "タイトルのみ", "セクション", "タイトルのみ", "タイトルのみ", "セクション", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "セクション", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "セクション", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "セクション", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ", "セクション", "タイトルのみ", "タイトルのみ", "タイトルのみ", "タイトルのみ"}
    
    
set uniList to uniquify1DList(themeList) of me
    
–> {"タイトルのみ", "タイトル(上)_飾りなし", "タイトル(上)広告用", "セクション"}
    
    
set tobiraKouhoList to {}
    
    
repeat with i in uniList
      set j to contents of i
      
set tmpSList to (every slide whose name of base layout is equal to j)
      
      
if length of tmpSList ≥ 2 then
        set tRatioList to {}
        
        
repeat with ii in tmpSList
          set jj to contents of ii
          
tell jj
            set aList to (every iWork item)
            
set the end of tRatioList to length of aList
          end tell
        end repeat
        
set d1Res to calcStddev(tRatioList) of me
        
set the end of tobiraKouhoList to {baseLayoutName:j, itemNumList:tRatioList, stdDev:d1Res}
      end if
      
    end repeat
    
    
return tobiraKouhoList
    
–> {{baseLayoutName:"タイトルのみ", itemNumList:{10, 3, 3, 7, 14, 16, 10, 8, 6, 17, 9, 11, 16, 17, 11, 3, 3, 3, 15, 7, 16, 7, 3, 8, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 12, 12, 10, 3, 3, 3, 13}, stdDev:4.939129779062}, {baseLayoutName:"タイトル(上)広告用", itemNumList:{56, 22}, stdDev:17.0}, {baseLayoutName:"セクション", itemNumList:{4, 3, 2, 2, 2, 2, 2}, stdDev:0.728431359085}}
  end tell
end tell

–標準偏差を計算する
on calcStddev(aList)
  –https://nshipster.com/nsexpression/
  
set anArray to NSMutableArray’s arrayWithArray:aList
  
set anExp to NSExpression’s expressionForFunction:"stddev:" arguments:{(NSExpression’s expressionForConstantValue:anArray)}
  
set valList to anExp’s expressionValueWithObject:(missing value) context:(missing value)
  
return valList as real
end calcStddev

on uniquify1DList(theList as list)
  set theSet to current application’s NSOrderedSet’s orderedSetWithArray:theList
  
return (theSet’s array()) as list
end uniquify1DList

★Click Here to Open This Script 

Posted in Object control | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | 1 Comment

DTKeychainのじっけん

Posted on 6月 2, 2022 by Takaaki Naganoya

オープンソースのFramework「DTKeychain」をUniversal Binaryビルドして、Script Debugger環境からこれをAppleScriptで呼び出すテストを行なったものです。

–> Download DTKeychain.framework (To ~/Library/Frameworks)

macOS 10.7でKeychain Scriptingが廃止されて以来、shell commandの「security」や、さまざまなCocoa Frameworkを呼び出すようにScript側の対応が迫られてきたわけですが、割とKeychain関連のFrameworkは入れ替わりが激しいジャンルです。

SSKeychain –> SAMKeychain

ときて、いまmacOS用のKeychain系のFrameworkとして個人的に注目しているのが、

DTKeychain

です。SAMKeychainでひととおりのKeychainの機能を持っていたので、まだ機能が少ないDTKeychainは完全に代わりになってはいないのですが、SAMKeychainで様子を見つつDTKeychainの機能の充実に期待といったところでしょうか。

# DTKeychainもそんなに新しくないプロジェクトではあるものの、SAMKeychainの作者に問い合わせたところ「SAMKeychainはもうメンテしていないので他人に推奨しないでくれ(意訳)」と言われています

AppleScript名:DTKeychainのじっけん 1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/31
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use framework "DTKeychain" –https://github.com/Cocoanetics/DTKeychain

— get shared instance
set keychain to current application’s DTKeychain’s sharedInstance()

— create a keychain query for generic passwords
set query to current application’s DTKeychainGenericPassword’s keychainItemQueryForService:"foo" account:(missing value)
–> {class:"genp", svce:"foo"}

— retrieve matching keychain items
set {itemList, errorRes} to keychain’s keychainItemsMatchingQuery:query |error|:(reference)
–> {{}, missing value}

if itemList as list is not equal to {} then
  log errorRes’s localizedDescription()
end if

★Click Here to Open This Script 

AppleScript名:DTKeychainのじっけん 2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/31
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use framework "DTKeychain" –https://github.com/Cocoanetics/DTKeychain

— get shared instance
set keychain to current application’s DTKeychain’s sharedInstance()

— just create a new instance of the generic password and set values
set pass to current application’s DTKeychainGenericPassword’s new()

pass’s setAccount:"bar"
pass’s setService:"foo"
pass’s setPassword:"PIYOMARU"

— write the new object to the keychain
set kRes to keychain’s writeKeychainItem:pass |error|:(missing value)
–> true

★Click Here to Open This Script 

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

新発売:AppleScript基礎テクニック集(13)ファイル処理

Posted on 6月 1, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第13巻、「ファイル処理」です。PDF 33ページ、サンプルAppleScriptのZipアーカイブを添付。

→ 販売ページ

AppleScriptによるファイル処理は、MacBook AirからはじまったSSD標準採用、macOS 10.10以降のCocoa Scriptingの標準化、高速なApple Siliconへの移行なども相まって、非常に高速なものとなってきました。とくに、NSFileManager経由で処理をしたときの速度がすさまじく高速です。最新のOS、最新のマシンの組み合わせで必携の一冊!

目次:

最近のmacOSのファイル処理事情

AppleScriptのファイル処理には3通り
フルディスクアクセスの設定を
64ビット化されてFinderは遅くなった
どこで差がつく? ファイル処理
複数の条件をつけてFinderでファイル取得

条件抽出

ファイル情報の抽出
Finderラベルによる抽出

リネーム(名称変更)

ファイルの名称変更=リネーム
フォルダの名称変更=リネーム

コピー(複製)

ファイルのコピー
フォルダのコピー

移動

ファイルの移動
フォルダの移動

削除

ゴミ箱への移動を行うだけの「ファイル削除」
ファイルの完全削除
ゴミ箱への移動を行うだけの「フォルダ削除」
フォルダの完全削除

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

RectangleBinPackを用いて2D Bin Packを解く v2.3

Posted on 5月 31, 2022 by Takaaki Naganoya

オープンソースの「RectangleBinPack」を用いて2D Bin Packagingを解き、Keynote上の汎用オブジェクト(iWork item)を指定矩形内に詰め込むAppleScriptです。

–> Watch Demo Movie

2D Bin Packは、指定のオブジェクトを面積で評価して、ターゲットの領域に「詰め込む」(オブジェクト回転あり)という処理で、ワードクラウドであるとか、記事レイアウト時の最適化配置といった用途に用いられます。

さまざまなアルゴリズムが提唱され、コンピュータの登場初期からどえらい先人たちが攻めまくった分野であるため、ありがたく、その成果をいただいているという用途でもあります。

よく、ゲームのテクスチャ画像を1枚の画像ファイルに詰め込む際に2D Bin Packの処理を用いている例を見かけます。なんでファイルごとに分けないのかはわかりませんけれども(ファイル容量の節約???)。

–> Download Script bundle with RectangleBinPack in its bundle + sample Keynote document

# This AppleScript requires RectangleBinPack executable in its bundle. So, download the whole AppleScript bundle archive from the link above (↑)

オープン中のKeynote書類の表示中のスライド(ページ)上にある矩形オブジェクト(Shape)を指定の矩形エリア内に2D Packingします。エリアの大きさが小さすぎると正常にPackingされなかったり、false(エラー)を返したりします。

変更履歴:

v2.1: BinPackTestをIntel x64とARM binaryのそれぞれのバイナリでビルドしてバンドルに入れた(Makeを書き換えて直接Universalバイナリに仕立てられるといいのに)
v2.2: BridgePlusがなくても動くように書き換えた(ないと動かないのはいろいろ運用上問題がある)
v2.3: shapeに対してBinPackしていたのを、Keynote上の汎用オブジェクトへのアクセス予約語iWork itemでアクセスするように変更した

AppleScript名:rectBinPack v2.3_Universal.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/31
—
–  Copyright © 2019-2022 Piyomaru Software, All Rights Reserved
—
— 2D Bin Packing by juj https://github.com/juj/RectangleBinPack
— v2.1: BinPackTestをIntel x64とARM binaryのそれぞれのバイナリでビルドしてバンドルに入れた(Universalバイナリに仕立てられるといいのに)
— v2.2: BridgePlusを外した(ないと動かないのはいろいろ運用上問題がある)
— v2.3: shapeに対してBinPackしていたのを、Keynote上の汎用オブジェクトへのアクセス予約語iWork itemでアクセスするように変更した

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

–Packaging Target Area
set binSizeX to 600
set binSizeY to 600

set packRes to packKeynoteObjectsOnCurrentSlide(binSizeX, binSizeY) of me

on packKeynoteObjectsOnCurrentSlide(binSizeX, binSizeY)
  set {tList, a0List} to retRectsFromKeynote() of me
  
  
set aList to sortList2DDecending(a0List, {"myWidth", "myHeight", "myArea"}) of me –Sorting key is Width(main) and Area(sub) and Height(sub)
  
  
set aRes to twoDBinPacking(binSizeX, binSizeY, aList) of me
  
if aRes = false then return false
  
  
tell application "Keynote"
    tell front document
      tell current slide
        repeat with i in aRes
          set {posX, posY} to myPos of i
          
set itemIndex to myID of i
          
set aDeg to myDegree of i
          
          
–sample data {itemCounter:5, myWidth:573, myHeight:52, myArea:29796}
          
set anObjID to itemCounter of (item itemIndex of aList)
          
          
set rotation of iWork item anObjID to aDeg
          
set position of iWork item anObjID to {posX, posY}
        end repeat
      end tell
    end tell
  end tell
  
  
return true
end packKeynoteObjectsOnCurrentSlide

on twoDBinPacking(binSizeX as integer, binSizeY as integer, boxList as list)
  set aParamList to {binSizeX, binSizeY}
  
  
repeat with i in boxList
    –copy i to {tmpID, tmpX, tmpY, tmpArea}
    
— {itemCounter:iCount, myWidth:aWidth, myHeight:aHeight, myArea:anArea}
    
set tmpID to itemCounter of i
    
set tmpX to myWidth of i
    
set tmpY to myHeight of i
    
set tmpArea to myArea of i
    
    
set aParamList to aParamList & tmpX
    
set aParamList to aParamList & tmpY
  end repeat
  
  
set aParam to retDelimitedText(aParamList, " ") of me
  
–> "800 800 340 243 340 73 340 73 155 240 147 125 147 125 147 125 147 125"
  
  
–Parameters for result parsing
  
set s1Str to "Packed to (x,y)=("
  
set s2Str to ")"
  
set s3Str to ","
  
  
set cpuRes to CPU type of (system info)
  
if cpuRes begins with "ARM" then
    set exName to "arm"
  else if cpuRes begins with "Intel" then
    set exName to "x86"
  end if
  
  
set binName to "BinPackTest_" & exName
  
set aPath to POSIX path of (path to resource binName)
  
  
try
    set aRes to do shell script quoted form of aPath & " " & aParam
  on error
    return false
  end try
  
  
if aRes does not end with "Done. All rectangles packed." then return false
  
  
set aList to paragraphs of aRes
  
  
set bList to {}
  
set aCount to 1
  
repeat with i in aList
    set j to contents of i
    
if j begins with "Packing rectangle of size " and j does not contain "Failed!" then
      set xyRes to pickUpFromToStrAndParse(j, s1Str, s2Str, s3Str) of me
      
      
–RectangleBinPackがオブジェクトの回転をサポートしているため、その対処
      
if xyRes is not equal to false then
        set s11Str to "(w,h)=("
        
set s12Str to ")"
        
set s13Str to ","
        
        
set whRes to pickUpFromToStrAndParse(j, s11Str, s12Str, s13Str) of me
        
set tmpBox to item aCount of boxList
        
        
— {itemCounter:5, myWidth:573, myHeight:52, myArea:29796}
        
–copy tmpBox to {tmpID, tmpX, tmpY, tmpArea}
        
set tmpID to itemCounter of tmpBox
        
set tmpX to myWidth of tmpBox
        
set tmpY to myHeight of tmpBox
        
set tmpArea to myArea of tmpBox
        
        
if whRes = {tmpX, tmpY} then
          set aDeg to 0
        else if whRes = {tmpY, tmpX} then
          set aDeg to 90
        else
          return false
        end if
        
        
set the end of bList to {myPos:xyRes, myID:aCount, myDegree:aDeg}
      end if
      
set aCount to aCount + 1
    end if
  end repeat
  
  
return bList
end twoDBinPacking

on pickUpFromToStrAndParse(aStr as string, s1Str as string, s2Str as string, s3Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
set {x, y} to parseByDelim(cStr, s3Str) of me
  
  
return {x as integer, y as integer}
end pickUpFromToStrAndParse

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 retDelimitedText(aList, aNewDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aNewDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimitedText

on retRectsFromKeynote()
  tell application "Keynote"
    tell front document
      tell current slide
        set tList to every iWork item
        
set bList to {}
        
set iCount to 1
        
        
repeat with i in tList
          set aWidth to width of i
          
set aHeight to height of i
          
set {xPos, yPos} to position of i
          
set anArea to aWidth * aHeight
          
          
set the end of bList to {itemCounter:iCount, myWidth:aWidth, myHeight:aHeight, myArea:anArea}
          
set iCount to iCount + 1
        end repeat
        
        
return {tList, bList}
      end tell
    end tell
  end tell
end retRectsFromKeynote

–入れ子のリストを降順ソート
on sortList2DDecending(a, keyLabelList)
  set fLen to length of keyLabelList
  
set fList to {}
  
  
repeat fLen times
    set the end of fList to false
  end repeat
  
  
return cocoaSortListAscending(a, keyLabelList, fList) of me
end sortList2DDecending

–Cocoaで入れ子のリストをソート true:昇順、false:降順
on cocoaSortListAscending(theList as list, keyLabelList as list, ascendingF as list)
  set anArray to current application’s NSMutableArray’s arrayWithArray:(theList)
  
  
set sortDesc to {}
  
set dLen to length of keyLabelList
  
repeat with i from 1 to dLen
    set tmpKeyLabel to contents of item i of keyLabelList
    
set tmpSortF to contents of item i of ascendingF
    
set theDescriptor to (current application’s NSSortDescriptor’s sortDescriptorWithKey:(tmpKeyLabel) ascending:(tmpSortF))
    
set the end of sortDesc to theDescriptor
  end repeat
  
  
set sortedList to anArray’s sortedArrayUsingDescriptors:(sortDesc)
  
  
return sortedList as list
end cocoaSortListAscending

★Click Here to Open This Script 

Posted in 2D Bin Packing list Sort | Tagged 11.0savvy 12.0savvy Keynote | 1 Comment

人類史上初、魔導書の観点から書かれたAppleScript入門書「7つの宝珠」シリーズ開始?!

Posted on 5月 30, 2022 by Takaaki Naganoya

いつものようにコードレス糸電話(FaceTime Audio)で企画会議を行なっていたら、「プログラミングを魔導書の形式で書くことが可能なのではないか?」というアイデアが登場。その場でアイデアスケッチを行い、あれよあれよという間に、実物ができてしまいました。

→ 販売ページ

ノリと勢いだけで作ってしまった1冊ですが、ビジュアル要素多めでまとめられました。ただ、宗教的なアレとかナニとかを完全に無視して作ったものなので、日本国内でしか流通させないほうがよいでしょう。

本書は、プログラミングという魔法について、「魔導書」の観点から記した人類最初の書物である。

難解なプログラミングを、なじみ深い魔導書の観点から説明すると親しみやすくなるのだろうか、という1つの魔術モルモット実験でもある。

本書で扱う内容はごくごく簡単で基礎的な内容だが、このぐらいにしぼって解説すれば難しく見えないという7テーマ、七宝珠である。

「習うより慣れろ」ということわざがあるように、難解な魔術であっても苦手意識を持たずに「慣れる」ことは重要である。 本書をもってしても、真の魔道士を育成することは難しい。だが、「だいたいこんなかんじ」という感覚をつかむためには、このぐらいの分量に抑えることが肝要だろう。

PDF 31ページ

目次

■魔導書「7つの宝珠」

神(Computer)との対話を行う人の子の書
失われし魔法の7つの宝珠を求めて
変数と代入文という最初の宝珠
if文〜条件分岐という宝珠
繰り返しループ 体力を削らせない宝珠
配列変数 詠唱呪文の機能を高める宝珠
コメント文 失われた知恵の宝珠
ログ表示 簡単に変数の中身を確認する宝珠
終了 そこで呪文実行を止める宝珠

■第1の宝珠 変数と代入文

神の言葉から人の子の言葉への移行
巻物で満ち溢れる人の子の世
牛飼いを羊飼いに変える変数
変数に牛や羊を入れるのが「代入」
変数の中に何がある?

■最短詠唱呪文集

魔術入門〜最短詠唱呪文
警告音を鳴らす魔術「beep」
現在の日付を知る魔法「current date」
クリップボードの内容を調べる魔法
時間待ちを行う魔法「delay」
ゆうしゃ(=あなた)のステータス

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

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

Posted on 5月 29, 2022 by Takaaki Naganoya

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

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

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

Keynoteで選択中のスライドのすべての表のセル内文字色を黒にする

Posted on 5月 27, 2022 by Takaaki Naganoya

Keynote v12.0以降で、最前面の書類で選択中のスライド(複数可)にある表のすべての文字色を「黒」に変更するAppleScriptです。

–> Watch Demo Movie

Keynote v12.0で「selection」がまともに機能するようになったので、Keynote用Scriptの実用性がたいへんに高まっています。

# ファイル保存できないとかいうバグが一刻も早く治ることを希望しています。とくに、Pages!

もともと、複数ページにわたって掲載している「表」の中に赤字でマークした箇所があって、そのマークの意図とは別の赤字を入れたかったので、いったんすべて書式をリセットしたかったので書いたものです。

もうちょっと長いScriptを書かなければならないかと思っていたのですが、ことのほかシンプルに書けました。
もっとシンプルに書けるか(everyを使ってスライドごと指定するとか)も試してみたのですが、どうやらこのあたりが限界のようです。

Keynoteのselectionを活かしたScriptでいまいちばん活躍しているのは、Keynoteのテキストアイテム(text item)から内容を取得して、メモリ上でAppleScriptとしてコンパイルし、構文色分けを反映させたスタイル付きテキストを取得して、テキストアイテムに書式を反映させるものです。実に、Keynote上にテキストで書いておいたAppleScriptのリストを構文色分けを反映させた掲載リストに変換できるので便利です。

AppleScript名:Keynoteで選択中のスライドのすべての表のセル内文字色を黒にする.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/27
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

tell application "Keynote"
  set aVer to version
  
  
considering numeric strings
    if aVer < 12.0 then return –Keynote v12.0より以前のバージョンでは実行できない
  end considering
  
  
tell front document
    set aaSel to selection
    
set selClass to class of contents of first item of aaSel
    
if selClass is not equal to slide then return –選択中のオブジェクトがslide(ページ)でなければ処理終了
    
    
repeat with i in aaSel
      set j to contents of i
      
      
tell j
        –現在のスライド上のすべての表のすべてのセルの文字色を黒 {0, 0, 0}に
        
set text color of every cell of every table to {0, 0, 0}
      end tell
      
    end repeat
    
  end tell
  
end tell

★Click Here to Open This Script 

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

新発売:AppleScript基礎テクニック集(12)Unix shell commandの利用

Posted on 5月 26, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第12巻、「Unix shell commandの利用」です。PDF 34ページ、サンプルAppleScriptのZipアーカイブを添付。

→ 販売ページ

Unix shell commandの利用といったときに、「AppleScriptからdo shell scriptコマンドでshell commandを呼び出す」話と、「shell commandやshell scriptの中でAppleScriptで書いたプログラムを呼び出す」という、まったく価値観の異なる別の話が含まれています。

本書は、これらのまったく別な話に含まれている概念やノウハウを整理し、わかりやすく具体的にその方法や制限についてご紹介する本です。

目次

■Terminal環境とdo shell script環境の違い

shell scriptをAppleScriptと組み合わせるために
ターミナルに書類のパスを入力する方法
Terminalからプロセスの確認と終了を
Terminalとdo shell sciptの環境変数
Terminal.appをAppleScriptで操作できる①
Terminal.appをAppleScriptで操作できる②

AppleScriptからshell scriptを呼び出す

do shell scriptコマンド
パス形式変換
Terminal.app上と同じ環境変数を使用するには
参考資料:新規インストールしたユーザーの環境変数
パラメータの与え方について
do shell scriptコマンドちょっといいノウハウ
コマンドライン呼び出しプログラムをScriptに同梱

shell scriptからAppleScriptを呼び出す

AppleScript関連のshell command
shell scriptからAppleScriptを呼び出す方法①
shell scriptからAppleScriptを呼び出す方法②
パラメータ指定できるAppleScriptの書き方
AppleScriptライブラリを呼び出せる?
パイプで指定した内容を受信できる?
GUI Scriptingを利用できる?
ホームディレクトリ下のFrameworkを呼べる?

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

Pages v12に謎のバグ。書類上に11枚しか画像を配置できない→解決

Posted on 5月 23, 2022 by Takaaki Naganoya

Pages v12に謎のバグを見つけました。Pagesでは書類上に任意の画像を配置できるわけですが、11枚目までは配置できるものの、12枚目を配置できません。実際には120枚ほど画像を用意してテストしていたので、12枚目が配置できればそれでOKかと言われれば、ぜんぜん不十分です。

→ OSの再起動を含む、追試を何回か行ってみたところ、その後このままでは画像の貼り込みができなくなっていました。そして、画像ファイル貼り込み前にパスの文字列をaliasにcastしたところ、問題なく120枚貼り込めました。

–> Watch Movie

以前にも、Keynoteに「特定サイズ以上の表を作るとエラーになる」とかいったバグが発生していましたが、この12個目を配置するとエラーになるというのも、内部で何か不可思議なリミッターを設けているように見えます。

スクリプトエディタ、Script Debuggerの両方で発生しています。おそらく、ランタイム環境が何であるかはこの問題に影響を与えていません。

macOS 10.12以降で、日本語環境限定で発生しているバグで有名なものに、「日本語入力Input Method経由でファイル名を入力している最中に、不必要な不可視文字が入力されてしまい、これがファイル処理を妨げる危険性がある」というものがありますが、これらの画像のファイル名をチェックしたところ、そうした危険な不可視文字は混入していませんでした。

# こうした、複数チームの担当製品の間で発生しているバグは、どこが担当してバグを調査するということはないようです。組織の細分化にともない、こうした組織境界面でバグが発生するととたんに無責任になるのがいまのAppleです(組織の構造上の問題です)

ちなみに、GUI経由で画像をPages書類上に配置してみたところ、12枚以上配置できました。Pagesにそのような上限が存在しているわけではないようです。

Pages書類(バンドル書類)内で何かファイル名の重複のようなものが発生したのかと考え、別の画像を(番号をずらして)指定してみましたが、同様の枚数を配置した時点でエラーになりました。

内部で発生している(していた)別のエラーを発生させないように、謎のリミッターをかけていた可能性もありますが、その必然性がよくわかりません。

AppleScript名:指定の画像をPagesに順次貼り込む(12枚で止まってしまう!).scpt
set baseName to "book24_"
set baseFol to (choose folder) as string

set pMax to 10

(*
tell application "Pages"
  –set newDoc to make new document
  
  tell front document
    set dCount to count every page
    
    repeat with i from (dCount + 1) to pMax
      make new page
    end repeat
    
    set newDCount to count every page
  end tell
end tell
*)

repeat with i from 1 to 120
  set aFN to baseFol & baseName & makeFN(i, 4) of me & ".jpg"
  
tell application "Pages"
    tell front document
      tell page i
        set newItem to make new image with properties {file:aFN}
        
tell newItem
          set position of it to {0, 0}
          
set height of it to 843
          
–set position of it to {-1, 0}
          
set locked to true
        end tell
      end tell
    end tell
  end tell
end repeat

on makeFN(aNum, aDigit)
  set aText to "00000000000" & (aNum as text)
  
set aLen to length of aText
  
set aRes to text (aLen – aDigit + 1) thru -1 of aText
  
return aRes
end makeFN

★Click Here to Open This Script 

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

iWorkアプリケーションv12に共通のバグ? 新規ファイルの保存ができない

Posted on 5月 23, 2022 by Takaaki Naganoya

Apple iWorkアプリケーション(Keynote、Pages、Numbers)の最新バージョンv12.0において、共通のバグがあるのではないか? と見ています。もちろん、見ているだけでなくAppleにバグレポートもしています。

症状は、新規作成した書類を「保存できない」というものです。

以前にも、PDFをexportできないという致命的なバグが発生していましたが、今回のも同様のメカニズムで発生しているものと見ています。つまり、「Appleが自社OSに設定したセキュリティ機能によって、自社アプリであるKeynote、Pages、Numbersが自家中毒を起こしている」という状態です。

自分の勘違いだとよいのですが….

あとは、Numbersのsaveコマンドをよく見てみると、書類フォーマットに「as Numbers」というenumがあるのですが、これはAppleScriptの処理系では「number」の複数形として認識されてしまうので、この予約語自体に無理があります。ここは、「as Numbers format」といった予約語に変えるべきです。

AppleScript名:Keynoteで新規書類作成して指定名称で新規保存.scpt
set dtPath to (path to documents folder) as string
set uuidStr to (do shell script "uuidgen") & ".key"
set savePath to dtPath & uuidStr

tell application "Keynote"
  set nDoc to make new document with properties {document theme:theme id "Application/21_BasicWhite/Standard", width:1024, height:768}
  
save nDoc in file savePath as Keynote
end tell

★Click Here to Open This Script 

AppleScript名:Pagesで新規書類を作成して指定名称で新規保存.scpt
set dtPath to (path to documents folder) as string
set uuidStr to (do shell script "uuidgen") & ".pages"
set savePath to dtPath & uuidStr

tell application "Pages"
  set nDoc to make new document with properties {document template:template id "Application/Blank/ISO"}
  
save nDoc in file savePath as Pages Format
end tell

★Click Here to Open This Script 

AppleScript名:Numbersで新規書類作成して指定名称で新規保存.scpt
set dtPath to (path to documents folder) as string
set uuidStr to (do shell script "uuidgen") & ".numbers"
set savePath to dtPath & uuidStr

tell application "Numbers"
  set nDoc to make new document
  
save nDoc in file savePath as numbers –change "Numbers" word into "numbers format" because "numbers" is alredy registered as "list of number" or "every number"
end tell

★Click Here to Open This Script 

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

新発売:AppleScript基礎テクニック集(11)AppleScriptアプレットとドロップレット

Posted on 5月 20, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第11巻、「AppleScriptアプレットとドロップレット」です。PDF 41ページ、サンプルAppleScriptのZipアーカイブを添付。

→ 販売ページ

本シリーズも、着手した頃には「そんなに細切れのテーマで書けるのか?」「そんな作り方で作れるはずがない」といった意見が集まっていたものですが(チーム内の打ち合わせ時には割と批判的です)、実際に作り出したらトンでもなく「書くべきこと」があって、書けば書くほど新たなテーマが見つかるという恐るべき状態。

今回の「アプレット」「ドロップレット」については、あまり振り返ったことがなかったのですが、いざ書いてみると尋常でないほどの情報が溜まっていました。

スクリプトエディタとScript Debuggerという2つの開発環境のちがい、アプレット、ドロップレット、Cocoa-AppleScriptアプレット、Script Debuggerの拡張ドロップレットなどなど。常駐タイプのアプレットに、タイマー割り込み処理のアプレット。アプレットのアイコンのカスタマイズに、アプレット内にAppleScriptライブラリを同梱する方法、Cocoa Frameworkを入れて呼び出す方法など、盛りだくさんな内容をお送りしています。

目次

■アプレット

AppleScriptをアプリケーション形式で書き出し
AppleScriptアプレットの種類
AppleScriptアプレットの作成方法
AppleScriptアプレットのオプション指定
常駐型AppleScriptアプレットの作成方法
常駐型AppleScriptアプレットの記述
アプレットの「初期画面」を指定
「初期画面」に画像をペーストした場合の動作
アプレット/ドロップレットのユーザーインタフェース
資料:スクリプト/アプレットのバンドル構造
資料:アプレットのカスタマイズ①
資料:アプレットのカスタマイズ②
資料:アプレットのカスタマイズ③

■Cocoa-AppleScriptアプレット

Cocoa-AppleScriptアプレットの作成方法
参考資料:Delegateスクリプトの内容確認方法
参考資料:Delegateスクリプトのヘッダー内容
参考資料:Delegateスクリプトのハンドラ

■Script Debuggerのアプレット/拡張アプレット

AppleScriptアプレット(SD)の作成方法
AppleScript拡張アプレット(SD)の作成方法
AppleScript拡張アプレット(SD)の作成方法

■ドロップレット

AppleScriptドロップレットの作成方法
AppleScriptドロップレットの作成方法
ドロップレットによるファイルの受信
macOS 10.12以降の問題への対策ドロップレット
macOS 12.4上でドロップレット処理を実験

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

新発売:AppleScript基礎テクニック集(10)ループ処理

Posted on 5月 13, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第10巻、「ループ処理」です。PDF 33ページ、サンプルAppleScriptのZipアーカイブを添付。

→ 販売ページ

ループ処理について、さまざまなrepeat文のバリエーションをまんべんなくすべて知って理解するよりも「間違いなく必要な場所で使える」ことが重要です。

repeat文にもいくつか書き方はあるものの、おおよそ2パターンぐらいでだいたい足ります。

それでも、複数の配列を同時にループしなくてはならないとか、ステップ値を想定の値に合わせるための調整とか、ノウハウらしきものはいろいろあります。

また、参照値をそのまま使うとエラーになる例もあるため、「contents of」でオブジェクトを取り出す必要があるといったささいなノウハウが必要なものでもあります。

目次

■ループによる繰り返し処理

AppleScriptの制御構文
繰り返しループ
repeat文①
repeat文②
repeat文③
repeat文④
repeat文⑤
repeat文⑥
exit repeat
多重ループ+exit repeat

■アプリケーションから取得したオブジェクトでループ

アプリケーションのオブジェクトを処理
Photos上の選択中の写真から情報を取得
Keynoteで選択中のオブジェクトを位置でソート
Numbersで表のセルが連結されていたら分離
targetが重複しているFinder Windowをクローズする
ミュージック.appで選択中のtrackの情報取得
大量のオブジェクト受信に備える

■高度な処理を簡潔に記述

複数の配列の同時ループ
ページ分け
再帰処理

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

Safariで表示中のYouTubeムービーのサムネイル画像を取得

Posted on 5月 9, 2022 by Takaaki Naganoya

Safariで表示中のYouTubeムービーのサムネール画像を取得、保存、表示するAppleScriptです。

YouTubeのムービーのサムネール画像の取得方法を確認し、動作確認用にダイアログ表示+画像保存の機能を追加したものです。Script Debugger上で動かしている分には、NSImageの内容を結果表示ビューワで自動表示されますが、ない人向けに付けた機能です。

画像自体は、「ピクチャ」フォルダにUUIDつきでPNG形式で保存します。

–> Download Script bundle with Library

掲載リストには、画像表示ライブラリが含まれていないため、そのままでは実行できません。上記のScript Bundleをダウンロードして実行する必要があります。

AppleScript名:Safariで表示中のYouTubeムービーのサムネイル画像を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/09
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use imgLib : script "imageDisplayLib"

property NSUUID : a reference to current application’s NSUUID
property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSURLComponents : a reference to current application’s NSURLComponents
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSMutableDictionary : a reference to current application’s NSMutableDictionary

tell application "Safari"
  tell front document
    try
      set aURL to URL
    on error
      set aURL to "https://www.youtube.com/watch?v=_fmDtIV9vvI"
    end try
  end tell
end tell

if aURL does not start with "https://www.youtube.com/watch?" then return

set urlDict to parseURLParamsAsDict(aURL) of me
set aParam to urlDict’s valueForKey:"v"
if aParam = missing value then return

set imgURL to "https://i1.ytimg.com/vi/" & (aParam as string) & "/mqdefault.jpg"
set newURL to |NSURL|’s URLWithString:imgURL
set aImg to NSImage’s alloc()’s initWithContentsOfURL:newURL

set imgPath to (POSIX path of (path to pictures folder) & ((aParam as string) & "_") & (NSUUID’s UUID()’s UUIDString()) as string) & ".png"

–Save
saveNSImageAtPathAsPNG(aImg, imgPath) of me

–Display
dispImage(aImg, "YouTube thumbnail") of imgLib

on parseURLParamsAsDict(aURL)
  set components to NSURLComponents’s alloc()’s initWithString:aURL
  
set qList to (components’s query())’s componentsSeparatedByString:"&"
  
  
set paramRec to NSMutableDictionary’s dictionary()
  
  
repeat with i in qList
    set keyAndValues to (i’s componentsSeparatedByString:"=")
    (
paramRec’s setObject:(keyAndValues’s objectAtIndex:1) forKey:(keyAndValues’s objectAtIndex:0))
  end repeat
  
  
return paramRec
end parseURLParamsAsDict

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
  
set myNewImageData to (aRawimg’s representationUsingType:(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 Image Record Text URL | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy Safari | Leave a comment

新発売:AppleScript基礎テクニック集(9)ダイアログ表示

Posted on 5月 6, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第9巻、「ダイアログ表示」です。PDF 43ページ、サンプルScript、AppleScriptライブラリのZipアーカイブを添付。

→ 販売ページ

ダイアログ表示については、たいへん基礎的な内容でありながらも数多くの機能が盛り込まれています。サードパーティ側でさまざまなダイアログを作れるようになってきて、「みんなが思っているよりも、けっこう便利」な環境ができています。

利用するかしないかは、皆様の判断によると思いますが、実際に利用した方は割と便利で手放せなくなるようです。

目次

ダイアログ表示

標準搭載のさまざまなダイアログ表示機能
メッセージ表示系ダイアログ
メッセージ表示系ダイアログ
ファイル選択ダイアログ
フォルダ選択ダイアログ
ファイル名選択ダイアログ
多項目選択系ダイアログ
色選択ダイアログ
LAN内のリモート資源の選択
ローカルのアプリケーションの選択
リモート・アプリケーションの選択

AppleScriptライブラリを利用したダイアログ表示

AppleScriptライブラリの用語辞書の確認方法
筆者のライブラリにはサンプルScript掲載
iPhoneやiPad、MacとAirDrop通信
チェックボックス選択ダイアログを表示
日付選択ダイアログを表示
場所選択ダイアログを表示
複数ポップアップ選択ダイアログを表示
指定のRTF書類から抽出した書式を選択するダイアログ
指定の場所を異なる拡大倍率で地図表示
表形式のデータをダイアログ表示
ラベルつきテキストフィールドを表示/データ修正
指定色の一覧選択ポップアップメニューを表示
Scriptでカスタマイズ可能な複雑なダイアログ

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

Keynoteのタイトル内の強制改行コードを置換….できない?

Posted on 5月 3, 2022 by Takaaki Naganoya

Keynote v12のスライド(ページ)内のタイトル(default title item)内のテキスト(object text)の強制改行を置換(削除)できないという件についての試行錯誤です。

もともと、v12以前のバージョンのKeynoteでは、LF+LFを削除することで、タイトル内のテキストの改行削除は行えていました。

ただ、同様の処理では強制改行を削除し切れないようで….

--> {"AppleSript+NSImageでよく使う

基礎的な処理一覧", "画像ファイル
変換処理", "画像回転処理", "画像ファイルからの

情報取得処理", "画像リサイズ処理", "画像フィルタ処理"}

いまひとつすっきりしません。

Keynoteのタイトル文字列をコピーして、CotEditor(文字コードをAppleScriptと同じUTF16BEに変更)の書類上にペーストすると0Ahと表示するのですが、どうもKeynote上では異なるようで困ります。

AppleScript名:Keynote v12上の選択中のスライドのタイトルをテキスト化(改行削除)(未遂).scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/03
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set repTargList to {string id 10 & string id 10, string id 10, string id 11, string id 13} –LF,CR,VTab一括置換

tell application "Keynote"
  tell front document
    set aSel to selection
    
set aList to {}
    
    
repeat with i in aSel
      set tmpClass to class of i
      
if tmpClass = slide then
        set tmpStr0 to object text of default title item of i
        
set hexList to retHexDumpedStr(tmpStr0) of me
        
set tmpStr1 to (paragraphs of tmpStr0) –パラグラフごとにlistにしてみた
        
log tmpStr1
        
set tmpStr2 to replaceTextMultiple(tmpStr1 as string, repTargList, "") of me as string
        
set the end of aList to tmpStr2
      end if
    end repeat
  end tell
end tell

return aList

–文字列の前後の改行と空白文字を除去
on cleanUpText(someText)
  set theString to current application’s NSString’s stringWithString:someText
  
set theString to theString’s stringByReplacingOccurrencesOfString:" +" withString:" " options:(current application’s NSRegularExpressionSearch) range:{location:0, |length|:length of someText}
  
set theWhiteSet to current application’s NSCharacterSet’s whitespaceAndNewlineCharacterSet()
  
set theString to theString’s stringByTrimmingCharactersInSet:theWhiteSet
  
return theString as text
end cleanUpText

–指定文字列からCRLFを除去
on cleanUpCRLF(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set bString to aString’s stringByReplacingOccurrencesOfString:(string id 10) withString:"" –remove LF
  
set cString to bString’s stringByReplacingOccurrencesOfString:(string id 13) withString:"" –remove CR
  
set dString to cString as string
  
return dString
end cleanUpCRLF

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

–任意のデータから特定の文字列を複数パターン一括置換
on replaceTextMultiple(origData as string, origTexts as list, repText as string)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to origTexts
  
set origData to text items of origData
  
set AppleScript’s text item delimiters to {repText}
  
set origData to origData as text
  
set AppleScript’s text item delimiters to curDelim
  
return origData
end replaceTextMultiple

on hexDumpString(aStr as string)
  set theNSString to current application’s NSString’s stringWithString:aStr
  
set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set theString to (theNSData’s |debugDescription|()’s uppercaseString())
  
  
–Remove "<" ">" characters in head and tail
  
set tLength to (theString’s |length|()) – 2
  
set aRange to current application’s NSMakeRange(1, tLength)
  
set theString2 to theString’s substringWithRange:aRange
  
  
–Replace Space Characters
  
set aString to current application’s NSString’s stringWithString:theString2
  
set bString to aString’s stringByReplacingOccurrencesOfString:" " withString:""
  
  
set aResList to splitString(bString, 2)
  
–> {​​​​​"E3", ​​​​​"81", ​​​​​"82", ​​​​​"E3", ​​​​​"81", ​​​​​"84", ​​​​​"E3", ​​​​​"81", ​​​​​"86", ​​​​​"E3", ​​​​​"81", ​​​​​"88", ​​​​​"E3", ​​​​​"81", ​​​​​"8A"​​​}
  
  
return aResList
end hexDumpString

–Split NSString in specified aNum characters
on splitString(aText, aNum)
  set aStr to current application’s NSString’s stringWithString:aText
  
if aStr’s |length|() ≤ aNum then return aText
  
  
set anArray to current application’s NSMutableArray’s new()
  
set mStr to current application’s NSMutableString’s stringWithString:aStr
  
  
set aRange to current application’s NSMakeRange(0, aNum)
  
  
repeat while (mStr’s |length|()) > 0
    if (mStr’s |length|()) < aNum then
      anArray’s addObject:(current application’s NSString’s stringWithString:mStr)
      
mStr’s deleteCharactersInRange:(current application’s NSMakeRange(0, mStr’s |length|()))
    else
      anArray’s addObject:(mStr’s substringWithRange:aRange)
      
mStr’s deleteCharactersInRange:aRange
    end if
  end repeat
  
  
return (current application’s NSArray’s arrayWithArray:anArray) as list
end splitString

–与えられたデータ内容をhexdumpして返す
on retHexDumpedStr(aStr)
  set aRes to do shell script "echo " & quoted form of aStr & " | hexdump -v "
  
return aRes
end retHexDumpedStr

★Click Here to Open This Script 

Posted in Object control Text | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | Leave a comment

新発売:AppleScript基礎テクニック集(5)〜変数、プロパティ名

Posted on 4月 20, 2022 by Takaaki Naganoya

電子書籍の新刊を発売しました。新シリーズ「AppleScript基礎テクニック集」の第5巻、「変数、プロパティ名」です。PDF 31ページ、掲載Scriptアーカイブつき。

→ 販売ページ

変数名の決め方……自分がそこで困ったり悩んだり苦しんだりしたことはないのですが、いろいろ聞いてみると意外なほど困っている様子。え、そこなの????

長い変数名、短い変数名、プロパティとグローバル変数はどこが違うの? といった聞きたいけど聞く相手がいないといった「素朴な疑問」をなるべくあぶり出して、明確になるようまとめてみました。PDF 31ページ、掲載ScriptのZipアーカイブを添付。

変数/プロパティとは?

変数ってなに?
変数に入れられるものは?
ローカル変数とグローバル変数
変数の型ってあるの?
変数の型の確認方法は?
propertyと変数の違い(1/2)
propertyと変数の違い(2/2)
暗黙のrunハンドラ
暗黙のrunハンドラ内の変数
propertyの有効範囲=スコープ
propertyの有効範囲を超える
暗黙のrunハンドラ内の変数と各ローカル変数との衝突?

変数/プロパティの名前の決め方

変数名の命名ルール
「予約語」と衝突しない命名を
「予約語」と衝突しない命名を
アプリケーションの予約語
AppleScriptの単語が何として認識されているか
かんたんな変数名/プロパティ名の付け方
変数/プロパティの運用の要点

Posted in Books news | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy | 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

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 13.6.5 AS系のバグ、一切直らず
  • CotEditorで2つの書類の行単位での差分検出
  • Apple純正マウス、キーボードのバッテリー残量取得
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • ディスプレイをスリープ状態にして処理続行
  • 指定のWordファイルをPDFに書き出す
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • macOS 13 TTS環境の変化について
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • 可変次元のベクトルに対応したコサイン類似度計算
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (206) 13.0savvy (163) 14.0savvy (112) 15.0savvy (89) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (19) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (71) Pages (53) Safari (44) Script Editor (26) 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)
  • 未分類

アーカイブ

  • 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