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

Bluetoothに接続中のデバイス名を取得するv6

Posted on 12月 13, 2024 by Takaaki Naganoya

3年ぐらい前に書いてあった、Mac本体にペアリングして接続しているBluetoothのデバイス名を取得するAppleScriptです。

AppleScript名:Bluetoothに接続中のデバイス名を取得するv6.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/13
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

set pRes to getBluetoothPowerState() of me
if pRes = false then return

set dArray to current application’s IOBluetoothDevice’s pairedDevices()
set dRes to my filterRecListByLabel1(dArray, "isConnected != 0")
set dNameList to (dRes’s valueForKeyPath:"name") as list
–> {"Logicool Z600", "Takaaki Naganoya のキーボード #1", "Takaaki Naganoya のマウス"}
–> {"Logicool Z600", "AirPods Pro", "DUALSHOCK 4 Wireless Controller"}

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

–Mac本体のBluetoothのパワー状態を取得
on getBluetoothPowerState()
  set aCon to current application’s IOBluetoothHostController’s alloc()’s init()
  
set pRes to (aCon’s powerState()) as boolean
end getBluetoothPowerState

★Click Here to Open This Script 

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

Skim v1.7.6でopen locationコマンドを実装するも動作せず

Posted on 12月 12, 2024 by Takaaki Naganoya

オープンソースのPDFリーダー「Skim」のバージョン1.7.6において「open location」コマンドが実装されましたが、実際に試してみると動きません。確認は最新版の1.7.7で行いました。

これまでにも追加したコマンドを次のバージョンで廃止して、翌々バージョンで復活させたりと、いろいろその歴史をひもとくと「おっとっと」な動きが見られるので、そういうものなんでしょう。

本Blog上に存在するPDFのURLを指定。open locationでダウンロード+表示を試みるものの、表示されずにエラーになる。

→ Skimが「http://」をサポートしていないとのこと。https://からのダウンロードおよび表示は確認しました。

AppleScript名:Skim v17.6で追加されたopen locationのテスト.scpt
set aURL to "http://piyocast.com/as/wp-content/uploads/2018/09/GUNDAM-UI.pdf"

tell application "Skim"
  set erRes to (open location aURL with error reporting)
end tell

★Click Here to Open This Script 

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

新刊電子書籍「AppleScript基礎テクニック(34)電源制御」を刊行

Posted on 12月 10, 2024 by Takaaki Naganoya

新刊電子書籍「AppleScript基礎テクニック(34)電源制御」を刊行しました。全57ページ、サンプルAppleScriptアーカイブつき。Piyomaru Softwareによる電子書籍の95冊目です。
→ 販売ページ

ちょっとAppleScriptを書けるようになった方が、必要に感じてふりかえる「基礎」的な内容をプレゼン資料風に絵でご紹介する「AppleScript基礎テクニック集」の34冊目、Macの電源制御に関する1冊です。 スリープ、シャットダウン、スリープ解除日時指定、バッテリー残量取得、電源種別の判定など、電源制御系の機能は、AppleScriptに添える「気の利いた」スパイス。知っておくと役立つ、実際に動かすと楽しい電源制御機能について、詳細にご紹介します。 いまはMacBook Airで1日中バッテリーで駆動できるのでシビアな計算が必要な場面は減ったように感じますが、それでもバッテリー残量を取得する処理はAppleScriptでも欠かせません。電源制御は使って動かすと面白い処理です。

目次

■最初に:macOS 13以降では最初にステージマネージャを必ずオフにしてください
  macOS 13.x
  macOS 14.x
  macOS 15.x
  その他、オフにすることが望ましい機能

■電源制御 関連機能
  macOSの各種電源コントロール機能
  AppleScriptからスリープ実行
  指定日時にスリープ解除
  電源種別判定
  バッテリー残量データ取得

■スリープ
  2つのスリープ処理
  スリープ処理
  ディスプレイ消灯処理

■スリープ解除
  スリープ解除(スケジュール登録)
  スリープ解除日時設定のAppleScript①〜③

■スリープ解除検出
  スリープ解除検出、2つの方法
  一番単純なスリープ解除検出
  システム通知を利用したスリープ解除検出①〜③

■電源オフ
  電源オフは2コース

■電源種別判定
  電源種別判定

■Mac本体のバッテリー残量取得
  バッテリー情報を取得する前に
  デスクトップ機とノート機の区別①〜③
  取得できるMac本体のバッテリー仕様
  Mac本体のバッテリー残量を取得

■その他資料
  ログアウト処理
  再起動
  CPU種別判定
  CPU動作クロック取得
  Apple Siliconの各種温度センサーの値を取得①〜③

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

Excel 現在のシート上に存在しているpictureをすべて削除する

Posted on 12月 7, 2024 by Takaaki Naganoya

Excelでオープンしている最前面の書類の現在表示中のシート上に配置されているpicture(画像)をすべて削除するAppleScriptです。

pictureを大量に配置するScriptの後始末をするために作成したものです(書き捨てレベル)。

数万セルのデータを取得して、ふたたび書き戻すような処理を行っても数秒。セルのデータのI/Oが超高速なExcelですが、画像などのオブジェクト操作は時間がかかり、本Scriptで900個程度のpictureオブジェクト(画像)を削除すると、それなりに待たされます。しかも、ignoring responsesで非同期実行しても待たされます。


▲実行前


▲実行後

AppleScript名:現在のシート上に存在しているpictureをすべて削除する.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/07
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

tell application "Microsoft Excel"
  tell active workbook
    tell active sheet
      ignoring application responses
        delete every picture
      end ignoring
    end tell
  end tell
end tell

★Click Here to Open This Script 

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

Excel 指定範囲のセルの上に画像を配置

Posted on 12月 7, 2024 by Takaaki Naganoya

指定範囲(30×30)のセルの位置に画像を配置するAppleScriptです。

画像配置Scriptに対して「特定のセルを指定すると配置できずにエラーになる」という反応があったので、テストを行うために書いたものです。

結局、セルアドレスを「B5」ではなく「b5」と小文字で書いたことがエラーの原因でした。Excelのセルアドレスを小文字で書くなんて聞いたことがないのですが、たしかにこれに対処できないのは問題です。

なので、セルのcolumnを計算するルーチンで大文字/小文字を無視するように書き換えました。

AppleScript名:指定範囲のセルの上に画像を配置.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/06
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSImage : a reference to current application’s NSImage

–Select Image file and get width and height
set anImagePath to choose file
set anImagePOSIX to POSIX path of anImagePath
set aURL to |NSURL|’s fileURLWithPath:anImagePOSIX
set aImage to NSImage’s alloc()’s initWithContentsOfURL:aURL
set overlaySize to aImage’s |size|()

repeat with targCellRow from 1 to 30
  repeat with targCellCol from 1 to 30
    
    
–Column No, & Row No. –> x position & y position
    
set {targCellX, targCellY} to retExcelCellPositiont(targCellCol, targCellRow) of me
    
    
–Place image on worksheet and resize and relocate it
    
tell application "Microsoft Excel"
      activate
      
      
tell active workbook
        tell active sheet
          ignoring application responses
            set newPic to make new picture at beginning with properties {file name:(anImagePOSIX), height:(overlaySize’s |height|), width:(overlaySize’s |width|), top:targCellY, left position:targCellX}
          end ignoring
        end tell
      end tell
    end tell
  end repeat
end repeat

–指定Row, ColumnのCellのpositionを返す
on retExcelCellPositiont(x as integer, y as integer)
  tell application "Microsoft Excel"
    tell active workbook
      tell active sheet
        tell row y
          tell cell x
            set xMin0 to left position
            
set yMin0 to top
            
set xWidth0 to width
            
set yHeight0 to height
          end tell
        end tell
      end tell
    end tell
  end tell
  
  
return {xMin0, yMin0}
end retExcelCellPositiont

script AddressEncoder
  property parent : AppleScript
  
use scripting additions
  
  
— 数値からセルアドレス(A1形式)への変換
  
on numberToCell(columnNumber)
    set columnAddress to ""
    
set tempNumber to columnNumber
    
    
— 列番号をA-Z形式に変換
    
repeat while tempNumber > 0
      set remainder to (tempNumber – 1) mod 26
      
