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

投稿者: Takaaki Naganoya

JSON形式のKeynote書類「.keyx」の現状

Posted on 11月 27 by Takaaki Naganoya

Apple Creator Studio版のKeynote、バージョン16.0以降で、JSON形式で記述されたKeynote書類「.keyx」に対応しました。

このことは以前から明らかにされていたものの、その詳細とv16.0時点の実装レベルが明らかになっていませんでした。

自分の予想はこちらの投稿記事のとおりですが、実際のところはどうなんでしょうか?

Keynote v16.0の.keyx作成手順

通常のKeynote書類から.keyxファイルを作成する手順をまとめておきます。Keynote上でファイルの保存(Save)機能から保存オプションを指定するのかと思っていたら、「ファイル」>「書き出す」>「Keynote X…」という手順で書き出すことになります。

このことは、.keyxの書き出しと解釈が未完成で、書き出し時にレイアウトが壊れたり欠落する要素が存在することを示唆しています。

実際に.keyxの書き出し画面ではこの機能が「ベータ版」であることについて、ほぼ上記内容どおりの注意が表示されます。

.keyx書類にはすでにUTI「.apple.keynote.interchange」が割り振られており、OS側からも認識されています。また、.keyxは「Keynote書類の1バージョン」ではなく、交換用の「Keynote Interchange Format」として位置づけられています。ネイティブ形式のかわりになるものではない、ということです。

現時点で、オンラインドキュメントを読んだかぎりでは、各オブジェクトの「影」(shadow)がサポートされていないようです。

.keyx書類の内部構造の確認方法

.keyx形式書類を書き出して、Finder上でダブルクリックしてオープンすると、Keynote上でそのままオープンされ、オープン後は.key書類として扱われます。つまり、オープンに見せてはいるものの、実質的にはインポート動作を行なっていることになります。

ただし、ファイルパス未決定の「未保存の書類」みたいな扱いになります。ファイル名は反映されています。拡張子は「.keyx」ではなく「.key」になります。

.keyx形式での書き出しは、まだKeynote v16.0のAppleScript用語辞書には反映されていません。

.key書類を.keyx書類に変換したさいのファイル容量の変化について、大幅に増加するものと予想していましたが、そのとおりでした。

3ページほどのサンプル書類、.key形式で531KBのファイル(シングルファイル、バンドルともに同容量)が、.keyx形式では19.1MBへと巨大化します。

書き出した.keyx書類は、拡張子を.zipに変更してダブルクリックすると、アーカイブが展開され、その内容を直接編集できるようになります。

書類名のフォルダの中に、Dataフォルダ(画像など)main.json、manifest.json、presets.jsonなどのファイルが存在しています。

Keynoteではいまでも書類形式をシングルファイル形式とパッケージ形式の2タイプ採用しており、このパッケージ形式と.keyx形式は(まったく同じではないものの)似たような雰囲気を持っています。

.keyx形式書類についての解説ドキュメント

Appleのオンラインドキュメントとして、「Keynote Interchange Format」が公開されています。

ただし、現状ではおおまかな構造を把握するのに役立つ程度で、詳細を見ていくと「not included」「not supported」のオンパレードです。

このことは、.keyx内部のJSONファイルを操作するプログラムを組んでも、今後のバージョンアップによって無駄になる可能性が高いことを示唆しています。

.keyx書類の操作と作成

一方、Appleは.keyx操作のためのPythonライブラリ「Creator Studio Document Format」をオープンソースで提供しています。

同ライブラリはPython 3.13以降を前提としているとのこと。

Pythonのサンプルスクリプトを眺めていると、ドキュメント内の厳密な階層構造を上から順にたどっていく必要もなく、部品から作ってスライドや書類の要素として取り込むスタイルのようです。

.keyx形式について、こうした仕組みが存在していないとAIから任意の書類を作成させるといった処理自体が行えないため、必要に迫られて策定したものでしょう。

本来やりたかった「同じロゴマークが貼り付けられているスライドを軽量版に差し替えろ」とか「こういう箇所の色を別の色に変更してほしい」といった処理ができそうな気もするものの、アプリを使い込むのと同様に、自然言語による命令を介して思い通りの処理ができるレベルになっているのかどうかは、実際に試してみないとわかりません。

「バージョン1.0」と言ってみたり、「ベータ版」と言ってみたりとその位置づけがいまひとつ定まりきっていない.keyxですが、今後のバージョンアップを見守りたいところです。

Posted in JSON news | Tagged .keyx 26.0savvy 27.0savvy Keynote Creator Studio | Leave a comment

SOML操作ライブラリ用サンプルScript date objectをエンコード/デコード

Posted on 11月 18 by Takaaki Naganoya

Sindre Sorhusによる、SOMLのAppleScriptライブラリ「SOML」がオープンソースで公開され、サンプルAppleScriptも公開されたものの、それだけでは動作内容がわからなかったので、エンコード/デコードを試してみました。

SOMLライブラリでは日付オブジェクトや期間を示すデータを独自形式(SOML Object)で保持するようになっていますが、ライブラリ内にそれをAppleScriptの日付オブジェクトに戻すためのルーチンも含んでいるため、その使い方も確認しておきました。

AppleScript名:SOMLで日付を含むデータのエンコード、デコード.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/11/17
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use scripting additions

use somlLib : script "SOML"

–Encode & Decode date object
set tmpDate to current date
–> (*date 2026年11月17日 火曜日 午後10:23:35")

set aRec to {aDate:tmpDate}
set aRes to encode(aRec) of somlLib
(*
"aDate: 2026-11-17T13:23:35Z
"
*)

set bRes to decode(aRes) of somlLib
–> {aDate:{class:SOML instant, value:"2026-11-17T13:23:35Z"}}

set cRes to toDate(aDate of bRes) of somlLib
return {aRes, bRes, cRes}
–>
(*
{"aDate: 2026-11-17T13:23:35Z
", {aDate:{class:SOML instant, value:"2026-11-17T13:23:35Z"}}, date "2026年11月17日 火曜日 午後10:23:35"}
*)

★Click Here to Open This Script 

Posted in SOML | Tagged 15.0savvy 26.0savvy 27.0savvy | Leave a comment

SOML操作ライブラリ用サンプルScript さまざまなデータタイプをエンコード/デコード

Posted on 11月 18 by Takaaki Naganoya

Sindre Sorhusによる、SOMLのAppleScriptライブラリ「SOML」がオープンソースで公開され、サンプルAppleScriptも公開されたものの、それだけでは動作内容がわからなかったので、ひととおりのデータ型でエンコード/デコードを試してみました。

SOMLはJSONのような可読性の高いデータ記述形式であり、データの保持や読み込みのひとつの方向性を示すものです。

AppleScript名:SOML_encode_decode_samples 1.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/11/17
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use scripting additions

use somlLib : script "SOML"

–Encode & Decode Integer
set aRec to {aLabel:1}
set aRes to encode(aRec) of somlLib
(*
"aLabel: 1
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:1}
log aRec is equal to bRes

–Encode & Decode Real
set aRec to {aLabel:1.0}
set aRes to encode(aRec) of somlLib
(*
"aLabel: 1.0
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:1.0}
log aRec is equal to bRes

–Encode & Decode String
set aRec to {aLabel:"1"}
set aRes to encode(aRec) of somlLib
(*
"aLabel: ’1’
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:"1"}
log aRec is equal to bRes

–Encode & Decode Integer Array
set aRec to {aLabel:{1, 2, 3}}
set aRes to encode(aRec) of somlLib
(*
"aLabel: [
  1
  2
  3
]
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:{1, 2, 3}}
log aRec is equal to bRes

–Encode & Decode String Array
set aRec to {aLabel:{"1", "2", "3"}}
set aRes to encode(aRec) of somlLib
(*
"aLabel: [
  ’1’
  ’2’
  ’3’
]
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:{"1", "2", "3"}}
log aRec is equal to bRes

–Encode & Decode Record
set aRec to {aLabel:{aaa:"1", bbb:"2", ccc:"3"}}
set aRes to encode(aRec) of somlLib
(*
"aLabel: {
  aaa: ’1’
  bbb: ’2’
  ccc: ’3’
}
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:{aaa:"1", bbb:"2", ccc:"3"}}
log aRec is equal to bRes

–Encode & Decode Record (Integer array)
set aRec to {aLabel:{aaa:{1, 2, 3}, bbb:{2, 3, 4}, ccc:{5, 6, 7}}}
set aRes to encode(aRec) of somlLib
(*
"aLabel: {
  aaa: [
    1
    2
    3
  ]
  bbb: [
    2
    3
    4
  ]
  ccc: [
    5
    6
    7
  ]
}
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:{aaa:{1, 2, 3}, bbb:{2, 3, 4}, ccc:{5, 6, 7}}}
log aRec is equal to bRes

–Encode & Decode Record (String array)
set aRec to {aLabel:{aaa:{"1", "2", "3"}, bbb:{"2", "3", "4"}, ccc:{"5", "6", "7"}}}
set aRes to encode(aRec) of somlLib
(*
"aLabel: {
  aaa: [
    ’1’
    ’2’
    ’3’
  ]
  bbb: [
    ’2’
    ’3’
    ’4’
  ]
  ccc: [
    ’5’
    ’6’
    ’7’
  ]
}
"
*)

set bRes to decode(aRes) of somlLib
–> {aLabel:{aaa:{"1", "2", "3"}, bbb:{"2", "3", "4"}, ccc:{"5", "6", "7"}}}
log aRec is equal to bRes

