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

カテゴリー: Object control

Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が

Posted on 7月 12, 2024 by Takaaki Naganoya

Pixelmator Proでたまに実行する「1024×1024の画像からアイコン用の各種解像度の画像を作成する」AppleScriptですが、Pixelmator Pro v3.6.4で久しぶりに動かしたら、エラーが出てうまく動かなくなっていました。

このAppleScriptは、1024×1024の画像をオープンした状態で実行するものです。

すぐに、各サイズにリサイズしつつ、ファイル名に解像度を反映させた状態で書き出しを行います。

AppleScript名:アイコン書き出しv2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/19
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set resolList to {1024, 512, 256, 128, 64, 32, 16}
set aTargFileBase to (choose file name with prompt "Select Export base name") as string

tell application "Pixelmator Pro"
  if (exists of document 1) = false then
    display dialog "There is no document" buttons {"OK"} default button 1 with icon 1
    
return
  end if
  
  
tell front document
    set aWidth to width
    
set aHeight to height
    
    
if {aWidth, aHeight} is not equal to {1024.0, 1024.0} then
      display dialog "Wrong Image Size (1024×1024 required)" buttons {"OK"} default button 1 with icon 2 with title "Size Error"
      
return
    end if
    
    
repeat with i in resolList
      resize image width i height i resolution 72 algorithm bilinear
      
export to file (aTargFileBase & "_" & (i as string) & "x" & (i as string) & ".png") as PNG
      
undo
    end repeat
  end tell
end tell

★Click Here to Open This Script 

これが、macOS 13.6.8+Pixelmator Pro v3.6.4の組み合わせで実行したらエラーが出て実行できなくなっていました。

問題点は割と明らかです。documentへのtellブロック内で、documentをパラメータとして要求するexportといったコマンドを実行したときに、tellブロックを認識せず、コマンドの直後にdocumentオブジェクトを表記しないとエラーになります。

解決策は、tellブロックでdocumentを指定するのをやめて、コマンドのパラメータとしてfront documentといったオブジェクトを表記することです。または、「属性値 of it」のようにdocumentへの参照を記述しておくことです(他の言語のユーザーが腰を抜かすので、なるべくitは使わないで記述していますが……)。

これで解決できるものの、macOS側で問題を起こしているのか、Pixelmator Pro側で問題を起こしているのかがわかりにくいところ。

おそらく、Pixelmator Pro側の問題かと思われますが、言い切ることもできないでしょう。

AppleScript名:アイコン書き出しv3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/19
–  Modified on: 2024/07/11
—
–  Copyright © 2020-2024 Piyomaru Software, All Rights Reserved
—

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

set resolList to {1024, 512, 256, 128, 64, 32, 16}
set aTargFileBase to (choose file name with prompt "Select Export base name") as string

tell application "Pixelmator Pro"
  if (exists of document 1) = false then
    display dialog "There is no document" buttons {"OK"} default button 1 with icon 1
    
return
  end if
  
  
tell the front document
    set aWidth to width
    
set aHeight to height
  end tell
  
  
if {aWidth, aHeight} is not equal to {1024.0, 1024.0} then
    display dialog "Wrong Image Size (1024×1024 required)" buttons {"OK"} default button 1 with icon 2 with title "Size Error"
    
return
  end if
  
  
repeat with i in resolList
    resize image front document width i height i resolution 72 algorithm bilinear
    
export front document to file (aTargFileBase & "_" & (i as string) & "x" & (i as string) & ".png") as PNG
    
undo
  end repeat
  
end tell

★Click Here to Open This Script 

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

Safariで「プロファイル」機能を使うとAppleScriptの処理に影響

Posted on 7月 6, 2024 by Takaaki Naganoya

Safariの最近のバージョンで導入されたものの、使わないでいた「プロファイル」機能。

Appleが提案してきた鳴り物入りの新機能のうち、ほとんどのものはその日のうちにオフにしていたり、「なかったもの」にしているものが(個人的に)多いです。最新のものでは、macOS 15.0の「ウィンドウの吸着機能」は、その日のうちにオフにしました。

「プロファイル機能」も、そんな「Appleが作った新たなゴミ機能」だと思っていたのですが、よくよく調べると、

拡張機能やクッキーなど環境情報をプロファイルごとに切り替えられるようになっています。

Safariを用いたプログラムの開発を行う必要があり、この「プロファイル」機能に注目。個人環境と開発環境を区分けできることにメリットを感じて使いはじめました。

ところが、AppleScriptでSafariのウィンドウのタイトルを取得する処理を実行すると、

AppleScript名:最前面のウィンドウのタイトルを取得する.scpt
set aTitle to getPageTitleOfFrontmostWindow()
–> "個人用 ― AppleScriptの穴 – Useful & Practical AppleScript archive. Click ’★Click Here to Open This Script’ Link to download each AppleScript"

on getPageTitleOfFrontmostWindow()
  tell application "Safari"
    if (count every window) = 0 then return false
    
tell window 1
      set aProp to properties
    end tell
    
set aDoc to document of aProp
    
set aText to name of aDoc
  end tell
  
return aText
end getPageTitleOfFrontmostWindow

★Click Here to Open This Script 

タイトルの前にプロファイル名がついてきてしまいます。これは、嬉しくない状況です。

現在のプロファイル名を取得できるとか、使用プロファイルを指定できるとかいった機能なら前向きなのですが……。

JavaScript経由でページのタイトルを取得したところ、プロファイル名はついてきませんでした。

この2つの方法を試すことで、どちらか最適な方を選ぶとか、両方を組み合わせてプロファイル名を抽出するといった処理を行うべきでしょう。

AppleScript名:最前面のウィンドウのタイトルを取得する(JS).scpt
set aTitle to getPageTitleOfFrontmostWindowByJS()
–> "AppleScriptの穴 – Useful & Practical AppleScript archive. Click ’★Click Here to Open This Script’ Link to download each AppleScript"

on getPageTitleOfFrontmostWindowByJS()
  tell application "Safari"
    if (count every window) = 0 then return false
    
set aRes to do JavaScript "document.title;" in front document
    
return aRes
  end tell
end getPageTitleOfFrontmostWindowByJS

★Click Here to Open This Script 

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

Pages本執筆中に、2つの書類モード切り替えに気がついた

Posted on 6月 18, 2024 by Takaaki Naganoya

目下、「Pages+AppleScriptで本をつくろう!」という電子書籍を執筆中です。

これまでの電子書籍作成のノウハウと、その中で必要に迫られて書いたAppleScriptのかずかずを盛り込んでいます。

AppleScriptについて詳しく説明を行わず、コンテンツの作成に比重を置いています(高機能なScriptは添付)。

そんな中、これまでに疑問に思っていたことについてPagesのヘルプでいろいろ調べてみたところ、いろいろ勘違いしていたことが分かりました。

Pagesは、ワープロ的に書類下地に本文を記入する「ワープロ的な世界観」と、ボックスを並べてテキスト流し込みを行う「DTP的な世界観」の2つの機能が混在していると思っていました。ただ、ワープロ的な世界観に無理やりにDTP的な世界観を統合したため、

・ページ単位の編集能力がない

と思っていました。しかし、これが自分の勘違いであることがわかりました。