set columnAddress to (character (remainder + 1) of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") & columnAddress
      
set tempNumber to (tempNumber – 1) div 26
    end repeat
    
    
— A1形式のアドレスを返す
    
return columnAddress
  end numberToCell
  
  
  
— セルアドレス(A1形式)から数値への変換
  
on cellToNumber(cellAddress)
    set columnPart to ""
    
set rowPart to ""
    
    
— 列部分と行部分を分離
    
repeat with char in cellAddress
      if char is in "0123456789" then
        set rowPart to rowPart & char
      else
        set columnPart to columnPart & char
      end if
    end repeat
    
    
— 列部分を数値に変換
    
set columnNumber to 0
    
repeat with i from 1 to length of columnPart
      set char to character i of columnPart
      
using terms from scripting additions
        ignoring case
          set columnNumber to columnNumber * 26 + (offset of char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
        end ignoring
      end using terms from
    end repeat
    
    
— 数値を返す
    
return {columnNumber, (rowPart as integer)}
  end cellToNumber
end script

★Click Here to Open This Script 

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

Excel 配置されている画像の左上のアドレスを取得してA1形式で返す

Posted on 12月 7, 2024 by Takaaki Naganoya

Microsoft Excelで、ワークシートに貼り込んだ画像の左上のセルアドレスを求めるAppleScriptです。

AppleScript名:配置されている画像の左上のアドレスを取得してA1形式で返す.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/06
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

tell application "Microsoft Excel"
  tell active workbook
    tell active sheet
      set aPic to picture 1
      
      
set tlCell to top left cell of aPic
      
set xCell to first column index of tlCell
      
set yCell to first row index of tlCell
      
      
set cellAdr to (numberToCell(xCell) of AddressEncoder) & (yCell as string)
      
–> "B5"
    end tell
  end tell
end tell

script AddressEncoder
  property parent : AppleScript
  
use scripting additions
  
  
— 数値からセルアドレス(A1形式)への変換
  
on numberToCell(columnNumber)
    set columnAddress to ""
    
set tempNumber to columnNumber
    
    
— 列番号をA-Z形式に変換
    
repeat while tempNumber > 0
      set remainder to (tempNumber – 1) mod 26
      
set columnAddress to (character (remainder + 1) of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") & columnAddress
      
set tempNumber to (tempNumber – 1) div 26
    end repeat
    
    
— A1形式のアドレスを返す
    
return columnAddress
  end numberToCell
  
  
  
— セルアドレス(A1形式)から数値への変換
  
on cellToNumber(cellAddress)
    set columnPart to ""
    
set rowPart to ""
    
    
— 列部分と行部分を分離
    
repeat with char in cellAddress
      if char is in "0123456789" then
        set rowPart to rowPart & char
      else
        set columnPart to columnPart & char
      end if
    end repeat
    
    
— 列部分を数値に変換
    
set columnNumber to 0
    
repeat with i from 1 to length of columnPart
      set char to character i of columnPart
      
using terms from scripting additions
        ignoring case
          set columnNumber to columnNumber * 26 + (offset of char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
        end ignoring
      end using terms from
    end repeat
    
    
— 数値を返す
    
return {columnNumber, (rowPart as integer)}
  end cellToNumber
  
end script

★Click Here to Open This Script 

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

Excel 指定セルに指定画像を貼り込む v2

Posted on 12月 6, 2024 by Takaaki Naganoya

Microsoft Excelで、指定画像を指定セルに貼り込むAppleScriptです。指定セルの座標を求めて、そこを左上の位置として画像を貼り込みます。

前バージョンが「動かない」という話があって、「そんなバカな?!」と、半信半疑でユーザーと同じドライブ名、フォルダ名、ファイル名、画像形式を採用したら(JPEG形式)同様にエラーになりました。自分がテストしたのは内蔵SSDで、画像形式はPNGだったのですが……

そこで、書き換えてJPEG画像でも、外付けドライブでもエラーにならないように書き換えてみました。

AppleScript名:指定セルに指定画像を貼り込む v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/06
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSImage : a reference to current application’s NSImage

–Excel Cell Address (A1) –> Column No, & Row No.
set targCellAddr to "C5"
set {targCellCol, targCellRow} to cellToNumber(targCellAddr) of AddressEncoder
log {targCellCol, targCellRow}

–Column No, & Row No. –> x position & y position
set {targCellX, targCellY} to retExcelCellPositiont(targCellCol, targCellRow) of me
log {targCellX, targCellY}

–Select Image file and get width and height
set anImagePath to choose file
set anImagePOSIX to POSIX path of anImagePath
set aURL to |NSURL|’s fileURLWithPath:anImagePOSIX
set aImage to NSImage’s alloc()’s initWithContentsOfURL:aURL
set overlaySize to aImage’s |size|()

–Place image on worksheet and resize and relocate it
tell application "Microsoft Excel"
  activate
  
  
tell active workbook
    tell active sheet
      set newPic to make new picture at beginning with properties {file name:(anImagePOSIX), height:(overlaySize’s |height|), width:(overlaySize’s |width|), top:targCellY, left position:targCellX}
    end tell
  end tell
end tell

–指定Row, ColumnのCellのpositionを返す
on retExcelCellPositiont(x as integer, y as integer)
  tell application "Microsoft Excel"
    tell active workbook
      tell active sheet
        tell row y
          tell cell x
            set xMin0 to left position
            
set yMin0 to top
            
set xWidth0 to width
            
set yHeight0 to height
          end tell
        end tell
      end tell
    end tell
  end tell
  
  
return {xMin0, yMin0}
end retExcelCellPositiont

script AddressEncoder
  property parent : AppleScript
  
use scripting additions
  
  
— 数値からセルアドレス(A1形式)への変換
  
on numberToCell(columnNumber)
    set columnAddress to ""
    
set tempNumber to columnNumber
    
    
— 列番号をA-Z形式に変換
    
repeat while tempNumber > 0
      set remainder to (tempNumber – 1) mod 26
      
set columnAddress to (character (remainder + 1) of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") & columnAddress
      
set tempNumber to (tempNumber – 1) div 26
    end repeat
    
    
— A1形式のアドレスを返す
    
return columnAddress
  end numberToCell
  
  
  
— セルアドレス(A1形式)から数値への変換
  
on cellToNumber(cellAddress)
    set columnPart to ""
    
set rowPart to ""
    
    
— 列部分と行部分を分離
    
repeat with char in cellAddress
      if char is in "0123456789" then
        set rowPart to rowPart & char
      else
        set columnPart to columnPart & char
      end if
    end repeat
    
    
— 列部分を数値に変換
    
set columnNumber to 0
    
repeat with i from 1 to length of columnPart
      set char to character i of columnPart
      
using terms from scripting additions
        set columnNumber to columnNumber * 26 + (offset of char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
      end using terms from
    end repeat
    
    
— 数値を返す
    
return {columnNumber, (rowPart as integer)}
  end cellToNumber
  
end script

★Click Here to Open This Script 

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

アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v4

Posted on 12月 6, 2024 by Takaaki Naganoya

アラートダイアログ上にWkWebViewを作成して、さまざまなグラフや3Dアニメーションを表示してきた「箱庭ダイアログ」の1つの到達点、「periodictable」(元素周期表)選択UIの表示デモAppleScriptです。

–> Download Script Bundle

実行は掲載リストではなく上記のリンクからダウンロードしたAppleScriptバンドルを、かならずスクリプトエディタでオープンして(Script Debugger不可)、Controlキーを押しながらスクリプトエディタの「スクリプト」メニューから「フォアグラウンドで実行」コマンドで実行してください。

「フォアグラウンド」はApple(の外注のローカライズ業者による)ローカライズ内容が間違っていて、実際には「メインスレッドで実行」が正しいのですが、まあいいです。

以前に掲載したバージョン(v3)は、掲載後しばらくはそのまま動いていることが確認されたのですが、その後のCDN上のJavaScriptライブラリのアップデートにともない、動作しなくなっていました。本v4はその点を解決したもので、技術的により進化したというよりも、「勝手に動かなくなる点に対処した」程度のものとお考えください。

periodictableのUser Interface自体、目を惹くものであり、とても楽しいものです。ただ、真剣にその内容を解析し、汎用的に利用できるかどうかを検討してみると、おおよそ120個程度の要素に対して、重みづけを与えずに自由選択するような用途でないと実用性が得られないことがわかりました。たいてい、情報には重要度などの重みがありますが、本User Interfaceはそれがあると邪魔な感じです。

また、少ないデータ……2個や3個の要素から選択するのでは、用をなしません。用途が限定されすぎているというべきなのか、この用途にしか合わないというべきなのか。

JavaScriptとAppleScriptの間での選択項目のやり取りを行う手段についても、edama2氏が実際に稼働するデモを作ったのを見せてもらい、たしかにそうした処理ができることを確認しています。

それでも、いまひとつ実用性がないので、あくまで本プログラムは「デモ用」と割り切っています。

「CDN上のJavaScriptライブラリがアップデートして動かなくなる問題」についても、1つの解決策が見えてきました。ローカルにJavaScriptライブラリを配置して読み込んで使えばいいというものです。実際に、本ScriptバンドルのResourceフォルダ内にそれらのファイルが入っています。

これで勝手にアップデートされないため、放っておくと動かなくなるといった問題への解決策となっています。ただ、その一方でメイン処理を呼び出すさいに強制的なメインスレッド実行を行わせても、実行できないという謎の現象が発生。これについては、問題解決の手段自体はあるはずです(たぶん)。

AppleScript名:アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v4.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/13
–  Modified on: 2023/03/07
—
–  Copyright © 2020-2023 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7"
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSAlert : a reference to current application’s NSAlert
property NSString : a reference to current application’s NSString
property NSButton : a reference to current application’s NSButton
property WKWebView : a reference to current application’s WKWebView
property WKUserScript : a reference to current application’s WKUserScript
property NSURLRequest : a reference to current application’s NSURLRequest
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property WKUserContentController : a reference to current application’s WKUserContentController
property WKWebViewConfiguration : a reference to current application’s WKWebViewConfiguration
property WKUserScriptInjectionTimeAtDocumentEnd : a reference to current application’s WKUserScriptInjectionTimeAtDocumentEnd

property returnCode : 0

on run
  –https://www.cresco.co.jp/blog/entry/7427/
  
— By sgi-chang @ UX Design Center
  
set myStr to (POSIX path of (path to me)) & "/Contents/Resources/index.html"
  
  
set paramObj to {myMessage:"WebGL & three.js Test", mySubMessage:"This is a WebGL UI using three.js", htmlPath:myStr}
  
my browseFileWebContents:paramObj –for debug
  
–my performSelectorOnMainThread:"browseFileWebContents:" withObject:(paramObj) waitUntilDone:true
end run

on browseFileWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlPathStr to (htmlPath of paramObj)
  
  
set aWidth to 1600
  
set aHeight to 900
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
tell current application
    set htmlString to read ((POSIX file htmlPathStr) as alias) as «class utf8»
  end tell
  
set jsSource to pickUpFromToStr(htmlString, "<script src", "</script>") of me
  
  
set userScript to WKUserScript’s alloc()’s initWithSource:jsSource injectionTime:(WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
set userContentController to WKUserContentController’s alloc()’s init()
  
userContentController’s addUserScript:(userScript)
  
aConf’s setUserContentController:userContentController
  
  
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
using terms from scripting additions
    set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  end using terms from
  
set htmlURL to current application’s |NSURL|’s fileURLWithPath:htmlPathStr
  
aWebView’s loadFileURL:(htmlURL) allowingReadAccessToURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseFileWebContents:

on doModal:aParam
  set (my returnCode) to (aParam’s runModal()) as number
end doModal:

on viewDidLoad:aNotification
  return true
end viewDidLoad:

on fetchJSSourceString(aURL)
  set jsURL to |NSURL|’s URLWithString:aURL
  
set jsSourceString to NSString’s stringWithContentsOfURL:jsURL encoding:(NSUTF8StringEncoding) |error|:(missing value)
  
return jsSourceString
end fetchJSSourceString

on pickUpFromToStr(aStr as string, s1Str as string, s2Str 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
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

on array2DToJSONArray(aList)
  set anArray to current application’s NSMutableArray’s arrayWithArray:aList
  
set jsonData to current application’s NSJSONSerialization’s dataWithJSONObject:anArray options:(0 as integer) |error|:(missing value) –0 is
  
set resString to current application’s NSString’s alloc()’s initWithData:jsonData encoding:(current application’s NSUTF8StringEncoding)
  
return resString
end array2DToJSONArray

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

★Click Here to Open This Script 

Posted in 3D Animation Web Contents Control | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

Excelで指定セルに指定画像を貼り込む

Posted on 12月 5, 2024 by Takaaki Naganoya

Microsoft Excelで、指定画像を指定セルに貼り込むAppleScriptです。指定セルの座標を求めて、そこを左上の位置として画像を貼り込みます。

本Scriptで、セルアドレスの指定時に「B4」などとアルファベット大文字で指定してください。英小文字で指定するとエラーになります(以後のバージョンでは、ignoring caseで判断部分を囲って対処しています)。

AppleScript名:指定セルに指定画像を貼り込む.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/05
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSImage : a reference to current application’s NSImage

–Excel Cell Address (A1)–+ Column No, & Row No.
set targCellAddr to "A2"
set {targCellCol, targCellRow} to cellToNumber(targCellAddr) of AddressEncoder
log {targCellCol, targCellRow}

–Column No, & Row No. –> x position & y position
set {targCellX, targCellY} to retExcelCellPositiont(targCellCol, targCellRow) of me
log {targCellX, targCellY}

–Select Image file and get width and height
set anImagePath to choose file
set anImagePOSIX to POSIX path of anImagePath
set aURL to |NSURL|’s fileURLWithPath:anImagePOSIX
set aImage to NSImage’s alloc()’s initWithContentsOfURL:aURL
set overlaySize to aImage’s |size|()

–Place image on worksheet and resize and relocate it
tell application "Microsoft Excel"
  activate
  
  
tell active workbook
    tell active sheet
      
      
set aPicShape to make new shape at the beginning
      
set width of aPicShape to (overlaySize’s |width|)
      
set height of aPicShape to (overlaySize’s |height|)
      
set top of aPicShape to targCellY
      
set left position of aPicShape to targCellX
      
      
user picture of aPicShape picture file anImagePOSIX
      
    end tell
  end tell
end tell

–指定Row, ColumnのCellのpositionを返す
on retExcelCellPositiont(x as integer, y as integer)
  tell application "Microsoft Excel"
    tell active workbook
      tell active sheet
        tell row y
          tell cell x
            set xMin0 to left position
            
set yMin0 to top
            
set xWidth0 to width
            
set yHeight0 to height
          end tell
        end tell
      end tell
    end tell
  end tell
  
  
return {xMin0, yMin0}
end retExcelCellPositiont

script AddressEncoder
  property parent : AppleScript
  
use scripting additions
  
  
— 数値からセルアドレス(A1形式)への変換
  
on numberToCell(columnNumber)
    set columnAddress to ""
    
set tempNumber to columnNumber
    
    
— 列番号をA-Z形式に変換
    
repeat while tempNumber > 0
      set remainder to (tempNumber – 1) mod 26
      
set columnAddress to (character (remainder + 1) of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") & columnAddress
      
set tempNumber to (tempNumber – 1) div 26
    end repeat
    
    
— A1形式のアドレスを返す
    
return columnAddress
  end numberToCell
  
  
  
— セルアドレス(A1形式)から数値への変換
  
on cellToNumber(cellAddress)
    set columnPart to ""
    
set rowPart to ""
    
    
— 列部分と行部分を分離
    
repeat with char in cellAddress
      if char is in "0123456789" then
        set rowPart to rowPart & char
      else
        set columnPart to columnPart & char
      end if
    end repeat
    
    
— 列部分を数値に変換
    
set columnNumber to 0
    
repeat with i from 1 to length of columnPart
      set char to character i of columnPart
      
using terms from scripting additions
        set columnNumber to columnNumber * 26 + (offset of char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
      end using terms from
    end repeat
    
    
— 数値を返す
    
return {columnNumber, (rowPart as integer)}
  end cellToNumber
  
end script

★Click Here to Open This Script 

Posted in Image list | Tagged 13.0savvy 14.0savvy 15.0savvy Excel | Leave a comment

Chat GPTに書かせたQuickSort(昇順・降順ソート)2D

Posted on 12月 4, 2024 by Takaaki Naganoya

2D List(2次元配列)のソートルーチンをChatGPTに書かせてみました。1,000項目のソートで0.6秒(MacBook Air M2)、10,000項目のソートで329秒(MacBook Air M2)。

そのままでは使い物にならないので、listの持ち方を変えて高速化対応を行い、10,000項目のソートで0.32秒まで速くなりました。

Cocoaの機能を利用して10,000項目の2D Listソートすると、0.08秒ほど(MacBook Air M2)でしたが、Cocoaでソートする場合にはList中にアプリケーションのオブジェクト情報を入れられないので、Vanilla Scriptのソートルーチンもそれなりに高速なものをそろえておく必要があります。

ChatGPTにソートルーチンを書かせてみたら、AppleScriptのListは遅いとか言い訳をしだしたので、「こうしたら速くなるよ、100倍ぐらい」と言い返したら、少しマシな内容を返してきました。人間だと思って相手をすると腹が立ちますが、人間だと思わず、あらかじめ正解を知っていればそちらに誘導するぐらいはできそうです。

AppleScript名:Chat GPTに書かせたQuickSort(昇順・降順ソート_高速化改造版)2D.scpt
use AppleScript
use scripting additions
use framework "Foundation"

script spd
  property aList : {}
end script

set (aList of spd) to {}

repeat 10000 times
  set end of (aList of spd) to {(random number 1000 from 1 to 9999), (random number 1000 from 1 to 9999)}
end repeat

–昇順ソート
set a1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
set sortedList to quickSort2DArray((aList of spd), 2, true) –ソート
set b1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
set c1Dat to b1Dat – a1Dat

–降順ソート
set a2Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
set sortedList to quickSort2DArray((aList of spd), 2, false) –ソート
set b2Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
set c2Dat to b2Dat – a2Dat

display dialog (c1Dat as number as text) & return & (c2Dat as number as text)
–> 0.01 sec @MacBook Air M2 (1,000 items)
–> 0.32 sec @MacBook Air M2 (10,000 items)

return {c1Dat, c2Dat}

— クイックソートの関数(高速化対応版)
on quickSort2DArray(array2D, columnIndex, ascendingOrder)
  script oBj
    property list : array2D
    
property lessList : {}
    
property greaterList : {}
  end script
  
  
if (length of (oBj’s list)) ≤ 1 then
    return (oBj’s list) — 要素が1つ以下の場合はそのまま返す
  else
    — ピボットを選択(最初の要素を基準)
    
set pivot to item 1 of (oBj’s list)
    
set pivotValue to item columnIndex of pivot
    
    
— ピボットより小さい要素のリスト
    
set (oBj’s lessList) to {}
    
— ピボット以上の要素のリスト
    
set (oBj’s greaterList) to {}
    
    
repeat with i from 2 to length of (oBj’s list) — ピボットを除いたリストを処理
      set currentItem to item i of (oBj’s list)
      
set currentValue to item columnIndex of currentItem
      
      
— 昇順または降順で分岐
      
if (ascendingOrder and currentValue ≤ pivotValue) or ((not ascendingOrder) and currentValue ≥ pivotValue) then
        set end of (oBj’s lessList) to currentItem
      else
        set end of (oBj’s greaterList) to currentItem
      end if
    end repeat
    
    
— 再帰的にソートして結合
    
return (quickSort2DArray((oBj’s lessList), columnIndex, ascendingOrder) & {pivot} & quickSort2DArray((oBj’s greaterList), columnIndex, ascendingOrder))
  end if
end quickSort2DArray

★Click Here to Open This Script 

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

Numbersで選択中の表を書籍掲載用にセル内容の整理(重複セルをまとめる)v2

Posted on 12月 3, 2024 by Takaaki Naganoya

Numbersの表を、書籍掲載用に体裁をととのえるAppleScriptのアップデート版です。書籍掲載時には、同じ値が横方向に連続している箇所は1つにまとめたいところなので、その作業を自動で行います。

新型のNumbers/Excelセルアドレス変換ルーチンを実際に使用してみました。モジュールを入れ替えただけです。


▲対象の表のいずれかのセルを選択してAppleScriptを実行


▲処理後の表

AppleScript名:Numbersで選択中の表を書籍掲載用にセル内容の整理(重複セルをまとめる)v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/03
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

tell application "Numbers"
  tell front document
    tell active sheet
      try
        set theTable to first table whose class of selection range is range
      on error
        return "" –何も選択されてなかった場合
      end try
      
      
      
–セルを選択中の表を処理する
      
tell theTable
        set headR to header row count
        
set headC to header column count
        
set rowC to count every row
        
set colC to count every column
        
        
repeat with y from (headR + 1) to (rowC)
          –1行分(ヘッダーカラムをのぞく)のデータを1D Listで取得
          
set tmpRangeStr to numberToCell(headC + 1) of AddressEncoder & (y as string) & ":" & numberToCell(colC) of AddressEncoder & (y as string)
          
set tValList to value of cells of range tmpRangeStr
          
          
–1D Listから値が連続している区間を求める
          
set sameBlock to detectSameValueRepeatationBlockIn1DArray(tValList) of detectRepeatation
          
          
–連続区間でループ
          
repeat with i in sameBlock
            copy i to {startX, endX} –データ内の項目Indexであることに留意
            
            
–重複値のセルをクリアする(初出セルの値は残す)
            
repeat with ii from (startX + 1) to endX
              set value of cell (ii + headC) of row y to ""
            end repeat
            
            
–重複していたセルをマージする
            
set mRangeStr to numberToCell(headC + startX) of AddressEncoder & (y as string) & ":" & numberToCell(headC + endX) of AddressEncoder & (y as string)
            
set mRange to range mRangeStr
            
merge mRange
          end repeat
        end repeat
      end tell
    end tell
  end tell
end tell

script detectRepeatation
  property parent : AppleScript
  
use scripting additions
  
use framework "Foundation"
  
  
–巨大なデータの処理に向いていないかも?
  
on detectSameValueRepeatationBlockIn1DArray(aList)
    set dList to returnDuplicatesOnly(aList) of me
    
–>  {​​​​​"年間仕様", ​​​​​"YP仕様", ​​​​​"月間仕様"​​​}
    
    
set anArray to current application’s NSMutableArray’s arrayWithArray:aList
    
anArray’s addObject:""
    
    
set resList to {}
    
repeat with i in dList
      set j to contents of i
      
set anIndex to (anArray’s indexOfObject:j)
      
repeat with ii from (anIndex + 1) to ((length of aList))
        set jj to (anArray’s objectAtIndex:ii) as string
        
if jj is not equal to j then
          set the end of resList to {anIndex + 1, ii}
          
exit repeat
        end if
      end repeat
    end repeat
    
    
resList
    
–>  {​​​​​{​​​​​​​4, ​​​​​​​6​​​​​}, ​​​​​{​​​​​​​7, ​​​​​​​9​​​​​}, ​​​​​{​​​​​​​10, ​​​​​​​17​​​​​}​​​}
  end detectSameValueRepeatationBlockIn1DArray
  
  
on returnDuplicatesOnly(aList)
    set countedSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
    
set simpleSet to current application’s NSSet’s setWithArray:aList
    
countedSet’s minusSet:simpleSet
    
return countedSet’s allObjects() as list
  end returnDuplicatesOnly
end script

script AddressEncoder
  property parent : AppleScript
  
use scripting additions
  
  
— 数値からセルアドレス(A1形式)への変換
  
on numberToCell(columnNumber)
    set columnAddress to ""
    
set tempNumber to columnNumber
    
    
— 列番号をA-Z形式に変換
    
repeat while tempNumber > 0
      set remainder to (tempNumber – 1) mod 26
      
set columnAddress to (character (remainder + 1) of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") & columnAddress
      
set tempNumber to (tempNumber – 1) div 26
    end repeat
    
    
— A1形式のアドレスを返す
    
return columnAddress
  end numberToCell
  
  
  
— セルアドレス(A1形式)から数値への変換
  
on cellToNumber(cellAddress)
    set columnPart to ""
    
set rowPart to ""
    
    
— 列部分と行部分を分離
    
repeat with char in cellAddress
      if char is in "0123456789" then
        set rowPart to rowPart & char
      else
        set columnPart to columnPart & char
      end if
    end repeat
    
    
— 列部分を数値に変換
    
set columnNumber to 0
    
repeat with i from 1 to length of columnPart
      set char to character i of columnPart
      
using terms from scripting additions
        set columnNumber to columnNumber * 26 + (offset of char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
      end using terms from
    end repeat
    
    
— 数値を返す
    
return {columnNumber, (rowPart as integer)}
  end cellToNumber
  
end script

★Click Here to Open This Script 

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

Excel__Numbersセルアドレスの相互変換

Posted on 12月 3, 2024 by Takaaki Naganoya

ExcelやNumbersで使われているセルのアドレス表記方法「A1形式」と数値の相互変換を行うAppleScriptです。

一応、自分でも昔に書いたルーチンを使い回していますが、26進数と10進数との間の変換で桁が増えたときの処理に難があって、上限値を設けてその間であれば変換できる、という感じになっていました。

もともと、このルーチンはExcel 2008でVBAの処理系を搭載しないことになったのを好機ととらえ、AppleScriptをエンコードしてExcelの隠しワークシート上に格納しておいて外部から実行する「ExcelAS」プロジェクトのために作成したものです。

実際に調布のMicrosoftでデモを行なって、US Microsoftに掛け合ってもらったものの、次バージョンでVBAの処理系を復活させることになって、(Visual BASIC互換の)「REALbasic」のエンジンを書いていたエンジニアをMSがヘッドハント。常識的に考えればVBAの廃止自体がおかしな決定だったので、その隙を狙えるかも? と企画して作ったものの、残念な結果になってしまいました。ただ、現在に至るもMac上のVBAの処理系、とくにエディタは作りが残念(Retina解像度に合ってないとか、日本語入力できないとか、フォームが使えないとか)なので、もうちょっとなんとかならないものかと思ってしまいます。

話をアドレス変換ルーチンに戻しましょう。実際に、そんなに大きな値の相互変換はしていないので問題視していませんでしたが、変換ルーチンに上限値のしばりがあるのはうっとおしいとは思っていました。ただ、ExcelASプロジェクトの頓挫により、アドレス変換処理を書き換えるほどのインセンティブがなかったので、ながらく放置状態に。

そこで、定期的に行なっているChatGPTによるAppleScript記述実用性チェックの「お題」としてこのセルアドレスの相互変換を行わせてみました。

ちゃんと動いているように見えます。こういうデータ変換系のプログラムは、割とChatGPTで書かせるのは「アリ」だと思います。本ルーチンの注意点は、Excelアドレス(カラム名指定)はアルファベット大文字で記述する必要があるということです。小文字のアルファベットで記述すると本バージョンではエラーになります。

ただ、アプリケーションの詳細なコントロールを行わせると、首をひねってしまうような書き方を返してきます。

AppleScript名:Excel__Numbersセルアドレスの相互変換.scpt
— 数値 → A1形式
set result1 to numberToCell(2024, 5) — "BYV5"
display dialog "Number to Cell: " & result1

— A1形式 → 数値
set result2 to cellToNumber("BYV5") — {2024, 5}
display dialog "Cell to Number: Column: " & item 1 of result2 & ", Row: " & item 2 of result2

— 数値からセルアドレス(A1形式)への変換
on numberToCell(columnNumber, rowNumber)
  set columnAddress to ""
  
set tempNumber to columnNumber
  
  
— 列番号をA-Z形式に変換
  
repeat while tempNumber > 0
    set remainder to (tempNumber – 1) mod 26
    
set columnAddress to (character (remainder + 1) of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") & columnAddress
    
set tempNumber to (tempNumber – 1) div 26
  end repeat
  
  
— A1形式のアドレスを返す
  
return columnAddress & rowNumber
end numberToCell

— セルアドレス(A1形式)から数値への変換
on cellToNumber(cellAddress)
  set columnPart to ""
  
set rowPart to ""
  
  
— 列部分と行部分を分離
  
repeat with char in cellAddress
    if char is in "0123456789" then
      set rowPart to rowPart & char
    else
      set columnPart to columnPart & char
    end if
  end repeat
  
  
— 列部分を数値に変換
  
set columnNumber to 0
  
repeat with i from 1 to length of columnPart
    set char to character i of columnPart
    
set columnNumber to columnNumber * 26 + (offset of char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  end repeat
  
  
— 数値を返す
  
return {columnNumber, (rowPart as integer)}
end cellToNumber

★Click Here to Open This Script 

Posted in Number Text | Tagged 10.10savvy 10.11savvy 10.12savvy 10.13savvy 10.14savvy 10.15savvy 11.0savvy 12.0savvy 13.0savvy 14.0savvy 15.0savvy Excel Numbers | Leave a comment

Pagesで選択中の表を書籍掲載用にセル内容の整理(重複セルをまとめる)

Posted on 12月 2, 2024 by Takaaki Naganoya

Pages書類上の表を、書籍掲載用に体裁をととのえるAppleScriptです。書籍掲載時には、同じ値が横方向に連続している箇所は1つにまとめたいところなので、その作業を自動で行います。


▲Pages書類上の表のいずれかのセルを選択しておいて、本Scriptを実行します


▲実行後

AppleScript名:Pagesで選択中の表を書籍掲載用にセル内容の整理(重複セルをまとめる).scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/02
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

tell application "Pages"
  tell front document
    try
      set theTable to first table whose class of selection range is range
    on error
      return "" –何も選択されてなかった場合
    end try
    
    
–セルを選択中の表を処理する
    
tell theTable
      set headR to header row count
      
set headC to header column count
      
set rowC to count every row
      
set colC to count every column
      
      
repeat with y from (headR + 1) to (rowC)
        –1行分(ヘッダーカラムをのぞく)のデータを1D Listで取得
        
set tmpRangeStr to numAdrToColumnEncode(headC + 1) of AddressEncoder & (y as string) & ":" & numAdrToColumnEncode(colC) of AddressEncoder & (y as string)
        
set tValList to value of cells of range tmpRangeStr
        
        
–1D Listから値が連続している区間を求める
        
set sameBlock to detectSameValueRepeatationBlockIn1DArray(tValList) of detectRepeatation
        
        
–連続区間でループ
        
repeat with i in sameBlock
          copy i to {startX, endX} –データ内の項目Indexであることに留意
          
          
–重複値のセルをクリアする(初出セルの値は残す)
          
repeat with ii from (startX + 1) to endX
            set value of cell (ii + headC) of row y to ""
          end repeat
          
          
–重複していたセルをマージする
          
set mRangeStr to numAdrToColumnEncode(headC + startX) of AddressEncoder & (y as string) & ":" & numAdrToColumnEncode(headC + endX) of AddressEncoder & (y as string)
          
set mRange to range mRangeStr
          
merge mRange
        end repeat
      end repeat
    end tell
  end tell
end tell

script detectRepeatation
  property parent : AppleScript
  
use scripting additions
  
use framework "Foundation"
  
  
–巨大なデータの処理に向いていないかも?
  
on detectSameValueRepeatationBlockIn1DArray(aList)
    set dList to returnDuplicatesOnly(aList) of me
    
–>  {​​​​​"年間仕様", ​​​​​"YP仕様", ​​​​​"月間仕様"​​​}
    
    
set anArray to current application’s NSMutableArray’s arrayWithArray:aList
    
anArray’s addObject:""
    
    
set resList to {}
    
repeat with i in dList
      set j to contents of i
      
set anIndex to (anArray’s indexOfObject:j)
      
repeat with ii from (anIndex + 1) to ((length of aList))
        set jj to (anArray’s objectAtIndex:ii) as string
        
if jj is not equal to j then
          set the end of resList to {anIndex + 1, ii}
          
exit repeat
        end if
      end repeat
    end repeat
    
    
resList
    
–>  {​​​​​{​​​​​​​4, ​​​​​​​6​​​​​}, ​​​​​{​​​​​​​7, ​​​​​​​9​​​​​}, ​​​​​{​​​​​​​10, ​​​​​​​17​​​​​}​​​}
  end detectSameValueRepeatationBlockIn1DArray
  
  
on returnDuplicatesOnly(aList)
    set countedSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
    
set simpleSet to current application’s NSSet’s setWithArray:aList
    
countedSet’s minusSet:simpleSet
    
return countedSet’s allObjects() as list
  end returnDuplicatesOnly
end script

script AddressEncoder
  property parent : AppleScript
  
  
–10進数数値をExcel 2004/2008的カラム表現にエンコードするサブルーチン(エンコード範囲:1~1351)
  
on numAdrToColumnEncode(origNum)
    if origNum > 1351 then
      error "エラー:Numbersのカラム表現(A1形式)への変換ルーチンにおいて、想定範囲外(1351以上)のパラメータが指定されました"
    end if
    
    
set upperDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
    
set lowerDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
    
    
set oNum to origNum
    
set nTh to 26
    
set stringLength to 4
    
    
–数字が1桁の場合の対応
    
if origNum < 27 then
      set aRes to (item origNum of upperDigitEncTable) as string
      
return aRes
    end if
    
    
if origNum > 702 then
      –3桁になる場合
      
set upupNum to oNum div 676 –整数除算–上の上の桁
      
set oNum to oNum – (upupNum * 676)
      
set upNum to oNum div 26 –整数除算–上の桁
      
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
      
      
–つじつま合わせ処理 【強引】
      
if lowNum = -1 then
        set upNum to upNum – 1
        
set lowNum to 25
      end if
      
      
set upupChar to (item upupNum of upperDigitEncTable) as string
      
set upChar to (item upNum of upperDigitEncTable) as string
      
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
      
set resText to upupChar & upChar & lowChar
      
    else
      –2桁の場合
      
set upNum to oNum div 26 –整数除算–上の桁
      
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
      
      
–つじつま合わせ処理 【強引】
      
if lowNum = -1 then
        set upNum to upNum – 1
        
set lowNum to 25
      end if
      
      
set upChar to (item upNum of upperDigitEncTable) as string
      
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
      
set resText to upChar & lowChar
      
    end if
    
    
return resText
  end numAdrToColumnEncode
  
  
–Numbersの横方向アドレス(A~Zの26進数)文字列を10進数に変換
  
on colAddrToNumDecode(origStr)
    return aNthToDecimal(origStr, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}) of me
  end colAddrToNumDecode
  
  
  
–n進数文字列を10進数に変換する
  
on aNthToDecimal(origStr, nTh)
    set resNumber to 0
    
    
set sList to reverse of (characters of origStr)
    
set aLen to length of nTh
    
set digitCount to 0
    
    
repeat with i in sList
      set j to contents of i
      
set aRes to offsetInList(j, nTh) of me
      
      
set resNumber to resNumber + (aLen ^ digitCount) * aRes
      
      
set digitCount to digitCount + 1
    end repeat
    
    
return resNumber as integer
  end aNthToDecimal
  
  
  
on offsetInList(aChar, aList)
    set anArray to NSArray’s arrayWithArray:aList
    
set aInd to (anArray’s indexOfObject:aChar)
    
if aInd = current application’s NSNotFound or (aInd as number) > 9.99999999E+8 then
      error "Invalid Character Error"
    else
      return (aInd as integer) + 1 –0 to 1 based index conversion
    end if
  end offsetInList
  
end script

★Click Here to Open This Script 

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

Numbersで選択中の表を書籍掲載用にセル内容の整理(重複セルをまとめる)

Posted on 12月 2, 2024 by Takaaki Naganoya

Numbersの表を、書籍掲載用に体裁をととのえるAppleScriptです。書籍掲載時には、同じ値が横方向に連続している箇所は1つにまとめたいところなので、その作業を自動で行います。


▲こんな感じに掲載している表を作るためのScript

いずれかのセルを選択した表に対して処理を行います。表の各行のデータを取得し、データ連続区間を検出。連続区間の2つ目以降のセルの内容を消去したうえで、当該区間のセルをまとめます。

そんなに大きな表を処理するようにはできていません。色をつけるところまで自動化しようかとも考えたのですが、色についてはケースバイケースだろうと考え、そこまでは処理していません。


▲対象の表のいずれかのセルを選択してAppleScriptを実行


▲処理後の表

AppleScript名:Numbersで選択中の表を書籍掲載用にセル内容の整理(重複セルをまとめる).scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/12/02
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

tell application "Numbers"
  tell front document
    tell active sheet
      try
        set theTable to first table whose class of selection range is range
      on error
        return "" –何も選択されてなかった場合
      end try
      
      
      
–セルを選択中の表を処理する
      
tell theTable
        set headR to header row count
        
set headC to header column count
        
set rowC to count every row
        
set colC to count every column
        
        
repeat with y from (headR + 1) to (rowC)
          –1行分(ヘッダーカラムをのぞく)のデータを1D Listで取得
          
set tmpRangeStr to numAdrToColumnEncode(headC + 1) of AddressEncoder & (y as string) & ":" & numAdrToColumnEncode(colC) of AddressEncoder & (y as string)
          
set tValList to value of cells of range tmpRangeStr
          
          
–1D Listから値が連続している区間を求める
          
set sameBlock to detectSameValueRepeatationBlockIn1DArray(tValList) of detectRepeatation
          
          
–連続区間でループ
          
repeat with i in sameBlock
            copy i to {startX, endX} –データ内の項目Indexであることに留意
            
            
–重複値のセルをクリアする(初出セルの値は残す)
            
repeat with ii from (startX + 1) to endX
              set value of cell (ii + headC) of row y to ""
            end repeat
            
            
–重複していたセルをマージする
            
set mRangeStr to numAdrToColumnEncode(headC + startX) of AddressEncoder & (y as string) & ":" & numAdrToColumnEncode(headC + endX) of AddressEncoder & (y as string)
            
set mRange to range mRangeStr
            
merge mRange
          end repeat
        end repeat
      end tell
    end tell
  end tell
end tell

script detectRepeatation
  property parent : AppleScript
  
use scripting additions
  
use framework "Foundation"
  
  
–巨大なデータの処理に向いていないかも?
  
on detectSameValueRepeatationBlockIn1DArray(aList)
    set dList to returnDuplicatesOnly(aList) of me
    
–>  {​​​​​"年間仕様", ​​​​​"YP仕様", ​​​​​"月間仕様"​​​}
    
    
set anArray to current application’s NSMutableArray’s arrayWithArray:aList
    
anArray’s addObject:""
    
    
set resList to {}
    
repeat with i in dList
      set j to contents of i
      
set anIndex to (anArray’s indexOfObject:j)
      
repeat with ii from (anIndex + 1) to ((length of aList))
        set jj to (anArray’s objectAtIndex:ii) as string
        
if jj is not equal to j then
          set the end of resList to {anIndex + 1, ii}
          
exit repeat
        end if
      end repeat
    end repeat
    
    
resList
    
–>  {​​​​​{​​​​​​​4, ​​​​​​​6​​​​​}, ​​​​​{​​​​​​​7, ​​​​​​​9​​​​​}, ​​​​​{​​​​​​​10, ​​​​​​​17​​​​​}​​​}
  end detectSameValueRepeatationBlockIn1DArray
  
  
on returnDuplicatesOnly(aList)
    set countedSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
    
set simpleSet to current application’s NSSet’s setWithArray:aList
    
countedSet’s minusSet:simpleSet
    
return countedSet’s allObjects() as list
  end returnDuplicatesOnly
end script

script AddressEncoder
  property parent : AppleScript
  
  
–10進数数値をExcel 2004/2008的カラム表現にエンコードするサブルーチン(エンコード範囲:1~1351)
  
on numAdrToColumnEncode(origNum)
    if origNum > 1351 then
      error "エラー:Numbersのカラム表現(A1形式)への変換ルーチンにおいて、想定範囲外(1351以上)のパラメータが指定されました"
    end if
    
    
set upperDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
    
set lowerDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
    
    
set oNum to origNum
    
set nTh to 26
    
set stringLength to 4
    
    
–数字が1桁の場合の対応
    
if origNum < 27 then
      set aRes to (item origNum of upperDigitEncTable) as string
      
return aRes
    end if
    
    
if origNum > 702 then
      –3桁になる場合
      
set upupNum to oNum div 676 –整数除算–上の上の桁
      
set oNum to oNum – (upupNum * 676)
      
set upNum to oNum div 26 –整数除算–上の桁
      
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
      
      
–つじつま合わせ処理 【強引】
      
if lowNum = -1 then
        set upNum to upNum – 1
        
set lowNum to 25
      end if
      
      
set upupChar to (item upupNum of upperDigitEncTable) as string
      
set upChar to (item upNum of upperDigitEncTable) as string
      
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
      
set resText to upupChar & upChar & lowChar
      
    else
      –2桁の場合
      
set upNum to oNum div 26 –整数除算–上の桁
      
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
      
      
–つじつま合わせ処理 【強引】
      
if lowNum = -1 then
        set upNum to upNum – 1
        
set lowNum to 25
      end if
      
      
set upChar to (item upNum of upperDigitEncTable) as string
      
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
      
set resText to upChar & lowChar
      
    end if
    
    
return resText
  end numAdrToColumnEncode
  
  
–Numbersの横方向アドレス(A~Zの26進数)文字列を10進数に変換
  
on colAddrToNumDecode(origStr)
    return aNthToDecimal(origStr, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}) of me
  end colAddrToNumDecode
  
  
  
–n進数文字列を10進数に変換する
  
on aNthToDecimal(origStr, nTh)
    set resNumber to 0
    
    
set sList to reverse of (characters of origStr)
    
set aLen to length of nTh
    
set digitCount to 0
    
    
repeat with i in sList
      set j to contents of i
      
set aRes to offsetInList(j, nTh) of me
      
      
set resNumber to resNumber + (aLen ^ digitCount) * aRes
      
      
set digitCount to digitCount + 1
    end repeat
    
    
return resNumber as integer
  end aNthToDecimal
  
  
  
on offsetInList(aChar, aList)
    set anArray to NSArray’s arrayWithArray:aList
    
set aInd to (anArray’s indexOfObject:aChar)
    
if aInd = current application’s NSNotFound or (aInd as number) > 9.99999999E+8 then
      error "Invalid Character Error"
    else
      return (aInd as integer) + 1 –0 to 1 based index conversion
    end if
  end offsetInList
  
end script

★Click Here to Open This Script 

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

macOS 15: Pasteboardにimageを設定したときの挙動が変わった?

Posted on 12月 1, 2024 by Takaaki Naganoya

これまで利用してきたAppleScriptの挙動が変わってしまい、面食らっています。SF Symbolsの内容(文字)をコピーして呼び出すと、いい感じに画像にレンダリングしてクリップボードに設定するというScriptです。

SF Symbolsは、Appleがアイコンなどの素材として用意した「フォント」であり、アプリ間の基礎的なアイコンを共通化して、文字が読めなくてもなんとなくアプリを操作できるようにしようという、現代において最も新しい象形文字ともいえます。

SF Symbolsをブラウズするアプリ「SF Symbols」(現行バージョン6.0)が配布されており、画像レンダリング機能もついているのですが、アプリの画面上のアイコンをねらって作られている機能であるため、いまひとつレンダリングサイズが小さいという不満があります。

かくして、クリップボードに入れたSF Symbolsの文字を指定色で透明画像の上にレンダリングしてクリップボードに入れるというAppleScriptは継続して使用しています。

ただ、ここに来て問題が発生しました。指定した色と、実際に画面上で表示される色が異なるという問題です。

macOS 13とmacOS 15の上で比較を行い、同一プログラムでもあきらかに処理結果が違います。

Script Debuggerを用いて、処理のステップごとに値を返すようにして(Script Debuggerだと、NSImageやらを直接画面上でブラウズ可能)確認してみたのですが、どのステップでも期待どおりの結果になっています。

結局残されたのは、Cocoaの機能を用いて記述されたペーストボード(クリップボード)にNSImageを設定する処理。ペーストボードにNSImageを設定したときに色が変わります。

そして、内容をKeynote上にペーストするとその現象の一端が見えてきます。

Keynoteの書類上にmacOS 13上で処理した画像とmacOS 15上で処理した画像を並べて、それぞれを選択してみると……画面右端の画像プレビューエリア上では色がまったく同じです。書類上では違う色に見えるのに、プレビューでは一緒。

これは、間違ったカラープロファイルが適用されてしまっているか、あるいは明示的に何かのカラープロファイルを付加したNSImageをペーストボードに設定する必要があるか、のどちらかでしょう。

–クリップボードに内容を設定する(復帰用)
on restoreClipboard:theArray
— get pasteboard
set thePasteboard to current application’s NSPasteboard’s generalPasteboard()

— clear it, then write new contents
thePasteboard’s clearContents()
thePasteboard’s writeObjects:theArray
end restoreClipboard:


▲クリップボードに設定する直前のNSImageをPNGに変換してファイルに書き出したもの。この時点でも色が変わっていないので、クリップボード設定部分が問題という見立てをした次第


▲Script実行直後の状態。Finder上でクリップボードの内容を表示させたところ。色は変わっていないようだが……

Posted in Clipboard | Tagged 15.0savvy NSPasteboard | Leave a comment

Cocoa-AppleScript AppletがRosettaオンで動いた!

Posted on 11月 29, 2024 by Takaaki Naganoya

macOS 13.6以降、スクリプトエディタに備わっているテンプレート「Cocoa-AppleScript Applet」から作成したアプレットが動作しなくなっていました。macOS 15.2Betaでもこの状況は変わりません。


▲スクリプトエディタ>ファイル>テンプレートから新規作成>Cocoa-AppleScript Applet.app を選択


▲Cocoa-AppleScript Appletのテンプレートで新規作成したところ


▲Cocoa-AppleScript Appletを作成して実行すると、このような警告ダイアログが表示される

通常のアプレットやScript Debuggerで作成したEnhanced Appletなどもあるため、致命傷ではないのですが……Scripter側でCocoaの利用経験がたまってきたために、「アプリケーション」という実行環境のさまざまなイベントを利用したいという声が出てきて、ようやくCocoa-AppleScript Appletが再評価されつつあった矢先の出来事でした。

# Cocoa-AppleScript Appletを使っているScripterなんて、edama2氏しか知りません

Appleにもバグレポートしているのですが、一向に直りません。そんな中、MacScripter.netにてred_menace氏が報告したところによると、「Rosettaをオンにして動かすと、動く」とのこと。なんの冗談だろうと疑いながら……

ためしに、Cocoa-AppleScript AppletをRosettaをオンにしてx64コードで動かすと、本当に動きました。これは驚きです。

ARM64Eバイナリが存在していないのかチェックしてみたら、

me@m1mini ~ % file /Users/me/Desktop/名称未設定Cocoa-AppleScript\ Applet.app/Contents/MacOS/CocoaApplet
/Users/me/Desktop/名称未設定Cocoa-AppleScript Applet.app/Contents/MacOS/CocoaApplet: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit executable x86_64] [arm64e:Mach-O 64-bit executable arm64e]
/Users/me/Desktop/名称未設定Cocoa-AppleScript Applet.app/Contents/MacOS/CocoaApplet (for architecture x86_64): Mach-O 64-bit executable x86_64
/Users/me/Desktop/名称未設定Cocoa-AppleScript Applet.app/Contents/MacOS/CocoaApplet (for architecture arm64e): Mach-O 64-bit executable arm64e

そういうわけではないようです。このことから、Appleの現場ではApple Siliconで動作チェックを行なっていないか、チェック自体を行なっていないか、文字が読めないようです。

Posted in Bug Cocoa-AppleScript Applet | Tagged 13.0savvy 14.0savvy 15.0savvy | Leave a comment

各Framework内のbridgesupportファイル情報の収集

Posted on 11月 29, 2024 by Takaaki Naganoya

macOS内の標準装備のFrameworkの情報を収集するAppleScriptです。AppleScriptからmacOS内のFrameworkを呼ぶには、Framework内にbridgesupportファイルが存在している必要があります。

これまで、さまざまな資料を作成するさいに、Frameworkの有無だけをまとめてきましたが……結局のところ、bridgesupportファイルの有無を調査しないと意味がないのでは? ということで書いてみたものです。

結果は、Framework名、x86版の有無、ARM64E版の有無がCSVファイルで出力されます。

AppleScript名:各Framework内のbridgesupportファイル情報の収集_v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/11/29
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use scripting additions

script spd
  property a1Res : {}
  
property a2Res : {}
  
property a3Res : {}
  
property allList : {}
  
property fNames : {}
end script

set outPath to POSIX path of (choose file name with prompt "Input file name (with \".csv\")")

–Frameworkフォルダ1から取得
set frPath to "/System/Library/Frameworks/"
set s1Text to "find " & frPath & " -name *.framework"
set (a1Res of spd) to paragraphs of (do shell script s1Text)

set osV to my numToHex((system attribute "sysv"), 4)

if osV ≥ "1200" then
  –Frameworkフォルダ2から取得
  
set frPath to "/System/DriverKit/System/Library/Frameworks"
  
set s1Text to "find " & frPath & " -name *.framework"
  
set (a2Res of spd) to paragraphs of (do shell script s1Text)
  
  
–合成
  
set (a3Res of spd) to (a1Res of spd) & (a2Res of spd)
else
  copy (a1Res of spd) to (a3Res of spd)
end if

–合成して重複を除去
set aRes to uniquify1DList((a3Res of spd)) of me

–フレームワークでループして、bridgesupportファイルをx64とApple Silicon版を検索
set (fNames of spd) to {}
repeat with i in aRes
  set t1Path to (current application’s NSString’s stringWithString:(i))
  
set t2Path to t1Path’s stringByResolvingSymlinksInPath() –リンクを解消
  
set tName to t2Path’s lastPathComponent()’s stringByDeletingPathExtension() as string
  
  
–Find x64 bridgesupport
  
set s1Text to "find " & t2Path & " -name " & tName & ".bridgesupport"
  
try
    set a1Res to do shell script s1Text
  on error
    set a1Res to ""
  end try
  
  
–Find Apple Silicon (ARM64E) bridgesupport
  
set s2Text to "find " & t2Path & " -name " & tName & ".arm64e.bridgesupport"
  
try
    set a2Res to do shell script s2Text
  on error
    set a2Res to ""
  end try
  
  
–Check result of x64 bridgesupport  
  
set ttList to {tName}
  
if a1Res is not equal to "" then
    set the end of ttList to "●"
  else
    set the end of ttList to ""
  end if
  
  
–Check result of Apple Silicon (ARM64E) bridgesupport   
  
if a2Res is not equal to "" then
    set the end of ttList to "●"
  else
    set the end of ttList to ""
  end if
  
  
–Store Results
  
if tName is not in (fNames of spd) then –重複出力を防ぐ
    set the end of (allList of spd) to ttList
    
set the end of (fNames of spd) to tName
  end if
end repeat

–結果のCSV書き出し
set sRes to saveAsCSV((allList of spd), outPath) of me

on numToHex(theNumber, stringLength)
  set hexString to {}
  
repeat with i from stringLength to 1 by -1
    set hexString to ((theNumber mod 16) as string) & hexString
    
set theNumber to theNumber div 16
  end repeat
  
return (hexString as string)
end numToHex

on getFileSizeFromPath(aPath)
  set aaPath to current application’s NSString’s stringWithString:(aPath)
  
set aaaPath to aaPath’s stringByResolvingSymlinksInPath() –リンクを解消
  
set aFM to current application’s NSFileManager’s defaultManager()
  
set anAttr to aFM’s attributesOfItemAtPath:(aaaPath) |error|:(missing value)
  
set sRes to anAttr’s fileSize()
  
return sRes as string
end getFileSizeFromPath

–文字置換
on repChar(origText as string, targChar as string, repChar as string)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

–2D List to CSV file
on saveAsCSV(aList, aPath)
  –set crlfChar to (ASCII character 13) & (ASCII character 10)
  
set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
return writeToFileAsUTF8(wholeText, bPath) of me
end saveAsCSV

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

on 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 System | Tagged 12.0savvy 13.0savvy 14.0savvy 15.0savvy | Leave a comment

書式つきテキストを組み立てて、画像を追加し、RTFDとして保存 v2

Posted on 11月 25, 2024 by Takaaki Naganoya

書式つきテキスト(NSAttributedString)にコンピュータのアイコン画像を添付し、RTFDとしてファイル保存するAppleScriptです。

RTFDはRTFに対して画像などの要素を追加したApple独自の拡張仕様です。書式つきテキストはRTFとしてファイルに書き込んだり、逆にRTFから読み込んで書式つきテキスト化することも可能ですが、画像を添付したらRTFDとして保存する必要があります。

AppleScript名:書式つきテキストを組み立てて、画像を追加し、RTFDとして保存 v2
— Created 2017-09-25 by Takaaki Naganoya
— Modified 2017-09-27 by Shane Stanley
— Modified 2024-11-25 by Takaaki Naganoya
— 2017-2024 Piyomaru Software
use AppleScript
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSFont : a reference to current application’s NSFont
property |NSURL| : a reference to current application’s |NSURL|
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSDictionary : a reference to current application’s NSDictionary
property NSTextAttachment : a reference to current application’s NSTextAttachment
property NSAttributedString : a reference to current application’s NSAttributedString
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSImageNameComputer : a reference to current application’s NSImageNameComputer
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSRTFDTextDocumentType : a reference to current application’s NSRTFDTextDocumentType
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSDocumentTypeDocumentAttribute : a reference to current application’s NSDocumentTypeDocumentAttribute
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

set aFile to POSIX path of (choose file name with prompt "保存するファイル名を入力(拡張子.rtfdつきで)")
set aURL to |NSURL|’s fileURLWithPath:aFile

–Attributed Stringを作成
set aFontSize to 48
set aString to "My Mac"
set anAssrStr to makeRTFfromParameters(aString, "HelveticaNeue-Light", aFontSize, -2, (aFontSize * 1.5)) of me

–添付画像を作成
set anAttach to NSTextAttachment’s alloc()’s init()
set anImage to NSImage’s imageNamed:(NSImageNameComputer)
set bImage to my resizeNSImage:anImage toSize:64
anAttach’s setImage:bImage

–添付画像をAttributed Stringに添付
set iconString to NSAttributedString’s attributedStringWithAttachment:anAttach
anAssrStr’s insertAttributedString:iconString atIndex:0 –冒頭に添付

–添付画像つきAttributed StringをRTFDとしてファイル保存
set aStrRange to current application’s NSMakeRange(0, anAssrStr’s |length|())
set attrDict1 to NSDictionary’s dictionaryWithObject:NSRTFDTextDocumentType forKey:NSDocumentTypeDocumentAttribute
set {aFileWrapper, anError} to anAssrStr’s fileWrapperFromRange:aStrRange documentAttributes:(attrDict1) |error|:(reference)
if anError is not equal to missing value then error

set {fRes, fError} to aFileWrapper’s writeToURL:aURL options:(current application’s NSFileWrapperWritingAtomic) originalContentsURL:(missing value) |error|:(reference)

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real)
  –Font
  
set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
–Color
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
–Kerning
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
–Underline
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
–Ligature
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
–縦書き指定–Japanese tategaki setting (Up to down, right to left direction drawing)
  
set aVal6 to false
  
set aKey6 to (current application’s NSVerticalGlyphFormAttributeName)
  
  
–Paragraph space
  
set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init()
  
aParagraphStyle’s setMinimumLineHeight:(aLineSpacing)
  
aParagraphStyle’s setMaximumLineHeight:(aLineSpacing)
  
set akey7 to (NSParagraphStyleAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3, akey4, akey5, aKey6, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aVal6, aParagraphStyle}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

on resizeNSImage:aImg toSize:aSize
  if (aImg’s isValid()) as boolean = false then error "Invalid NSImage"
  
  
set tmpView to current application’s NSImageView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aSize, aSize))
  
tmpView’s setImageScaling:(current application’s NSImageScaleProportionallyUpOrDown)
  
tmpView’s setImage:aImg
  
  
set newRect to tmpView’s frame()
  
set newRep to tmpView’s bitmapImageRepForCachingDisplayInRect:newRect
  
  
tmpView’s cacheDisplayInRect:newRect toBitmapImageRep:newRep
  
set newData to newRep’s TIFFRepresentation() –representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)
  
  
return current application’s NSImage’s alloc()’s initWithData:newData
end resizeNSImage:toSize:

★Click Here to Open This Script 

Posted in Image RTF | Tagged 13.0savvy 14.0savvy 15.0savvy NSAttributedString NSFileWrapper NSTextAttachment | Leave a comment

書式つきテキストを組み立てて、画像を追加

Posted on 11月 25, 2024 by Takaaki Naganoya

書式つきテキスト(NSAttributedString)を作成し、その先頭にコンピュータアイコン画像を追加してダイアログ表示するAppleScriptです。

–> Download Script Archive with Libraries

AppleScript名:書式つきテキストを組み立てて、画像を追加
— Created 2017-09-25 by Takaaki Naganoya
— Modified 2017-09-27 by Shane Stanley
— Modified 2024-11-25 by Takaaki Naganoya
— 2017-2024 Piyomaru Software
use AppleScript
use scripting additions
use framework "Foundation"
use framework "AppKit"
use tv : script "tvLib"
use hwName : script "hardwareNameLib"

property NSFont : a reference to current application’s NSFont
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSTextAttachment : a reference to current application’s NSTextAttachment
property NSAttributedString : a reference to current application’s NSAttributedString
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSImageNameComputer : a reference to current application’s NSImageNameComputer
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

–Attributed Stringを作成
set aFontSize to 48
set aString to getSystemProfileInAGenre("SPHardwareDataType", "machine_name") of hwName
set anAssrStr to makeRTFfromParameters(aString, "HelveticaNeue-Light", aFontSize, -2, (aFontSize * 1.5)) of me

–添付画像を作成
set anAttach to NSTextAttachment’s alloc()’s init()
set anImage to NSImage’s imageNamed:(NSImageNameComputer)
anAttach’s setImage:anImage

–添付画像をAttributed Stringに添付
set iconString to NSAttributedString’s attributedStringWithAttachment:anAttach
anAssrStr’s insertAttributedString:iconString atIndex:0 –冒頭に添付

–ライブラリを用いてダイアログ表示
dispAttrStr(aString, "Computer Icon", anAssrStr, 600, 200) of tv

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real)
  –Font
  
set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
–Color
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
–Kerning
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
–Underline
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
–Ligature
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
–縦書き指定–Japanese tategaki setting (Up to down, right to left direction drawing)
  
set aVal6 to false
  
set aKey6 to (current application’s NSVerticalGlyphFormAttributeName)
  
  
–Paragraph space
  
set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init()
  
aParagraphStyle’s setMinimumLineHeight:(aLineSpacing)
  
aParagraphStyle’s setMaximumLineHeight:(aLineSpacing)
  
set akey7 to (NSParagraphStyleAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3, akey4, akey5, aKey6, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aVal6, aParagraphStyle}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

★Click Here to Open This Script 

Posted in dialog RTF | Tagged 13.0savvy 14.0savvy 15.0savvy NSAttributedString NSTextAttachment | Leave a comment

15インチMacBook Air用チャージガイド・シール発売

Posted on 11月 24, 2024 by Takaaki Naganoya

15インチMacBook Air用の充電アダプタの位置合わせ用「チャージガイド・シール」を発売しました。

→ 販売ページ

注文が発生したらプリンターで印刷するので、在庫の山で部屋が埋もれるといったことはないはずです。

Posted in news | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

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

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (132) CotEditor (66) Finder (51) iTunes (19) Keynote (117) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

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

アーカイブ

  • 2025年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