–Encode & Decode Record (With whitespace label)
set aRec to {|a Label|:{|aaa aaa|:{"1", "2", "3"}}}
set aRes to encode(aRec) of somlLib
(*
"’a Label’: {
  ’aaa aaa’: [
    ’1’
    ’2’
    ’3’
  ]
}
"
*)

set bRes to decode(aRes) of somlLib
–> {|a label|:{|aaa aaa|:{"1", "2", "3"}}}
log aRec is equal to bRes

–Encode & Decode Record (With Japanese Character label)
set aRec to {|ラベル|:{|日本語ラベル|:{"あ", "い", "う"}}}
set aRes to encode(aRec) of somlLib
(*
"’ラベル’: {
  ’日本語ラベル’: [
    ’あ’
    ’い’
    ’う’
  ]
}
"
*)

set bRes to decode(aRes) of somlLib
–> {|ラベル|:{|日本語ラベル|:{"あ", "い", "う"}}}
log aRec is equal to bRes

★Click Here to Open This Script 

Posted in SOML | Tagged 15.0savvy 26.0savvy 27.0savvy | Leave a comment

SOML操作ライブラリ用サンプルScript

Posted on 11月 18 by Takaaki Naganoya

Sindre Sorhusによる、SOMLのAppleScriptライブラリ「SOML」がオープンソースで公開されました。

SOMLは設定ファイルなどを保存するさいに、XMLのタグの煩雑さを一部省略したplist、さらにタグを簡略化したJSONがあり、そこからさらに簡略化したのがSOMLやYAMLだとSOMLのライブラリ説明ページに書かれています。

SOMLの記法は以下のようなものです。

name: 'api-gateway'
port: 8080 # The load balancer expects this port.
timeout: 30s
launch-date: 2027-09-19
windows-path: 'C:\Users\sindre\dev'
description:
	'''
	Terminates TLS.
	Routes requests to internal services.
	'''
allowed-origins: [
	'https://example.com'
	'https://example.org'
]

タグというよりも、インデントで階層構造を記述したようなかっこうです。

AppleScriptで設定値を書き込むには、ながらくAppleScript自身のproperty宣言を自身で書き換えることで行われてきました。

しかし、セキュリティ上の都合によりこうした運用は、とくにアプレット形式での自己書き換えは禁止されるようになりました。

plist形式を利用することで、設定値の保存は行えますが、アプリケーションのオブジェクトやAppleScriptオブジェクトは書き込めません(文字列化すれば無理ではありませんが)。

JSONやSOMLもそうしたplistに近い仕様であるため、AppleScript関連やアプリケーションオブジェクトのデータをそのまま保存することはできませんが、JSONが広く使われるようになり、OS側にも認知されるようになったのと同様、SOMLも同じような扱いになるかもしれません。

SOML用のAppleScriptライブラリについていたサンプルScriptを確認してみました。ただ、いろいろ書き換えないとユーザー環境では動かないうえに、AppleScriptの流儀とは異なっていました。

ライブラリ自体には割と豊富な機能がそろっているようなのですが、サンプルScriptが動かしにくいので、そのままでは利用されずにもったいないので「常識的にはこのぐらいサンプルがないと使いにくい」という不便を解消するためにいろいろ書いてみました。

以下のAppleScriptはAppleScriptライブラリ「SOML」のインストールを必要とします。

AppleScript名:sample script 1.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/11/17
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use scripting additions
use soml : script "SOML"

set aPOSIXPath to POSIX path of (choose file)

set config to soml’s decodeFile(aPOSIXPath)

set n1Res to |name| of config
–=> "api-gateway"

set n2Res to |port| of server of config
–=> 8080

set n3Res to |host| of item 2 of servers of config
–=> "b.internal"

set n4Res to |socket.io| of deps of config
–=> "^4"

set n5Res to soml’s toSeconds(|timeout| of config)
–=> 90.0

return {n1Res, n2Res, n3Res, n4Res, n5Res}
–> {"api-gateway", 8080, "b.internal", "^4", 90.0}

★Click Here to Open This Script 

AppleScript名:sample script 2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/11/17
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use scripting additions
use soml : script "SOML"

set config to {|name|:"api-gateway", replicas:3, |timeout|:{class:SOML duration, value:"1m30s"}, |launch-date|:{class:SOML date, value:"2027-09-19"}, server:{|host|:"localhost", |port|:8080}, servers:{{|host|:"a.internal"}, {|host|:"b.internal"}}, deps:{|socket.io|:"^4"}}

set n1Res to |name| of config
–=> "api-gateway"

set n2Res to |port| of server of config
–=> 8080

set n3Res to |host| of item 2 of servers of config
–=> "b.internal"

set n4Res to |socket.io| of deps of config
–=> "^4"

set n5Res to soml’s toSeconds(|timeout| of config)
–=> 90.0

return {n1Res, n2Res, n3Res, n4Res, n5Res}
–> {"api-gateway", 8080, "b.internal", "^4", 90.0}

★Click Here to Open This Script 

AppleScript名:sample script 3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/11/17
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use scripting additions
use somlLib : script "SOML"

set configStr to "# config.soml
name: ’api-gateway’
replicas: 3
timeout: 1m30s
launch-date: 2027-09-19
server: {
  host: ’localhost’
  port: 8080
}
servers: [
  {host: ’a.internal’}
  {host: ’b.internal’}
]
deps: {’socket.io’: ’^4’}
"

set config to decode(configStr) of somlLib

set n1Res to |name| of config
–=> "api-gateway"

set n2Res to |port| of server of config
–=> 8080

set n3Res to |host| of item 2 of servers of config
–=> "b.internal"

set n4Res to |socket.io| of deps of config
–=> "^4"

set n5Res to somlLib’s toSeconds(|timeout| of config)
–=> 90.0

return {n1Res, n2Res, n3Res, n4Res, n5Res}
–> {"api-gateway", 8080, "b.internal", "^4", 90.0}

★Click Here to Open This Script 

Posted in SOML | Tagged 15.0savvy 26.0savvy 27.0savvy | Leave a comment

結合順をラベルのリストで指定し、record in listをlist in listに書き換える(CSV書き出し用下処理)

Posted on 11月 2 by Takaaki Naganoya

record in listをCSV書き出しのために、ルール指定listの内容にのっとって、list in list(2D list)に変換するAppleScriptです。

とくに、ルール指定listの中にはrecordのラベルを指定しておくのですが、ヌル項目を出力するために、ルール中に””を指定しておくと、””を2D List中に出力するようになっています。

recordから任意のラベルの値を取り出すのにrun scriptを使ってevalのような動作を行なっています。これが処理速度上のボトルネックになるかどうか。もしも、ボトルネックになるようなら、NSRecordNSDictionaryに変換したのちにValueForKey:で取り出してもよいでしょう。

ただ、ほとんどの場合にCocoa Objectを使ったほうが遅くなると思います(データが小さすぎるケースがほとんどなので)。

AppleScript名:結合順をラベルのリストで指定し、record in listをlist in listに書き換える(CSV書き出し用下処理).scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/11/02
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

set aData to {{aaa:"01", bbb:"02", ccc:"03"}, {aaa:"11", bbb:"12", ccc:"13"}}
set aRule to {"", "ccc", "bbb", "aaa", ""}

set aRes to getValueFieldWithRule(aData, aRule) of me
–> {{"", "03", "02", "01", ""}, {"", "13", "12", "11", ""}}

set bRule to {"", "aaa", "bbb", "ccc", ""}
set bData to {{aaa:1, bbb:2, ccc:3}, {aaa:11, bbb:12, ccc:13}}

set bRes to getValueFieldWithRule(bData, bRule) of me
–> {{"", 1, 2, 3, ""}, {"", 11, 12, 13, ""}}

–結合順をラベルのリストで指定し、record in listをlist in listに書き換える(CSV書き出し用下処理)
on getValueFieldWithRule(aData, aRule)
  
  
script spd
    property aData : {}
    
property aResult : {}
    
property aRow : {}
  end script
  
  
set (aData of spd) to aData
  
set (aResult of spd) to {}
  
  
repeat with aRecord in (aData of spd)
    
    
set (aRow of spd) to {} –1行分のデータ
    
    
repeat with oneLabel in aRule
      set aLabel to contents of oneLabel
      
      
if aLabel is not equal to "" then
        set aScript to "on run {aRecord}" & linefeed & "return " & aLabel & " of aRecord" & linefeed & "end run"
        
        
set aValue to run script aScript with parameters {contents of aRecord}
      else
        set aValue to "" –空きフィールドの出力
      end if
      
      
set end of (aRow of spd) to aValue
    end repeat
    
    
set end of (aResult of spd) to (aRow of spd)
  end repeat
  
  
return (aResult of spd)
  
end getValueFieldWithRule

★Click Here to Open This Script 

Posted in list | Tagged 26.0savvy 27.0savvy | Leave a comment

Apple Creator StudioのKeynoteがMCP+JSONベースのファイル形式に対応

Posted on 10月 29 by Takaaki Naganoya

2026年11月に、Apple Creator StudioのKeynoteが、MCP(Model Context Protocol)とJSONベースのファイル形式である.keyxをサポートするとのこと。

MCPは、AIエージェントがアプリを操作する際の共通規約で、REST APIとほぼ同じ手続きで呼び出せるものですが、「なんでもあり」なREST APIと異なり、規約にのっとった問いかけと回答が得られます。

MCPでは「Prompts(AIへの指示)」「Resources(データ・コンテキスト)」「Tools(実行するアクション)」の3つの枠組みに100%固定されています。

