Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: System

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

指定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

macOS Big Surがバージョン番号に「11.0」を返してくるようになった

Posted on 8月 5, 2020 by Takaaki Naganoya

これまで、macOS 10.16.0というバージョン番号を返してきたmacOS Big Surが、Beta 4でAppleScript系、shell系、Cocoa系のさまざまなOSバージョン確認方法に対して「11.0」というバージョン番号を返してくるように変更になりました。

ここから先は、正式に11.0として扱うことにします。

ただし、いつものApple仕事なので、いつどのランタイム環境でOSバージョン取得を間違えるかわかったものではありません。OSバージョン取得まわりは今後も継続的に疑いの目で厳しく確認しておく必要のある箇所であると考えます。どうせAppleなので。

Posted in System | Tagged 11.0savvy | Leave a comment

カラーリストの処理

Posted on 7月 27, 2020 by Takaaki Naganoya

カラーリストまわりの情報を取得するAppleScriptです。

カラーピッカーで取得できる各種色セットの内容を取得できたりと、割と使いでがあります。

AppleScript名:使用可能なカラーリスト名称一覧を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/07/26
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set cList to ((current application’s NSColorList’s availableColorLists())’s valueForKeyPath:"name") as list
–> {"Apple", "System", "World", "Europe", "Japanese", "Scrivener", "AquaPro", "Crayons", "Web セーフカラー"}

★Click Here to Open This Script 

AppleScript名:指定名称のカラーリストに登録されているNSColorを配列で取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/07/26
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set aColList to (current application’s NSColorList’s colorListNamed:"Crayons")

set kList to (aColList’s allKeys()) as list
set colList to {}
repeat with i in kList
  set j to contents of i
  
set cVal to (aColList’s colorWithKey:j)
  
set the end of colList to cVal
end repeat

return colList

★Click Here to Open This Script 

Posted in Color System | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy NSColor NSColorList | Leave a comment

CPUタイプを取得

Posted on 7月 23, 2020 by Takaaki Naganoya

実行中のMacのCPUタイプを取得するAppleScriptです。ARM Macではまた別の結果が返ってくることでしょう。

追記:
匿名希望のDTKユーザー1号さんから教えてもらいました。

set cpuStr to CPU type of (system info)

のDTKマシン上での実行結果は、Rosetta2環境では「Intel」、ARMネイティブ環境では「ARM」と返ってくるのだとか。1号さんに念を押されたのですが、まだβ段階なので将来的に同じ値が返ってくるかは保証できないということです。

正直、予想していたのは「ARM」か「Apple」かの2択だったので納得な内容です(詳細なモデル識別子をスペースを付けて出力してこないことも予想ずみ)。

おそらくですが、Mac用のApple Silicon(ARM)は複数タイプのもの(ノート用、外部GPUを用いるハイエンドデスクトップ用)が出てくるでしょうし、世代ごとにモデル名が変わっていくことでしょう(A14XBionicとか)。それでも、CPUタイプが識別できることの意義は、

「ARM Mac上なのにRosetta2環境で動作しているからパフォーマンスが落ちるかもしれないよ?」

といった警告メッセージを表示するぐらいでしょうか。AppleScriptのsystem infoコマンドで得られるCPU typeについては、Intel Macになってもながらく「Intel 80486」といったいい加減な名前を返してくるぐらいだったので、アーキテクチャ判定以上の情報を得られるという期待は持たないほうがよいでしょう。逆を言えば、Intel 80486の時代にすでにその定数が内部で定義されていた(Intel CPU上でMacOSを動作させるプロジェクトがあった)という証拠ともいえます(Star Trek projectの時代?)。

--macOS 10.14.6+Intel Mac (system info)
{AppleScript version:"2.7", AppleScript Studio version:"1.5.3", system version:"10.14.6", short user name:"me", long user name:"Takaaki Naganoya", user ID:504, user locale:"en_JP", home directory:alias "Machintosh HD:Users:me:", boot volume:"Machintosh HD", computer name:"MBPretina", host name:"MBPretina.local", IPv4 address:"xx.xx.xx.xx", primary Ethernet address:"xx:xx:xx:xx:xx:xx", CPU type:"Intel 80486", CPU speed:2600, physical memory:8192}

--macOS 10.15.6+Intel Mac (system info)
{AppleScript version:"2.7", AppleScript Studio version:"1.5.3", system version:"10.15.6", short user name:"me", long user name:"Takaaki Naganoya", user ID:502, user locale:"ja_JP", home directory:alias "Macintosh HD:Users:me:", boot volume:"Macintosh HD:", computer name:"YasMBP", host name:"YasMBP.local", IPv4 address:"xx.xx.xx.xx", primary Ethernet address:"xx:xx:xx:xx:xx:xx", CPU type:"Intel 80486", CPU speed:2700, physical memory:8192}

--macOS 11.0+Intel Mac (system info)
{AppleScript version:"2.7", AppleScript Studio version:"1.5.3", system version:"11.0", short user name:"me", long user name:"Takaaki Naganoya", user ID:501, user locale:"ja_JP", home directory:alias "Macintosh HD:Users:me:", boot volume:"Macintosh HD:", computer name:"Mac mini 2014", host name:"MacMini2014.local", IPv4 address:"xx.xx.xx.xx", primary Ethernet address:"xx:xx:xx:xx:xx:xx", CPU type:"Intel x86-64h Haswell", CPU speed:2600, physical memory:16384}
AppleScript名:CPUタイプを取得.scpt
set aRes to getCPUType() of me
–> "PowerPC"
–> "Intel"

on getCPUType()
  set cpuStr to CPU type of (system info)
  
set aInd to (offset of " " in cpuStr)
  
if aInd = 0 then return cpuStr
  
set cpuStr to text 1 thru (aInd – 1) of cpuStr
  
return cpuStr
end getCPUType

★Click Here to Open This Script 

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

CPUのバイトオーダーを取得

Posted on 7月 22, 2020 by Takaaki Naganoya

実行中のコンピュータ(多分Mac)のCPUのバイトオーダーを取得するAppleScriptです。

これまでに、68k(Big Endian)→PowerPC(Big Endian)→Intel(Little Endian)と来て、次はARM。

一応、IntelとArmは同じLittle Endianなので問題は少ないはずですが、ARM DTKをお持ちの方は試してコッソリ教えていただけるとありがたいです。

この情報がAppleScriptで取得できると何か「いいこと」があるかですが、別にメリットはありません。