数十ページも書き換える必要が出てきて頭を抱えているところです。

ものすごくわかりにくい場所に、モード切り替えスイッチが存在

これら2つの世界観に対して公式に名前が割り振られていることをヘルプで確認(ものすごくわかりにくい)。

ワープロ的世界観の書類のことを「文章作成書類」、DTP的な世界観の書類のことを「ページレイアウト書類」と呼んでいることを見つけました。画面上にそうした切り替え機能が(メニューなどに)、明確に用意されているものではありません。

Pagesで書類を新規作成したときに、作成されるのは「文章作成書類」(ワープロ的)です。

これまで、自分はこの「文章作成書類」の上にテキストボックスを並べて、DTPソフト的に使っていました。結果として、ページ単位の削除やならべかえが行いにくく、「ページ単位の編集ができないので、書類を小分けにして対処しよう」という作り方をしてきました。

ところが、このDTPソフト的な使い方に適した「ページレイアウト書類」モードに切り替えるスイッチが存在していたのです(こんなの気づかないぞ!)。

この、インスペクタを「書類」に設定し、「書類」タブを選択した中に存在している「書類本文」チェックボックス。デフォルトではこれが選択されています。

では、このチェックをはずすとどうなるか?

わざわざ「ページレイアウト書類に変換してもよろしいですか?」というダイアログを表示して警告します。

これが、「文章作成書類」モードと「ページレイアウト書類」モードの切り替えを行う操作です。最初から、ページレイアウト書類の「空白」テンプレートを用意しておいてほしいぐらいです(ユーザーによる追加は可能)。

Macのアプリでは「モーダルな処理をなるべく避けること」といったガイドラインが存在しているのですが、Pagesの場合はモーダルな機能を隠した結果、余計にわかりにくくなった印象です。

この2つの書類モードの切り替えは不可逆的なものではなく、随時切り替え操作が可能です。ただし、先のダイアログによる警告どおり、文章作成書類(ワープロモード)で本文テキストを入力していた場合には、それはすべて削除されます。

ページレイアウト書類に切り替えると機能も変わる

ページレイアウト書類モードに切り替えると、機能自体も変わります。

(1)ページ単位の編集が可能に

文章作成書類モードでは謎機能だった「セクション」が「ページ」と呼び替えられます。普通にページ挿入や、ページのサムネールを入れ替えるとページが入れ替えられたり、ページ単位の削除が行えます。

(2)オブジェクトの配置がなくなる

本文テキストとともにオブジェクトが移動したり、移動しなかったりという制御を行う「オブジェクトの配置」機能が、インスペクタ上から消えます。

「ページレイアウト書類」モードでは、本文というものがなくなるのに合わせて、インスペクタから消えます。

(3)ページ挿入ができるようになる

「セクションの挿入」が「ページの挿入」に切り替わります。

ページレイアウト書類モードに切り替えると、これまでPagesに感じてきた違和感がなくなります。

こんな重要な機能はもっとわかりやい場所に配置しておくべきです。

書類モードのAppleScriptからの検出

AppleScript名:書類モードの検出(文章作成書類、ページレイアウト書類).scpt
tell application "Pages"
  tell front document
    set dStat to document body
    
–> false –ページレイアウト書類
    
–> true –文章作成書類
  end tell
end tell

★Click Here to Open This Script 

AppleScriptからdocumentの属性値「document body」を取得するとtrueなら文章作成書類、falseならページレイアウト書類であることが分かります。

なお、この「document body」という属性値はr/o(Read Only)であるため、属性値の書き換えで切り替えることはできません。

Pagesの「文章作成書類」を前提とした末尾ページの削除や指定ページから末尾までの一括削除AppleScriptを作りためていましたが、これらは「ページレイアウト書類」モードでは機能しません。

ただ、ページレイアウト書類モードではページのサムネールを選択してページ削除が行えるので、これらのAppleScriptが機能しなくても問題はないでしょう。

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

Keynote上で選択中のテキストアイテムを、位置情報をもとにテキスト連結してクリップボードへ

Posted on 5月 13, 2024 by Takaaki Naganoya

Keynoteで作業がめんどくさくなったら、その場でAppleScriptを書いて使うシリーズ。Keynote v14で動かしていますが、別にバージョン依存している箇所はありません。もっと古いKeynoteでも動くと思います(KeynoteのAppleScript対応機能的には、slideのselectionができるようになったv12が実用下限だと思っています)。

Keynote書類の、章トビラに内容を個別のテキストアイテムで箇条書きしていたような場合に、

これを、全部結合して1つのテキストアイテムに入れたくなる時があります。

そこで、本ScriptのようなものをmacOS標準搭載のスクリプトメニューに入れて、

呼び出すために作ったものです。

実行すると、それぞれのテキストアイテムをY座標に着目してソートを行い、上→下の順番にならべかえて、テキストを取り出し、改行をはさみつつ連結します。

この後で、もとのテキストアイテムにこの連結したテキストを入れることになります。

一番上(positionのY座標が一番小さい)のテキストアイテムだけ残してあとは削除するわけですが、このあたりのオブジェクト操作もAppleScriptから操作してしまったほうがよさそうです。

ただし、Keynoteはテキストアイテム内の文字の上寄せ/下寄せの制御をAppleScriptからできないので(キーボードショートかメニューでも操作する?)そのあたりに「残念感」が残ってしまうかもしれません。

macOS標準搭載のスクリプトメニューに入れるAppleScriptで、絵文字を大量に入れるのは、大量のAppleScriptをメニューに入れるため文字だけだと視認性が低く、色付き文字を入れてそれぞれを識別しやすくするためです。

AppleScript名:🧭位置情報🧭をもとに🈴テキスト連結🈴して📎📎クリップボードへ📎📎.scpt
use AppleScript
use scripting additions
use framework "Foundation"

set outList to {}
set outStr to ""

tell application "Keynote"
  tell front document
    set aSel to selection
    
    
if length of aSel = 0 then
      display dialog "Keynote書類上で何も選択されていません。" with title "オブジェクト選択エラー" buttons {"OK"} default button 1 with icon 2
      
return
    else if length of aSel = 1 then
      display dialog "Keynote書類上で複数のオブジェクトが選択されていません。" with title "オブジェクト選択エラー" buttons {"OK"} default button 1 with icon 2
      
return
    else if (class of first item of aSel = slide) then
      display dialog "Keynote書類上でスライドが選択されてしまっています。" with title "オブジェクト選択エラー" buttons {"OK"} default button 1 with icon 2
      
return
    end if
    
    
repeat with i in aSel
      set j to contents of i
      
set aClass to class of j
      
if aClass = text item then
        set {aPosX, aPosY} to position of j
        
set aCon to object text of j
        
set the end of outList to {xPos:aPosX, yPos:aPosY, textCon:aCon}
      end if
    end repeat
    
  end tell
end tell

set bList to sortListAscending(outList, "yPos") of me

repeat with i in bList
  set j to contents of i
  
set aText to textCon of j
  
set outStr to outStr & aText & return
end repeat

set the clipboard to outStr
beep 1

–入れ子のリストを昇順ソート(AppleScriptObjC)
on sortListAscending(theList as list, keyLabel)
  set anArray to current application’s NSMutableArray’s arrayWithArray:(theList)
  