状態を維持するなど、ステートレスなREST APIとは「基本的な考え方」が違うともいえ、SOAPに近づいたJSON-RPCなどと言えるかもしれません(どれだけ共感を得られるか謎な表現)。

ただ、Appleのやることなので……「なんでもできる理想の機能セット」という実装になるかどうか。すべての機能やプロパティを呼び出せるようになってはいないと予想します。

一方、JSONベースのファイル形式「.keyx」については、たしかに仕様が公開されていれば、テキストとして組み立ててKeynote書類を作成できて便利でしょう。

ただ、あのAppleのやることなので必ず「落とし穴」があるはずです。500ページもある書類でのテストとかはしていないでしょうし、英語環境以外のテストもしていないはずです。まともな検証が行われていると考えてはいません。1年ぐらいはバグだらけで使えないと予想します。

既存形式の書類を.keyxで保存し直すとレイアウトが壊れるとか、書き出した.keyxを読み込めないとか。ネイティブ形式よりもファイルサイズが大きくなるとか(さすがにZipで圧縮してあるとは思います)。

.keyxで様子を見て、バグがこなれたころに.pagesxとか.numbersxのように範囲を広げていくつもりなんでしょう。

新しいバージョンが出てきたら、「.key」形式の書類を「.keyx」に書き出して(そのぐらいのAppleScript用語辞書の修正はする……と期待したいです)、PDFに書き出して書類間の差分を検証して、違いが発生した場所を指摘するAppleScriptを書いてテストしたいところです。Appleが絶対にやらないことなので。

Posted in news | Tagged Apple Creator Studio Keynote Creator Studio Numbers Creator Studio Pages Creator Studio | Leave a comment

指定日における年齢を計算する_v2

Posted on 10月 19 by Takaaki Naganoya

指定日における誕生日を計算するAppleScriptの修正版です。

macOS 27で前バージョンがうまく動いていなかったので、ChatGPTにチェックしてもらったところ、Time Zoneが合っていないという指摘があったので、修正してみました。

割とCocoa Scriptingに手を出した直後あたりで試行錯誤していた時代に、「正しくはないが、API側が気を利かせて動いていた」というものをいくつか見つけたので、アップデートしておく必要性を感じます。

AppleScript名:指定日における年齢を計算する_v2.scpt
—
— Created 2015-09-10 by Takaaki Naganoya
— Revised 2026-10-19
— Piyomaru Software
—

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

— 誕生日(日本時間)
set aBirthday to "2000-08-08 12:00:00"
set anAge to getAgeFromBirthdayAndSpecifiedDay(aBirthday, 2026, 10, 19, "Asia/Tokyo") of me
–> 26

–誕生日を求める(生年月日(ISO)
on getAgeFromBirthdayAndSpecifiedDay(aBDStr as string, tYear as integer, tMonth as integer, tDay as integer, tTz as string)
  
  
— 年齢を求める基準日時(日本時間)
  
set targetDate to getDateInternational(tYear, tMonth, tDay, 23, 59, 59, tTz) of me
  
  
— 日時文字列をNSDateに変換
  
set aFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
aFormatter’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:"en_US_POSIX")
  
aFormatter’s setCalendar:(current application’s NSCalendar’s calendarWithIdentifier:(current application’s NSCalendarIdentifierGregorian))
  
aFormatter’s setDateFormat:"yyyy-MM-dd HH:mm:ss"
  
aFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithName:tTz)
  
  
set aBirthdayDate to aFormatter’s dateFromString:aBDStr
  
  
if aBirthdayDate is missing value then
    error "Birthday format error"
  end if
  
  
— 年齢計算用のカレンダー
  
set aCalendar to current application’s NSCalendar’s calendarWithIdentifier:(current application’s NSCalendarIdentifierGregorian)
  
aCalendar’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithName:tTz)
  
  
— 誕生日から基準日時までの暦上の年数を計算
  
set ageComponents to aCalendar’s components:(current application’s NSCalendarUnitYear) fromDate:aBirthdayDate toDate:targetDate options:0
  
  
set myAge to (ageComponents’s |year|()) as integer
  
  
return myAge
end getAgeFromBirthdayAndSpecifiedDay

— 指定したタイムゾーンでNSDateを生成
on getDateInternational(aYear, aMonth, aDay, anHour, aMinute, aSecond, timeZoneName)
  set aCalendar to current application’s NSCalendar’s calendarWithIdentifier:(current application’s NSCalendarIdentifierGregorian)
  
aCalendar’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithName:timeZoneName)
  
  
set theDate to aCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:anHour minute:aMinute |second|:aSecond nanosecond:0
  
return theDate
end getDateInternational

★Click Here to Open This Script 

Posted in date | Tagged 26.0savvy 27.0savvy | Leave a comment

StreamDock用にAppleScript実行プラグインを作成

Posted on 10月 2 by Takaaki Naganoya

Macなどにつないで本体を操作する「左手デバイス」と呼ばれる製品群があります。代表的な製品として、ElgatoのStream Deck(ストリームデッキ)が知られています。

StreamDock(ストリームドック)は、Stream Deckに機能や見た目を似せて作られた、他社製(主に中華系)の互換・廉価デバイスの総称です。名前がまちまち(ストリームコントローラーデックとか、ストリームコントローラーとか)だったりするようですが、設定アプリは同じ「StreamDock」です。

「ガンダム」に対する「ガンガル」みたいな関係で、⚫︎かろう⚫︎かろうという想像が、ほぼそのまま当たります。日本市場に出しているのに、画面上の表示に中国語が残っていたりと、作りが粗い部分が散見されます。

ElgatoのStream Deckは、純粋な作業効率向上のための「左手デバイス」として見ると、さまざまな効果音やBGM的な素材は不要で、こうした素材のための価格が添加されているものと考えると割高感が否めません。単なる左手デバイスとして利用したいニーズは確実に存在しています。

Amazonで「Stream Deck」で検索すると、検索結果の後ろの方にやけに安い価格の似たような製品が出てきます。それが、StreamDock(ストリームドック)です。

いわゆる「●ったもん」とも言える製品であり、あまりの怪しさに個人的には手を出さないようにしていました。

それがたまたま、製品レビュー対象品(USB-Cハブ)にその機能がついていて、はじめてStreamDockと対面することに。

設定アプリの画面UIなどもElgatoのStream Deckそっくりですが、細かい点で違っています。

Stream Deckのような「開く」アクションでAppleScriptのパスを渡すと実行する、という機能は用意されていません。

それでも、StreamDockとStream DeckではWeb系の機能でUIを構成し、利用できる機能も似ていることから、JavaScriptなどでプラグインを作れることが見て取れました(このあたり、Stream Deckと互換性があるとかないとか)。

せっかく手元にあるのに「AppleScriptを実行できないかわいそうな左手デバイス」では困るので、いろいろ調べてChatGPTをこづき回してAppleScript実行プラグインを作ってしまいました。JavaScript経由でosascriptコマンドを呼び出しているだけで、余計な処理はしていません。

ひととおり評価したところ、AppleScriptの実行機能についてはStream Deckとだいたい同レベルの機能が実現できてしまいました。

Piyomaru Software製「StreamDock」用のAppleScript実行プラグインの性能:

GUI Scriptingの実行:可能
AppleScriptのメインスレッド実行:可能
外部のAppleScriptライブラリ呼び出し:可能
AppleScriptの実行パス取得:(テキストなので無理)
Cocoa呼び出し:可能
Cocoaオブジェクトのメモリ常駐+イベント取得:不可
Script ObjectごしのHandler呼び出し:可能
Modifier Keyのキースキャン:可能
CDN上のJavaScriptライブラリ呼び出し+実行:可能
Address Geocoderの実行:可能

まだ、広域に配布するようなレベルではありませんが、個人的に試してみたいという方はコメントを残してください。

Posted in news | Tagged StreamDock | Leave a comment

Script Debugger 8.0.10とmacOS 27の不整合が発生。8.0.11β版が発表される

Posted on 10月 2 by Takaaki Naganoya

macOS 27になって、Script Debugger 8.0.10上で複数のScript書類をオープンし、最前面の書類をクローズするとすべての書類がクローズされてしまう、という不具合が発生しています。

Script Debuggerの販売・開発は終わっていますが、この不具合に対処するためにv8.0.11β版(Build 8A89)が登場しました。

https://forum.latenightsw.com/t/announce-script-debugger-8-0-11-8a89/5938

いまのところ、上記の問題については解消されているように見えます。

Posted in news | Tagged 27.0savvy Script Debugger | Leave a comment

macOS 27でSafari+スクリプトエディタ間のapplescript://リンクが無視される

Posted on 10月 2 by Takaaki Naganoya

本サイトで利用している「applescript://」URLスキームは、Webサイトに掲載したAppleScriptを、スクリプトエディタに転送する仕組みです。

性善説に立脚していえば、便利に使えるものといえます。しかし、最近これが攻撃に利用されていることが確認されています。

間違って「applescript://」リンクをクリックないしオープンしてしまった場合でも、スクリプトエディタ上で実行しなければ問題はないのですが、実行したら攻撃者の思う壺です。

macOS 27以降、Safari+スクリプトエディタの組み合わせでは、このapplescript://スキームが効かなくなっていることを確認しました。

macOS 27搭載のスクリプトエディタのInfo.plistからapplescript://スキームに関するエントリが削除されていることを確認しました。

つまり、これはバグではなく意図的な改変です。Release時にきちんと説明してほしいところです。一応、文句のひとつぐらいは言っておいてもいいでしょう。

対処方法はすぐに見つけられました。スクリプトエディタではなく、Script Debuggerでapplescript://スキームを受信するよう設定すれば、Script Debuggerで受信できます。