ただ、CPUの名前が取得できると、処理速度を推測できてよいでしょう。Intel CPUに対してApple Silicon(ARM)がどの程度のパフォーマンスを発揮できるのか、実機が出てこないとわかりません。

PowerPCからIntelに変わったときには、先読みが深くなったためか(?)連番ファイルの処理で問題が出て、書き直しが必要になったことがありました。IntelからARMへの移行時には、iOS系のアプリケーションの操作に試みて問題が出たり、セキュリティ上の制限にひっかかったりすることでしょう。

AppleScript名:CPUのバイトオーダーを取得.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/07/22
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set bRes to getByteOrder() of me
–> true –Little Endian

on getByteOrder()
  set aRes to do shell script "sysctl -n hw.byteorder"
  
if aRes = "4321" then
    return false –Big Endian (PowerPC)
  else
    return true –Little Endian (Intel, Arm..maybe)
  end if
end getByteOrder

★Click Here to Open This Script 

Shane Stanleyからの投稿です。こっちの方がシンプルでいいですね。

AppleScript名:CPUのバイトオーダーを取得 v2.scptd
—
–  Created by: Shane Stanley
–  Created on: 2020/07/23
—

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

set bRes to current application’s NSHostByteOrder() — 1 = little endian, 2 = big endian, 0 = unknown

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy NSHostByteOrder | Leave a comment

指定TTSボイスキャラクタの読み上げ例文テキストを取得

Posted on 7月 6, 2020 by Takaaki Naganoya

指定のテキスト読み上げ(Text To Speech)ボイスキャラクターの読み上げ例文テキストを取得して実際に読み上げるAppleScriptです。

TTS音声は言語や性別、年齢、高音質かどうかなどの情報を持っているので、これらを指定して絞り込むことが可能です。また、指定TTS音声キャラクターの例文テキストもこのように取得できます。

AppleScript名:指定TTSボイスキャラクタの読み上げ例文テキストを取得.scpt
— Created 2015-08-25 by Takaaki Naganoya
— Modified 2015-08-26 by Shane Stanley, Takaaki Naganoya
— Modified 2020-07-06 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use scripting additions

set vList to getVoiceNames() of me
using terms from scripting additions
  set aTargTTSVoiceName to contents of (choose from list vList)
end using terms from

using terms from scripting additions
  set v1Res to getDemoText(aTargTTSVoiceName) of me
  
say v1Res using aTargTTSVoiceName
end using terms from

–Get TTS Voice sample text
on getDemoText(aName as string)
  set vList to getVoiceNames() of me
  
if aName is not in vList then return ""
  
set anID to getSpecifiedVoiceIDfromVoiceName(aName) of me
  
  
set aDemoText to ((current application’s NSSpeechSynthesizer’s attributesForVoice:anID)’s VoiceDemoText)
  
return aDemoText as string
end getDemoText

–Get all voice names
on getVoiceNames()
  –Make Blank Array
  
set outArray to current application’s NSMutableArray’s arrayWithObject:{}
  
set aList to {}
  
  
–Make Installed Voice List
  
set nameList to current application’s NSSpeechSynthesizer’s availableVoices()
  
repeat with i in nameList
    set j to contents of i
    
    
set aDic to ((current application’s NSSpeechSynthesizer’s attributesForVoice:j))
    
    
set aDemoText to (aDic’s VoiceDemoText) as string
    
set aName to (aDic’s VoiceName) as string
    
    
set the end of aList to aName
  end repeat
  
  
return aList as list
end getVoiceNames

–Voice Name –> Voice ID
on getSpecifiedVoiceIDfromVoiceName(VoiceName as string)
  set outArray to current application’s NSMutableArray’s arrayWithObject:{}
  
  
set aList to current application’s NSSpeechSynthesizer’s availableVoices()
  
set bList to aList as list
  
  
repeat with i in bList
    set j to contents of i
    
set aDic to (current application’s NSSpeechSynthesizer’s attributesForVoice:j)
    (
outArray’s addObject:aDic)
  end repeat
  
  
–Filter Voice
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat_("VoiceName == %@", VoiceName)
  
  
set filteredArray to outArray’s filteredArrayUsingPredicate:aPredicate
  
set aReList to (filteredArray’s valueForKey:"VoiceIdentifier") as list
  
  
if length of aReList = 1 then
    return first item of aReList
  else
    return ""
  end if
end getSpecifiedVoiceIDfromVoiceName

★Click Here to Open This Script 

Posted in list Record System Text to Speech | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy NSMutableArray NSPredicate NSSpeechSynthesizer | Leave a comment

InstrumentsがAppleScriptに対応

Posted on 5月 19, 2020 by Takaaki Naganoya

InstrumentsはXcodeに同梱されているメモリ使用状況などの記録、ビジュアル化を行うツールで、アクティビティモニタの強化版といったものです。

監視対象のモジュール(Instruments)を選択してドキュメント上に配置し、監視対象プロセスを選択して記録すると、動作中のプロセスの各種リソース使用状況がわかります。

そのInstrumentsがAppleScriptに対応している(sdefを持っている)ことがわかりました(調べたことがなかった)。

Dock上でXcodeのサブメニューから起動が可能です。


▲macOS 10.14.6上で動作するInstruments version 11.3.1。バージョン番号はインストールされているXcodeと同じものを名乗っているもよう

Instrumentsを使って開発中のアプリケーションのメモリ使用状況を記録して可視化(グラフを眺めるぐらい?)してみると、ダラダラ長時間記録するよりも、目的の箇所で記録を行なったほうが使い勝手がよく、Instrumentで記録した書類が複数できてきます。

それらを選択してオープンするのに、Instruments書類(単なるログ?)はファイルサイズが巨大。これをオープンするとけっこうな処理時間がかかります。Scriptから操作できたほうがよさそうだと考えて、冗談半分でAS対応していないか調べたところ、対応していると出ました。

InstrumentsのAppleScript用語辞書の内容を見てみると、ファイルのオープン/クローズができる程度で、他に何ができるというわけでもありません。

Documentの新規作成ぐらいはできそうですが、試してみたところクラッシュします。新規作成時に、どのリソースを監視するかというモジュール(Instruments)を指定する必要があるので、ドキュメント作成時にこのInstrumentsを指定できないあたりでGUI側との機能の不一致が起こっているのでしょう。

また、ドキュメントを新規作成したあとで、個別にInstrumentsを追加できるコマンドも必要になっていくことでしょう。

AppleScript名:指定書類をオープン
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/19
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

