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

タグ: 10.13savvy

Uni Detector v1.2.1がMac App StoreのUtility部門で28位

Posted on 11月 28, 2020 by Takaaki Naganoya

Uni Detector v1.2.1がMac App StoreのUtility部門で28位(瞬間最大風速)になりました。トータルでは、163位です。

# ニホン(Japanese Version)のMac App Storeだけでしょうか?

Mac App Storeのランキングはひんぱんに再計算されるため、見ている間に順位が37位になりました。儚い。

ランキングの上の方を見ると、Brotherさん(企業)のスキャンユーティリティが2位にいます。無料ソフトなのに、けっこういろいろ言われていてドキドキします。有償にしてもよさそうな雰囲気ではあるのですが、そのあたりの動向は見ものです。

macOS 10.15内蔵のZipライブラリがこれまでと異なり7-zip(分割アーカイブ対応)を使ったことでおかしな挙動を示すようになり、アーカイバに対しての需要が強いことを感じさせます。

あとは、ランキング上位でも「なにこれ?」というものもあったりで、(子供の作ったような電卓アプリには驚きました)なかなか驚かされます。

Posted in PRODUCTS | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Uni Detector | 2 Comments

Uni Detector v1.2.1をリリース

Posted on 11月 27, 2020 by Takaaki Naganoya

ケアレスミスで、「Scroll BarをWindowの枠外に配置してしまった」Uni Detector v1.2のリテイク版、v1.2.1をリリースしました。


▲MacBook Air 11インチを基準に、このマシンで最低限の操作が行えることを想定したUser Interface

バージョン1.2以降のUni DetectorのAppleScript用語辞書には、「check arch」のコマンドしか用意していませんが、Sandboxのセキュリティを乗り越えつつ必要な機能(ユーザーによる任意の指定フォルダ以下のアプリケーションのチェック)を実現することが目的です。

本来のScriptableなアプリケーションの意義を考えると、アプリケーションのチェック結果をリストで取得するべきですが、さすがに無償配布アプリケーションでそれはやりすぎなので、実装を控えています。

AppleScript名:アプリケーションのプロパティを取得.scpt
tell application "Uni Detector"
  properties
end tell
–> {frontmost:false, class:application, name:"Uni Detector", version:"1.2.1"}

★Click Here to Open This Script 

AppleScript名:指定アプリケーションをUni Detectorでチェック.scpt
use AppleScript version "2.7" –macOS 10.13 or later
use scripting additions
use framework "Foundation"

set anApp to choose file of type {"com.apple.application-bundle"} with prompt "Select target one App"

with timeout of 3600 seconds
  tell application "Uni Detector"
    set aRes to check arch anApp
  end tell
end timeout

★Click Here to Open This Script 

AppleScript名:指定フォルダ以下にあるアプリケーションすべてをUni Detectorでチェック.scpt
use AppleScript version "2.7" –macOS 10.13 or later
use scripting additions
use framework "Foundation"

set anApp to choose folder with prompt "Select target Folder"
set appList to getFileListWithSpotLight("kMDItemContentTypeTree", "*com.apple.application*", anApp) of me

with timeout of 3600 seconds
  tell application "Uni Detector"
    set aRes to check arch appList
  end tell
end timeout

on getFileListWithSpotLight(aMetaDataItem, aParam, startDir)
  
  
set sDirText to quoted form of POSIX path of startDir
  
set shellText to "mdfind ’" & aMetaDataItem & " == " & aParam & "’ -onlyin " & sDirText
  
try
    set aRes to do shell script shellText
  on error
    return {}
  end try
  
set pList to paragraphs of aRes
  
set aList to {}
  
repeat with i in pList
    set aPath to POSIX file i
    
set aPath to aPath as alias
    
set the end of aList to aPath
  end repeat
  
return aList
end getFileListWithSpotLight

★Click Here to Open This Script 

Posted in Bug PRODUCTS | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Uni Detector | Leave a comment

Uni Detector v1.2をMac App Storeに提出

Posted on 11月 26, 2020 by Takaaki Naganoya

Universal Binary Checker「Uni Detector」のバージョン1.2をMac App Storeの審査に提出しました。

目下、Universal Binary対応アプリの提出騒乱状態なので、審査側がパンクしないようにイージーモードの審査が続いており、平時では通らないようなバグがそのまま残っていたv1.1.1でした(これは自分のせいです)。

Uni Detector v1.2はまだUniversal Binaryではありません。1つには、macOS 11.0上でUniversal Binary化できることは確認ずみで、いつでも対応可能であること。その割に、ビルド環境をmacOS 10.14.6から移行するのには(Mac App Store向けビルド環境の移行)手間がかかること。あと、どうせAppleScriptで書いたアプリケーションなので、Universal Binary化してもスピードアップの恩恵が限定的である(ことが予想される)ためです。

Uni Detector v1.2はScriptableになりました。外部からAppleScriptでコントロール可能です。AppleScript用語辞書には、本Blog同様ワンクリックですぐに利用可能なScriptサンプルを掲載しています。

ただし、実装した「check arch」コマンドはユーザーのホームディレクトリ以下に置いたアプリケーションやネットワークサーバー上のアプリケーションなどをチェックしたいという需要に応えるための必要最低限のものであり、チェックした結果のデータをlistやrecordで返すものではありません。

さすがに、他のソリューションに組み込んだり連携可能なデータを返す機能については、発展機能を持つ有償版で対処したいところです。フリー版の機能はこの程度にしておきたいところ。

AppleScriptで作ったGUIアプリケーションにAppleScript用語辞書をつけて外部のAppleScriptから呼び出すというのは、ひどく本末転倒といいますか、豆から作った豆腐を崩してふたたび固めて作る日本料理の「ひろうす」のような感じといいますか、妙な感じがします(普通にGUIつけないでフル機能をAppleScriptだけで書けるのに、変に遠回りなやりかたです)。

あとは、小さい画面の環境でも「Mac CPU Architecture Trend」の図が見えるように、ポップアップで別途表示できるようにしました。

この表示を行うために、既存のViewの内容をPDFとして取得してPDFViewで表示しています。

些細なスペルミスを修正したり、Fileメニュー以下のコマンドが一切動作していないというバグを修正したり、CM表示機能を強化したりと細かい点の修正を行っています。

Mac App Storeに提出したアプリケーションをAppleScript対応にしたのは今回が初めてです。Store未提出のアプリケーションではScriptableにしたことはありますし、AppleScript LibrariesにAppleScript用語辞書をつけて配布したことはありますが、GUIアプリにAppleScript用語辞書をつけて配布したのははじめてのことです。

次は、本アプリケーションをUniversal Binary化するぐらいでしょうか。それで、ひとまず「しなくてはならないこと」は一段落だと思います。一部のマシンでSpotlight DBが壊れたままで運用しているものがあるらしく、それを強制的にプログラムから再生成する機能でも呼び出せたほうがよいかと思っていますが、はたして、、、、

Posted in PRODUCTS | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Uni Detector | Leave a comment

Uni Detectorのアイコンを変更!

Posted on 11月 16, 2020 by Takaaki Naganoya

Uni Detectorのアイコンを変更します。ウニ(Sea Urchin)のアイコンには個人的に思い入れも深く、この現行のアイコンも随分前に奥方様と一緒に行った寿司屋でデジカメで撮影したものです(8年ぐらい昔?)。

つまり、「どうせPowerPCからIntelに移行したんだし、10年ぐらいたったら再びCPUの移行はあるだろう」と読んで、ものすごく時間をかけてアイコン候補の写真を撮影するような、凝ったことをしていたわけです。

ただ、いろいろダウンロード状況を分析するに、U.S.のユーザーが全然食いつかない(大統領選が終わっても変化なし)。不思議なぐらい食いつかない。無料のアプリケーションという「撒き餌」にまったく食いつかない。食い気が感じられない。

なぜだろう? と、首をひねっていたのですが、われわれには美味しい食材にしか見えない海鮮丼の写真が、海外のユーザーにはグロい写真で嫌がらせをしているようにしか見えないのでは? という仮説に至りました。

その仮説をもとにSNS上で意見を募ってみたところ、

  「Dock上に置きたくないデザイン」
  「ハイコンテクストすぎてApp Store向けアプリには不向き」
  「そういうのは趣味でやれ」

という散々な結果に。

タイミングをねらって、必要な道具をピンポイントでリリース。ユーザーへの知名度の向上と、各種ソフトウェアの宣伝を意図した戦略的なソフトウェアが、アイコンというきわめて重要度の低い構成要素のために本来の役割を果たしていないものと判断。ここに、苦渋の決断をもってアイコンを無難なものに変更することといたしました。


▲新旧アイコン。右側が新しいアイコン(Appleにリジェクトされなければ)

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

Uni Detector v1.1をMac App Storeで配布開始

Posted on 11月 14, 2020 by Takaaki Naganoya

Universal Binary判定ツール「Uni Detector」のv1.1をMac App Storeで配布開始しました。対象OSは、macOS 10.13以降です。ただし、macOS 10.13だと(ツールバーボタンのクリックからは)グラフ表示が行えない(メニューからはできる)ので、10.14と言いたいところです。


▲初代「うにばーさる」。久しぶりに引っ張り出してきたら動作して驚き。そして、Finder経由でファイル情報を取得しているので現行環境だと目が回るほど遅い(64bit化されたCocoa Finderでファイル処理を行うと劇遅)