Script DebuggerのPreferences…から、Script Debuggerの設定ウィンドウの「General」>「MacOS Settings」の「Respond to applescript:// URLs in web pages」にチェックを入れることで、Safari上のapplescript://リンクをScript Debuggerで受信できるようになります。

一方で、GoogleのChromiumベースのWebブラウザがapplescript:// スキームに反応しないように変更されました。これをもとに作られているさまざまなWebブラウザでも、applescript:// スキームを無視するように変わっていくことでしょう。

Posted in news | Tagged 27.0savvy Script Editor | Leave a comment

簡易カラーチャート画像の出力 v2.1

Posted on 9月 3 by Takaaki Naganoya

簡易的なカラーチャートの画像を出力するAppleScriptです。

カラーチャートを用いて色のチェックを行いたいことはありますが、既存の著名なカラーチャートには著作権が存在しており、おいそれと紹介記事などで利用できないケースが多々あります。

そこで、そこそこの品質で納得できる内容の、簡易的なカラーチャート画像を出力するAppleScriptを作成してみました(Geminiに書かせたものを清書)。


▲当初(v1.0)はこのようなチャートを出力していたが、書くのに時間がかかりすぎるのと実用性がいまひとつだったので現状(v2.x)に変更した

出力画像サイズや、枠線の太さ、出力先のファイルパスを指定できるようになっており、各種レビューなどで著作権に気を使うことなくカラーチャートを使用できます。

各種AIにプログラムを書かせると、サブルーチンも何も宣言せず「とりあえず動けばいい」という内容のコードを出力しがちですが、サブルーチンとして使い回せるようにしておけば、パラメータの変更などを行うやすくなります。

また、「大きなプログラム」を組み立てるさいにも、サブルーチン化しておいたほうが都合がよくなります。

AppleScript名:簡易カラーチャート画像の出力 v2.1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/08/28
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

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

— 保存先の指定
set filePath to choose file name with prompt "カラーチャートの保存先を指定してください" default name "ColorChart.png" default location (path to pictures folder)
if filePath is false then return

— Posix pathの取得
set posixPath to POSIX path of filePath
if not (posixPath ends with ".png") then
  set posixPath to posixPath & ".png"
end if

— 出力画像サイズ (1200 x 800 pixel)
set canvasWidth to 1200
set canvasHeight to 800

— グリッド(マス目)の分割数設定
— 横方向(色相 H): 24段階
— 縦方向(明度/彩度 B/S): 16段階
set cols to 24
set rows to 16

— マスの間の隙間(枠線)の幅(ピクセル指定、0にすると隙間なし)
set gap to 8

–カラーチャート画像を作成して指定パスにPNGファイルとして書き込み
set {aRes, aMes} to genColorChartImage(gap, cols, rows, canvasWidth, canvasHeight, posixPath) of me
if aRes = false then display dialog aMes

on genColorChartImage(gap, cols, rows, canvasWidth, canvasHeight, posixPath)
  
  
— 1マスのサイズ計算
  
set cellWidth to canvasWidth / cols
  
set cellHeight to canvasHeight / rows
  
  
— NSBitmapImageRepの作成
  
set imgRep to current application’s NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:canvasWidth pixelsHigh:canvasHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application’s NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
— 描画コンテキストの作成
  
current application’s NSGraphicsContext’s saveGraphicsState()
  
set currentContext to current application’s NSGraphicsContext’s graphicsContextWithBitmapImageRep:imgRep
  
current application’s NSGraphicsContext’s setCurrentContext:currentContext
  
  
— 背景を黒で塗る(マスの間のグリッド線になります)
  
current application’s NSColor’s blackColor()’s |set|()
  
current application’s NSRectFill(current application’s NSMakeRect(0, 0, canvasWidth, canvasHeight))
  
  
— カラーチャート(グリッド)の描画
  
repeat with col from 0 to (cols – 1)
    — X軸: 色相 (Hue: 0.0 〜 1.0)
    
set hueVal to col / cols
    
    
repeat with row from 0 to (rows – 1)
      — Y軸: 明度 (Brightness: 上に行くほど明るく、下に行くほど暗く)
      
set brightnessVal to (rows – row) / rows
      
— 彩度 (Saturation: 1.0 固定、または縦方向に応じて調整可能)
      
set saturationVal to 1.0
      
      
— 特例: 一番下の行はグレースケール(無彩色)にする場合
      
if row is (rows – 1) then
        set cellColor to (current application’s NSColor’s colorWithCalibratedWhite:(col / (cols – 1)) alpha:1.0)
      else
        set cellColor to (current application’s NSColor’s colorWithHue:hueVal saturation:saturationVal brightness:brightnessVal alpha:1.0)
      end if
      
      
cellColor’s |set|()
      
      
— 描画するマスの位置とサイズ(隙間gapを考慮)
      
set rectX to col * cellWidth + (gap / 2)
      
set rectY to row * cellHeight + (gap / 2)
      
set rectW to cellWidth – gap
      
set rectH to cellHeight – gap
      
      
set rectToFill to current application’s NSMakeRect(rectX, rectY, rectW, rectH)
      
current application’s NSRectFill(rectToFill)
    end repeat
  end repeat
  
  
— グラフィックスコンテキストの復元
  
current application’s NSGraphicsContext’s restoreGraphicsState()
  
  
— PNG表現に変換して保存 (NSPNGFileType / 数値4を指定)
  
set pngFileType to current application’s NSPNGFileType
  
if pngFileType is missing value then set pngFileType to 4 — 互換性フォールバック
  
  
set pngData to imgRep’s representationUsingType:pngFileType |properties|:(missing value)
  
set writeResult to pngData’s writeToFile:posixPath atomically:true
  
  
if writeResult as boolean then
    set targSizeStr to (canvasWidth as string) & "x" & (canvasHeight as string)
    
    
return {true, targSizeStr & "のカラーチャートを出力しました"}
  else
    return {false, "ファイルの保存に失敗しました。"}
  end if
end genColorChartImage

★Click Here to Open This Script 

Posted in Color Image | Tagged 15.0savvy 26.0savvy 27.0savvy | 8 Comments

macOS 26.4で実装されたAppleScript scanning機能

Posted on 8月 6 by Takaaki Naganoya

Appleが現地時間2026年08月03日付けで公開/アップデートした「Apple Platform Security (PDF)」によると、Appleは悪意のあるコマンドをターミナルにコピー&ペーストさせたり、悪意のあるスクリプトをダウンロードし実行させるソーシャルエンジニアリング攻撃に対処するため、ターミナルのペースト保護機能を含め3つの保護機能を macOS 26.4で実装。

それが、「Terminal paste protection」「Pasteboard command blocking」そしてAppleScriptに関する「AppleScript scanning」です。

全文を含むPDF(英文)
https://help.apple.com/pdf/security/en_US/apple-platform-security-guide.pdf

(原文)
AppleScript scanning for AppleScript and JavaScript for Automation (JXA) scripts uses XProtect technology. Because the scanning is integrated into the OpenScripting framework, all AppleScript executions on macOS are subject to local inspection, whether the script is loaded from storage or from memory.

「AppleScript scanning for AppleScript and JavaScript for Automation (JXA) scripts 」はXProtect技術を用いています。このスキャニングはOpen Scripting Architecture frameworkに組み込まれており、すべてのmacOS上のローカルの資源への探索を行うAppleScriptの実行がスキャン対象です。これは、SSDやHDDなどのストレージから読み込まれたか、メモリ上から読み込まれたかを問いません。すべてが対象です。

(原文)
When a script matches a known malicious signature, macOS blocks execution and presents the user with a notification.

これらのScriptが既知の悪意ある署名にマッチした場合、macOSは通知を表示しつつ実行をブロックします(XProtectがマルウェアの検出を、バイナリ全体を見て実行)。

(原文)
If the blocked script is associated with a file stored on one of the following, the user can choose to override the block through the existing malware protection override in Finder: •Internal storage •External device •Cloud-based service •Mounted file server

実行をブロックされたScriptがストレージ(内蔵SSD、外付けドライブ、クラウドストレージ、マウントしたファイルサーバー)上のファイルに関連づけられている場合、ユーザーは Finder の既存のマルウェア保護オーバーライドを通じてブロックをオーバーライドすることを選択できます(実際にブロックされるところを見ていないので不明)。

(原文)
Scripts executed without an associated file—such as those run directly from memory—can’t be overridden. The user needs to save the script first before requesting an override.

関連ファイルなしで実行されるスクリプト (メモリから直接実行されるスクリプトなど) はオーバーライドできません。ユーザーは、オーバーライドをリクエストする前に、まずスクリプトをファイルに保存する必要があります。

Piyomaru Softwareの所見

マルウェアがAppleScriptバイナリを含む場合、その実行Scriptのチェックサム同士で比較している印象を受けます。実行時に実行Scriptのチェックサムを取得し、問題があるScriptと同一であれば実行をブロック、と読めます。

気になる点は2つ。

XProtectによってマルウェアScriptとの比較を行うのにどの程度の処理のオーバーヘッドが発生するのか? 
単独のファイルとして存在していないScriptのチェックを行えるのか? 

メモリ上で組み立てたScriptについてはチェック対象ではないといった記述があるため、他の実行ファイルのバイナリ内部に埋め込んだScriptについては、対処できないように見えます。

また、URL Events経由で流し込まれた悪意あるAppleScript(スクリプトエディタでオープン)の構文確認時(Apple Eventsへのコンパイル時)にXProtectのチェックが動かないと意味がないのでは? とも考えます。