set aFile to choose file

with timeout of 3600 seconds
  tell application "Instruments"
    open aFile
  end tell
end timeout

★Click Here to Open This Script 

AppleScript名:最前面のドキュメントから情報を取得
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/19
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

tell application "Instruments"
  tell front document
    properties
    
–> {file:file "Cherry:Users:me:Documents:Instruments_withoutRetina.trace:", modified:false, name:"Instruments_withoutRetina.trace", class:document}
    
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:新規書類作成(クラッシュ)
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/19
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

tell application "Instruments"
  make new document –This command cause crash
end tell

★Click Here to Open This Script 

Posted in System | Tagged 10.14savvy 10.15savvy Instruments Xcode | Leave a comment

システムフォントをWeightつきで指定

Posted on 5月 15, 2020 by Takaaki Naganoya

システムフォントをWeightつきで指定するAppleScriptです。

NSFontまわりの、フォント名を具体的に文字列で指定「しない」フォントの指定方法を、(必要があったので)いろいろ調べてみました。

ここに紹介したサンプルでは、System FontをWeightおよびSize指定して取得していますが、本当にやりたいのは言語(英語、日本語など)とセリフつき(Timesなど)サンセリフ(Helveticaなど)、Handwritingフォントかなどの属性情報を指定すると、なんとなくフォントを特定してくれる処理で、とてもOS内にありそうな気もするのですが、まだ見つけられておりません。

AppleScript名:システムフォントをWeightつきで指定.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/14
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set aFont1 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightRegular)
—> (NSFont) ".AppleSystemUIFont 48.00 pt. P [] (0x60000154c060) fobj=0x7f8bb176bfc0, spc=10.20"
set aFont1Name to aFont1’s fontName() as string
–> ".AppleSystemUIFont"

set aFont2 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightUltraLight)
–> (NSFont) ".AppleSystemUIFontUltraLight 48.00 pt. P [] (0x6000012d42a0) fobj=0x7f8bb8925090, spc=10.10"
set aFont2Name to aFont2’s fontName() as string
–> ".AppleSystemUIFontUltraLight"

set aFont3 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightThin)
–> (NSFont) ".AppleSystemUIFontThin 48.00 pt. P [] (0x6000013fd350) fobj=0x7f8bb3ba1140, spc=10.12"
set aFont3Name to aFont3’s fontName() as string
–> ".AppleSystemUIFontThin"

set aFont4 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightLight)
–> (NSFont) ".AppleSystemUIFontLight 48.00 pt. P [] (0x6000013fd410) fobj=0x7f8bb3bbf890, spc=10.17"
set aFont4Name to aFont4’s fontName() as string
–> ".AppleSystemUIFontLight"

set aFont5 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightMedium)
–> (NSFont) ".AppleSystemUIFontMedium 48.00 pt. P [] (0x60000151c8a0) fobj=0x7f8bb79289e0, spc=10.08"
set aFont5Name to aFont5’s fontName() as string
–> ".AppleSystemUIFontMedium"

set aFont6 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightSemibold)
–> (NSFont) ".AppleSystemUIFontDemi 48.00 pt. P [] (0x6000013fd710) fobj=0x7f8bb69ef060, spc=9.96"
set aFont6Name to aFont6’s fontName() as string
–> ".AppleSystemUIFontDemi"

set aFont7 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightBold)
–> (NSFont) ".AppleSystemUIFontBold 48.00 pt. P [] (0x600000bfa430) fobj=0x7f8bb3b55630, spc=9.84"
set aFont7Name to aFont7’s fontName() as string
–> ".AppleSystemUIFontBold"

set aFont8 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightHeavy)
–> (NSFont) ".AppleSystemUIFontHeavy 48.00 pt. P [] (0x600000898a50) fobj=0x7f8bb3b79730, spc=9.66"
set aFont8Name to aFont8’s fontName() as string
–> ".AppleSystemUIFontHeavy"

set aFont9 to current application’s NSFont’s systemFontOfSize:48 weight:(current application’s NSFontWeightBlack)
–> (NSFont) ".AppleSystemUIFontBlack 48.00 pt. P [] (0x6000015a57a0) fobj=0x7f8bb14cb330, spc=9.49"
set aFont9Name to aFont9’s fontName() as string
–> ".AppleSystemUIFontBlack"

★Click Here to Open This Script 

AppleScript名:システムフォントをWeightつきで指定(monospacedDigitSystemFont).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/14
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set aFont1 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightRegular)
—> (NSFont) ".SFNSText 16.00 pt. P [] (0x600001557d80) fobj=0x7f8bb7e011b0, spc=4.20"
set aFont1Name to aFont1’s fontName() as string
–> ".SFNSText"

set aFont2 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightUltraLight)
–> (NSFont) ".SFNSText-Light 16.00 pt. P [] (0x6000015e08d0) fobj=0x7f8bb8914700, spc=4.02"
set aFont2Name to aFont2’s fontName() as string
–> ".SFNSText-Light"

set aFont3 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightThin)
–> (NSFont) ".SFNSText-Light 16.00 pt. P [] (0x600000b789f0) fobj=0x7f8bb697f020, spc=4.02"
set aFont3Name to aFont3’s fontName() as string
–> ".SFNSText-Light"

set aFont4 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightLight)
–> (NSFont) ".SFNSText-Light 16.00 pt. P [] (0x6000015a3c90) fobj=0x7f8bb88c2130, spc=4.02"
set aFont4Name to aFont4’s fontName() as string
–> ".SFNSText-Light"

set aFont5 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightMedium)
–> (NSFont) ".SFNSText-Medium 16.00 pt. P [] (0x6000014667f0) fobj=0x7f8bb891bdd0, spc=4.06"
set aFont5Name to aFont5’s fontName() as string
–> ".SFNSText-Medium"

set aFont6 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightSemibold)
–> (NSFont) ".SFNSText-Semibold 16.00 pt. P [] (0x6000014b7120) fobj=0x7f8bb8866210, spc=3.95"
set aFont6Name to aFont6’s fontName() as string
–> ".SFNSText-Semibold"

set aFont7 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightBold)
–> (NSFont) ".SFNSText-Bold 16.00 pt. P [] (0x600001412dc0) fobj=0x7f8bb8920310, spc=3.81"
set aFont7Name to aFont7’s fontName() as string
–> ".SFNSText-Bold"