v1.1では、主にmacOS 11.0, Big SurおよびApple Siliconへの言及を追加しました。

新規追加機能は、

・アプリケーションのフィルタリング機能:書類形式(ファイル拡張子)、カスタムURLプロトコルでフィルタ表示できます。HEIFをサポートしているアプリケーションの一覧を表示する、という絞り込み(フィルタ)表示や、URLプロトコル「http://」をサポートしているアプリケーションの一覧を表示することが可能です。

・選択中のアプリケーション情報表示機能:書類タイプ、ローカライズ言語一覧、サポートURLスキーム一覧表示

・各アプリケーションの情報表示機能:ターゲットプラットフォーム名表示(Apple Silicon Mac上にiOSアプリケーションをインストールした場合の識別用に)

・Scriptableなアプリケーション判定機能を強化:「えせScriptable」なアプリケーションの一覧データを保持し、AppleのiBooks Authorなどの「えせScriptable」なアプリケーションをAppleScript対応アプリケーションから除外する機能です。データリストを固定で保持して、「えせScriptable」なアプリケーションの除外を行っています

Posted in PRODUCTS | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

えせScriptable App

Posted on 11月 6, 2020 by Takaaki Naganoya

Macのアプリケーションの中には、Info.plistに「NSAppleScriptEnabled = true」の表記があっても、実際にsdefファイルが入っていなかったり、sdefが入っていても、まったくアプリケーションの機能と関係ないダミー辞書が入っているものがたまにあります。

これを、個人的に「えせScriptable」と呼んでいます。英語に翻訳しづらいですが、Fake Scriptable AppとかDummy Scriptable Appなどと呼ぶところでしょうか。

最悪の「えせScriptable」なアプリケーションはAppleのiBooks Authorでしょうか。電子書籍市場を立ち上げるためには、既存のInDesignなどの他のアプリケーションのデータをiBooks形式にScriptで変換できる必要があると思っていたところに「カス」なAppleScript用語辞書しか入っておらず、「プログラムで変換できないのかー」という落胆をもたらしました。

辞書内容がアプリケーションの機能とぜんぜん合っていない「えせScritable」。実際に、これらの用語を使っても、起動や終了ぐらいはできるものの、アプリケーション本来の機能は1つも呼び出せません。

GUI Scripting経由で無理やりメニュー操作やボタンのクリックは行えますが、これをもって「AppleScriptに対応している」とは言ってはいけないレベルです。

Chipmunk Basicの現行バージョンがScriptableで、本来はAppleScript用語辞書がバンドル中に入っているはずなのですが、確認してみたら入っていないことに気づきました。早速、作者のRon Nicholsonにレポート。さて、どうなりますやら。

現行のUni Detectorでは、これらの「えせScriptable」なアプリケーションも一律「Scriptable」として表示してしまうため、これらをScriptableではないものとして表示を抑止するために専用のデータをバンドル内に格納してチェックするかというところでしょうか。

Microsoft officeの補助アプリケーション類がScriptableな表示になっていますが、単独で起動ができないためにScriptableなアプリケーションの範疇に入れてはいけないところでしょう。ちょっと古めのアプリケーションで、AppleScript Studioで作られているものが存在しており、AppleScript用語辞書が入っているものも見られます。これも、外部からコントロールするための辞書ではないので、正確な意味では「Scriptable」ではありませんが、意外と多いのと古いものが中心なので放置しておいています。

com.nicholson.chipmunkbasic3co		1.368.21
com.kapeli.dashdoc	4.6.7
com.apple.Maps	*
com.apple.iBooksAuthor	*
com.peterborgapapps.Lingon3	*
com.peterborgapapps.LingonX7	*
com.adobe.devicecentral.application	*
com.readpixel.wakeonlan	*
com.bombich.ccc	*
com.microsoft.OrgChart	*
com.microsoft.myday	*
com.microsoft.office_pg	*
com.microsoft.Graph	*
com.microsoft.entourage.database_utility	*
com.microsoft.entourage.database_daemon	*
com.microsoft.outlook.databaseutility	*
com.microsoft.entourage.databasedaemon	*
com.microsoft.entourage.ClipGallery	*
com.microsoft.openxml.chart.app	*
com.microsoft.openxml.excel.app	*
com.microsoft.office.uploadcenter	*
com.microsoft.office.uploadcenter	*
com.tinyspeck.slackmacgap	*
org.mozilla.firefox	*
com.twitter.teitter-mac	*
com.nchsoftware.wavepod	*
com.nchsoftware.expressjp	*
com.digitalspokes.AppKiDo	*
com.parallels.mobile	*
com.epson.East-Photo-Scan	*
Posted in Bug sdef | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

ステータスバーアイテムの点滅

Posted on 11月 4, 2020 by Takaaki Naganoya

自分で作成したNSStatusItemを点滅させるAppleScriptです。

ステータスバーアイテムを動的に作成して、メニューを表示して簡易メニュー的なユーザーインタフェースをAppleScriptで作成することは、割とあります。

Xcode上で作成したCocoa AppleScriptアプリケーションでも、プログラムでステータスアイテムを作成することはあります。

とくに、Window表示とステータスバーのメニュー表示を切り替えた場合など、ステータスバーアイテムを点滅させて「表示を切り替えた」ことを表現したいケースがあります。

本件は、例によって前例が見つからず、自前でいろいろ調べていたのですが、わかってしまえば簡単でした。AppleScriptで前例が見つからないのは別にそんなもんですが、Objective-Cでも見つからないのはどうかと思います。

NSStatusItemからbuttonを取得でき、これにsetWantsLayer:trueを実行すると普通にCoreAnimationでアニメーション表示させることができました。

本Scriptはスクリプトエディタ、Script Debuggerなど動作環境をとくに選ぶことなく動作します。たぶん、Switch Controlから呼び出したAppleScriptでも動作するはずです。

自分は点滅させるぐらいで満足していますが、その他のアニメーションエフェクトもいろいろ試してみました。みましたが……メニューバーという狭い領域に表示する関係上、「表示させても目立たないアニメーション」(拡大縮小など)や、「そもそも指定してもアニメーションしないアニメーション」なども見られます。

本サンプルは絵文字を表示していますが、これはあくまで「タイトル」を点滅させているものです。別途、ステータスバーアイテムに「アイコン」を指定している場合でも問題なく点滅アニメーションの表示を行えています。

AppleScript名:ステータスバーアイテムの点滅.scptd
— Created 2017-03-03 by Takaaki Naganoya
— Modified 2018-02-15 by Shane Stanley–Thanks!!
— Modified 2018-02-15 by Takaaki Naganoya
— Modified 2020-11-04 by Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property aStatusItem : missing value

on run
  my performSelectorOnMainThread:"init:" withObject:(missing value) waitUntilDone:true
end run

on init:aSender
  set aList to {"Piyomaru", "Software", "", "Takaaki", {"Yes", "No"}, "", "Machine", {"MacBook Pro", "MacBook Air", "Mac mini"}, "", "Quit"}
  
  
set aStatusItem to current application’s NSStatusBar’s systemStatusBar()’s statusItemWithLength:(current application’s NSVariableStatusItemLength)
  
  
aStatusItem’s setTitle:"🍎"
  
aStatusItem’s setHighlightMode:true
  
aStatusItem’s setMenu:(createMenu(aList) of me)
  
  
–Blink Status Bar Item
  
set aButton to aStatusItem’s button()
  
aButton’s setWantsLayer:true
  
my blinkObject:aButton withRepeat:10 withDuration:1.0 –OK
  
–my scaleObject:aButton withRepeat:10 withDuration:0.5 –OK
  
–my rotateObject:aButton forAxis:90 withRepeat:10 withDuration:0.5 –NG
  
–my moveObject:aButton withRepeat:10 withDuration:0.5–NG
end init:

on createMenu(aList)
  set aMenu to current application’s NSMenu’s alloc()’s init()
  
set aCount to 10
  
  
set prevMenuItem to ""
  
  
repeat with i in aList
    set j to contents of i
    
set aClass to (class of j) as string
    
    
if j is equal to "" then
      set aMenuItem to (current application’s NSMenuItem’s separatorItem())
      (
aMenu’s addItem:aMenuItem)
    else
      if (aClass = "text") or (aClass = "string") then
        
        
if j = "Quit" then
          set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:j action:"actionHandler:" keyEquivalent:"")
        else
          set aMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:j action:"actionHandler:" keyEquivalent:"")
        end if
        
        (
aMenuItem’s setTag:aCount)
        (
aMenuItem’s setTarget:me)
        (
aMenu’s addItem:aMenuItem)
        
        
set aCount to aCount + 10
        
copy aMenuItem to prevMenuItem
        
        
      else if aClass = "list" then
        –Generate Submenu
        
set subMenu to current application’s NSMenu’s new()
        (
aMenuItem’s setSubmenu:subMenu)
        
        
set subCounter to 1
        
        
repeat with ii in j
          set jj to contents of ii
          
          
set subMenuItem1 to (current application’s NSMenuItem’s alloc()’s initWithTitle:jj action:"actionHandler:" keyEquivalent:"")
          (
subMenuItem1’s setTarget:me)
          (
subMenuItem1’s setTag:(aCount + subCounter))
          (
subMenu’s addItem:subMenuItem1)
          
          
set subCounter to subCounter + 1
        end repeat
        
      end if
      
    end if
    
  end repeat
  
  