さらに、何かの手違いで手元のScriptが「マルウェアScript」と判定された場合の異議申し立て方法については一切何も説明されていません。

いきなり強めのセキュリティしばりを加えるよりも、段階的にセキュリティ機能を追加するという方針は(なんとなく)理解できはするのですが、例によってApple社内の誰が本件について担当しているのかが不明なので、文句を言う先がよくわかりません。

Posted in Security | Tagged 26.0savvy 27.0savvy | Leave a comment

macOS 27 AppleScriptからApple Foundation Modelsを呼び出す

Posted on 8月 4 by Takaaki Naganoya

macOS 27から標準搭載されるシェルコマンド「fm」(/usr/bin/fm)を通じて、Apple Foundation Models(=Apple IntelligenceのLLM)を呼び出すことができます。

macOS 27のBetaをインストールしてある環境であれば、AFMを試すことができます。開発者登録している方、あるいは一般のユーザーでもβユーザー登録してあればmacOS 27をインストールできます。

Apple Silicon搭載Macであればこれらの環境を利用可能ですが、念のためRAM 16Gバイト以上だと安心できることでしょう。

その他、fmコマンドを利用するには、システム設定でSiriをオンにしてある必要があります。AFMが使用可能になっているかどうかをfmコマンド自体で確認可能です。

ターミナル(Terminal.app)上で以下のように「fm available」コマンドを実行することで、現在使用中の(macOS 27以降の)環境でAFMが使用可能かどうかを確認できます。

% fm available
System model available
PCC model available

有効/無効確認の手段が用意されていることは前向きに評価できます。

fmコマンドでできること

fmコマンドができることは、LLMへの問い合わせです。おおよそChatGPTやGeminiなどへの問い合わせを行うのと同様に自然言語によるテキストチャットによる対話も行えます。

英語でも日本語でも応答してくれますが、応答/翻訳できるのは15言語程度です。

日本語、英語(米国、英国、オーストラリア、カナダ、ニュージーランド、インド、シンガポール)、フランス語、ドイツ語、イタリア語、ポルトガル語、中国語(簡体字、繁体字)、韓国語、ベトナム語、デンマーク語、オランダ語、ノルウェー語、スウェーデン語、トルコ語

AFMからの応答は必要に応じてMarkdownで装飾されて返ってきます(プログラムリストや見出しなど)。

用途に応じて2つのモデルを指定可能

AFMにはデフォルトで用意されているLLMモデルが2つあります。

ローカルで完結する「system」と、Appleのプライベートクラウドのサーバー群で動作する「pcc」の2つです。インターネット接続不要のsystem、接続必須のpccと見ることもできます。

ローカルのモデルは、「とりあえず動く」程度の内容であり、ちょっと込み入った内容になると、

「Appleのウェブサイトで、最新の製品情報や機能をご確認ください。」

といった当たり障りのない(情報量のない)内容を返すようになります。

コマンドラインからfmコマンドを介してモデルを指定して応答を取得してみましょう。モデルによって情報量が大幅に異なります。

% fm respond "AppleScriptとは何ですか?" --model system
% fm respond "AppleScriptとは何ですか?" --model pcc

(system)AppleScriptは、Appleのコンピュータで動作するスクリプト言語で、アプリケーションやシステムの操作を自動化するために使用されます。テキストベースの言語であり、テキスト編集やファイル操作、アプリケーションの起動など、さまざまなタスクを簡潔に記述できる点が特徴です。

(pcc)AppleScriptは、Appleが開発したスクリプト言語で、macOS上でアプリケーションやシステム機能を自動化するために使用されます。この言語は、英語に近い自然な構文を持っているため、プログラミングの経験が少ない人でも比較的簡単にスクリプトを書くことができます。

AppleScriptを使うことで、例えば以下のような作業を自動化できます:

- ファイルやフォルダの管理
- アプリケーションの操作(メールの送信、ドキュメントの作成など)
- システム設定の変更
- インターネットからのデータの取得

スクリプトは「Script Editor」というアプリケーションを使って作成・実行され、他のアプリケーションとAppleEventsというメカニズムを通じて通信します。これにより、macOS環境での作業効率を大幅に向上させることができます。

AFMの使用可能な残トークン確認

pccはAppleの自社クラウド上にあるLLMのサービスであるため、ローカルのsystemとは異なり、使用可能なトークン上限が設定されています。Web上で探してみると「4096トークン/日」となっているようですが、macOS 27のリリース時にこのままなのかは不明です。まだβ版であるため、最終仕様ではありません。

% fm quota-usage --model pcc
PCC: ✓ Available
% fm quota-usage --model system
System: Not applicable (quota only applies to PCC)

fmコマンド経由では、使用可能なトークン数を厳密に取得することはできないようです。あくまで、使用可能(Available)かどうかを返してきます。

なお、実行するまえにクエリがどの程度のトークンを消費するかを確認できるようになっています。

% fm count-tokens "AppleScriptとは何ですか?"
Token count: 15

このとき、pccかsystemかといったモデルの指定はできませんが、暗黙の了解でpcc使用時の消費トークン数でしょう(ローカル動作のsystemではトークン消費を気にする必要がありませんし)。

AFMの情報最新日付を確認

LLMへの一般的なアプローチがAFMでも有効で、モデルの学習データの最新日付がいつなのかを問い合わせると答えてくれます。

% fm respond 'あなたの現在の日付を教えてください。' --model pcc
% fm respond 'あなたの現在の日付を教えてください。'

  pcc: 2025年04月29日
  system: 2024年10月29日

つまり、これよりも新しいネット上の情報は反映されていない状態です。macOS 27のリリース時(iOS 27のリリース時?)にはこれらのモデルも更新される可能性がありますが、本稿執筆時点では上記のとおりです。

# 本稿を書いて塩漬けにしている間に上記の応答が変わりました。

----system(Local LLM)の応答(2026/08/04)
私はAppleによって開発された言語モデルです。

[必要なツールを検索]
今日の日付を取得するためのツールが存在しません。しかし、現在の日付を正確に把握するには、サーバー上のタイムサーバーからの情報が必要であり、その情報を提供できる機能は存在しません。そのため、具体的な日付を提供することはできません。
---

AFMも一般的なLLMと同様に、個人情報に関わることには答えてくれなかったり、米国における政治状況やAppleの利益に反することには回答してくれません。

fmコマンドを実行する環境ごとに利用できるmodelも異なる

macOS標準搭載のTerminal.app上では、modelがsystem(Local)でもpcc(クラウド)でもどちらも指定して実行できます。

しかし、AppleScriptのdo shell scriptコマンド上では制限がかかっており、利用できるのはsystem(Local)のみです。

do shell scriptコマンド内でも環境変数の設定により、Terminal.app上と同様にpcc(クラウド)を利用できるようになるのかはわかりませんが、現状ではsystem(Local)のみであると認識しています。

逆をいえば、Swiftでそのような処理を行うプログラムを書いてAppleScriptからdo shell scriptで呼び出せばよいだけでしょう。そういう使い方ができないAppleScript実行環境(ライブラリ呼び出し不可+バンドル形式Script実行不可)では、system(Local)のみ利用できることになるでしょう。

Posted in Apple Inteligence | Tagged 27.0savvy | Leave a comment

ディスプレイ選択ダイアログ

Posted on 7月 21 by Takaaki Naganoya

現時点でMacに接続されているディスプレイ情報を取得して、座標値からその位置関係や大きさを計算して画像にレンダリングし、ポップアップメニューから処理対象のディスプレイを選択してNSRectを返すAppleScriptです。

まだ試作品レベルですが、macOS 27 beta上で動作しています。ただ、NSAlertによるダイアログを表示させた場合に、アイコンもタイトルもサブタイトルもすべて左寄せになってしまうところがいまひとつです。

なんでこんなものを作ったかといえば、複数ディスプレイがつながっているMac上で任意のディスプレイ上に表示されているウィンドウ(に含まれるdocument)だけを処理対象とし、他のディスプレイ上のウィンドウを無視するといった処理をしたいと考えたからです。

少々AIにお願いしてコードを書いてもらっていますが、そのためにやや不要な処理までやっているような気もします。

AppleScript名:ディスプレイ情報を取得して、位置関係を画像化_take2_1b.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/07/19
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

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

property K_MAX_WIDTH : 600.0
property K_MAX_HEIGHT : 300.0
property selectedDispRes : missing value

set {aInfoList, aIMG, aSizeList} to drawDisplayLayout() of me
–return aIMG

set aInfoList to aInfoList as list
if length of aInfoList = 1 then return

set aParamRec to {myDispInfo:aInfoList, myImgView:aIMG, mySizeList:aSizeList, mymainTitle:"ディスプレイ選択", mySubTitle:"メイン画面が「1」、その他は左上から「2, 3…」となります。"}

–my dispLayoutAndPopup:aParamRec–for debugging on Script Editor
my performSelectorOnMainThread:"dispLayoutAndPopup:" withObject:(aParamRec) waitUntilDone:true
return (visibleFrame of selectedDispRes)’s |description|() as string –For Debugging

–Macに接続されているディスプレイ一覧から処理対象を選択するダイアログを表示
on dispLayoutAndPopup:aParam
  set dList to (myDispInfo of aParam) as list
  
set aIMG to myImgView of aParam
  
set aMainTitle to (mymainTitle of aParam) as string
  
set aSubTitle to (mySubTitle of aParam) as string
  
set {imgWidth, imgHeight} to (mySizeList of aParam) as list
  
set dNum to length of dList
  
set numStrList to makeNumberStringList(dNum) of me
  
  
set currentAlert to current application’s NSAlert’s alloc()’s init()
  