set aFont8 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightHeavy)
–> (NSFont) ".SFNSText-Heavy 16.00 pt. P [] (0x600001443720) fobj=0x7f8bb6cea5f0, spc=3.61"
set aFont8Name to aFont8’s fontName() as string
–> ".SFNSText-Heavy"

set aFont9 to current application’s NSFont’s monospacedDigitSystemFontOfSize:16 weight:(current application’s NSFontWeightBlack)
–> (NSFont) ".SFNSText-Heavy 16.00 pt. P [] (0x60000145b5d0) fobj=0x7f8bb6996ff0, spc=3.61"
set aFont9Name to aFont9’s fontName() as string
–> ".SFNSText-Heavy"

★Click Here to Open This Script 

Posted in Font System | Tagged 10.13savvy 10.14savvy 10.15savvy NSFont | Leave a comment

Switch Controlがオンになっているか調べる

Posted on 5月 3, 2020 by Takaaki Naganoya

Switch Controlが起動中かどうかをNSWorkspace経由で調べるAppleScriptです。

いろいろなAppleScriptをSwitch Controlのパネルに盛り込んで利用していますが、けっこう使いでがあっていい感じです。Script MenuにAppleScriptを入れて呼び出すのも実用性が高くてよいのですが、Switch Controlのパネルに入れると常時フローティングパネルで表示される(消したり最小化も可)ため、アプリケーションの機能が不完全であると感じるところをユーザーが自分で勝手に補える感覚がとてもいい感じです。

ただ、1つ問題があるとすれば、Switch Controlをプログラム側から起動する方法が公開されていないようである点。本Scriptのように、起動中であることを判定する方法は提供されているのですが。

Switch Control(=AssistiveControl)がオンになっていると、InputManager側から見えるので

このあたりに解決の鍵がありそうな気もします。ただ、文字入力に介在できる機能でもあるため、セキュリティ上の懸念から「あえて」そうしたAPIを公開していないのかも。

現状では唯一、GUI Scriptingで野蛮にチェックボックスをクリックするか、あるいいはチェックボックスの値を変更するぐらいでしょう。実際に試してはいないので、これもできるか100%の保証があるものではありませんけれども。

AppleScript名:スイッチコントロールがオンになっているか調べる.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/02
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

current application’s NSWorkspace’s sharedWorkspace()’s isSwitchControlEnabled()
–> true / false

★Click Here to Open This Script 

Posted in System | Tagged 10.13savvy 10.14savvy 10.15savvy NSWorkspace Switch Control | Leave a comment

システム環境設定の「ディスプレイ」>「ディスプレイ」を表示

Posted on 4月 28, 2020 by Takaaki Naganoya

システム環境設定の「ディスプレイ」paneの「ディスプレイ」を表示するAppleScriptです。

やりかたは山のようにあるものの、Cocoa系の機能を使うとこんな感じ。

AppleScript名:システム環境設定の「ディスプレイ」>「ディスプレイ」を表示_asobjc.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/04/28
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

current application’s NSWorkspace’s sharedWorkspace()’s openFile:"/System/Library/PreferencePanes/Displays.prefPane"

★Click Here to Open This Script 

まんま、同じ内容をshell呼び出しで書くとこんな感じ。

AppleScript名:システム環境設定の「ディスプレイ」>「ディスプレイ」を表示_shell.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/04/28
—
–  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 "open /System/Library/PreferencePanes/Displays.prefPane"

★Click Here to Open This Script 

System Events経由でファイルオープンするとこんな感じ。POSIX pathをfileとして指定できて驚きました。aliasにcastしないとopenできないかと思っていました。

AppleScript名:システム環境設定の「ディスプレイ」>「ディスプレイ」を表示_System Events.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/04/28
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

tell application "System Events"
  open file "/System/Library/PreferencePanes/Displays.prefPane"
end tell

★Click Here to Open This Script 

AppleScript的にいろいろルーチンを整備して汎用性を持たせつつ、十分な機能を用意するとこんな感じでしょうか。

AppleScript名:システム環境設定の「ディスプレイ」>「ディスプレイ」を表示
— Created 2017-10-10 by Takaaki Naganoya
— Created 2020-04-28 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–Get every pane ID
set aList to getEveryPaneID() of me

–Get every anchor in a pane
set pList to getEveryAnchorName("com.apple.preference.displays") of me
–> {"displaysArrangementTab", "displaysNightShiftTab", "displaysColorTab", "displaysGeometryTab", "displaysDisplayTab"}

set aRes to dispSystemPreferences("com.apple.preference.displays", "displaysDisplayTab") of me
–> true

on dispSystemPreferences(paneID, anchorID)
  tell application "System Preferences"
    activate
    
set pList to id of every pane
    
if paneID is not in pList then return false
    
    
set current pane to pane paneID
    
tell current pane
      set nList to name of every anchor
      
if anchorID is not in nList then return false
      
reveal anchor anchorID
    end tell
  end tell
  
  
return true
end dispSystemPreferences

on getEveryPaneID()
  tell application "System Preferences"
    return id of every pane
  end tell
end getEveryPaneID

on getEveryAnchorName(paneID)
  tell application "System Preferences"
    set pList to id of every pane
    
if paneID is not in pList then return false
    
set current pane to pane paneID
    
tell current pane
      return name of every anchor
    end tell
  end tell
end getEveryAnchorName

★Click Here to Open This Script 

Posted in System | Tagged 10.13savvy 10.14savvy 10.15savvy NSWorkspace System Preferences | Leave a comment

ディスプレイのミラーリング表示(sandbox対応)

Posted on 4月 23, 2020 by Takaaki Naganoya

Mac用のオープンソースのディスプレイミラーリング・ツール「mirror-displays」を改変して、Xcode上でコードサインしやすく、かつAppleScriptアプリケーション(Xcode上で記述)から呼び出しやすくしたものです。

ディスプレイのミラーリング表示のOn/Offを行うmirror-displaysを、そのままMac App Storeに申請するアプリケーションの中にバイナリで入れようとしたら、Xcode上のValidate(Mac App Storeにアップロードする前段階の各種妥当性チェック)でひっかかってしまいました。

アプリケーションバンドル中のResourcesフォルダに入れてdo shell scriptで呼ぶという「お気楽」な呼び方が(Code Signの問題で)できなかったわけです。

# コマンドライン・ツールとしてビルドするときにCode Signすればよかったんじゃないか、という話もありますが、いずれ最終的にこの形式にする必要があったので、これでいいんじゃないかと