return aMenu
end createMenu

on actionHandler:sender
  set aTag to tag of sender as string
  
set aTitle to title of sender as string
  
  
if aTitle is equal to "Quit" then
    current application’s NSStatusBar’s systemStatusBar()’s removeStatusItem:aStatusItem
  else
    display notification (aTag as string)
  end if
end actionHandler:

on blinkObject:aObject withRepeat:aTimes withDuration:durationSec
  set animation to current application’s CABasicAnimation’s animationWithKeyPath:"opacity"
  
animation’s setDuration:durationSec –0.1
  
animation’s setAutoreverses:true
  
animation’s setRepeatCount:aTimes
  
animation’s setFromValue:(current application’s NSNumber’s numberWithFloat:1.0)
  
animation’s setToValue:(current application’s NSNumber’s numberWithFloat:0.0)
  
aObject’s layer()’s addAnimation:animation forKey:"blink"
end blinkObject:withRepeat:withDuration:

on scaleObject:aObject withRepeat:aTimes withDuration:durationSec
  set animation to current application’s CABasicAnimation’s animationWithKeyPath:"transform.scale"
  
animation’s setDuration:durationSec
  
animation’s setAutoreverses:true
  
animation’s setRepeatCount:aTimes
  
animation’s setFromValue:(current application’s NSNumber’s numberWithFloat:1.0)
  
animation’s setToValue:(current application’s NSNumber’s numberWithFloat:2.0)
  
aObject’s layer()’s addAnimation:animation forKey:"scale-layer"
end scaleObject:withRepeat:withDuration:

on rotateObject:aObject forAxis:anAxis withRepeat:aTimes withDuration:durationSec
  set animation to current application’s CABasicAnimation’s animationWithKeyPath:("transform.rotation." & anAxis)
  
animation’s setDuration:durationSec
  
animation’s setAutoreverses:true
  
animation’s setRepeatCount:aTimes
  
animation’s setFromValue:(current application’s NSNumber’s numberWithFloat:0.0)
  
animation’s setToValue:(current application’s NSNumber’s numberWithFloat:4.0 * 3.1415926)
  
aObject’s layer()’s addAnimation:animation forKey:"rotate-layer"
end rotateObject:forAxis:withRepeat:withDuration:

on moveObject:aObject withRepeat:aTimes withDuration:durationSec
  set animation to current application’s CABasicAnimation’s animationWithKeyPath:"position"
  
animation’s setDuration:durationSec
  
animation’s setAutoreverses:false
  
animation’s setRepeatCount:aTimes
  
animation’s setFromValue:(current application’s NSValue’s valueWithCGPoint:(aObject’s layer()’s position()))
  
animation’s setToValue:(current application’s NSValue’s valueWithCGPoint:(current application’s CGPointMake(320, 480)))
  
aObject’s layer()’s addAnimation:animation forKey:"move-layer"
end moveObject:withRepeat:withDuration:

★Click Here to Open This Script 

Posted in Animation GUI | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy CABasicAnimation NSMenu NSMenuItem NSNumber NSStatusBar NSValue | Leave a comment

アプリケーションが扱えるデータ拡張子を取得

Posted on 10月 28, 2020 by Takaaki Naganoya

指定のアプリケーションが扱えるデータ拡張子を取得するAppleScriptです。

アプリケーションバンドル内のInfo.plistの、CFBundleDocumentTypesエントリの中のCFBundleTypeExtensionsを拾ってリストで返します。用途は、このアプリケーションに表示させるためのものです。

ただ、この標準的といいますか一般的な処理でこのデータを拾ってこれないアプリケーション(凝った処理をしているもよう)がかなりの数存在し、それらについては個別に対応処理を書かないとダメっぽいです。

だいたい、AppleのiWork Appsが全滅。BBEditも独自の記述をしているらしく、Pixelmator Proも少し凝った書き方をしているもよう(Pixelmator Proが「凝っていない」部分なんてないみたいですが)。個別にInfo.plistからエントリをたどって拡張子リストを作るしかなさそうです。

OS内、具体的に言えばNSApplicationとかNSBundleにそういうInfo.plistをあさってこなくても対応ドキュメントデータ型を渡してくれるようなサービスがありそうな気がとてもするのですが、なかなか見つかりそうにありません。

あまりに対応が大変だった場合には、機能を盛り込むことを断念するかもしれません。メタデータから拾ってこれたりすると楽でよいのですが……。


▲結局、できた模様

AppleScript名:アプリケーションが扱えるデータ拡張子を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/28
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set aPath to POSIX path of (choose file of type {"com.apple.application-bundle"})
set aURL to (current application’s |NSURL|’s fileURLWithPath:aPath)
set exResList to getDocumentTypesExtensionsFromPath(aURL) of me

return exResList
–> {".INDD", ".INX", ".IDMS", ".INCD", ".INCX", ".ICML", ".INCA", ".ICMA", ".P65", ".T65", ".PMD", ".PMT", ".QXD", ".QXT", ".INDT", ".INDB", ".INDL", ".INLX", ".FLST", ".PRST", ".PDFS", ".joboptions", ".DCST", ".LNST", ".UDC", ".InDesignPlugin", ".PSET", ".SMRD", ".SMWT", ".IDML", ".IDPP", ".INDK", ".INLK", ".CSF", ".ASE", ".ACB", ".ACBL", ".IDPK", ".INJB", ".INRS", ".INCP", ".INDP", ".ICAP", ".IDAP", ".INMS", ".epub"}

on getDocumentTypesExtensionsFromPath(aURL)
  set aRes to getDocumentTypesFromAppURL(aURL) of me
  
  
set exRes to {}
  
repeat with i in (aRes as list)
    set j to (current application’s NSDictionary’s dictionaryWithDictionary:(contents of i))
    
set tmpExt to (j’s valueForKey:"CFBundleTypeExtensions")
    
    
if tmpExt is not equal to missing value then
      set tmpExt to tmpExt as list
      
repeat with ii in tmpExt
        set jj to "." & (contents of ii)
        
if (jj is not in exRes) and (jj is not equal to ".*") and (jj is not equal to ".???") then
          set the end of exRes to jj
        end if
      end repeat
    end if
  end repeat
  
  
return exRes
end getDocumentTypesExtensionsFromPath

on getDocumentTypesFromAppURL(aURL)
  set aBundle to current application’s NSBundle’s bundleWithURL:aURL
  
if aBundle = missing value then return {}
  
set aInfo to aBundle’s infoDictionary()
  
if aInfo = missing value then return {}
  
set aRes to aInfo’s objectForKey:"CFBundleDocumentTypes" –Document Types
  
if aRes = missing value then return {}
  
return aRes
end getDocumentTypesFromAppURL

★Click Here to Open This Script 

Posted in file File path | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy NSBundle NSDictionary NSURL | Leave a comment

Window表示とMenu表示を切り替える

Posted on 10月 26, 2020 by Takaaki Naganoya

Xcode上で記述するCocoa AppleScriptアプリケーションで、通常のWindow表示とステータスバーから呼び出すメニュー内に表示するスタイルの切り替えテストプログラムです。

macOS 10.14.6上でXcode 11.3.1を動かして確認しています。

–> Download toggleWindow.zip (Xcode Project Archive)

この機能は実際に使いたいと思っていたものの、なかなかうまく実装できていませんでした。

個人的に、GUIベースのアプリケーションを作っていると、環境設定まわりの機能を実際に組む段階でやたらと時間がかかって大変でした。

アプリケーションのメインウィンドウ上に表示している部品を環境設定ウィンドウにも同様に出す必要が出てくるわけで、その場合同じものを2度作ることは避けたいところです。通常表示している部品と、環境設定ウィンドウで表示する部品は同じものを使いまわしたいところです。

それをどのように共通化してGUI部品のかたまりを「使い回す」かについては、頭の痛い問題でした。なかなか過去形で表現するのがはばかられる状況ですが(未解決)、ここをクリアしないことには話になりません。

本テストプログラムでは、Window上に表示するビュー(NSView)とメニュー内に表示するビューに同じものを指定しています。これで、複数の場所に同じビューを使いまわしやすくなるだろうか、というところです。

NeXTstepにティアオフ・メニューという、メニューをドラッグ&ドロップするとメニューから切り離してフローティングパレットのように運用できる機能がありました。Macのアプリケーションでもこれを実装したものを見たことはありますが、使い勝手がいいかと言われると「それほどでも」といった印象でした

途中、NSMenuを閉じる処理で行き詰まっていたところ、Twitter上で@masakihoriさんに解決策を教えていただきました(aMenu’s cancelTracking())。ありがとうございます。

実際に、Window表示されているViewをメニューに入れてみたところ、いろいろ挙動が変わってくることを確認できました。ポップアップメニューについては操作できず、NSTabViewを配置して切り替えてみても、切り替えたことが内部のビューに通知されない様子。メニューに入れて使うべきではないと思われました。

テキストビューも、一応入力はできるもののコピー&ペーストなどの操作は行えません。もともと、メニューにテキストビューが入っていると違和感がすごいので、するべきではないでしょう。