currentAlert’s setMessageText:aMainTitle
  
currentAlert’s setInformativeText:aSubTitle
  
  
set imageView to current application’s NSImageView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, imgWidth, imgHeight))
  
imageView’s setImage:aIMG
  
  
set a1Button to (current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, imgWidth – 100, 30)) pullsDown:false)
  
a1Button’s removeAllItems()
  (
a1Button’s addItemsWithTitles:(numStrList))
  
  
  
— 画像ビュー
  
set imageView to current application’s NSImageView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, imgWidth, imgHeight))
  
imageView’s setImage:aIMG
  
imageView’s setImageScaling:(current application’s NSImageScaleProportionallyUpOrDown)
  
  
— ポップアップ
  
set popupWidth to imgWidth – 80
  
set a1Button to (current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, popupWidth, 30)) pullsDown:false)
  
a1Button’s removeAllItems()
  (
a1Button’s addItemsWithTitles:(numStrList))
  
  
— OKボタン幅に合わせると見た目がよい
  
a1Button’s setControlSize:(current application’s NSControlSizeRegular)
  
  
————————————————–
  
— 中央寄せコンテナ
  
————————————————–
  
set containerWidth to imgWidth
  
set containerHeight to imgHeight + 60
  
  
set containerView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, containerWidth, containerHeight))
  
  
— StackView
  
set stackView to current application’s NSStackView’s alloc()’s initWithFrame:(containerView’s |bounds|())
  
  
stackView’s setOrientation:(current application’s NSUserInterfaceLayoutOrientationVertical)
  
stackView’s setAlignment:(current application’s NSLayoutAttributeCenterX)
  
stackView’s setDistribution:(current application’s NSStackViewDistributionGravityAreas)
  
stackView’s setSpacing:16.0
  
  
— Auto Layout
  
stackView’s setTranslatesAutoresizingMaskIntoConstraints:false
  
  
— 追加
  
stackView’s addArrangedSubview:imageView
  
stackView’s addArrangedSubview:a1Button
  
  
containerView’s addSubview:stackView
  
  
————————————————–
  
— StackViewをコンテナ中央へ固定
  
————————————————–
  
set centerX to (stackView’s centerXAnchor())
  (
centerX’s constraintEqualToAnchor:(containerView’s centerXAnchor()))’s setActive:true
  
  
set centerY to (stackView’s centerYAnchor())
  (
centerY’s constraintEqualToAnchor:(containerView’s centerYAnchor()))’s setActive:true
  
  
————————————————–
  
— accessoryView設定
  
————————————————–
  
currentAlert’s setAccessoryView:containerView
  
currentAlert’s runModal()
  
  
–popup buttonの選択肢を取得する
  
set tmpSegSel to (a1Button’s indexOfSelectedItem()) as number
  
set tRes to (tmpSegSel + 1)
  
  
set selectedDispRes to (contents of item tRes of dList)
end dispLayoutAndPopup:

on makeNumberStringList(aMax)
  set aList to {}
  
set aCount to 1
  
repeat aMax times
    set the end of aList to (aCount as string)
    
set aCount to aCount + 1
  end repeat
  
return aList
end makeNumberStringList

on drawDisplayLayout()
  set allScreens to current application’s NSScreen’s screens()
  
if allScreens is missing value or allScreens’s |count|() = 0 then return
  
  
— 1. メイン画面(配列の先頭)を取得
  
set mainScreen to allScreens’s firstObject()
  
  
— 2. サブ画面たちをリストとして抽出
  
set otherScreensList to {}
  
repeat with i from 1 to (allScreens’s |count|()) – 1
    copy (allScreens’s objectAtIndex:i) to end of otherScreensList
  end repeat
  
  
— 3. サブ画面を「左上から順(Y座標の降順 > X座標の昇順)」に手動ソート
  
— ※AppleScript側でハンドリングした方がCocoaの構造体ネスト問題を回避できて確実です
  
repeat with i from 1 to (count otherScreensList)
    repeat with j from i + 1 to (count otherScreensList)
      set scrI to item i of otherScreensList
      
set scrJ to item j of otherScreensList
      
set frameI to scrI’s frame()
      
set frameJ to scrJ’s frame()
      
      
set yI to current application’s NSMinY(frameI)
      
set yJ to current application’s NSMinY(frameJ)
      
set xI to current application’s NSMinX(frameI)
      
set xJ to current application’s NSMinX(frameJ)
      
      
— Yが小さい(下にある)か、Yが同じでXが大きい(右にある)場合は入れ替え
      
if (yI < yJ) or (yI = yJ and xI > xX) then
        set item i of otherScreensList to scrJ
        
set item j of otherScreensList to scrI
      end if
    end repeat
  end repeat
  
  
— 4. 最終的な順序の配列を作成(1番目がメイン、2番目以降がサブ)
  
set sortedScreens to current application’s NSMutableArray’s array()
  (
sortedScreens’s addObject:mainScreen)
  
repeat with aScr in otherScreensList
    (sortedScreens’s addObject:aScr)
  end repeat
  
  
— 5. 全体を含むバウンディングボックスの計算
  
set minX to 9.9999E+4
  
set maxX to -9.9999E+4
  
set minY to 9.9999E+4
  
set maxY to -9.9999E+4
  
  
repeat with aScreen in sortedScreens
    set f to aScreen’s frame()
    
set sx to current application’s NSMinX(f)
    
set sy to current application’s NSMinY(f)
    
set sw to current application’s NSWidth(f)
    
set sh to current application’s NSHeight(f)
    
    
if sx < minX then set minX to sx
    
if sy < minY then set minY to sy
    
if (sx + sw) > maxX then set maxX to (sx + sw)
    
if (sy + sh) > maxY then set maxY to (sy + sh)
  end repeat
  
  
set totalWidth to maxX – minX
  
set totalHeight to maxY – minY
  
  
— 6. スケール比率の計算
  
set scaleX to K_MAX_WIDTH / totalWidth
  
set scaleY to K_MAX_HEIGHT / totalHeight
  
set theScale to scaleX
  
if scaleY < theScale then set theScale to scaleY
  
  
set imgWidth to totalWidth * theScale
  
set imgHeight to totalHeight * theScale
  
set canvasSize to current application’s NSMakeSize(imgWidth, imgHeight)
  
set displayImage to current application’s NSImage’s alloc()’s initWithSize:canvasSize
  
  
— 7. 描画処理
  
displayImage’s lockFocus()
  
  
current application’s NSColor’s clearColor()’s |set|()
  
current application’s NSRectFill(current application’s NSMakeRect(0, 0, imgWidth, imgHeight))
  
  
set screenCount to sortedScreens’s |count|()
  
repeat with idx from 0 to screenCount – 1
    set aScreen to (sortedScreens’s objectAtIndex:idx)
    
set f to aScreen’s frame()
    
    
set rx to ((current application’s NSMinX(f)) – minX) * theScale
    
set ry to ((current application’s NSMinY(f)) – minY) * theScale
    
set rw to (current application’s NSWidth(f)) * theScale
    
set rh to (current application’s NSHeight(f)) * theScale
    
set drawRect to current application’s NSMakeRect(rx, ry, rw, rh)
    
    
— 枠と背景
    
current application’s NSColor’s windowBackgroundColor()’s |set|()
    
current application’s NSRectFill(drawRect)
    
current application’s NSColor’s textColor()’s |set|()
    
current application’s NSFrameRectWithWidth(drawRect, 1.5)
    
    
— ★【修正】数字の文字列生成方法をNSNumber経由に修正
    
set numObj to (current application’s NSNumber’s numberWithInteger:(idx + 1))
    
set numStr to numObj’s stringValue()
    
    
set fontHeight to rh * 0.4
    
if fontHeight > 24.0 then set fontHeight to 24.0
    
if fontHeight < 12.0 then set fontHeight to 12.0
    
    
set numFont to (current application’s NSFont’s systemFontOfSize:fontHeight weight:(current application’s NSFontWeightBold))
    
set paraStyle to current application’s NSMutableParagraphStyle’s alloc()’s init()
    (
paraStyle’s setAlignment:(current application’s NSTextAlignmentCenter))
    
    
set attrDict to current application’s NSMutableDictionary’s dictionary()
    (
attrDict’s setObject:numFont forKey:(current application’s NSFontAttributeName))
    (
attrDict’s setObject:paraStyle forKey:(current application’s NSParagraphStyleAttributeName))
    (
attrDict’s setObject:(current application’s NSColor’s textColor()) forKey:(current application’s NSForegroundColorAttributeName))
    
    
set strSize to (numStr’s sizeWithAttributes:attrDict)
    
set textY to ry + ((rh – (strSize’s height)) / 2.0)
    
set textRect to current application’s NSMakeRect(rx, textY, rw, strSize’s height)
    
    (
numStr’s drawInRect:textRect withAttributes:attrDict)
  end repeat
  
  
displayImage’s unlockFocus()
  
  
return {sortedScreens, displayImage, {imgWidth, imgHeight}}
end drawDisplayLayout

★Click Here to Open This Script 

Posted in dialog System | Tagged 10.15savvy 26.0savvy 27.0savvy | Leave a comment

Apple Creator Studio 15.3 Update

Posted on 7月 2 by Takaaki Naganoya

Apple Creator Studio(以下、ACSと略)に所属するKeynote、Pages、Numbers(旧iWork Apps)がバージョン15.3にアップデートしました。同じくACSに所属するApple純正の画像編集アプリ「Pixelmator Pro」で各書類上の画像を編集するための連携機能が追加されました。