そこで、コマンドラインから呼び出す形式ではなく、Objective-Cのプログラム「らしい」形式に変更して(ヘッダファイルをゼロから書き起こしました)、AppleScriptから呼び出しやすく変更してみました。配布条件がGPLだったので、ここにmirror-displayまわりのソースと最低限の呼び出し側のAppleScriptアプリケーションのプロジェクトを掲載した次第です。

–> Download Xcode Project’s zip-archive

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— mirrorTest
—
— Created by Takaaki Naganoya on 2020/04/15.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
  
on applicationWillFinishLaunching:aNotification
    — Insert code here to initialize your application before any files are opened
  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:sender
    current application’s mirrorObjC’s alloc()’s init()’s mirror()
  end clicked:
end script

★Click Here to Open This Script 

Posted in Sandbox System | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

Xcode上で作成したアプリケーション上でDark Mode検出

Posted on 4月 22, 2020 by Takaaki Naganoya

Xcode上で作成したAppleScriptアプリケーションでDark Modeの検出を行いたいときに、NSAppearance’s currentAppearance()で取得したら、正しくModeの検出が行えませんでした。同じコードをスクリプトエディタ/Script Debugger上で動かした場合には正しくModeの判定が行えているのですが。

そこで、System Eventsの機能を用いてMode判定を行うように処理を書き換えたりしてみたのですが、Mac App Storeに出すアプリケーションでこの処理を記述していたら、これを理由にリジェクトされてしまいました。

仕方なく解決策を探してみたところ、macOS 10.13用に書いたshell scriptによる迂回処理を、そのまま他のOSバージョンでも動かせばよいのではないかと気づき、結局そこに落ち着きました。

AppleScript名:Dark Modeの検出(Xcode上でも正しく判定)
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/04/22
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set apRes to retLightOrDark() of me
–> true (Dark), false (Light)

on retLightOrDark()
  try
    set sRes to (do shell script "defaults read -g AppleInterfaceStyle")
    
return (sRes = "Dark") as boolean
  on error
    return false
  end try
end retLightOrDark

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

ディスプレイの設定切り替えをAppleScriptでも行えるSwitchResX

Posted on 4月 19, 2020 by Takaaki Naganoya

Cocoaの機能やサードパーティのFrameworkの機能を呼び出して、ディスプレイの回転コントロールを行なったり、解像度の変更を行うなどの制御がAppleScript単体でできるようになってきましたが、ディスプレイの位置関係を定義して変更したいとか凝ったことを言い出すと、さすがにまだまだ市販のツール類を併用したほうが話が早かったりします。

以前からSwitchResX(16USドル)がAppleScriptからコントロールできることを知っていましたが、どの程度のコントロールが行えるかについては調べたことはありませんでした。どのように使えて、どのようにコントロールできて、どのような点に注意すべきなのかを実際に調べてみました。

SwitchResX v4.9.2を実際にためしてみた

SwitchResXの解像度変更機能自体は水準通りだと思います。この手のツールは割といろいろ存在しており、自分はQuickResを利用しています。どちらのツールも画面のオーバースキャン(実解像度よりも大きな解像度の表示)ができます。画面の回転や色数、画面の相対位置の変更、アプリケーションごとに解像度を変更する機能などが本ツールの特徴でしょう。

画面解像度の変更機能について1つ、QuickResを大幅に上回っているものがありました。HiDPI(Retina解像度)の表示サポートです。非Retina解像度のディスプレイであっても、表示ピクセル数を抑えることでHiDPI表示を可能とするもので、表示すること自体にはあまり意味はありませんが、「HiDPI解像度の画面キャプチャが行える」というメリットがあります(非Retina環境でRetina解像度の画面キャプチャが行えるのは、資料作成時にとても便利)。このあたり、Mac miniでちょっと困らされた点でした。

Mac mini 2014(macOS 10.15.4)+HDMI Display(1980x1080)の組み合わせで、OSが標準で提供しているのは960x540解像度におけるHiDPI表示ですが、SwitchResXは1280x800 / 960x600 / 840x525 / 1280x720 / 800x450 などの解像度におけるHiDPI表示もサポートしています。

SwitchResXはメニューバーに常駐して、解像度設定の切り替えが行えるようになっています。設定自体はこのメニューバーから「SwitchResX Preferences…」を選択するか、システム環境設定の「SwitchResX」を選択すると起動される「SwitchResX Control」というGUIアプリケーションから行います。

SwitchResXでは、画面解像度、色(カラー、グレイ)、表示ON/OFF、ミラーリング、メインディスプレイ、画面回転、カラープロファイルなどを設定したディスプレイセットを作成し、このディスプレイセットをメニューやキーボードショートカット、コンテクストメニューから切り替えられるようになっており、その一環としてAppleScriptから同様にディスプレイセットの切り替えが行えるようになっています。

AppleScriptからのコントロール

SwitchResXのAppleScript用語辞書は以下のとおりです。

AppleScriptによるコントロールは「SwitchResX Daemon」という不可視アプリケーションプロセスに対して行うようになっており、基本的には各種ディスプレイの状態を取得(Read Only)することと若干の基本的なコマンドの実行と、ユーザーが定義したディスプレイセットの切り替えを行う、という内容です。

AppleScript側からこまかくディスプレイのIDを指定して個別にグレースケール表示を行わせるといったことはできません。逆に、指定したIDのディスプレイの現在の状況(properties)を取得することはできます。そういう感じです。

けっこう多い注意点

ディスプレイセットを新規作成したあとで、GUI側から明示的に保存(Command-S)を実行しないと、追加したディスプレイセットは認識されませんでした。ここは、たいへんに注意が必要です(なかなか気づきませんでした)。

ディスプレイの回転や位置関係の変更など、込み入った設定変更を行ったディスプレイセットを作成した場合には、それらを元に戻したディスプレイセットを作成しておく必要があります。restore desktopコマンドで元の状態に戻してくれるのかと思っていたのですが、そういうものではないようです。

こういうツールを使おうかと考えているユーザーは複数のディスプレイをMacにつないで使っているはずなので、本ツールで一気に切り替えたあと、戻す設定が定義されていないと手作業で元に戻すというScripterにとってはたいへんに屈辱的な作業を強いられることになります。

ディスプレイセットには、すべての設定項目が同居できるというわけではなく、特定の設定項目のみが単独で切り替えられるというものもあるようなので、この点も注意が必要です(注意点ばっかりやな)。