セグメントビューについてはまともに使えますし、スライダーもまともに動作します。試してはいませんが、Date Picker(カレンダー表示)あたりが限界ではないでしょうか。WebViewもメニューに入れられると思いますが、どの程度インタラクティブに操作できるかについては未確認です。

本サンプルについて、当初はステータスバー上のステータスアイテムからPopoverを表示させようかと考えたのですが、menu bar extra(ステータスアイテム)からPopoverは表示できないんですね(Uni Detectorのときに実験してうまく行かず、github上で公開している人のコードも眺めてみましたが……上から下まで全部自前で作っているようでした)。

そのうえ、Appleからも「menu bar extra(ステータスアイテム)からPopoverを表示するんじゃねえ」と釘を刺されているとのことで、ステータスアイテムからメニューを表示、その中にカスタムビューを入れてみた次第です。

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— Toggle Window test
—
— Created by Takaaki Naganoya on 2020/10/26.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property theView : missing value
  
property aButton : missing value
  
  
property aFlag : true
  
property aStatusItem : missing value
  
  
property aMenu : missing value
  
property bMenuItem : missing value
  
  
on applicationWillFinishLaunching:aNotification
    aButton’s setTitle:"–> Status Menu"
    
set aFlag to true
    
theWindow’s setContentView:theView
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    — Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
  
on clicked:aSender
    set aTag to (tag of aSender) as integer
    
    
if aTag = 100 then
      if aFlag = true then
        –通常Window表示→Menu表示
        
my makeStatusItem()
        
theWindow’s performClose:aSender
        
aButton’s setTitle:"–> Window"
      else
        –Popup表示→通常Window表示
        
        
bMenuItem’s setHidden:true
        
theView’s setHidden:true
        
aMenu’s cancelTracking()
        
        
theWindow’s setContentView:theView
        
theView’s setHidden:false
        
theWindow’s makeKeyAndOrderFront:aSender
        
        
current application’s NSStatusBar’s systemStatusBar()’s removeStatusItem:aStatusItem
        
        
aButton’s setTitle:"–> Status Menu"
        
        
–自分を最前面に
        
current application’s NSApp’s activateIgnoringOtherApps:true
      end if
      
      
set aFlag to not aFlag –Flip Flap
      
    else if aTag = 110 then
      display notification "Clicked 1"
      
    else if aTag = 120 then
      display notification "Clicked 2"
      
    else if aTag = 130 then
      display notification "Clicked 3"
      
    end if
    
    
  end clicked:
  
  
on actionHandler:aSender
    –Do nothing
  end actionHandler:
  
  
  
on makeStatusItem()
    –if aStatusItem = missing value then return
    
    
set aStatusItem to current application’s NSStatusBar’s systemStatusBar()’s statusItemWithLength:(current application’s NSVariableStatusItemLength)
    
    
aStatusItem’s setTitle:"🍎"
    
aStatusItem’s setHighlightMode:true
    
aStatusItem’s setDelegate:me
    
aStatusItem’s setAction:"statusclicked:"
    
    
set aMenu to current application’s NSMenu’s alloc()’s init()
    
    
set bMenuItem to (current application’s NSMenuItem’s alloc()’s initWithTitle:"" action:"actionHandler:" keyEquivalent:"")
    
bMenuItem’s setView:theView
    (
bMenuItem’s setTarget:me)
    (
aMenu’s addItem:bMenuItem)
    
    
aStatusItem’s setMenu:aMenu
  end makeStatusItem
  
  
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | 2 Comments

Finderファイルタグの設定、取得、クリア

Posted on 10月 23, 2020 by Takaaki Naganoya

Finderタグの削除(クリア)を行うAppleScriptです。

AppleScript名:Finderファイルタグの設定、取得、クリア
–Created By Shane Stanley
–Modified By Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSOrderedSet : a reference to current application’s NSOrderedSet
property NSURLTagNamesKey : a reference to current application’s NSURLTagNamesKey

set anAlias to (choose file)
clearTagsForPath(anAlias) of me –delete tags
set aRes to getTagsForPath(anAlias) of me –check