これらのアプリのAppleScript対応機能については、Keynote 15.3が新たなトランジッション「radial wipe」(日本語ローカライズ名は「放射状ワイプ」)を指定できるようになりました。他に変更点はありません。

ただし、radial wipeで画面上で指定できるパラメータ「方向」(時計回り/反時計回り)や角度、ぼかしはAppleScriptから指定できないので、実用上は微妙な感じです。

「放射状ワイプ」自体は、Keynote 14.xでは実装されていませんでした。15.xのどこかのバージョンで追加されたものと思われますが、どの時点で追加されたかは明確ではありません。

ただ、個人的にはそんなことはどうでもいいから、Keynote/Pages/Numbers上で画像の内容やパスを取得できるようにしてほしいです。

tell application "Keynote Creator Studio"
  tell front document
    –radial wipeは、画面上では「放射状ワイプ」と表示
    
set transition properties of current slide to {transition effect:radial wipe, transition duration:2.0, transition delay:0, automatic transition:false}
    
–角度、ぼかし、方向(時計回り/反時計回り)などは指定できない
  end tell
end tell

★Click Here to Open This Script 

Posted in news | Tagged 15.0savvy 26.0savvy 27.0savvy Keynote | Leave a comment

macOS 27.0, Golden Gate #2

Posted on 6月 26 by Takaaki Naganoya

macOS 27, Golden Gateのベータ版(Beta 2)を利用していますが、従来のβよりもマシといえど、やはりβ版であることを感じさせます。

標準搭載アプリのバージョンが割といいかげん

各アプリのバージョン表記でおかしいところがあります。「ヒント(Hints)」はバージョン27.0がおそらく正しい番号ですが、1.0が割り当てられています。

メッセージ(Messages)もバージョン26.0が割り振られていますが、(何も意図がなければ)27.0が正しい番号でしょう。バージョン番号を見て判定するような処理には不安があります。

macOS 15.5 macOS 26.0 macOS 27.0
Finder 16 16 27
System Events 1.3.6 1.3.6 1.3.6
連絡先(Contacts) 14 14 14
Safari 18 19 27
Photos 10 11 12
Reminders 7 7 7
Notes 4.12.6 4 4
Messages 14 14 26
Mail 16 16 16
Music 1.5.5 2 2
Maps 3 3 3
Preview 11 11 11
TextEdit 1 1 1
Calendar 15 16 27
TV 1.5.5 2 2
QuickTime Player 10 10 10
Automator 2 2 2
Terminal 2 2 2
Console 1 1 1
Instruments 16 26 27
ScriptEditor 2.11 2.11 2.11
System Information 11 11 11
VoiceOver Utility 10 10 10
Shortcuts 7 7 10
Screen Sharing 5 6 7
ヒント(Hints) 16 26 1

standard additionsの用語を使う際に注意

Cocoa Script(use framework “Foundation”あるいは”Cocoa”を含むAppleScript)において、コンパイル(構文確認)時に、standard additionsの予約語を含む場合にエラーになるケースが増えました。