set theDescriptor to current application’s NSSortDescriptor’s sortDescriptorWithKey:(keyLabel) ascending:(true)
  
set sortedList to anArray’s sortedArrayUsingDescriptors:{theDescriptor}
  
return sortedList as list
end sortListAscending

★Click Here to Open This Script 

Posted in list Object control Record Sort | Tagged 12.0savvy 13.0savvy 14.0savvy Keynote | Leave a comment

Keynoteで2階層のスライドのタイトルをまとめてテキスト化

Posted on 5月 10, 2024 by Takaaki Naganoya

Keynoteでページ数の多い書類、この場合は電子書籍「Cocoa Scripting Course」の9巻「File Processing」で章ごとの目次を作ろうとしたときに、各ページのタイトルを記事のレベルを反映しつつ文字列化するのが大変なので、AppleScriptで半自動化しました。

実際には、機械的に全スライドのタイトルを取得してテキスト化するAppleScriptを作って使っていたのですが、機械的にタイトルを取り出したあとで、レベルを反映させるといった「手作業」が発生していたので、半自動処理に変更したほうがまだ作業量が少なくなるという見立てになりました。

Keynote書類をオープンして、最終階層のスライドを畳んだ状態で処理範囲(同一レベルのスライド)を選択しておいた状態で本Scriptを実行します。もともと、章トビラに掲載する内容をテキストで取り出すためのものなので、1つの章を構成する中トビラのみを選択した状態にしてから実行する必要があります。

Keynoteでは、ウィンドウ左端にナビゲータを表示させ、各スライドのレベルを変更し、アウトラインプロセッサのように下位スライドの表示を隠したり、表示させたりできます。つまり、ページ数の多いスライドの整理を行いやすくなっています。

本来、このスライドのインデントレベルを数値で取得できる必要があります。それでも、KeynoteのAppleScript用語辞書にその機能は実装されていません。ただ、ないものにないと文句を言っているだけでは前に進めません。

Keynoteのウィンドウ上で下位スライドを非表示状態にして選択すると、selection中の第1階層のスライドのみ選択された状態になるため、スライド番号を取得すると、selection中の第2階層のスライド番号が「抜けた」状態になります。この違いによってスライドの階層を識別できます。

スライド番号を取得できたselection中の第1階層のスライドと、スライド番号を取得できなかったselection中の第2階層のスライドで別々に処理(インデント文字=tab)することで、文字列で階層の違いも表現できます。

出力例:

◽️再帰処理によるファイル検索  –第1階層
  再帰によるファイルパスの取得  –第2階層
  再帰によるファイルパスの取得+拡張子による抽出  –第2階層
  ファイル名衝突回避つきリネーム  –第2階層

処理結果はクリップボードに転送されます。つまり、他のテキストエディタに内容をそのままペーストできます。

スライドのインデントレベルを取得できないことへの対処は、スライドのbase layoutにインデント情報を書いておくとか、種別で判定するやりかたもあります。出現確率をそれぞれのbase layoutについて計算し、登場頻度の低いものをより上位の章トビラとして認識するといったAppleScriptもありますが、完全自動よりも決定前にユーザーに確認を取るぐらいの作りになっているほうが実用性が高い感じです。

AppleScript名:選択中のスライドから、2段階の階層のタイトルを取得してクリップボードへ.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/05/04
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use scripting additions

property headerChar : "◽️" –1階層目のタイトルの行頭に入れる
property indentChar : tab –2階層目のタイトルの行頭に入れる

tell application "Keynote"
  tell front document
    set aSel to selection
    
set aFirst to class of first item of aSel
    
if aFirst is not equal to slide then
      display dialog "スライド単位で選択されていません(スライド内のオブジェクトが選ばれている)" buttons {"OK"} default button 1
      
return
    end if
    
    
–スライドの逆順選択が発生していた場合には、listを逆順に入れ替えて正順(開始ページ→終了ページ)に修正  
    
set fItem to slide number of first item of aSel
    
set lItem to slide number of last item of aSel
    
if fItem > lItem then set aSel to reverse of aSel
    
    
–スライド番号を選択部分から取り出す
    
set pNumList to {}
    
repeat with i in aSel
      set the end of pNumList to (slide number of i)
    end repeat
    
    
–選択中の最終スライドの次のスライドは説明部分とみなし、説明部分が続く(同じベースレイアウト)ブロックを検出
    
set totalCount to count every slide
    
set aMasterSlide to base layout of slide ((last item of pNumList) + 1)
    
set hitF to false
    
    
repeat with i from (last item of pNumList) + 2 to totalCount
      set tmpBase to base layout of slide i
      
if aMasterSlide is not equal to tmpBase then
        set hitF to true
        
exit repeat
      end if
    end repeat
    
    
if hitF = false then error "Page selection Error"
    
    
—末尾の情報を補う。そのため、本Scriptではスライド末尾までの選択が行えないが、実用上問題がないので無視している
    
copy i to lastThreadShould
    
copy pNumList to pNumList2
    
set the end of pNumList to i
    
    
    
–メインループ
    
set outList to {}
    
set aCount to 1
    
    
–1階層目のタイトル収集ループ
    
repeat with i in (pNumList2)
      
      
tell slide i
        try
          set tmpTitle1 to object text of default title item
        on error
          set tmpTitle1 to "" –タイトルが存在しないスライドなどの場合
        end try
      end tell
      
      
–オブジェクト内の強制改行文字を削除
      
set tmpTitle13 to repChar(tmpTitle1, string id 8232, "") of me
      
      
–出力用のリストに追加
      
set the end of outList to (return & headerChar & tmpTitle13)
      
      
–2階層目のタイトル収集ループ
      
repeat with ii from (i + 1) to ((item (aCount + 1) of pNumList) – 1)
        if ii ≥ (lastThreadShould) then exit repeat
        
        
tell slide ii
          try
            set tmpTitle2 to object text of default title item
          on error
            set tmpTitle2 to "" –タイトルが存在しないスライドなどの場合
          end try
        end tell
        
        
–オブジェクト内の強制改行文字を削除
        
set tmpTitle22 to repChar(tmpTitle2, string id 8232, "") of me
        
        
–出力用のリストに追加
        
set the end of outList to (indentChar & tmpTitle22)
      end repeat
      
      
set aCount to aCount + 1
      
    end repeat
    
    
–クリップボードに結果文字列を設定
    
set outStr to retListedText(outList, return) of me
    
set the clipboard to outStr
  end tell
end tell

–1D Listにデリミタ文字を入れつつテキスト化
on retListedText(aList, aSeparator)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aSeparator
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retListedText

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

★Click Here to Open This Script 

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

Keynoteでslideの逆順選択状態を解消する

Posted on 5月 9, 2024 by Takaaki Naganoya

Keynoteで日々さまざまな書類を作っており、Keynoteを使わない日はないと言って過言ではないほどです。

当然、Keynote関連の作業の効率化のためのAppleScriptを書くことが多くなります。そして、Keynote書類の連続したスライド(ページ)を選択し、それらのタイトルを加工するようなAppleScriptをよく使います。

たとえば、マル付き数字(例:①②③)の付け直し(リナンバー)AppleScriptはよく使いますが、