AppleScriptのプログラム中からSwitchResXの機能を呼び出して画面構成の変更を自由に行えるわけですが、個人的には「そこまでやる必要があるのか?」という印象です。あと、AppleScript用語辞書にサンプルScript掲載しとけとか画面キャプチャのグラフィックを入れておかないとわかりにくいので、そのあたり改善の余地ありといったところでしょうか。他人のアプリケーションについては、山のように不満点や改善点が出てくるものです。

あと、SwitchResXを操作するAppleScriptをどこから呼び出すことになるのか、については少し興味があります。macOS標準搭載のスクリプトメニューから呼び出すのが一番「ありそう」な利用パターンですが、それ単体で呼び出すと「隣り合ったSwitchResXのメニューから呼び出すのとほぼ等価な内容をスクリプトメニューに入れたAppleScriptから呼び出す」という間抜けな状態になります。

まとまった自動処理を行うのに必要な画面設定(速度重視のために画面解像度を極端に落とすとか、メニュー操作が想定外の動きを行わないように特定の解像度に明示的に変更するとか)を行い、処理本体を実行したうえで、後処理で画面設定を元に戻しておく、といったところでしょうか。

AppleScript名:ディスプレイを数えて、プロパティを取得
tell application "SwitchResX Daemon"
  set dCount to count every display
  
–> 2
  
  
repeat with i from 1 to dCount
    properties of display i
    
–> {built in:false, position:{0, 0}, name:"Cinema HD Display", class:display, brightness:-1.0, id:69501836, mirroring:{}, enabled:true, overscan:false, index:1, current mode:mode 1 of display 1 of application "SwitchResX Daemon", orientation:0, underscan:1.0, current depth:32, display profile:profile "Cinema HD Display" of application "SwitchResX Daemon"}
    
    
–> {built in:false, position:{-1920, 0}, name:"Cinema HD", class:display, brightness:-1.0, id:69513479, mirroring:{}, enabled:true, overscan:false, index:2, current mode:mode 1 of display 2 of application "SwitchResX Daemon", orientation:0, underscan:1.0, current depth:32, display profile:profile "Cinema HD" of application "SwitchResX Daemon"}
  end repeat
end tell

★Click Here to Open This Script 


▲display set 2だと2行目の「disp set 2 (90 degree rotation)」が指定される

AppleScript名:display set の切り替え
tell application "SwitchResX Daemon"
  set dSet to display set 2
  
apply dSet
end tell

★Click Here to Open This Script 

Posted in System | Tagged 10.14savvy 10.15savvy SwitchResX | Leave a comment

システムフォントの名称を取得

Posted on 4月 13, 2020 by Takaaki Naganoya

システムフォントの名称を取得するAppleScriptです。

GUIベースのアプリケーションを作っているときに、「もう、無難なフォントなんでもいいからとりあえず指定できるものがあれば指定しておこうよ」という局面はあります。ないフォントを指定するとクラッシュすることもあるので、とりあえずコレ指定しておけば大丈夫だから!

という「安全パイ」のフォントとしてSystem Fontを取得&指定したいという時に書いたScriptでもあります。プログラム内容がつまらない割には、切実なニーズを満たすためのものです。

AppleScript名:システムフォントの名称を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/04/06
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set aFont to current application’s NSFont’s systemFontOfSize:24.0
set aInfo to aFont’s fontDescriptor()
set aSize to (aInfo’s pointSize()) as real
set aPSName to (aInfo’s postscriptName()) as string
–> ".SFNSDisplay"

set bFont to current application’s NSFont’s boldSystemFontOfSize:24.0
set bInfo to bFont’s fontDescriptor()
set bSize to (bInfo’s pointSize()) as real
set bPSName to (bInfo’s postscriptName()) as string
–> ".SFNSDisplay-Bold"

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode Font | Tagged 10.13savvy 10.14savvy 10.15savvy NSFont | Leave a comment

NSFontPanelでフォントを選択

Posted on 4月 7, 2020 by Takaaki Naganoya

自前でメニューを作ってフォントおよびサイズの選択を行おうとするとめんどくさい(時間がかかるし管理も大変)ので、NSFontPanelを用いてフォントを選択する試作品を作ってみました。

ただし、まだ完全ではなく「1つ前の状態が取得できる」という状態なので、修正が必要です。作成はmacOS 10.14.6+Xcode 11.3.1上で行っています。

–> Download Xcode Project

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— fontPanel
—
— Created by Takaaki Naganoya on 2020/03/12.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property theField : missing value
  
  
property aFontNameField : missing value
  
property aFontSizeField : missing value
  
  
property aFontManager : missing value
  
  
property font : missing value
  
property aFP : missing value
  
  
on applicationWillFinishLaunching:aNotification
    set aFontManager to current application’s NSFontManager’s sharedFontManager()
    
aFontManager’s setAction:"appSpecificChangeFont:"
    
set aFP to current application’s NSFontPanel’s sharedFontPanel()
    
set aFont to current application’s NSFont’s fontWithName:"Helvetica" |size|:16
    
aFontManager’s setSelectedFont:aFont isMultiple:false
    
    
theField’s setStringValue:"ぴよまるソフトウエア, Piyomaru Software"
  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
    theWindow’s makeFirstResponder:theField
    
aFP’s makeKeyAndOrderFront:me
  end clicked:
  
  
on appSpecificChangeFont:sender
    set aSelFont to sender’s selectedFont()
    
set aDesc to aSelFont’s fontDescriptor()
    
set aPSID to (aDesc’s postscriptName()) as string
    
set aSize to (aDesc’s pointSize()) as real
    
theField’s setFont:aSelFont
    
aFontNameField’s setStringValue:aPSID
    
aFontSizeField’s setStringValue:(aSize as string)
  end appSpecificChangeFont:
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode Font | Tagged 10.13savvy 10.14savvy 10.15savvy NSFont NSFontManager NSFontPanel | 1 Comment

マウスカーソルを変更

Posted on 3月 24, 2020 by Takaaki Naganoya

Xcode上で記述するAppleScriptアプリケーションにおいて、マウスカーソルを変更するAppleScriptです。

NSCursorにアクセスして、macOS側で用意しているカーソルにマウスカーソルのイメージを変更します。

–> Watch Demo Movie

あらかじめmacOSが用意しているカーソルはいくつかあるわけですが、これで満足するわけがなくて……任意のNSImageをカーソルに指定する方法について調べていたものの、なかなかうまくいかなかったので、このOS側で用意しているカーソルへの切り替えのみまとめておきました。