on writeToFileAsUTF8(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data as «class utf8» to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end writeToFileAsUTF8

★Click Here to Open This Script 

これだとエラーになります。「using terms from scripting additions」〜「end using terms from」で囲う必要が出てくるケースに遭遇しました。

on writeToFileAsUTF8(this_data, target_file, append_data)
  tell current application
    using terms from scripting additions
      try
        set the target_file to the target_file as text
        
set the open_target_file to open for access file target_file with write permission
        
if append_data is false then set eof of the open_target_file to 0
        
write this_data as «class utf8» to the open_target_file starting at eof
        
close access the open_target_file
        
return true
      on error error_message
        try
          close access file target_file
        end try
        
return error_message
      end try
    end using terms from
  end tell
end writeToFileAsUTF8

★Click Here to Open This Script 

Posted in Bug | Tagged macOS 27 | Leave a comment

macOS 27, Golden Gate

Posted on 6月 9 by Takaaki Naganoya

US Appleによる開発者向けイベントWWDC 26において、macOS 27, Golden Gateが発表されました。

前バージョン(macOS 26)で導入され、いまひとつ人気を得ていなかった「Liquid Glass」から、前々バージョンの「macOS 15」のデザインに差し戻したような印象を受けます。

macOS 26から過剰な装飾を削ぎ落としたようなデザインに変更。さらに、各種バグについて解消を図るほか、Siri AIの機能強化が行われたと発表されています。

珍しくUser系のBeta Program「Apple Seed」にもBeta 1が回ってきた(例年、Beta 1はDeveloper Betaにしか回ってこない)ので、さっそくMacBook Air M2にmacOS 27 Beta 1をインストールしたところ、まだ全体的にバグはあるものの、Beta 1としてはかなり評価できる印象です(常用はつらそう)。

不評だったmacOS 26を「なかったこと」にしつつ、悪かった点は改め、よい点は伸ばすというのがmacOS 27の位置付けのようです。ティム体制下ではこれまでになかった動きであり、これまでの「中身のない、株価対策のためだけのバージョンアップ」よりも評価できる動きです。

AppleScriptの仕様を調べてみるとバージョン2.8で変更はありません。スクリプトエディタにも変更はないようです。特筆すべき点として、このところ毎度毎度Beta初期段階で動作しないまま出てきていた「スクリプトメニュー」が、このBeta 1から動作していて驚かされました。

その他、Beta初期段階で何度も発生していた「aliasをPOSIX pathにcastするとおかしな表記のパスが返ってくる」という恥ずかしいバグも、このBeta 1では見られていません(それでも油断できない)。

バグ修正については、「Cocoa-AppleScript Applet」がまともに動いているように見えます。簡単な(ダイアログを表示する程度の)アプレットを作成し、アプレットとして保存。アプレットを実行すると、問題なくダイアログ表示されました。ただ、このアプレットを通常終了することができなかったので、その点は問題といえるでしょう。

Xcode上でAppleScriptで作成したDocument Basedなアプリが起動しなかったり(Kamenoko)、まだ初期段階だから発生しているのか、それとも他の問題によるものなのか不明な問題も確認しています。

Posted in Bug news | Tagged macOS 27 | Leave a comment

ワークスペース切り替えv2.1

Posted on 5月 6 by Takaaki Naganoya

macOSのSpaces(仮想デスクトップ機能)で、任意のワークスペースに切り替えを行うAppleScriptです。

–> Download changeSpace_v2.1.scptd(with spaces_tool in its bundle)

Spaces系の機能はAPIが公開されておらず、Private APIを叩きまくることになります。現在定義されているSpacesの名称一覧の取得(list)、現在表示中のSpacesの名称(current)についてはこの方法で情報を取得できています。

肝心のSpaces間の切り替えについては、GUI Scripting経由でキーコード(Control 1、Control 2など)を送出することで行なっています。これらのキーボードショートカットが有効になっていないと切り替え自体が行えません(このあたりの機能がOS内部で十分にサポートされていないため、このような行き当たりばったりの実装になってしまいます)。

そのため、本AppleScriptを実行するプログラム……スクリプトエディタ上で実行するのであればスクリプトエディタに、Script Menuで実行するのであればScript MenuにGUI Scriptingの実行権限(アクセシビリティ)を許可しておく必要があります。また、同様の理由からGUI Scripting呼び出し権限を取得できないAppleScriptの実行プログラムからはSpacesの切り替え操作を行えません。

以下のAppleScriptは内蔵ツールを呼び出すだけのものであり、これだけでは実行できません。上記リンクからバンドルスクリプト自体をダウンロードして、実行してください。

# もしかしたら、space_toolは各クライアント上でビルドし直さないとダメかもしれないので、実行時にビルド+実行する形態に書き換えるかもしれません

AppleScript名:ワークスペース切り替えv2.1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/05/05
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

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

set aPath to path to resource "space-tool"
set pPath to POSIX path of aPath

delay 0.5 –超重要。スクリプトエディタ上で実行するには必須

— ① 一覧取得
set allSpaces to do shell script (quoted form of pPath) & " list"
(*
"Desktop_1
Desktop_2"
*)

— ② 現在選択されているSpaces名称を取得
set currentSpace to do shell script (quoted form of pPath) & " current"
–> "Desktop_1"

— ③ 切り替え(例:Desktop_2へ)
my switchToSpace(2)

on switchToSpace(spaceNumber)
  — 数字キーのキーコードマップ (1=18, 2=19, 3=20, 4=21, 5=23, 6=22, 7=26, 8=28, 9=25)
  
set keyCodes to {18, 19, 20, 21, 23, 22, 26, 28, 25}
  
set theCode to item spaceNumber of keyCodes
  
  
tell application "System Events"
    key code theCode using {control down}
  end tell
end switchToSpace

★Click Here to Open This Script 

Posted in Spaces System | Tagged 26.0savvy | Leave a comment

Safariの最前面のウィンドウで表示されているAmazon.co.jpの製品ページへの最短リンクを取得

Posted on 3月 30 by Takaaki Naganoya

Safariの最前面のウィンドウで表示中のamazon.co.jpの製品ページへの最短リンクを取得して、クリップボードに入れるAppleScriptです。動作確認はmacOS 26.4+Safari 26.4で確認しています。添付のアプレットはScript Menuに入れて呼び出しています。

–> Download Enhanced Applet with Framework

Amazon.co.jpの製品URLをWebブラウザのURL欄からコピー&ペーストで取得しようとしても、不要な情報が大量に付加されているため、Blogなどに投稿するのにけっこう苦労します。

そこで、実際に対象の製品ページへのリンクが可能な最短のURL(短縮URLではなく)を作成してクリップボードに入れます。

HTMLの解析については、いつものHTMLReader Framework(https://github.com/nolanw/HTMLReader)を利用しています。そのため、Script DebuggerからExportしたEnhanced Appletとして動作するように想定しています。

正直なところ、やり方はいくつもありますし、プログラム内容もやっつけで書いているので見るに堪えない部分はあるのですが、実際に動作する日常的なScriptなんてこんなもんだろうかと。

本Scriptは、日本のAmazon(amazon.co.jp)のURLを対象に処理していますが、他国のAmazon用に書き換えるのもとくに難しくはありません。

Google Chromeなど他のWebブラウザ用に改変するのもとくに難しくないので、試してみるといいのではないでしょうか。

AppleScript名:最前面に表示中のAmazonのページから製品リンクURLを抽出する_v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/03/01
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

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

property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property HTMLDocument : a reference to current application’s HTMLDocument
property NSMutableArray : a reference to current application’s NSMutableArray

–URL Check
set uRes to retURLFromActiveSafariTab() of me
if uRes does not start with "https://www.amazon.co.jp" then return –change each location’s Amazon URL

set aURL to getProductURLFromAmazon() of me
if aURL = "" then return

set bURL to current application’s |NSURL|’s URLWithString:aURL
set aList to bURL’s pathComponents()
aList’s removeObjectAtIndex:1 –2番目のアイテムを削除

set bList to aList as list
set bLen to length of bList
if bLen is not equal to 3 then return

if contents of item 1 of bList is not equal to "/" then return
if contents of item 2 of bList is not equal to "dp" then return

set aScheme to bURL’s |scheme|() as string
set aHost to bURL’s |host|() as string

set resURL to aScheme & "://" & aHost & "/" & (contents of item 2 of bList) & "/" & (contents of item 3 of bList)

set the clipboard to resURL
beep 1

on getProductURLFromAmazon()
  –Get HTML Source
  
set hRes to retHTMLSourceFromActiveSafariTab() of me
  
  
  
set aHTML to current application’s HTMLDocument’s documentWithString:(hRes as string)
  
set linkList to (aHTML’s nodesMatchingSelector:"link")
  
  
log linkList
  
  
repeat with i in (linkList as list)
    set j to contents of i
    
    
set aProp to (j’s attributes’s valueForKeyPath:("rel")) as string
    
    
if aProp = "canonical" then
      set resURL to (j’s attributes’s valueForKeyPath:("href"))
      
return resURL as string
    end if
    
  end repeat
  
  
return ""
end getProductURLFromAmazon

on retHTMLSourceFromActiveSafariTab()
  tell application "Safari"
    if running then
      if (every document) = {} then return false
      
tell front document
        set htmlRes to source
      end tell
    else
      return false
    end if
  end tell
  
  
set aStr to current application’s NSString’s stringWithString:htmlRes
  
set aNFC to (aStr’s precomposedStringWithCanonicalMapping()) as text –Normalize Text
  
return aNFC
end retHTMLSourceFromActiveSafariTab

on retURLFromActiveSafariTab()
  tell application "Safari"
    if running then
      if (every document) = {} then return missing value
      
tell front document
        set htmlRes to URL
      end tell
    else
      return missing value
    end if
  end tell
end retURLFromActiveSafariTab

★Click Here to Open This Script 

Posted in URL | Tagged 15.0savvy 26.0savvy Safari | Leave a comment

翻訳テスト

Posted on 3月 25 by Takaaki Naganoya

翻訳対象の文と、翻訳先の言語コード(2文字コード)を指定すると、macOS内のサービスを呼び出して翻訳して返します。

翻訳を司るTranslation.frameworkはAppleScriptObjCから呼び出せないため、Swiftを介して呼び出してみました。

実際に、AppleScriptObjCから呼び出すことも試みてみたのですが、結局できず……逆に、この手の処理はAppleScriptから呼び出せると有用性が高いもののはずなので、呼び出せないことに納得が行かず、いろんな方法を試行。

実行処理を考えると、AppleScriptバンドル書類内にSwiftからビルドした実行バイナリを入れて呼び出す方が速くてよいのですが、実行環境の多さを考慮してテキスト形式のSwiftを組み込むようにしてみました。

AppleScript名:翻訳テスト_v5.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/03/25
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

set targetLang to "ja"
set textList to {"Stay hungry, stay foolish.", "Innovation distinguishes between a leader and a follower."}
set sRes to translateList(targetLang, textList) of me
–>
(*
"飢え続け、愚かであり続けてください。
イノベーションはリーダーとフォロワーを区別します。"
*)

on translateList(targetLang, textList)
  — 引数の組み立て
  
set argString to targetLang
  
repeat with aText in textList
    set argString to argString & " " & (quoted form of aText)
  end repeat
  
  
— Swiftソースコード
  
— 実行速度と安定性を考慮し、RunLoopを使用して非同期完了を待機します
  
set shellCmd to "swift – " & argString & " <<’EOF’
import Foundation
import Translation
import NaturalLanguage

let args = CommandLine.arguments
guard args.count >= 3 else { exit(1) }

let targetLanguage = args[1]
let textsToTranslate = Array(args.dropFirst(2))

let recognizer = NLLanguageRecognizer()
recognizer.processString(textsToTranslate.joined(separator: \" \"))
guard let identifiedLanguage = recognizer.dominantLanguage?.rawValue else { exit(1) }

let source = Locale.Language(identifier: identifiedLanguage)
let target = Locale.Language(identifier: targetLanguage)

// 翻訳実行フラグ
var isFinished = false

Task {
let session = TranslationSession(installedSource: source, target: target)
do {
let requests = textsToTranslate.map { TranslationSession.Request(sourceText: $0) }
let response = try await session.translations(from: requests)
for result in response {
print(result.targetText)
}
} catch {
fputs(\"Error: \\(error.localizedDescription)\\n\", stderr)
}
isFinished = true
}

// 非同期処理が完了するまでRunLoopを回して待機する
while !isFinished {
RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.1))
}
EOF"

  
  
try
    — do shell script は標準出力が返るまで待機します
    
set translatedResults to do shell script shellCmd
    
return translatedResults
  on error errMsg
    error "翻訳エラー" & return & errMsg
  end try
end translateList

★Click Here to Open This Script 

AppleScript名:翻訳言語コードを取得.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2026/03/25
—
–  Copyright © 2026 Piyomaru Software, All Rights Reserved
—

set langList to returnLangCodes() of me
–> {"ar", "de", "en", "es", "fr", "hi", "id", "it", "ja", "ko", "nl", "pl", "pt", "ru", "th", "tr", "uk", "vi", "zh"}

on returnLangCodes()
  set shellCmd to "swift – <<’EOF’
import Foundation
import Translation

Task {
let availability = LanguageAvailability()
let supportedLanguages = await availability.supportedLanguages

// languageCode(ja, enなど)のみを抽出し、重複を除いてソート
let codes = Set(supportedLanguages.compactMap { $0.languageCode?.identifier }).sorted()

for code in codes {
print(code)
}
exit(0)
}

RunLoop.main.run(until: Date(timeIntervalSinceNow: 5))
EOF"

  
  
try
    — 言語コードを改行区切りで取得
    
set supportedCodes to do shell script shellCmd
    
    
— リスト形式に変換
    
set oldDelims to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to string id 13
    
set codeList to text items of supportedCodes
    
set AppleScript’s text item delimiters to oldDelims
    
    
— 結果を表示
    
if (count of codeList) > 0 then
      return codeList
    else
      error "言語コードが見つかりませんでした。"
    end if
    
    
set the clipboard to (codeList as string)
  on error errMsg
    error "取得エラー" & return & errMsg
  end try
end returnLangCodes

★Click Here to Open This Script 

Posted in Natural Language Processing Swift Text | Tagged 26.0savvy | 2 Comments

Post navigation

  • Older posts

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

Google Search

Popular posts

  • 最初期に書かれた書籍「AppleScript道入門」の序文をいま振り返る
  • 簡易カラーチャート画像の出力 v2.1
  • Apple Creator Studioに含まれるKeynote/Pages/Numbersは新バージョン?
  • ASCII ART QR Encoder
  • 「AppleScriptセキュリティ実践ガイド」を発売
  • 翻訳テスト
  • Keynote->Keynote Creator Studio(以下同様)
  • Finder上で選択中のHEIC画像から位置情報を削除_v5
  • FSFindFolder failed with error=-43
  • YouTubeムービー再生実験
  • 2025年に書いた価値あるAppleScript
  • 関数計算ライブラリで一部のユーザーから再現しない問題が報告される件
  • ワークスペース切り替えv2.1
  • YouTubeムービー再生実験 v2c
  • macOS 26.xのSystem Events/Screen Saver preferencesにバグ
  • macOS 26.1が登場。Finderのバグが直らない?
  • 住所ジオコーダー2026年最新版
  • ignoring時の超高速化にともなう処理内容の信頼性低下のその後
  • Gender APIを使って名前から性別を判定
  • macOS 26.3beta2が登場。System Eventsのバグ直らず

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (440) 11.0savvy (283) 12.0savvy (212) 13.0savvy (204) 14.0savvy (159) 15.0savvy (176) 26.0savvy (58) CotEditor (68) Finder (53) Keynote (123) 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 (80) Pages (58) Safari (45) Script Editor (28) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • Apple Inteligence
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Newt On Project
  • NFC
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • process
  • 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
  • Scripting Additions
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • SOML
  • Sort
  • Sound
  • Spaces
  • Spellchecker
  • Spotlight
  • SVG
  • Swift
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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