Keynote上で末尾ページから先頭ページに向かってページ選択できる、いわば「逆順選択状態」を画面上からの操作によって作り出せてしまうことに気づきました。

この状態でAppleScriptからselectionを取得すると、P-197、196、195、194、193、192、191と、意図しない順番でスライドオブジェクトを取得できてしまうことがわかりました。この逆順選択状態で、マル付き数字のリナンバーScriptを実行すると、末尾から番号が振られてしまいます。

この状態は、たとえば197ページを選択しておいて、SHIFTキーを押しながら、上向き矢印キーを押すことで選択範囲を拡張した場合に発生することがわかりました。この現象は、Keynote v14.0+macOS 13.6.7で発生を確認しています。

これは、バグではありません。ただ、意図しない状態を作り出せてしまうことについては、知っておく必要がある内容です。

selectionでアクセスできるSlideオブジェクトが、かならずしもページの先頭方向から順に末尾方向へと並んでいるわけではない、ということで対策が必要になりました。この手の、複数Slideを選択して実行するAppleScriptは割と多いので。

そこで、selctionから取得したSlideオブジェクトの先頭と末尾のSlide numberを取得し、先頭のSlide Numberが大きければ、selectionから取得したデータをその場で逆順に並べ替えるという対処を行いました。

AppleScript名:スライドの逆順選択状態を解消する.scpt
tell application "Keynote"
  tell front document
    set aaSel to selection
    
set fItem to class of first item of aaSel
    
if fItem is not equal to slide then
      display dialog "Slide内のオブジェクトが選択されています。Slide単位で選択してください。" buttons {"OK"} default button 1
      
return
    end if
    
    
set fItem to slide number of first item of aaSel
    
set lItem to slide number of last item of aaSel
    
    
–逆順選択が発生していた場合には、listを逆順に入れ替える
    
if fItem > lItem then
      set aaSel to reverse of aaSel
    end if
    
    
set fItem2 to slide number of first item of aaSel
    
set lItem2 to slide number of last item of aaSel
    
return {fItem2, lItem2}
  end tell
end tell

★Click Here to Open This Script 

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

Keynote/Pagesで選択中の表カラムの幅を均等割

Posted on 5月 5, 2024 by Takaaki Naganoya

Keynote/Pagesの書類上の「表」のうち、選択中のカラムについて「幅」を均等割する(等しい幅に設定する)AppleScriptです。Keynote/Pages v14.0で動作確認していますが、とくにバージョン固有の機能などに依存する部分はありません。


▲Keynote書類上の表のカラムを選択しておいてAppleScript実行


▲Keynote書類上で選択しておいた表カラムが均等幅に設定される


▲Pages書類上の表のカラムを選択しておいてAppleScript実行


▲Pages書類上で選択しておいた表カラムが均等幅に設定される

AppleScript名:選択中の表カラムの幅を均等割.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/05/05
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

tell application "Keynote"
  tell front document
    set aSel to selection
    
set fObj to class of first item of aSel
    
if fObj is not equal to table then
      display notification "tableが選択されていません"
      
return
    end if
    
    
tell current slide
      try
        set theTable to first table whose class of selection range is range
      on error
        display notification "table中のセル(カラム)が選択されていません"
        
return –何も選択されてなかった場合
      end try
      
      
tell theTable
        
        
set vList to address of column of every cell of selection range
        
set vUList to uniquify1DList(vList) of uniquifyKit of me
        
        
–均等割したカラム幅を計算
        
set totalW to 0
        
repeat with i in vUList
          tell column i
            set tmpW to width
            
set totalW to totalW + tmpW
          end tell
        end repeat
        
        
–選択カラム幅に均等割した幅を設定
        
set aColW to totalW / (length of vUList)
        
repeat with i in vUList
          tell column i
            set width to aColW
          end tell
        end repeat
        
      end tell
    end tell
    
  end tell
end tell

script uniquifyKit
  use scripting additions
  
use framework "Foundation"
  
property parent : AppleScript
  
  
on uniquify1DList(theList as list)
    set theSet to current application’s NSOrderedSet’s orderedSetWithArray:theList
    
return (theSet’s array()) as list
  end uniquify1DList
end script

★Click Here to Open This Script 

AppleScript名:選択中のカラムの幅を均等割.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/05/05
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

tell application "Pages"
  tell front document
    set aSel to selection
    
set fObj to class of first item of aSel
    
if fObj is not equal to table then
      display notification "tableが選択されていません"
      
return
    end if
    
    
try
      set theTable to first table whose class of selection range is range
    on error
      display notification "table中のセル(カラム)が選択されていません"
      
return –何も選択されてなかった場合
    end try
    
    
tell theTable
      
      
set vList to address of column of every cell of selection range
      
set vUList to uniquify1DList(vList) of uniquifyKit of me
      
      
–均等割したカラム幅を計算
      
set totalW to 0
      
repeat with i in vUList
        tell column i
          set tmpW to width
          
set totalW to totalW + tmpW
        end tell
      end repeat
      
      
–選択カラム幅に均等割した幅を設定
      
set aColW to totalW / (length of vUList)
      
repeat with i in vUList
        tell column i
          set width to aColW
        end tell
      end repeat
      
    end tell
    
  end tell
end tell

script uniquifyKit
  use scripting additions
  
use framework "Foundation"
  
property parent : AppleScript
  
  
on uniquify1DList(theList as list)
    set theSet to current application’s NSOrderedSet’s orderedSetWithArray:theList
    
return (theSet’s array()) as list
  end uniquify1DList
end script

★Click Here to Open This Script 

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

指定のWordファイルをPDFに書き出す

Posted on 5月 4, 2024 by Takaaki Naganoya

ほとんど書き捨てレベルのAppleScriptですが、Microsoft Office用のAppleScriptの動作状況(ランタイム環境を変更すると動かなくなるなど)に興味があったので、書いてみました。

初回実行時にWord書類が入っているフォルダへのアクセス許可を求めるダイアログが出ますが、2回目以降はとくに聞かれません。

また、PowerPoint用のAppleScriptで、スクリプトメニューから実行すると実行がブロックされるという「Microsoft、正気か?」という仕様になっていましたが、いまMicrosoft Word用の本AppleScriptをスクリプトメニューに入れて呼び出しても実行できることを確認しています(macOS 13.6.7+Word バージョン 16.84 (24041420))。

AppleScript名:指定のWordファイルをPDFに書き出す.scpt
set aFile to choose file
automatorRun({aFile}, missing value) of me

on automatorRun(input, parameters)
  repeat with i in input
    set ipath to i as text
    
    
tell application "System Events"
      set o to name of i
    end tell
    
    
set o to repChars(ipath, ".docx", ".pdf") of me
    
    
tell application "Microsoft Word"
      close every document without saving
      
open i
      
save as document 1 file name o file format (format PDF)
      
close every document without saving
    end tell
  end repeat
  
  
return ""
end automatorRun