–> Download Xcode Project

他のアプリケーションに切り替えると通常のカーソルに戻ってしまうので、本プロジェクト側でアプリケーション切り替えのイベントハンドラでカーソルの再変更などを行うべきなのかも。

  set aImage to current application's NSImage's  imageNamed:(current application's NSImageNameComputer)
  set tmpCursor to current application's NSCursor's alloc()'s initWithImage:aImage hotSpot:{0,15}
tmpCursor's |set|()

結局、コンピュータのアイコンをマウスカーソルに指定するというところまでは持って行けた(カーソル画像の差し替えができた)わけなんですが、NSCursorの挙動を評価してみたら、カーソルが標準のものに戻るタイミングがバラバラ(他のディスプレイにカーソルが移動したとき、というわけでもない)で、挙動が謎すぎであります。

その後、対象のビュー(NSViewなど、その派生クラス)にマウスカーソルが入った/出たことを検出するイベントハンドラでマウスカーソルの形状変更を明示的に指定するような実装で落ち着きました(Edama2さんから教えていただきました。ありがとうございます)。

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— CursorTest
—
— Created by Takaaki Naganoya on 2020/03/24.
— Copyright © 2020 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
  
on applicationWillFinishLaunching:aNotification
    — Insert code here to initialize your application before any files are opened
  end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    — Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNoww
  end applicationShouldTerminate:
  
  
on clicked:aSender
    set aTag to (aSender’s tag) as integer
    
if aTag = 100 then
      current application’s NSCursor’s arrowCursor()’s |set|()
    else if aTag = 101 then
      current application’s NSCursor’s disappearingItemCursor()’s |set|()
    else if aTag = 102 then
      current application’s NSCursor’s contextualMenuCursor()’s |set|()
    else if aTag = 103 then
      current application’s NSCursor’s openHandCursor()’s |set|()
    end if
  end clicked:
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode System | Tagged 10.13savvy 10.14savvy 10.15savvy NSCursor NSImage | Leave a comment

mirroringの設定と解除

Posted on 3月 11, 2020 by Takaaki Naganoya

自分はディスプレイのミラーリング機能は日常的にあまり使っていません。実際にやってみたらどうだったのかをまとめてみました。

この手の処理をAppleScriptで書こうとしても、そのための命令が標準で内蔵されていないため、アプローチの方法はかぎられています。

 (1)思いっきりハードウェア寄りのプログラム(Cとかで書いた)を呼び出す
 (2)アクセシビリティ系の機能(GUI Scripting)を使ってシステム環境設定を操作する

の2つです。(2)は、画面上の要素の些細な変更によりプログラムを書き換える必要が出てくるうえに、信頼性が高くないので、あまりやりたくありません。もちろん、画面上の要素を検索しながら処理する方法もあるわけですが、それなりに(画面要素の検索に)時間がかかります。

そうなると、(1)を採用することになります。探すと………すぐにみつかりました。「mirror-displays」というコマンドラインアプリケーションです。ソースコードを読んでみると、CoreGraphics系の各種フレームワークを呼び出している、Objective-Cで書かれた(ほとんどCのコード)プログラムです。

これをスクリプトバンドルの中に入れて呼び出してみました。1回実行するとメインモニタの内容が他のモニタにミラーリングされます。もう1回実行すると、ミラーリングが解除されます。

–> Download mirroring_toggle (Script Bundle with executable command in its bundle)

mirrorコマンドのオプションには、「どのモニタをミラーリングさせるか」といった指定ができるようですが、試していないのでとくに凝った指定も何もしていません。

mirrorコマンドはmacOS 10.14でビルドして10.10以降をターゲットにしてみましたが、そこまで古い環境は手元に残っていないのでテストしていません。また、macOS 10.15のマシンには複数台のモニタをつないでいないので、macOS 10.15上でのテストも行っていません。

AppleScript名:mirroringの設定と解除
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/03/11
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

–https://github.com/hydra/mirror-displays
–バンドルの中に入れたmirrorコマンドをただ呼んでるだけ
set myPath to POSIX path of (path to me)
set comPath to myPath & "/Contents/Resources/mirror"
do shell script quoted form of comPath

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

ServerInformationで製品情報を取得

Posted on 3月 9, 2020 by Takaaki Naganoya

AppleのPrivate Frameworkである「ServerInformation.framework」を呼び出すAppleScriptです。

AppStoreを通じて配布するアプリケーションではPrivate Frameworkの使用は問題になる可能性がありますが、ユーザーの手元で動かしているAppleScriptでPrivate Frameworkを煮ようが焼こうが関係ないと思います。

「ServerInformation.framework」は割と利用価値が高そうなものであります。実際にGithub上で探したサンプルをAppleScriptに翻訳して試してみました。

本サンプルは、/System/Library/PrivateFrameworks/という、ふだんFrameworkを呼び出す先「ではない」ディレクトリに入っているFrameworkを呼び出すサンプルでもあり、NSBundleを通じてFrameworkを呼び出す実例でもあります。

この方法を利用すれば、最新のmacOSで(SIPを解除しないで)そのままでは呼び出せなくなっていたホームディレクトリ下のFrameworkとかアプレット内に同梱したFrameworkをローディングして呼び出すことができそうな雰囲気があります。

AppleScript名:ServerInformationで製品情報を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/03/09
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
— https://gist.github.com/erikng/d90d21f502351d64a541600226626a28

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

set ServerInformation to current application’s NSBundle’s bundleWithPath:"/System/Library/PrivateFrameworks/ServerInformation.framework"
set ServerCompatibility to current application’s NSBundle’s bundleWithPath:"/System/Library/PrivateFrameworks/ServerCompatibility.framework"

set ServerInformationComputerModelInfo to ServerInformation’s classNamed:"ServerInformationComputerModelInfo"
set SVCSystemInfo to ServerCompatibility’s classNamed:"SVCSystemInfo"

set myInfo to SVCSystemInfo’s currentSystemInfo()

set exInfo to (ServerInformationComputerModelInfo’s attributesForModelIdentifier:(myInfo’s computerModelIdentifier())) as record

set anArchitecture to exInfo’s architecture
–> "x86_64"

set aMonoImageSel to exInfo’s monochromeSelectedHardwareImage
–> NSImage (Gray)

set aMonoImage to exInfo’s monochromeHardwareImage
–> NSImage (Gray)

set aDesc to exInfo’s |description|
–> "15インチMacBook Pro Retinaディスプレイを装備、デュアルコアIntel Core i7プロセッサ搭載(アルミニウムユニボディ)、2012年の中期に投入。"
–> "Mac mini Intelデュアルコアプロセッサおよび統合型グラフィックス搭載、2014年後期に投入。"
–> "MacBook Air 11インチディスプレイを装備、2011年の中期に投入。"

set aModel to exInfo’s model
–> "MacBook Pro"
–> "Mac mini"
–> "MacBook Air"

set aProcessor to exInfo’s processor
–> "Intel Core i7"
–> "デュアルコアIntel Core i5、デュアルコアIntel Core i7"
–> "Dual-Core Intel Core i5、Intel Core i7"

set aMarketModel to exInfo’s marketingModel
–> "15インチMacBook Pro, Retinaディスプレイ, Intel Core i7 (Mid 2012)"
–> "Mac mini(Late 2014)"
–> "11インチMacBook Air(Mid 2011)"

set aColorImage to exInfo’s hardwareImage
–> NSImage (Color)

★Click Here to Open This Script 

Posted in System | Tagged 10.14savvy 10.15savvy | Leave a comment

使用中のMacの製品呼称を取得する v4

Posted on 3月 8, 2020 by Takaaki Naganoya

使用中のMacの製品呼称を取得するAppleScriptです。

ながらく、この手のルーチンを使い続けてきましたが、macOS 10.15でエラーが出るようになりました。

理由を確認してみたところ、パス名の一部がmacOS 10.15で変更になっていることがわかりました。

目下、Xcode上でアプリケーションを作成すると、ローカライズしたリソースのフォルダについては、「English.lproj」ではなく「en.lproj」と、言語コードが用いられるようになってきました。この、「English」と「en」の変更がOS内部のコンポーネントについても行われた「だけ」というのが理由のようです。

ちなみに、パス名を無意味に途中で切ってつなげているのは、Blog(HTML)やMarkDownのドキュメントに入れたときに、折り返しされずにレンダリング品質を下げる原因になる(行がそこだけ伸びるとか、ページ全体の文字サイズが強制的に小さくなるとか)ためです。

AppleScript名:使用中のMacの製品呼称を取得する v4.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/03/08
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set myInfo to retModelInfo() of me
–> "Mac mini (Late 2014)"

on retModelInfo()
  set v2 to system attribute "sys2"
  
— macOS 10.15.3 –> 15
  
  
if v2 < 15 then
    –macOS 10.14まで
    
set pListPath to "/System/Library/PrivateFrameworks/ServerInformation.framework/" & "Versions/A/Resources/English.lproj/SIMachineAttributes.plist"
  else
    –macOS 10.15以降
    
set pListPath to "/System/Library/PrivateFrameworks/ServerInformation.framework/" & "Versions/A/Resources/en.lproj/SIMachineAttributes.plist"
  end if
  
  
set aRec to retDictFromPlist(pListPath) of me
  
set hwName to (do shell script "sysctl -n hw.model")
  
–>  "Macmini7,1"
  
  
set aMachineRec to retRecordByLabel(aRec, hwName) of me
  
  
set aMachineRec2 to contents of first item of aMachineRec
  
return (marketingModel of _LOCALIZABLE_ of aMachineRec2)
end retModelInfo

on retDictFromPlist(aPath)
  set thePath to current application’s NSString’s stringWithString:aPath
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theDict to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
  
return theDict as record
end retDictFromPlist

on retRecordByLabel(aRec as record, aKey as string)
  set aDic to current application’s NSDictionary’s dictionaryWithDictionary:aRec
  
set aVal to aDic’s valueForKey:aKey
  
return aVal as list
end retRecordByLabel

on retRecordByKeyPath(aRec as record, aKey as string)
  set aDic to current application’s NSDictionary’s dictionaryWithDictionary:aRec
  
set aVal to aDic’s valueForKeyPath:aKey
  
return aVal
end retRecordByKeyPath

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.15savvy NSDictionary NSString | Leave a comment

Post navigation

  • Older posts

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

Google Search

Popular Posts

  • 画面上の指定座標にマウスカーソルを強制移動させてクリック
  • Numbersで選択範囲のセルのデータを取得して重複データを抽出
  • フルパスからファイル名を取得する
  • 【基礎】AppleScriptの実行を(操作により)中断する
  • macOS 11.0, Big Sur AppleScript関連の変更点
  • フォルダの存在確認
  • 指定した文字で囲まれたキーワードの色を置換する
  • AppleScriptでキースキャン
  • 文字列の長さを求める
  • mouseClickを用いて指定座標をクリック
  • CSVデータを読み込んで表インタフェースで表示確認 v2
  • DSCaptureで画面キャプチャ
  • アラートダイアログの背景色を指定してTable Viewを表示
  • AVFAudioでオーディオ再生のじっけん
  • 文字種類変換(ASOC)
  • ディスプレイを回転させる
  • Dynamic Menu Clicker
  • 指定フォルダ以下のすべてのファイルとフォルダ名から絵文字を除去する v2
  • SMCkitで各種センサー値を取得する
  • macOS 10.14で新設されたエラーコード-1743を確認する

Tags

10.11savvy (1109) 10.12savvy (1249) 10.13savvy (1387) 10.14savvy (512) 10.15savvy (303) 11.0savvy (112) CotEditor (48) Finder (43) iTunes (25) Keynote (61) NSAlert (59) NSAlertSecondButtonReturn (16) NSArray (50) NSBitmapImageRep (20) NSBundle (19) NSButton (33) NSColor (48) NSDictionary (26) NSFileManager (23) NSFont (18) NSImage (40) NSJSONSerialization (21) NSMutableArray (61) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (55) NSScreen (30) NSScrollView (22) NSString (114) NSURL (93) NSURLRequest (22) NSUTF8StringEncoding (30) NSUUID (18) NSView (33) NSWindow (17) NSWorkspace (19) Numbers (42) Pages (16) Safari (34) System Events (16) WKUserContentController (20) WKUserScript (19) WKUserScriptInjectionTimeAtDocumentEnd (17) WKWebView (21) WKWebViewConfiguration (21)

カテゴリー

  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Bluetooth
  • boolean
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • History
  • How To
  • Icon
  • Image
  • Input Method
  • Internet
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Language
  • list
  • Locale
  • Machine Learning
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • shell script
  • 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)
  • 未分類

アーカイブ

  • 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
Proudly powered by WordPress
Theme: Flint by Star Verte LLC