— clear all tags
on clearTagsForPath(anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
aURL’s setResourceValue:{} forKey:(NSURLTagNamesKey) |error|:(missing value)
end clearTagsForPath

— get the tags
on getTagsForPath(anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set {theResult, theTags} to aURL’s getResourceValue:(reference) forKey:(NSURLTagNamesKey) |error|:(missing value)
  
if theTags = missing value then return {} — because when there are none, it returns missing value
  
return theTags as list
end getTagsForPath

— set the tags, replacing any existing
on setTagsForPath(tagList, anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
aURL’s setResourceValue:tagList forKey:(NSURLTagNamesKey) |error|:(missing value)
end setTagsForPath

— add to existing tags
on addTagsForPath(tagList, anAlias)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
— get existing tags
  
set {theResult, theTags} to aURL’s getResourceValue:(reference) forKey:(NSURLTagNamesKey) |error|:(missing value)
  
if theTags ≠ missing value then — add new tags
    set tagList to (theTags as list) & tagList
    
set tagList to (NSOrderedSet’s orderedSetWithArray:tagList)’s allObjects() — delete any duplicates
  end if
  
aURL’s setResourceValue:tagList forKey:(NSURLTagNamesKey) |error|:(missing value)
end addTagsForPath

★Click Here to Open This Script 

Posted in file Tag | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

Universal Binaryチェックツール「Uni Detector」をMac App Storeでリリース

Posted on 10月 21, 2020 by Takaaki Naganoya

Universal Binaryチェックツール「Uni Detector」をMac App Storeで無料リリースしました。macOS 10.13以降用です。私の作るものなので、すべてAppleScriptで記述してあります。

前作「うにばーさる」はPowerPCからIntelへの切り替え時に、AppleScript Studioで作りました。

「Uni Detector」はAppleScriptObjCで作成。いろいろこなれてきているのですが、商品にはなりそうにもなかったので(そんなにひんぱんにバイナリアーキテクチャを調べたい人はいない)宣伝用にフリー配布です。

# Macの販売店の店頭でデモするのには向いているかも?

バイナリ対応度を調べるだけのソフトウェアでは、一度試したらおしまいです。日常的にこのソフトウェアを使うと便利なよう、自分で使い込んでさまざまな機能を実装しました。アプリケーションのメタデータを読み込んで、しぼり込み検索してカテゴリごとのバイナリアーキテクチャ分布を調べられるようにしました。

また、Universalバイナリ対応のほかに「AppleScript対応度」の調査もこのアプリケーションの1つの大きなテーマにすえました。AppleScript対応度もカテゴリごとに調査できます。「Microsoft」や「Adobe」をキーワードに絞り込んで、アーキテクチャやAppleScript対応度を調査することも可能です。

Scriptableなアプリケーションの一覧を表示したり、選択中のアプリケーションのAppleScript用語辞書を表示させたり、とくに本Blog上のサンプルScriptを表示させる機能がよそには真似できないところでしょう。

一覧で選択したアプリケーション名をキーとして本Blogの記事を検索・表示させる「サンプルScript表示機能」。これだけのためにポップアップするミニWebブラウザを実装しています。

「Universal Binary」は、NeXT時代のMAB(Multi Architecture Binary)、FATバイナリを引き継いだもので、NEXTSTEP(正確には後継のOPENSTEP)時代にはx86(Intel)、68K(NeXT)、SPARC(Sun)、PA-RISC(HP)などの複数アーキテクチャ向けバイナリをまとめてパッケージ内に格納できていました。

当時は複数アーキテクチャ、複数環境をサポートするための技術と受け取っていましたが、Mac OS X上での使われ方は自社プラットフォームのCPU切り替えを円滑に行うためのもので……MAB/FATバイナリとはモノが同じでありながら運用の仕方が全然違いますね。

技術的には、ツールバー上のSegmented Controlで作ったボタンがmacOS 11.0上でどう見えるか、きちんと見えるのか、Betaのたびにコロコロ見え方が変わるので、そのあたりを回避したらどうなるのかとか、そういう実証試験を行なっています。

また、macOS 10.15以降でアプリケーションフォルダ(/Applications)の内容が、/Applicationsと/System/Applications/に分かれ、フォルダの内容をScriptから取得できないあたりで悩まされました。アプリケーションのアイコンをInfo.plist経由で取得できないケースも見られ(とくに、Apple純正アプリケーション)、そのあたりの対処も悩まされたところです(フリー配布なのに手間がかかりまくっていて大変です)。

Terminal.appのコントロールを行なったら一発リジェクトでしたが、スクリプトエディタのコントロールはいいんだ、へーという発見はありました(macOS 10.14で「execute」コマンドが削除されたので無害?)。アプリケーションのAppleScript用語辞書を表示させているだけなので、コントロールというレベルではありませんけれども。

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

LAN上の別のMacでYouTubeムービー再生をハンズオーバー v2

Posted on 10月 8, 2020 by Takaaki Naganoya

Safariの最前面のウィンドウで再生中のYouTubeムービーの情報を取得し、LAN上の別のMacで再生を引き継ぐ(ハンズオーバーする)AppleScriptです。

macOS 10.13以降、リモートAppleEvents経由でGUIアプリケーションを直接操作する機能が復活しました(Mac OS X 10.7〜10.12ぐらいまでAppleScriptアプレット間のみリモート通信が許可されていた状態)。

メインマシンで再生中のYouTubeムービーを、LAN上の他のマシンに引き継がせてみました。再生を引き継がれる方のマシンでは、システム環境設定の「共有」で「リモートApple Events」の項目をオンにしています(自分のマシンではすべてこの項目をオンにしています)。

(1)リモートマシン上のユーザーのパスワード

AppleScript書類のコメント(Finderコメント)にパスワードを書いておくと、それを読み取って使用するようにしてみました。

(2)リモートマシン上のSafariの起動

リモートマシン上のアプリケーションの操作は、ただリモートマシン上のアプリケーションを指定すればOKなのですが、操作対象のアプリケーションが起動していない場合にはエラーになります。これは、とても困る仕様です。

そこで、リモートマシンのFinder経由でアプリケーションファイルをオープンすることで、リモートマシン上でSafariを起動します。オープン対象をapplication file “Safari”と指定するとエラーになりますが、application file id “com.apple.Safari”と指定するとエラーになりません。

(3)YouTubeで再生中の情報取得

以前調査しておいた内容をそのまま使っています。再生中ならPauseし、再生中の位置(時間)情報を取得し、文字列で指定するために加工してYouTubeのURLに追加しています。URLの加工部分は少々手抜きをしています。

とくに問題なく、メインマシンから他のマシン(macOS 10.15.7/macOS 11.0beta9)にLAN経由で再生をハンズオーバーできました。

実際に、コントロール先のマシン名(Bonjour名)をremoteMachineNameに、ユーザー名をremoteUserNameに、パスワードを実行するAppleScript書類のFinderコメントに書き込んで実行してください。スクリプトエディタ上でもスクリプトメニューからでも問題なく実行できています。

あとは、Safari上のYouTube再生をフルスクリーンで行えるとよいのですが、少し試した範囲ではできなかったので、また地道に調べておく感じでしょうか。

AppleScript名:LAN上の別のMacでYouTubeムービー再生をハンズオーバー v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/08
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

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

set remoteMachineName to "MacMini2014.local"
set remoteUserName to "maro"

–ScriptのCommentに書いておいたパスワードを拾って使う
set mePath to (path to me)

–FinderからCommentは拾えるが、メタデータ経由で取得する処理も試してみた
set remoteUserPass to getFinderComment(POSIX path of mePath) of me

tell application "Safari"
  if running then
    tell front document
      set aURL to URL
      
–最前面のウィンドウがYouTubeの場合のみ処理
      
if aURL does not start with "https://www.youtube.com/" then
        display notification "エラー: YouTubeを再生していないため、ハンズオーバーしませんでした"
        
return
      end if
      
      
–再生中のポジションを取得
      
set tRes to (do JavaScript "document.querySelector(’#movie_player video’).currentTime;")
      
      
–再生状況を取得
      
set pRes to (do JavaScript "document.querySelector(’#movie_player video’).paused;")
      
      
if pRes = false then
        –再生中であればPauseする
        
set aRes to (do JavaScript "document.querySelector(’#movie_player .ytp-play-button’).click();")
      end if
      
      
openYouTubeOnRemoteMachine(remoteUserName, remoteUserPass, remoteMachineName, tRes, aURL) of me
    end tell
  end if
end tell

–指定のリモートマシン上のSafariでYouTubeの指定ムービーの指定箇所からの再生を行う
on openYouTubeOnRemoteMachine(remoteUser, remotePass, remoteMachineLocal, newDuration, newURL)
  set remoteMachineName to "eppc://" & remoteUser & ":" & remotePass & "@" & remoteMachineLocal
  
  
–URLの加工。ちょっと手抜きをした
  
if newDuration is not 0 then
    set tText to retTimeText(newDuration) of me
    
if newURL contains "&" then
      set sepChar to "?"
    else
      set sepChar to "&"
    end if
    
    
set newURL to newURL & sepChar & "t=" & tText
  end if
  
  
using terms from application "Safari"
    tell application "Safari" of machine remoteMachineName
      if not running then
        –起動していなかったらあらためてSafariを起動
        
launchRemoteSafari(remoteMachineName) of me
      end if
      
      
try
        close every document
      end try
      
      
set aWin to make new document
      
      
tell aWin
        set URL to newURL
        
–フルスクリーン再生をためしてみたが、こういう書き方ではなかった模様(URLオープンを待つ必要もある)
        
–set aRes to (do JavaScript "document.querySelector(’#movie_player playFullscreen’).click();")
      end tell
      
    end tell
  end using terms from
end openYouTubeOnRemoteMachine

–リモートマシン上でSafariを起動する
on launchRemoteSafari(aMachine)
  using terms from application "Finder"
    tell application "Finder" of machine aMachine
      open application file id "com.apple.Safari"
    end tell
  end using terms from
end launchRemoteSafari

–数値を「h」「m」「s」でフォーマットして返す
on retTimeText(aTime)
  set aHour to aTime div 3600
  
set aMinute to (aTime – (aHour * 3600)) div 60
  
set aSeconds to (aTime mod 60)
  
  
set aString to ""
  
  
if aHour > 0 then
    set aString to aHour & "h"
  end if
  
  
if aMinute > 0 then
    set aString to aString & (aMinute as integer) & "m"
  end if
  
  
if aSeconds > 0 then
    set aString to aString & (aSeconds as integer as string) & "s"
  end if
  
  
return (aString as string)
end retTimeText

–Finderコメントをメタデータ経由で取得
on getFinderComment(aPOSIX)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIX
  
set aMetaInfo to NSMetadataItem’s alloc()’s initWithURL:aURL
  
set metaDict to (aMetaInfo’s valuesForAttributes:{"kMDItemFinderComment"}) as record
  
if metaDict = {} then return ""
  
set aComment to kMDItemFinderComment of (metaDict)
  
return aComment
end getFinderComment

★Click Here to Open This Script 

Posted in Internet JavaScript Remote Control | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Finder NSMetadataItem NSURL Safari | 14 Comments

AppleScriptによるクリップボード処理

Posted on 10月 6, 2020 by Takaaki Naganoya

Classic Mac OSの頃は「しかたなく」クリップボードを使って行う処理がありましたが、最近(Mac OS X移行後)では極力使わないようにしています。文字コード変換、スタイル付きテキストのプレーンテキスト化などクリップボードを経由しないとできない処理がたくさんありました。画像の形式変換ですらクリップボードを経由して処理していた記憶があります。

仕方なく使っていましたが、「なんでこれしきの処理でクリップボードを経由しないといけない?」と不満だらけでした。クリップボードを経由する処理があるということは、人間がGUI経由で作業をしている裏で動かすScriptを作りにくくなるということです。クリップボード処理を多用していた頃のAppleScriptのプログラムは、絶対に人がマシンに手を触れないようにして動かす必要がありました(最前面のアプリケーションを変更してしまうと処理が破綻するなど)。

クリップボード経由の処理は確実さという意味で100%といえませんし、挙動が非同期っぽくて、値が反映されるまでに時間差があるため、クリップボードの内容変更をAppleScript側から監視して反映されるまでループで待つなどのケアが必要になります。

また、クリップボードを利用する方法によって100倍以上も差が出ます。遅い方法を選択すると、遅いばかりではなく信頼性もいまひとつです。

(1)Cocoa Scripting

Cocoaの機能を呼び出して、クリップボード(ペーストボード)の操作を行います。多彩な機能を呼び出すことができ、スピードも最速です。ただし、初回実行時のみ遅くなる傾向があるのと、HDD搭載機では極端に遅くなる場合がある(SSD必須)ので注意が必要です。

(2)AppleScript内蔵標準コマンドを利用

クリップボードにデータを入れる「set the clipboad」、クリップボードからデータを取り出す「the clipboard」、クリップボードの情報を取得する「clioboard info」などがあります。スピードも遅くないのですが、本コマンドでクリップボード内容を捕捉できるまでに(クリップボードの内容が反映されるまでに)若干時間がかかります。

(3)do shell scriptコマンド経由でpbcopyコマンドを実行

shell commandの「pbcopy」「pbpaste」を呼び出して実行します。可もなく不可もなく。スピードは(1)(2)にくらべると10倍以上遅いですが、問題にはなりにくいでしょう。ただ、これをあえて使う状況が考えられません。

(4)GUI Scripting経由でメニュー操作してコピー/ペースト

もっとも遅くて信頼性のない方法です。最速の①や②にくらべると、100倍以上も遅くなります。信頼性もなく、あまり多用できないため、本当に最後の最後に部分的に使うぐらいです。AppleScriptからは生成できないオブジェクトをアプリケーションの書類上で移動させる場合などに、仕方なくGUIを操作してコピー&目的の場所(別のページなど)でペーストを行うような感じでしょうか。それでも、各オブジェクトを逐一コピー&ペーストするのではなく、まとめてコピー&まとめてペーストすべきでしょう。コピー&ペーストの回数を減らすことが安全動作につながります。

その他、クリップボードを用いた処理を行う場合には、処理の最初にクリップボード内容を退避しておき、処理後に退避内容を戻すなどのケアも必要になります。


▲(c)秋本治、集英社

注:AppleScriptの書類形式が通常形式かバンドル書類形式かで実行速度に差が出ることはありません。ただし、アプリケーション内部のメニューやフォルダアクション、SwitchControlなどの各実行環境において「通常形式のみ。バンドル形式は受け付けない」といった制約が生じることはあります。実行速度については、Automatorやショートカット上のAppleScript実行アクションで動かすと、とりわけ遅くなります

AppleScript名:①ASOCでクリップボード操作.scpt
–Created 2015-08-03 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit" — for NSPasteboard

my restoreClipboard:{"ABC"}

–クリップボードに内容を設定する
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:

★Click Here to Open This Script 

AppleScript名:②set the clipboardコマンド.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/06
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set the clipboard to "ABC"

★Click Here to Open This Script 

AppleScript名:③do shell script経由でpbcopy.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/06
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

do shell script "echo ’ABC’ | pbcopy"

★Click Here to Open This Script 

AppleScript名:④GUI Scripting経由でメニュー操作.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/06
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

activate application "Safari"
tell application "System Events"
  tell process "Safari"
    click menu item "コピー" of menu 1 of menu bar item "編集" of menu bar 1
  end tell
end tell

★Click Here to Open This Script 

Posted in Clipboard | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

AppleScriptでリアルタイムキースキャンを行いCotEditor書類上にカーソル描画

Posted on 10月 4, 2020 by Takaaki Naganoya

Modifier Keyのリアルタイムキースキャンを行なって、CotEditor書類上に文字でカーソル描画するAppleScriptです。30 x 30 の文字数のテキストを作成し、CotEditor書類に随時転送することで書き換えています。

AppleScriptでキースキャンといえば、Script/Applet起動時にoptionやcontrolなどのmodifier keys(装飾キー)が押されているかどうかを確認して、動作内容を変更するような用途でした。AppleScriptでGUIを作るのが大変だとか、AppleScriptで気軽にGUIを呼び出せない時代には、割と使われてきた手段です。

そんな中、macOS 10.10以降でCocoaの機能が気軽に利用できるようになってきたことで、Cocoaのキースキャン機能が利用できるようになりました。前述のModifier KeysのスキャンはmacOS側のセキュリティ機構でも問題視していないようで、気軽に使えそうです。ちなみに、SHIFTキーの左右は区別できません。

先日Pixelmator Proで「もぐら叩きゲーム」を作った際にも、このModifier Keysのスキャンは利用しましたが、実際にどの程度使い物になるのか確認しておきたいと考え、AppleScriptからの操作が高速なアプリケーションで試してみることにしてみました。

CotEditorにテキストで描画した画面を転送し、毎回テキスト内容をすべて書き換えることで本格的なゲームの用途に使えるのではないかと考えました。自分ではほとんどゲームを作ったこともないので、別にゲームを量産するつもりはありませんが……。テトリスぐらいならCotEditorのメニューから呼び出すAppleScript内で実行できそうな感じがします。

→ 冗談半分でAppleScriptで作られたTetrisを探してみたら、見つかりました

CotEditorでなくても、他のエディタでも同様の操作はできると思います。

AppleScript名:KeyScan TEST v3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/03
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit" — for NSEvent
use scripting additions

–Initialize
set curPosX to 1
set curPosY to 1
set curMax to 30

set rText to ""
repeat curMax times
  set rText to rText & "🛑"
end repeat

tell application "CotEditor"
  write to console "Real-time Keyscan test with Modifier Keys
  [ Control ]    : Move Left
  [ Shift ]    : Move Right
  [ Option ]    : Move Up
  [ Command ]  : Move Down

  [ Caps Lock ]  : Quit this script"
  
  
make new document
  
activate
end tell

–Main Loop
repeat
  set leftF to my checkModifier:"control"
  
set rightF to my checkModifier:"shift"
  
set upF to my checkModifier:"option"
  
set downF to my checkModifier:"command"
  
  
set quitF to my checkModifier:"caps"
  
  
if quitF = true then return
  
  
if leftF = true then
    if curPosX > 1 then
      set curPosX to curPosX – 1
    end if
  else if rightF = true then
    if curPosX ≤ curMax then
      set curPosX to curPosX + 1
    end if
  end if
  
  
if upF = true then
    if curPosY > 1 then
      set curPosY to curPosY – 1
    end if
  else if downF = true then
    if curPosY < curMax then
      set curPosY to curPosY + 1
    end if
  end if
  
  
  
–make display text
  
set aText to ""
  
repeat with i from 1 to curMax + 1
    if i = curPosX then
      set aText to aText & "🛑"
    else
      set aText to aText & "㍳"
    end if
  end repeat
  
  
  
set bText to ""
  
repeat with y from 1 to curMax
    if y = curPosY then
      set bText to bText & rText & return
    else
      set bText to bText & aText & return
    end if
  end repeat
  
  
my displayText(bText)
  
end repeat

–テキスト画面描画
on displayText(aText)
  tell application "CotEditor"
    tell front document
      set contents to aText
    end tell
  end tell
end displayText

–複数同時検出に対応
on checkModifier:keyName
  if keyName = "option" then
    set theMask to current application’s NSAlternateKeyMask as integer
  else if keyName = "control" then
    set theMask to current application’s NSControlKeyMask as integer
  else if keyName = "command" then
    set theMask to current application’s NSCommandKeyMask as integer
  else if keyName = "shift" then
    set theMask to current application’s NSShiftKeyMask as integer
  else if keyName = "caps" then
    set theMask to current application’s NSEventModifierFlagCapsLock as integer
  else if keyName = "num" then
    set theMask to current application’s NSEventModifierFlagNumericPad as integer
  else if keyName = "help" then
    set theMask to current application’s NSEventModifierFlagHelp as integer
  else if keyName = "fn" then
    set theMask to current application’s NSEventModifierFlagFunction as integer
  else
    return false
  end if
  
  
set theFlag to current application’s NSEvent’s modifierFlags() as integer
  
if ((theFlag div theMask) mod 2) = 0 then
    return false
  else
    return true
  end if
end checkModifier:

★Click Here to Open This Script 

Posted in System | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy CotEditor NSEvent | Leave a comment

前後に存在するスペースと、文字列中に存在する2個以上の連続するスペースを削除して返す

Posted on 9月 29, 2020 by Takaaki Naganoya

それほど長くない文字列の空白文字列クリーニングを行うAppleScriptです。

 "    First model, with mechanical scroll wheel.           10 GB model released later                             ."

のようなデータを、

 "First model, with mechanical scroll wheel.  10 GB model released later ."

のようにクリーニングします。

フィールド文字列のクリーニング用なので、だいたい256バイト以内。長くても1024バイト程度のデータを想定しています。

とくに、データが長くなった場合に備えての高速化対応処理はしていませんが、それでもCocoaの正規表現系の機能を使った実装よりもだいたい5倍ぐらいは高速です。

画像処理ぐらいのデータ量があるとCocoa系の機能を使ったほうがはるかに高速ですが、この手の小ぶりなデータの処理にはNativeなAppleScriptの処理を行ったほうが高速です。

文字列の先頭と末尾に入っている無駄なスペース(空白文字)を除去し、文字列本体中に入っている「2つ以上連続して存在するスペース」についても除去します。

AppleScript名:前後に存在するスペースと、文字列中に存在する2個以上の連続するスペースを削除して返す.scpt
— Created 2020-09-27 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–指定文字列の前後に存在するスペースと、文字列本体中に存在する2個以上の連続するスペースを削除して返す
set a0Str to " First model, with mechanical scroll wheel. 10 GB model released later ."
set aRes to removeWhiteSpaceRepeatation(a0Str, " ") of me
–> "First model, with mechanical scroll wheel. 10 GB model released later ."

–クリーニング対象文字(たぶんスペース)が処理対象文字列の前後にあったり、途中に2つ以上連続して存在している場合には削除
on removeWhiteSpaceRepeatation(a0Str as string, aChar as string)
  if length of aChar is not equal to 1 then return false
  
  
set a1Str to trimFromHeadAndTail(a0Str, aChar) of me
  
–> "First model, with mechanical scroll wheel. 10 GB model released later ."
  
  
set sucList to detectSuccsessionOfSpace(a1Str, aChar) of me
  
–> {{43, 53}, {80, 108}}
  
  
if sucList = {} then return a1Str
  
  
set allRes to removeRepeatedSpaceChar(a1Str, sucList)
  
  
return allRes
end removeWhiteSpaceRepeatation

–同一文字(スペース)の連続出現リスト({{start pos 1, end pos 1}, {start pos 2, end pos 2}……})をもとにテキストを切り抜く
on removeRepeatedSpaceChar(a1Str as string, sucList as list)
  set aList to characters of a1Str
  
  
set aLen to length of aList
  
set outStr to ""
  
set aCount to 1
  
copy contents of item aCount of sucList to {sItem, eItem}
  
  
repeat with i in sucList
    copy i to {tmpS, tmpE}
    
if aCount = tmpS then
      –Skip
      
copy tmpE to aCount
    else
      set tmpStr to text (aCount) thru tmpS of a1Str
      
set outStr to outStr & tmpStr
      
copy tmpE to aCount
    end if
  end repeat
  
  
if tmpE < aLen then
    set tmpStr to text (tmpE + 1) thru -1 of a1Str
    
set outStr to outStr & tmpStr
  end if
  
  
return outStr
end removeRepeatedSpaceChar

–対象文字列で、2個以上同一文字(スペースを想定)が連続して存在する場合には削除する
on detectSuccsessionOfSpace(a1Str as string, sucTargChar as string)
  set aList to characters of a1Str
  
set aLen to length of aList
  
set newList to {}
  
  
set tmpS to 0
  
set tmpE to 0
  
set spcF to false –false:spaceではない。true:spaceをみつけた
  
set spcCount to 0
  
  
repeat with i from 1 to aLen
    set j to contents of item i of aList
    
    
if j = sucTargChar then –Space 1 char (must be a char)
      
      
if spcF = true then
        –スペースが連続している最中
        
set spcCount to spcCount + 1
      else
        –スペースの連続部分(?)の先頭をフェッチした状態
        
set spcF to true
        
set spcCount to 1
        
copy i to tmpS
      end if
      
    else
      –連続スペースの末端部分
      
if spcF = true then
        copy i to tmpE
        
if spcCount > 1 then
          set the end of newList to {tmpS, tmpE – 1}
        end if
        
set spcCount to 0
        
set spcF to false
      else
        –何もしない
      end if
    end if
    
  end repeat
  
  
return newList
end detectSuccsessionOfSpace

–文字列の先頭と末尾から連続するスペースを検索して削除する
on trimFromHeadAndTail(aStr as string, trimChar as string)
  set aLen to length of aStr
  
set aList to characters of aStr
  
  
–Find not target character from head to tail
  
set aCount to 1
  
repeat with i in aList
    set j to contents of i
    
if j is not equal to trimChar then
      exit repeat
    end if
    
set aCount to aCount + 1
  end repeat
  
  
if aLen ≤ aCount then return ""
  
  
–Find not target character from tail to head
  
set bCount to 1
  
repeat with ii in (reverse of aList)
    set jj to contents of ii
    
if jj is not equal to trimChar then
      exit repeat
    end if
    
set bCount to bCount + 1
  end repeat
  
  
set resStr to text aCount thru (aLen – bCount + 1) of aStr
  
return resStr
end trimFromHeadAndTail

–Written By Philip Aker
–文字置換ルーチン
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 Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

mergelyでdiff表示

Posted on 9月 27, 2020 by Takaaki Naganoya

alert dialog上のWebViewに、オープンソースのJavaScript Library「mergely」を呼び出すHTMLを表示し、指定の文字列のdiff表示を行うAppleScriptです。

–> Download diff_disp

CDN上のmergely.jsおよびcssを呼び出しているので、実行にはインターネット接続を必要とします。

Webダイアログ表示部分はscript bundleの中に入れてあるので、上記のアーカイブをダウンロード&アーカイブ展開したものを実行してください。下記のリストではWebダイアログ部分は含んでいないので、Script Linkをクリックして内容をスクリプトエディタに転送して実行しても、必要なファイルが入っていないため動きません(Script Linkではバンドル構造を転送することはできません)。あくまで掲載リストは参考にしていただくためのものです。本Scriptの本体部分はバンドル内に同梱しているHTML(の中のJavaScript部分)です。

diff表示用の部品がOSに用意されていると楽ですが、macOS上のdiff表示用ツール「FileMerge」のdiff表示部品が再利用可能な状態で提供されていないため、よそで部品を探してくることに。FileMerge自体はAppleScript用語辞書を持っていないため、ダイレクトにaliasを指定して2つのファイルの差分表示を行わせることはできません(do shell scriptコマンド経由でオープンさせることは可能)。

サードパーティのGUIアプリケーションでdiff表示機能を持つものをコントロールする場合には、BBEditのdiff表示機能を呼び出すのが手頃で使いやすいでしょうか。

独立した(他のGUIアプリケーションに依存しない)ソリューションとして提供できる形態を想定すると、部品として組み込めるものを探すことになります。この条件に見合うdiff表示用部品はいろいろ探してはいるものの、なかなかいいものが見当たりません。UKDiffViewはAppleのFileMergeに似たルック&フィールを提供する最強クラスの部品ですが、メンテナンスされていなくて現行環境で動かすように書き換えるには手間がかかりそうです(自分には無理です)。

Double PDFをMac App Storeに申請したときには、Reviewでリジェクトをくらっていた中で苦し紛れに「Vimdiff」でdiff表示するバージョンを提出したこともありましたが、これは「Terminal.appをコントロールするアプリケーションは提出不可」というルールに明記されていない理由によりリジェクトを食らいました(セキュリティ上の理由だったか)。

mergelyは(使いこなせれば)なかなかいい部品に見えます。目下、自分はパラメータに改行を含んだ文字列を指定できていないので、そのあたり試行錯誤する必要があることでしょう。

AppleScript名:mergelyでdiff表示.scptd
set aStr to "左側のフィールドの文章をここに書いた。犬と猫を見かけた。"
set bStr to "右側のフィールドの文章をここに書いた。犬と蛇を見かけた。"
set aSize to {1024, 220}
dispDiff(aStr, bStr, aSize) of diffDispLib

script diffDispLib
  –  Created by: Takaaki Naganoya
  
–  Created on: 2020/09/27
  
—
  
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
  
–  https://mergely.com
  
use AppleScript version "2.7" — High Sierra (10.13) or later
  
use framework "Foundation"
  
use scripting additions
  
use webD : script "webDialogLib"
  
  
on dispDiff(aStr, bStr, aSize)
    using terms from scripting additions
      set mePath to path to me
      
set resPath to (mePath as string) & "Contents:Resources:index.html"
      
set myStr to (read (resPath as alias) as «class utf8») as string
    end using terms from
    
    
set aString to current application’s NSString’s stringWithFormat_(myStr, aStr, bStr) as string
    
set paramObj to {myMessage:"Browse diff", mySubMessage:"This is an mergely test", htmlStr:aString, viewSize:aSize}
    
    
webD’s displayWebDialog(paramObj)
  end dispDiff
end script

★Click Here to Open This Script 

Posted in dialog | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

SFPSDWriterのじっけん v2

Posted on 9月 21, 2020 by Takaaki Naganoya

AppleScriptからPhotoshopのデータ(PSD)を出力するテストプログラムです。

AppleScriptにはPhotoshopのデータを書き出す関数や機能はとくに用意されていないため、Photoshopのデータを書くためにはPhotoshopにコマンドを送って実行してもらうのが定番です。

この定番の方法だと、Photoshopが存在しない環境でPhotoshopのデータを作ることができません。この問題を解決するためにはオープンソースで公開されている「Photoshopデータを書くプログラム部品」を呼び出すことになります。

Photoshopデータについては一定の需要があるためか、AdobeがPhotoshopデータ形式の詳細な資料を公開しているためか、Reader(読むプログラム)とWriter(書くプログラム)の2通りのプログラムが存在します。

■PSD Reader/Parser
PSD-Font-Reader
psdparse

■PSD Writer
FMPSD
PSDWriter
SFPSDWriter

ここでは、「SFPSDWriter」内に含まれる「SFPSDWriter」Frameworkを呼び出しています。

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

実行にあたっては、macOS 10.14以降ではScript Debuggerを用いるか、お使いのMacをSIP解除してScript Editor上で呼び出して実行する必要があります。

ちょっと書き換えるとXcode上でも呼び出せることでしょう。Mac App Storeに出すAppleScript Cocoaアプリケーション(Sandbox対応)内で利用する場合には、ファイル書き込みパスをユーザーに明示的に選択させる必要があるため、choose file nameダイアログでファイル名を入力・選択してもらうようにすべきです(デフォルト指定のファイル名をUUIDで自動生成するとか)。

本AppleScriptはKamenokoから書き出せるデータを増やすべく「Photoshop形式のデータを書けたらどうだろう?」と実験してみた残骸です。結局、PDFで書き出せるしPDFなら拡大縮小しても荒くなったりしないので、PDFのほうがいいという結論に。

Pixelmator Proのデータ形式とかPSD形式で書き出す実験は行っているのですが、処理結果を見るとどちらも「PDF形式のほうがいい」という結論に至っています。


▲ベクターデータではないので、拡大するとアラが見える

AppleScript名:SFPSDWriterのじっけん v2
— Created 2016-03-12 by Takaaki Naganoya
— Modified 2019-02-27 by Takaaki Naganoya
— Modified 2020–09-21 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "SFPSDWriter" –https://github.com/shinyfrog/SFPSDWriter

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSUUID : a reference to current application’s NSUUID
property NSImage : a reference to current application’s NSImage
property SFPSDWriter : a reference to current application’s SFPSDWriter
property NSWorkspace : a reference to current application’s NSWorkspace

property SFPSDResolutionUnitPPI : 1
property SFPSDResolutionUnitPPC : 2

set anWriter to (SFPSDWriter’s alloc()’s initWithDocumentSize:(current application’s CGSizeMake(1200, 400)) andResolution:72.0 andResolutionUnit:(SFPSDResolutionUnitPPI))

set aCount to 1

repeat with yPos from 0 to 400 by 110
  repeat with xPos from 0 to 1024 by 110
    set aImage to (current application’s NSImage’s alloc()’s initWithSize:{100, 100})
    
set aColor to current application’s NSColor’s redColor()
    
my drawCircleOnNSIMage(aImage, 100, 0, 0, aColor)
    
    (
anWriter’s addLayerWithNSImage:aImage andName:("Layer_" & aCount as string) andOpacity:1.0 andOffset:{x:(xPos as real), y:(yPos as real)})
    
set aCount to aCount + 1
  end repeat
end repeat

set aPSD to anWriter’s createPSDData()

set theName to NSUUID’s UUID()’s UUIDString()
set pathString to NSString’s stringWithString:("~/Desktop/output_" & theName & ".psd")
set newPath to pathString’s stringByExpandingTildeInPath()

aPSD’s writeToFile:newPath atomically:true

#  MARK: Call By Reference
on drawCircleOnNSIMage(aImage, aRadius, aXpos, aYpos, aColor)
  set aBezier to generateCircle(aRadius, aXpos, aYpos) of me
  (
aImage)’s lockFocus()
  
aColor’s |set|()
  
aBezier’s fill() –ぬりつぶし
  (
aImage)’s unlockFocus()
end drawCircleOnNSIMage

#  MARK: circleのBezier曲線を作成して返す
on generateCircle(theRadius, x, y)
  set aRect to current application’s NSMakeRect(x, y, theRadius, theRadius)
  
set aCirCle to current application’s NSBezierPath’s bezierPath()
  
aCirCle’s appendBezierPathWithOvalInRect:aRect
  
return aCirCle
end generateCircle

★Click Here to Open This Script 

Posted in file Image | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Photoshop | Leave a comment

Mac App Storeで「White Pages」を販売開始

Posted on 9月 12, 2020 by Takaaki Naganoya

例によってAppleScriptで開発したアプリケーション「White Pages」のMac App Storeでの販売を開始しました。macOS 10.13以降に対応しています。

PDFの空白ページを削除・出力するアプリケーションです。空白ページの検出のため、全ページを画像にレンダリングして、空白判定。空白判定には速度と精度で定評のある空白画像検出ルーチンを使用しています。

決して、ページごとに文字の有無を判断するだけのソフト(Fredrik Method)ではありません。それだと、グラフィックだけのページを「空白」と判定してしまいますので。

アイコンは、macOS 11.0, Big Surに合わせた形状。手の色を赤くしているのは、何らかの特定の人種を想起させるような塗り色を避けたためです。

Posted in PDF PRODUCTS | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

現在のスライドと次のスライドでオーバーラップしている画像とグループを検出して位置をそろえる

Posted on 9月 10, 2020 by Takaaki Naganoya

Keynoteの最前面の書類で、現在表示中のスライドと次のスライドの間で、矩形座標が重なっている「画像」と「グループアイテム」(複数のオブジェクトをグループ化したアイテム)を検出して、現在のスライドの開始位置に場所をそろえるAppleScriptです。

# 最初掲載したもの(v1)は、動作しているものの処理内容に誤りがあったので修正しました(v2)

連続したスライド上に画面図を配置して、その画面図の位置をそろえるためのものです。何回か書いたような気がします。見た目より書くのが大変ではないので、ついつい書いてしまう処理です。

単にそれぞれの対象候補のオブジェクトの矩形開始座標と幅&高さをリスト化して、それをNSRectに変換して重ね合わせが発生していないかをCocoaの機能で判定しているだけです。この、一番めんどくさい部分をCocoaに丸投げしているので、おおよそ知性というものを感じさせないレベルのScriptです。

画像やグループアイテム 以外の表オブジェクト同士の重なりあいの検出を行うものに書き換えるのは簡単ですが、複数のオブジェクトの重なり合いが発生している場合には対処できません。

AppleScript名:現在のスライドと次のスライドでオーバーラップしている画像とグループを検出して位置をそろえる v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/09/10
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Keynote"
  set dCount to count every document
  
if dCount = 0 then return –ドキュメントがオープンしていないと処理終了
  
  
tell front document
    set allNum to count every slide
    
if allNum < 2 then return –slideの枚数が少なかった場合に処理終了
    
    
set curSlide to current slide
    
if allNum = curSlide then return –current slideが末尾だった場合処理終了
    
    
set sNum to slide number of curSlide
    
set nextSlide to slide (sNum + 1)
    
    
–最初のページ(スライド)からオブジェクトを収集
    
tell current slide
      set curObj1 to every image
      
set curObj2 to every group
      
set curObjList to curObj1 & curObj2
      
if curObjList = {} then return
    end tell
    
    
–次のページ(スライド)からオブジェクトを収集
    
tell nextSlide
      set nextObj1 to every image
      
set nextObj2 to every group
      
set nextObjList to nextObj1 & nextObj2
      
if nextObjList = {} then return
    end tell
    
    
set nexObjRes to calcOverlappedObj(curObjList, nextObjList) of me
    
repeat with i in nexObjRes
      copy i to {origID, targID}
      
set aOrigObj to contents of item origID of curObjList
      
set aTargObj to contents of item origID of nextObjList
      
set origPos to position of aOrigObj
      
set position of aTargObj to origPos
    end repeat
    
    
set current slide to slide sNum
  end tell
end tell

–与えられた2つのリストに入っているKeynoteオブジェクトの矩形座標が重なっているものをIDペアで出力する
–同時に複数のオブジェクトが重なっていないことが前提
on calcOverlappedObj(objList1, objList2)
  tell application "Keynote"
    –最初のページのオブジェクトからオブジェクトIDとNSRectからなるリストを作成
    
set objRecList1 to {}
    
set aCount to 1
    
repeat with i in objList1
      if contents of i is not equal to {} then
        set {x1, y1} to position of i
        
set aRect to {origin:{x:x1, y:y1}, |size|:{|width|:(width of i), |height|:(height of i)}}
        
        
set the end of objRecList1 to {objID:aCount, rect:aRect}
      end if
      
set aCount to aCount + 1
    end repeat
    
    
–次のページのオブジェクトからオブジェクトIDとNSRectからなるリストを作成
    
set objRecList2 to {}
    
set aCount to 1
    
repeat with i in objList2
      if contents of i is not equal to {} then
        set {x1, y1} to position of i
        
set aRect to {origin:{x:x1, y:y1}, |size|:{|width|:(width of i), |height|:(height of i)}}
        
        
set the end of objRecList2 to {objID:aCount, rect:aRect}
      end if
      
set aCount to aCount + 1
    end repeat
    
    
–最初のページのオブジェクトと次のページのオブジェクトで矩形エリアが重なっているオブジェクトを抽出してそれぞれのIDをペアにしたリストを作成
    
set matchList to {}
    
repeat with i in objRecList1
      
      
set origRect to rect of i
      
set origID to objID of i
      
      
repeat with ii in objRecList2
        
        
set targRect to rect of ii
        
set targID to objID of ii
        
set tRes to detectRectanglesCollision(origRect, targRect) of me
        
        
if tRes = true then
          set the end of matchList to {origID, targID}
        end if
      end repeat
      
    end repeat
    
    
return matchList
  end tell
end calcOverlappedObj

–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

★Click Here to Open This Script 

Posted in list Record | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Keynote | Leave a comment

指定Finderウィンドウがどのディスプレイ上に表示されているかをIDで返す(0はじまり)

Posted on 9月 7, 2020 by Takaaki Naganoya

指定座標がどのディスプレイ上に表示されているかをIDで返すAppleScriptです。

試しに、Finderの最前面のウィンドウの始点座標を取得して、どのディスプレイ上に表示されているかを地道にループで計算しています。

0はメニューを配置しているメインディスプレイで、その後のIDについてはNSScreen’s screens()の出現順に割り振られています。

MacBook Pro 10,1にディスプレイ3枚接続して(通常状態)、さらにUSB経由でiPadをDuet Displayで外部ディスプレイ化。4枚のディスプレイで動作確認しています。

本来、どのディスプレイ上にあるかをきっちり判定できるはずなのですが、最後のIDのものだけうまく判定できていないので例外処理しています。

このあたりの動作内容が怪しかったので、ながらく放置状態になっていましたが、実際にディスプレイを4枚つないで動作確認してみたら大丈夫そうだったので掲載することに。

AppleScript名:指定Finderウィンドウがどのディスプレイ上に表示されているかをIDで返す(0はじまり).scptd
— Created 2015-11-01 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

tell application "Finder"
  if (count every window) = 0 then return
  
tell front window
    set {xPos, yPos} to position
    
log {xPos, yPos}
  end tell
end tell

set dispID to getPointInWhichScreen(xPos, yPos) of me

–指定座標がどのディスプレイ上に表示されているかをIDで返す(0はじまり。0はメインディスプレイ)
on getPointInWhichScreen(xPos, yPos)
  set dList to getScreensResol() of me
  
  
set aPoint to current application’s NSMakePoint(xPos, yPos)
  
set dCount to 0
  
repeat with i in dList
    set dRes to current application’s NSPointInRect(aPoint, i) as boolean
    
    
if dRes = true then
      return dCount
    end if
    
set dCount to dCount + 1
  end repeat
  
  
return dCount – 1 –ちょっと怪しいが、動作している様子
end getPointInWhichScreen

on getScreensResol()
  set dispList to (current application’s NSScreen’s screens()) as list
  
set dList to {}
  
repeat with i in dispList
    set framePref to i’s visibleFrame()
    
set {xPos, yPos} to first item of framePref
    
set theInfo to (i’s deviceDescription()’s NSDeviceSize) as record
    
set a1Rect to {origin:{x:xPos, y:yPos}, |size|:theInfo}
    
set the end of dList to a1Rect
  end repeat
  
return dList
end getScreensResol

★Click Here to Open This Script 

Posted in System | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy NSScreen | 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で選択中の表カラムの幅を均等割
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • Keynote、Pages、Numbers Ver.14.0が登場
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値

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