on repChars(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChars

★Click Here to Open This Script 

本Scriptを書くことになったreddit上の投稿への回答となるScriptはこちら。

AppleScript名:指定のWordファイルをPDFに書き出す(For Automator Action).scpt

on run {input, parameters}
  repeat with i in input
    set ipath to i as text
    
    
tell application "System Events"
      set o to name of i
    end tell
    
    
set o to repChars(ipath, ".docx", ".pdf") of me
    
    
tell application "Microsoft Word"
      close every document without saving
      
open i
      
save as document 1 file name o file format (format PDF)
      
close every document without saving
    end tell
  end repeat
  
  
return ""
end run

on repChars(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChars

★Click Here to Open This Script 

Posted in Object control PDF | Tagged 12.0savvy 13.0savvy 14.0savvy Word | Leave a comment

Numbersで最前面の書類のすべてのシート上の表の行数を合計

Posted on 4月 5, 2024 by Takaaki Naganoya

Numbersの最前面の書類で、全シート上のすべての表の行数を合計して返すAppleScriptです。

大量のシートを持つ書類上のすべての表の行数をカウントします。それぞれの表からは、ヘッダー行の分はカウントしていません。

Numbersは、Pagesのように「表示範囲にないページ上のオブジェクトからの情報取得ができない(その割に指定ページを表示状態にするための機能もない)」といった動作はしないので、カウント対象のシートをいちいち表示状態にして切り替えるという必要はありません。

AppleScript名:全シート上のtableの行数を合計.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/04/05
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

set totalC to 0

tell application "Numbers"
  tell front document
    set nList to name of every sheet
    
repeat with i in nList
      set j to contents of i
      
      
tell sheet j
        set tCount to count every table
        
        
repeat with ii from 1 to tCount
          tell table ii
            set hCnt to header row count
            
            
set tmpCount to count every row
            
set totalC to totalC + tmpCount – hCnt
          end tell
        end repeat
      end tell
      
    end repeat
  end tell
end tell

return totalC

★Click Here to Open This Script 

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

Pagesで、現在表示中のページから離れたページのオブジェクト情報を取得できない

Posted on 3月 10, 2024 by Takaaki Naganoya

Pagesのいつかのバージョンから現在表示中のページから離れたページのオブジェクト情報取得および操作ができなくなっていました。バージョン13.xではすでにそうなっていました。12.xからそうだったかもしれません。

2024/4/3追記:Pages v14.0で確認したところ、同じ挙動でした

1〜2ページを表示中に、3〜4ページのオブジェクト情報取得および操作は行えるものの、7〜8ページ以降のオブジェクト情報は取得できないという状況です。自分が確認したのはtableオブジェクトのposition情報。

25%の縮小表示を行った場合には、

問題なく、すべてのページのtable(ツメ)のpositionを取得できますが、

拡大表示すると……

7ページ以降のtableのpositionを取得できていません。

この現象は、全ページに対してツメ(Dictionary index)を付加して統一操作を行うAppleScriptにおいて問題になっていました。実際に、ファイル名に「章番号」を書いておくと、それをピックアップして、ツメの見た目を変更するというAppleScriptを作成して運用しています。このScriptは、ツメの塗りの状態を自動検知して当該章の塗り方を自動で反映するようになっています。

このような高機能Scriptを実用化したものの、最近になっておかしな挙動が確認されていました。

・現在表示中のページのオブジェクト操作は行える
・表示中から離れたページのオブジェクト操作/情報取得が行えない

なんじゃこら????

Pages書類のツメ操作で、いろいろ問題に。

そこで、実験のために表示ページを移動しながらオブジェクト情報を取得してみたら、問題なく情報取得できました。

Pagesには表示対象ページの変更機能はないので、GUI Scriptingで「次のページ」コマンドを強引に実行。あるいは、実行前にPagesの書類表示ズーム倍率を、25%に変更しておく……というほうが「楽」かもしれません。

これをバグとして報告すべきなのか、アプリケーションの挙動として「知っておくべき情報」なのかは判断できません。処理速度向上のための「改善」の結果としてこのような状況が生まれてしまったのかもしれないためです。

ただ、特定のページを表示状態にする機能がないのに、表示範囲外(現在の見開きから+2見開きを超える範囲)のオブジェクトの情報を取得できないのは、片手落ちの状態でしょう。

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

Adobe AcrobatをAppleScriptから操作してPDF圧縮

Posted on 2月 23, 2024 by Takaaki Naganoya

Adobe Acrobatは、一応AppleScript用語辞書がついてはいるものの、ほぼ「使えないアプリ」「役に立たない用語辞書」の名をほしいままにしてきました。AppleScript界における「がっかり遺産」のような存在です。

登場以来、一番期待されるPDF本文テキスト抽出の用途にまったく役に立たない(文字化けした謎テキストを出力)うえに、TOCやBookmarkへのアクセスもさっぱりです。

Classic MacOS時代にAdobe AcrobatのAppleScript用語辞書への深い失望があって、そこからフリーの「Skim PDF Viewer」の登場とか、のちにCocoaを直接呼べるようになって、十分なPDFへのアクセスが行えるようになりました。もはや、「もっといいもの」がいろいろ存在しているため、PDFを操作したいとか情報を抽出したいという需要は別のものによって満たされている状態です。

いまや、Adobe AcrobatのAppleScript用語辞書の存在感は「歴史上、そんなものがあったと語りつがれさえもしない」という「Air」のようなレベルです。事実、それに見出せる価値は何もありません。

そうした歴史認識と前提となる話がありつつも、それでも1つだけAdobe Acrobatには価値ある機能が存在します。本当に1つだけ。

それが、PDFの圧縮機能です。

最近は、macOS上のQuartzFilterのPDF圧縮もまったく機能しておらず、逆に呼び出すとファイルサイズが大きくなるとかいう笑えない冗談みたいな状態。PDFの圧縮ソリューションについてはAdobe Acrobatないしはactobat.adobe.comのWebアプリぐらいしか、手軽に使えるものが存在していない状態です。

とはいうものの、Adobe AcrobatのPDF圧縮機能は、AppleScript用語辞書に呼び出し用のコマンド用語が用意されてはいません。強引にGUIを操作するしかないようです。

Adobe AcrobatのAppleScript用語辞書の中にも「execute」コマンドが用意されており、任意のメニュー項目を操作できるような雰囲気が漂っていますが、いくら指定しても操作できません。

というわけで、とても嫌ではあるもののGUI Scripting経由で機能にアクセス。ちなみに、こういう時のために用意しておいた「dynamicMenuClicker」ライブラリは、Adobe Acrobat向けにはうまく動作しません。アプリケーション名、プロセス名、表示プロセス名などでAdobe Acrobatは不具合を持つ「特異点」であるため、Acrobatを操作する場合にのみ別の対処ルーチンを組み込んでおく必要があることでしょう。

AppleScript名:GUI Scripting経由でオープン中のPDFのファイルサイズを縮小.scpt
tell application "Adobe Acrobat"
  tell front document
    set aCount to count every document
    
if aCount = 0 then return
  end tell
end tell

activate application "Adobe Acrobat"
tell application "System Events"
  tell process "Acrobat"
    –ファイル>その他の形式で保存>サイズが縮小されたPDF…
    
click menu item 1 of menu 1 of menu item 9 of menu 1 of menu bar item 3 of menu bar 1
    
    
delay 0.5
    
    
–ダイアログ上のボタン「OK」をクリック
    
tell window 1
      click button "OK"
    end tell
    
    
delay 0.5
    
    
–保存ダイアログ(名前を付けて保存)
    
tell window 1
      click button "保存" –Localized
      
      
delay 0.5
      
      
set sList to every sheet
      
      
if length of sList is not equal to 0 then
        tell sheet 1
          click button "置き換え" –Localized
        end tell
      end if
    end tell
    
    
  end tell
end tell

★Click Here to Open This Script 

下記Scriptは、動作しません。

AppleScript名:本来はこう書けば動くはずだったメニュー操作.scpt
use dynC : script "dynamicClicker"

set appName to "AdobeAcrobat" –Application Name
set aList to {"ファイル", "その他の形式で保存", "サイズが縮小されたPDF…"} –Localized Menu Titles

set aRes to clickSpecifiedMenuElement(appName, aList) of dynC

★Click Here to Open This Script 

Posted in Object control PDF | Tagged 13.0savvy Adobe Acrobat | Leave a comment

最前面の書類中の選択中のテキストアイテムの文字サイズを、特定サイズのみ対象にして置換 v3

Posted on 2月 18, 2024 by Takaaki Naganoya

Pages書類で選択中のtext item(Pagesでこれを識別するクラスがないのでshape)内のテキストに複数の文字サイズが存在している場合に、特定の文字サイズ部分のみ異なるものに置き換えるAppleScriptです。

–> Play demo movie

ただし、本Scriptで使用している自作のdisplay text fieldsライブラリを、本ScriptをmacOS標準搭載の「スクリプトメニュー」に入れた状態で呼び出すと、ダイアログ中への文字入力ができませんでした(macOS 13.6.5)。Pagesの書類の方に文字入力フォーカスが残ってしまっています。文字サイズをポップアップメニューからの選択方式にするなど、テキスト入力「以外」の方法に差し替えることで対処できることは判明しています。

このあたりのmacOS側の挙動に対して、「ナニコレ?」と違和感をおぼえつつも……スクリプトメニューに入れて呼び出す場合には対処するしかないのでしょう。細かい機能がAppleScriptランタイム環境ごとに「使える」「使えない」といった違いを生んでいるうえに、こうしたGUIの挙動についてもAppleScriptランタイム環境ごとに違っている点について、より細かい点をチェックする必要がありそうです(メーカー側がどんどん基礎的な部品の挙動を変更しては発表もしない状況)。


▲架空の本のPages書類のうち、処理対象のtext itemを選択状態にして実行


▲どのフォントサイズを置き換えるかをダイアログ選択。リサイズ後の数値を入力するとリサイズ。空欄のままにすると、リサイズしない

AppleScript名:最前面の書類中の選択中のテキストアイテムの文字サイズを、特定サイズのみ対象にして置換 v3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/02/16
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.7" — macOS 10.13 or later
use framework "Foundation"
use scripting additions
use tfLib : script "display text fields"

tell application "Pages"
  tell front document
    set tmpList to selection
    
    
repeat with i in tmpList
      set j to contents of i
      
set tmpC to class of j
      
      
–選択中のアイテムがshape(text itemを指定したいが、PagesではこのClassは存在しない)の場合のみ処理
      
if tmpC is equal to shape then
        –最大サイズの文字のみ抽出
        
set cRes to (size of every character of object text of j)
        
set uRes to removeDuplicates(cRes) of me
        
        
set selection to {j}
        
        
–ダイアログ表示
        
set strList to stringfyListItems(uRes) of me
        
set blankList to makeBlankListByIndicatedItem(strList, "") of me
        
        
set dRes to confirm text fields main message "テキストアイテムの文字サイズ置換" sub message "置換しない場合には空欄のまま。サイズはポイント数で指定" key list strList value list blankList
        
if dRes = false then exit repeat
        
        
–文字サイズ置換
        
repeat with ii from 1 to (length of strList)
          set targSize to (contents of item ii of strList) as real —From Size
          
set repSize to contents of item ii of dRes –To Size
          
          
if repSize is not equal to "" then
            set repSizeNum to repSize as real
            
set size of (every character of object text of j whose size is targSize) to repSizeNum
          end if
        end repeat
        
      end if
    end repeat
  end tell
end tell

–指定リストの項目数によって、空白アイテムが入ったリストを返す
on makeBlankListByIndicatedItem(aList, blankItem)
  set newList to {}
  
set aLen to length of aList
  
  
repeat aLen times
    set the end of newList to blankItem
  end repeat
  
  
return newList
end makeBlankListByIndicatedItem

–リストの全項目をテキスト化
on removeDuplicates(aList)
  set newList to {}
  
repeat with i from 1 to (length of aList)
    set anItem to item 1 of aList
    
set aList to rest of aList
    
if {anItem} is not in aList then set end of newList to anItem
  end repeat
  
return newList
end removeDuplicates

–リスト内の要素をすべてテキストに変換する
on stringfyListItems(a as list)
  set newL to {}
  
repeat with i in a
    set j to contents of i
    
set j to j as string
    
set the end of newL to j
  end repeat
  
  
return newL
end stringfyListItems

★Click Here to Open This Script 

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

PowerPoint書類の各スライドのタイトルを取得

Posted on 8月 3, 2023 by Takaaki Naganoya

PowerPoint書類(presentation)の各スライドのタイトルを取得するAppleScriptです。

正確にいえば、タイトルを取得するかもしれないAppleScriptです。本Scriptの実行時にはPowerPointで何らかのPPTX書類をオープンしていることを期待しています。

PowerPointをこづき回してみると、各スライドのタイトルを保持しているプロパティとかいったものが「ない」ことに気づきます。

ではどうやって取り出すかといえば、

(1)slideのplace holderを取得する
(2)place holder内にtext frameが存在しているかを確認
(3)text frameが存在している場合には、内部にアクセスして文字を取り出す

という手順になるようです。

ただし、place holderにアクセスする都合上、

スライドのレイアウトの種類によってはplace holderが存在していないものもあるため、place holderの存在確認から行うべきかもしれません。

また、slide内に複数のplace holderが存在する場合に、どれがtitleに該当するのかを調べる必要があるとか(座標とか、文字サイズとかを頼りに推測)、いろいろと処理が破綻しそうな「例外条件」が多数存在していそうです。

AppleScript名:各slideのタイトル文字列を取得 v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/08/03
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

set tList to getEveryPPTSlideTItles() of me
–> {"Title", "1章", "Slide1", "Slide2", "2章", "Slide3", "Slide4"}

on getEveryPPTSlideTItles()
  set tList to {}
  
  
tell application "Microsoft PowerPoint"
    tell active presentation
      set sList to every slide
      
      
repeat with i in sList
        set j to contents of i
        
        
tell j
          
          
set plaList to every place holder
          
set aPla to contents of first item of plaList
          
set hText to (has text of text frame of aPla) as boolean
          
          
if hText = true then
            set hTextR to (content of text range of text frame of aPla) as string
          else
            set hTextR to ""
          end if
          
        end tell
        
        
set the end of tList to hTextR
      end repeat
      
      
return tList
      
    end tell
  end tell
end getEveryPPTSlideTItles

★Click Here to Open This Script 

Posted in Object control | Tagged 13.0savvy PowerPoint | Leave a comment

PowerPointが扱うファイルパス形式が支離滅裂な件

Posted on 8月 2, 2023 by Takaaki Naganoya

いろいろ調べてみたら、PowerPointが扱うファイルパス形式に整合性がまったくないことがわかりました。なんなんでしょう、これは。

ファイルのオープン時:alias(HFS path)

これは、とくに問題はありません。最低限のラインはクリアしているといってよいでしょう。

PDF書き出し時:HFS pathのテキスト

fileオブジェクトではなくHFS pathの文字列です。ここでかなり「おかしなプログラムだな」という感想を抱きます。こんなおかしなデータを要求するのはPowerPointぐらいだと思いますよ?

PPTX書類の新規保存時:HFS pathのテキスト

PDF書き出しもPPTX書類の保存も、同じく「save」コマンドで行うので、仕様が同じなのも納得ですが、通常書類のsaveにこれでは相当変わった仕様にしか見えません。

書類のフルパス情報:POSIX path

これは、致命的におかしな挙動であり、呆れるほどおかしな仕様です。担当者が正気なのか疑わしいレベルです。Office 2011のPowerPointでpresentation(書類)のfull name(フルパス情報)を取得してみたところ、HFS path文字列が返ってきたという調査結果が残っていました。

いま、バージョン16.75のPowerPointのpresentation(書類)のfull name(フルパス情報)を取得すると、POSIX pathが返ってきます。


▲Office 2011のPowerPointのパス情報の記述


▲バージョン16.75のPowerPointのパス情報の記述

AppleScript用語辞書上の記載内容にはたいして変化はないのですが、こんな頭のおかしな状態になっているとは思いませんでした。正直、PowerPointで何かまとまった処理を行おうとは思ったことが(それほど)なかったのですが、Keynoteで山のようにいろいろ強烈なScriptを書いているので、PowerPointでもいろいろできるのでは? と、冗談半分で試してこの通りです。

まさか、ExcelとWordもこの調子なのでは?(^ー^;

AppleScript名:オープン中の最前面のPowerPoint書類のフルパスの文字列を取得.scpt
set a to getPPTpath() of me
–> "Cherry:Users:me:Documents:2013-MacUDingCFUD.ppt"–Office 2011
–> "/Users/me/Documents/AppleScript 13/PowerPoint/TESTプレゼンテーション1 .pptx"–Office 2019

–オープン中の最前面のPowerPoint書類のフルパスの文字列を取得
on getPPTpath()
  tell application "Microsoft PowerPoint"
    set pCount to count every presentation
    
if pCount = 0 then return false
    
tell active presentation
      –Documentのフルパスを取得する
      
set aPath to full name
      
return aPath
    end tell
  end tell
end getPPTpath

★Click Here to Open This Script 

PowerPointの書類からTOCつきのPDFを書き出すAppleScriptを書いた際には、頭のおかしなPowerPoint 16.75が返してくるパス形式をサブルーチン側で吸収して処理するようにしました。ただ、将来的にこの頭のおかしな形式からまともな形式に戻してきたときに問題が発生するので、再変更に備えてもう少し準備しておいたほうがよいのかもしれません。

このPowerPointの担当者は、頭がおかしいです。

AppleScript名:オープン中のPowerPoint書類のパスをalias形式で取得.scpt
set pptPath to getPPTpath() of me
–> alias "Macintosh HD:Users:me:Documents:AppleScript 13:PowerPoint:TESTプレゼンテーション1 (Sectionなし).pptx"

–オープン中の最前面のPowerPoint書類のフルパスの文字列を取得
on getPPTpath()
  tell application "Microsoft PowerPoint"
    set pCount to count every presentation
    
if pCount = 0 then return false
    
    
tell active presentation
      –Documentのフルパスを取得する
      
set aPath to full name
    end tell
  end tell
  
  
set aFile to POSIX file aPath
  
set anAlias to aFile as alias
  
return anAlias
end getPPTpath

★Click Here to Open This Script 

Posted in File path Object control | Tagged 13.0savvy PowerPoint | Leave a comment

PowerPointのスライドから各種情報を取得

Posted on 8月 2, 2023 by Takaaki Naganoya

KeynoteからPDF書き出しを行う際に、デフォルトの機能ではTOCも何もついていないのですが、AppleScriptからあらゆる手段を講じてTOCつきで書き出せるようにしています(新刊「Keynote Scripting Book with AppleScript」に掲載)。

一方、PowerPointではどうかといえば、sectionを作成し章構成を分けて、スライドを章ごとに折りたためるようになっています。PDF書き出し時にこのsectionが反映されるということはまったくなく、sectionを追加しようが書き出されたPDFはそのままです。

このsection内のインデント情報が取得できれば、それを元にTOCを作ってもよいのですが、残念ながらインデント情報は取り出せないようです。

ただ、処理に必要な最低限の情報が取れるので、Keynoteと同レベルのTOCつきPDFをAppleScriptで合成することは可能と思われます。

AppleScript名:各スライドから情報を取得.scpt
tell application "Microsoft PowerPoint"
  tell active presentation
    set sList to every slide
    
    
repeat with i in sList
      set j to contents of i
      
tell j
        set sInd to section index
        
set sNum to section number
        
set myLayout to layout as string
        
log {sInd, sNum, myLayout}
      end tell
    end repeat
  end tell
end tell

★Click Here to Open This Script 

各スライドのタイトルを取得しようとしたら、素直に取得できず……かといって取れなさそうでもないので、いろいろ調べてみたら、どうやら取得できたようです。

AppleScript名:各slideのタイトル文字列を取得.scpt
tell application "Microsoft PowerPoint"
  tell active presentation
    set sList to every slide
    
    
repeat with i in sList
      set j to contents of i
      
tell j
        set sInd to section index
        
set sNum to section number
        
set myLayout to layout as string
        
log {sInd, sNum, myLayout}
        
        
set plaList to every place holder
        
set aPla to contents of first item of plaList
        
set hText to (has text of text frame of aPla) as boolean
        
log hText
        
        
if hText = true then
          set hTextR to (content of text range of text frame of aPla) as string
          
log hTextR
        end if
      end tell
    end repeat
  end tell
end tell

★Click Here to Open This Script 

Posted in Object control | Tagged 13.0savvy PowerPoint | Leave a comment

Keynote上でテキストアイテムとn重のシェープの重なりを検出 v2

Posted on 6月 25, 2022 by Takaaki Naganoya

Keynoteでオープン中の最前面の書類の現在のスライド(ページ)の上で3重のshapeオブジェクトを下に敷いているテキストアイテムを検出し、文字色を変更するAppleScriptです。

macOS 12.5beta+Keynote v12.1の組み合わせで作成・チェックしてみましたが、Keynote v12.xの固有の機能などは使っていないので、もっと古い環境でも動くはずです。

–> Watch Demo Movie


▲処理前


▲処理後 右側のテキストの色まで変わってしまっているのは意図しなかった処理(わかってたけど)

Keynote書類上でshapeオブジェクトを重ねて何かを表現することはよくありますが、重ねた場所の上に置いてある文字色だけ変更したい場合が往々にしてあります。

さっさと動かすことだけ考えて、ありものの「オブジェクトの重ね合わせ検出」Scriptを使い回しました。そのため、本当に入れ子状態の3つのオブジェクトを検出しているわけではなく、重ね合わせが3回発生しているテキストアイテムを検出しています。

もうちょっと凝った処理を行えば、本当に3階層の入れ子状態のshapeを検出できそうな気はしますが、さすがに使い捨てレベルのScriptにそんなに手間暇をかけるわけにもいかないので、現状ではこんなものでしょう。

Keynoteのselectionがまともに動くようになったので、いろいろ実践的なレベルのScriptを書けるようになりましたが、オブジェクトの重ね合わせ順なども取れたりすると、もっといろいろ書けそうです。

オブジェクトのposition、width、heightを取得する処理は、もうちょっと高速に実行できるように書けそうです(まだまだ、安全第一の処理内容)。

あとは、imageオブジェクトのpathとかイメージデータそのものを取得して、各種画像フィルタをかけてKeynote書類に書き戻せるとよさそうな気がします。

AppleScript名:テキストアイテムと1重のシェープの重なり検出 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/06/25
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

set collisonNum to 1
set targPointSize to 32.0
set targColList to {0, 0, 0} –Black

set tList to {} –text items
set trList to {}

set sList to {} –shapes
set srList to {}
–set bgColList to {} –background color

set colList to choose color

tell application "Keynote"
  tell front document
    tell current slide
      
      
–text itemの情報抽出ループ
      
set allTList to every text item
      
repeat with i in allTList
        set j to contents of i
        
        
tell j
          set {xPos, yPos} to position
          
set aWidth to width
          
set aHeight to height
          
set aRect to makeRect(xPos, yPos, aWidth, aHeight) of me
        end tell
        
        
set the end of tList to j
        
set the end of trList to aRect
      end repeat
      
      
      
–shapeの情報抽出ループ
      
set allSList to every shape
      
repeat with i in allSList
        set j to contents of i
        
tell j
          set {xPos, yPos} to position
          
set aWidth to width
          
set aHeight to height
          
–set aBGCol to background color
          
set aRect to makeRect(xPos, yPos, aWidth, aHeight) of me
        end tell
        
        
set the end of sList to j
        
set the end of srList to aRect
        
set the end of bgColList to aBGCol
        
      end repeat
      
      
set atLen to length of trList
      
set arLen to length of srList
      
      
set outTlist to {}
      
      
      
–shapeと重ね合わせが発生しているtext itemの検出ループ
      
repeat with i from 1 to atLen
        set atRec to contents of item i of trList
        
set atObj to contents of item i of tList
        
set collisionC to 0
        
        
set tmpCSize to point of first character of object text of atObj
        
        
–当該text itemに対して、shapeオブジェクトとのNSRectの重ね合わせが指定数発生しているかをチェック
        
repeat with ii from 1 to arLen
          set tmpRect to contents of item ii of srList
          
set aF to detectRectanglesCollision(atRec, tmpRect) of me
          
          
–背景色(background color)のリストを確認
          
set aBG to contents of item ii of bgColList
          
          
–if {aF, aBG, tmpCSize} = {true, targColList, targPointSize} then set collisionC to collisionC + 1
          
if {aF, tmpCSize} = {true, targPointSize} then set collisionC to collisionC + 1
        end repeat
        
        
–オブジェクトのRectangleが重なり合っている「回数」で判定
        
if collisionC = collisonNum then
          set the end of outTlist to atObj
        end if
      end repeat
    end tell
  end tell
end tell

–文字色を塗り替えるループ
tell application "Keynote"
  tell front document
    tell current slide
      repeat with i in outTlist
        set j to contents of i
        
ignoring application responses
          set color of object text of j to colList
        end ignoring
      end repeat
    end tell
  end tell
end tell

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

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

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

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

★Click Here to Open This Script 

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

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

Posted on 6月 5, 2022 by Takaaki Naganoya

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

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

トビラのページとは、

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

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

Posted on 5月 27, 2022 by Takaaki Naganoya

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

–> Watch Demo Movie

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

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

Posted on 5月 3, 2022 by Takaaki Naganoya

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

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

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

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

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

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

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

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

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

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

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

return aList

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

CotEditor v4.1.2でAppleScript系の機能を追加

Posted on 2月 22, 2022 by Takaaki Naganoya

オープンソース開発されているフリーのテキストエディタ「CotEditor」v4.1.2において、AppleScript系の機能が追加されています。

・DocumentオブジェクトのhasBOM属性

has BOM (boolean, r/o) : Is the file encoding of the document has BOM (byte order mark)?

・convertコマンドのBOMオプション

convert v : Convert the document text to new encoding.
convert document : The document to convert encoding.
[lossy boolean] : Allows lossy conversion?
[BOM boolean] : Has the new encoding a BOM (byte order mark)?
to text : The new encoding, either in localized encoding name or an IANA charset name.
→ boolean : Did the convertion succeed?

・新設のjumpコマンド

jump v : Move the caret to the specified location. At least, either one of a parameter is required.
jump document : The document to move.
to line integer : The number of the line to go. If a negative value is provided, the line is counted from the end of the document.
[column integer] : The location in the line to jump. If a negative value is provided, the column is counted from the end of the line.

こんなサンプル書類があったとして、

AppleScriptのdocumentオブジェクトの文字データを取得してダンプしてみても、

--No BOM
{"E3", "81", "B4", "E3", "82", "88", "E3", "81", "BE", "E3", "82", "8B", "E3", "82", "BD", "E3", "83", "95", "E3", "83", "88", "E3", "82", "A6", "E3", "82", "A7", "E3", "82", "A2", "0A", "61", "62", "63", "64", "E9", "AB", "98", "E5", "B3", "B6", "E5", "B1", "8B", "65", "66", "67", "68", "69", "0A", "0A"}

--with BOM
{"E3", "81", "B4", "E3", "82", "88", "E3", "81", "BE", "E3", "82", "8B", "E3", "82", "BD", "E3", "83", "95", "E3", "83", "88", "E3", "82", "A6", "E3", "82", "A7", "E3", "82", "A2", "0A", "61", "62", "63", "64", "E9", "AB", "98", "E5", "B3", "B6", "E5", "B1", "8B", "65", "66", "67", "68", "69", "0A", "0A"}

この状態ではhasBOM属性値で差があっても、内部データでは差が出ません。これをファイルに書き込んで、ファイル内容についてチェックを行うと、

--No BOM
0000000 81e3 e3b4 8882 81e3 e3be 8b82 82e3 e3bd
0000010 9583 83e3 e388 a682 82e3 e3a7 a282 610a
0000020 6362 e964 98ab b3e5 e5b6 8bb1 6665 6867
0000030 0a69 000a                              
0000033

--With BOM
0000000 bbef e3bf b481 82e3 e388 be81 82e3 e38b
0000010 bd82 83e3 e395 8883 82e3 e3a6 a782 82e3
0000020 0aa2 6261 6463 abe9 e598 b6b3 b1e5 658b
0000030 6766 6968 0a0a                         
0000036

のように、差を検出できます。

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

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • 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を使った「自動化」とは?
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • Keynote、Pages、Numbers Ver.14.0が登場
  • macOS 15 リモートApple Eventsにバグ?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • AppleScript入門① AppleScriptってなんだろう?

Tags

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

カテゴリー

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

アーカイブ

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