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

カテゴリー: GUI

display YouTube Script Library

Posted on 8月 25, 2019 by Takaaki Naganoya

アラートダイアログ上で指定URLのYouTubeムービーを再生表示するAppleScriptライブラリ+呼び出しサンプルです。

用途はお察しですが、あまり実用性をねらったものではありません。

–> Download display youtube.scptd (To ~/Library/Script Libraries/)

この、「display youtube」という用語が微妙にGoogleの商標を侵害していそうなので、用語辞書内で説明して逃げを打っていますがどんなもんでしょうか。

display youtubeコマンドにURLを指定すると、

https://www.youtube.com/watch?v=XXXXXXXX

という表記のURLを、ライブラリ内部で、

https://www.youtube.com/embed/XXXXXXXX

と書き換えて表示しています。また、組み込み再生用のオプションと、高解像度表示用のオプションを追加で指定しています。

AppleScript名:display youtube sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use utbLib : script "display youtube"

set aURL to "https://www.youtube.com/watch?v=GP_tVXTYdmY"
display youtube main message "Replay Movie" sub message "My Senjo No Kizuna replay movie on YouTube" with URL aURL with size {600, 400}

set bURL to "https://www.youtube.com/embed/GP_tVXTYdmY"
display youtube main message "Replay Movie" sub message "My Senjo No Kizuna replay movie on YouTube" with URL bURL with size {900, 600}

★Click Here to Open This Script 

Posted in dialog GUI OSA sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | 1 Comment

display location Script Library

Posted on 8月 25, 2019 by Takaaki Naganoya

指定の緯度・経度情報の場所を4つの異なる表示倍率の地図でダイアログ表示するAppleScriptライブラリ+呼び出しサンプルです。

–> Download display location.scptd (To ~/Library/Script Libraries/)

サンプルScriptでは、指定のIPアドレスの位置情報をipinfo.io上で調べて表示しています。

本ライブラリは、掲載サンプルのように「display multiple map」コマンドを提供するもので、地図.appに頼らずにAppleScriptだけで簡単な地図表示UIを利用できるようにします。

AppleScript名:display location sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions
use dispLoc : script "display location"

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set anIP to "193.228.57.200"
set locList to getGeoLocationByIPinfo(anIP) of me

display multiple map main message "侵略場所の表示" sub message "今回の地球侵略の目的地は、地球上の以下の場所になります" with location locList with size {900, 600}

–http://ipinfo.io/developers
on getGeoLocationByIPinfo(myIP)
  set aURL to "http://ipinfo.io/" & myIP
  
set aRes to callRestGETAPIAndParseResults(aURL, 10) of me
  
  
if aRes = missing value then
    error "Network Error"
  end if
  
set aInfo to loc of aRes
  
set aPos to offset of "," in aInfo
  
set aLatitude to text 1 thru (aPos – 1) of aInfo
  
set aLongitude to text (aPos + 1) thru -1 of aInfo
  
  
return {aLatitude, aLongitude}
end getGeoLocationByIPinfo

on callRestGETAPIAndParseResults(reqURLStr as string, timeoutSec as integer)
  set tmpData to (do shell script "curl -X GET \"" & reqURLStr & "\"")
  
set jsonString to NSString’s stringWithString:tmpData
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
if aJsonDict = missing value then return false
  
return (aJsonDict as record)
end callRestGETAPIAndParseResults

★Click Here to Open This Script 

Posted in geolocation GUI JSON Network sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

choose multiple path Script Library

Posted on 8月 25, 2019 by Takaaki Naganoya

NSPathControlで複数のファイルパス入力ダイアログを表示して選択パスを受け付けるAppleScript Librariesです。

–> Download choosePathLib.scptd(~/Library/Script Libraries)

AppleScript名:choose path のサンプル
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/24
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use choosePath : script "choosePathLib"

set mesList to {"移動元1", "移動先1", "移動元2", "移動先2"}
set defaultLocList to {"~/Movies", "~/Desktop", "~/Documents", "~/Library"}

set cRes to choose multiple path main message ¬
  "メインメッセージ" sub message ¬
  
"サブメッセージ" with titles mesList ¬
  
with default locations defaultLocList

–> {alias "Macintosh HD:Users:me:Desktop:mathfuncs.png", alias "Macintosh HD:Users:me 1:Desktop:PDF Page composer test.scpt", alias "Macintosh HD:Users:me:Desktop:dTEST.pdf", alias "Macintosh HD:Users:me:Desktop:aTEST2.pdf"}

★Click Here to Open This Script 

Posted in dialog File path GUI | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

displayTextView Script Library

Posted on 8月 24, 2019 by Takaaki Naganoya

テキストビューでテキストを表示するAppleScriptライブラリです。

–> Download displayTextView.scptd (To ~/Library/Script Libraries)

表示するテキスト、フォント名、サイズ、テキストビューの幅と高さを指定してアラートダイアログで表示を行います。ただそれだけです。

AppleScript名:display text view library sample AppleScript
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/24
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use radioLib : script "displayTextView"

set aStr to do shell script "cal 2019"

display text view aStr main message "Main Message" sub message "Sub Message" with properties {font name:"Courier", size:13, width:600, height:600}

★Click Here to Open This Script 

Posted in GUI OSA sdef | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

checkboxで項目選択するありふれたScriptにsdefをつけてみる

Posted on 8月 12, 2019 by Takaaki Naganoya

アラートダイアログにcheckboxを表示して、項目選択するAppleScriptにsdef(AppleScript用語辞書)をつけてみました。

内容は、先日書いた「アラートダイアログ上にcheckboxを表示 v2」そのものです。この手のScriptは、機能の割に行数が多くて、そんなに難しくない(単にCocoaの仕様にもとづいて書いているだけ)んですが、コード量が多いことで難しそうに見えてしまうとしたら残念です。sdefをつけて英語っぽい記法で簡潔に呼び出せると有用性がどのぐらい増すのか実験してみました。

–> Download checkboxLib.scptd(with sdef)

Step 1:普通に動作するAppleScriptをバンドル形式で保存

アラートダイアログ上にcheckboxを表示 v2が動作しているのを確認します。また、フラットな(バンドルではない)AppleScript(拡張子:.scpt)の場合には、バンドルScript(拡張子:.scptd)に変換します。

また、この際にバンドルIDをきっちり設定しましょう。

Step 2:sdefファイルを作成する

テキストエディタでsdefファイルを書いてみましょう。他のAppleScript対応アプリケーションのsdefファイルを参考にします。構文色分け機能のあるテキストエディタの場合(CotEditorなど)、XMLを指定しておくと色分けされるので間違いが少なくなることでしょう。

こんな感じに書いてみました。コマンド1つに、パラメータが4つ。sdefファイルを書いて、AppleScriptバンドル内(/Contents/Resources フォルダ)にコピーし、スクリプトエディタ上やScript Debugger上でsdefの名称(拡張子は省略)を「スクリプティング定義」の欄に記載します(textを「(text)」と書いていますが、「text」と書くのが正しいので念のため)。

このような変更を行った場合には、保存してスクリプトエディタ/Script Debuggerをいったん終了させると間違いがなくていい感じです。

Step 3:sdefに記述した予約語でハンドラを記述する


sdefファイルに記載した予約語がAppleScriptライブラリ内ですぐに使用できるようになります。ただし、呼び出し部分にだけ使うようにしないと、メンテナンス性が下がりまくる(作者以外誰も読めなくなる)ので注意が必要です。ライブラリ本体の機能をライブラリのsdefで定義した予約語を使いまくって、作者以外誰もメンテナンスできない状態になっているライブラリの実例がこちらで確認できます(applescript-stdlib)。

これで、sdefに記載した予約語を使ってScriptを呼び出せるようになりました。エラーになるようなら、いったんスクリプトエディタ/Script Debuggerを終了させるとよいでしょう(sdefが不完全な場合もありますが)。

— Created 2019-08-12 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use checkLib : script "checkboxLib"

set tList to {"にんじん", "ごぼう", "だいこん", "りんご", "キャベツ", "レタス", "じゃがいも", "にんじん", "小松菜", "青梗菜", "しいたけ", "舞茸"}

set cRes to choose checkbox main message "項目選択" sub message "適切なものを以下からえらんでください" with columns 2 with titles tList

★Click Here to Open This Script 

Step 4:パラメータ省略時に対応できるようにハンドラを書き換え

ただ、これだけだと「毎回パラメータをすべて指定しないと動かない」という間抜けライブラリになってしまいます。

そこで、パラメータの型宣言+省略時パラメータの指定を行えば省略に対応できます。パラメータ指定部はすべて省略指定に対応できるように書いておきましょう。

こんなところでしょうか。パラメータのうち必須でないものの省略を許容するためには、sdefでoptionalの指定を行うことも必要です。

この手の「1回書いたらあんまり書き換えないし、使い回しするにはコード量が多くてめんどくさい」処理については、sdefをつけたライブラリにしておくといいのかもしれません。全部が全部、すべてそういう形式にするわけにもいきませんが、自分で予約語を拡張できるようになっているので、使ってみるとよいでしょう。

この段階になって、ライブラリ>Script Library(~/Library/Script Libraries)フォルダに入れてスクリプトの書き換えなどを行っていると、前回書き換えた内容が再オープン時に反映されないといった現象が発生することがあります。書き換えた、保存したはずなのに元に戻っているというのは、ライブラリのキャッシュを別途行っているためということだと理解しました。

なので、ライブラリの書き換えを行うさいには、テキスト形式などで別途ソースを保存しておくことを強くおすすめします。ここだけ、怪奇現象っぽい挙動に直面するところですが、焦らず慌てず作業すれば「単なる作業」なので、難しくありません。

AppleScript名:check box sample 2
— Created 2019-08-12 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use checkLib : script "checkboxLib"

set tList to {"にんじん", "ごぼう", "だいこん", "りんご", "キャベツ", "レタス", "じゃがいも", "にんじん", "小松菜", "青梗菜", "しいたけ", "舞茸"}

set cRes to choose checkbox main message "項目選択" sub message "適切なものを以下からえらんでください" with columns 2 with titles tList
set cRes to choose checkbox main message "項目選択" sub message "適切なものを以下からえらんでください" with titles tList
set cRes to choose checkbox main message "項目選択" with titles tList
set cRes to choose checkbox with titles tList
set cRes to choose checkbox

★Click Here to Open This Script 

Posted in dialog GUI sdef | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

アラートダイアログ上にcheckboxを表示 v2

Posted on 8月 11, 2019 by Takaaki Naganoya

アラートダイアログ上にチェックボックスで選択肢の入力を求めるAppleScriptです。


▲macOS 10.14上のLight Mode(Left)、Dark Mode(Right)

ラジオボタンで項目選択を行うのと同じぐらい、チェックボックスで項目選択を行うのは「よくある処理」です。ただ、それだけのためにXcode上でAppleScriptのプログラムを作るのは大袈裟なのと、できることはなるべく普通のAppleScript(Xcode上ではない)のランタイム環境上でできたほうがよいとの考えから、こうして箱庭UIをちまちま作っているものです。

本AppleScriptは、スクリプトエディタ上、スクリプトメニュー、AppleScriptアプレット、Script Debugger上などのランタイム環境で動作します。他のAppleScriptのバンドル中に入れてAppleScript Librariesとして呼び出して使うことを前提に整備してあります。

チェックした項目の番号がリストで返ってきます。各項目番号は1始まり(1-based index)です。


▲「?」ボタン(Help Button)をクリックすると、すべてのチェックボックスをオン/オフにするかを指定できる(ないと不便そうだったので)

ボタンのタイプはいくつか変更して試していますが、このあたりは最近のOSアップデートでいろいろ変更が加わっており、実際に指定しても有意な結果が得られない(なんで存在するのかよくわからない)ものもあり、実際に指定して試してみることをおすすめします。

本Scriptにはいくつか制約事項があります。選択肢の個数が奇数の場合にうやむやにする処理はつけていません。また、選択肢の文字数が長い場合への対処も一切していません。このあたりは真面目にプログラムを組む際には問題になってくることでしょう。


▲NSButtonTypeOnOff


▲NSButtonTypePushOnPushOff


▲NSButtonTypeRadio


▲NSButtonTypeSwitch


▲NSButtonTypeToggle(クリックすると遅れてステートが変化する。なにこれ?)

実際には、ライブラリ化してこんな風に呼び出して使うことを想定しています。

— Created 2019-08-07 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use checkLib : script "checkboxLib"

set paramObj to {myMessage:"Select target Item", mySubMessage:"適切なものを以下からえらんでください", mySuppression:"", myColNum:2, matrixTitleList:{"にんじん", "ごぼう", "だいこん", "りんご", "キャベツ", "レタス", "じゃがいも", "にんじん", "小松菜", "青梗菜", "しいたけ", "舞茸"}}
set aRes to dispCheckBoxMain(paramObj) of checkLib
–> {1, 2}

★Click Here to Open This Script 

AppleScript名:アラートダイアログ上にcheckboxを表示 v2
— Created 2019-08-07 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSButton : a reference to current application’s NSButton
property NSOnState : a reference to current application’s NSOnState
property NSOffState : a reference to current application’s NSOffState
property NSMutableArray : a reference to current application’s NSMutableArray
property NSButtonTypeSwitch : a reference to current application’s NSButtonTypeSwitch
property NSRunningApplication : a reference to current application’s NSRunningApplication

property theResult : 0
property returnCode : 0
property bArray : {} –Checkbox button object array

on run
  set paramObj to {myMessage:"Select target Item", mySubMessage:"適切なものを以下からえらんでください", mySuppression:"", myColNum:2, matrixTitleList:{"にんじん", "ごぼう", "だいこん", "りんご", "キャベツ", "レタス", "じゃがいも", "にんじん", "小松菜", "青梗菜", "しいたけ", "舞茸"}}
  
  
–my chooseItemByCheckBox:paramObj –for Debugging
  
my performSelectorOnMainThread:"chooseItemByCheckBox:" withObject:(paramObj) waitUntilDone:true
  
return my sort1DNumList:theResult ascOrder:true
  
–> {1, 3, 5, 7, 9, 11}
end run

on chooseItemByCheckBox:(paramObj)
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aMatList to (matrixTitleList of paramObj) as list
  
set aLen to length of aMatList
  
set aSupMes to mySuppression of paramObj
  
  
set colNum to (myColNum of paramObj) as integer
  
set rowNum to (aLen div colNum) + (aLen mod colNum)
  
  
set aButtonCellWidth to 150
  
set aButtonCellHeight to 24
  
  
set viewWidth to aButtonCellWidth * colNum
  
set viewHeight to aButtonCellHeight * rowNum
  
  
–define the matrix size where you’ll put the radio buttons
  
set matrixRect to current application’s NSMakeRect(0.0, 0.0, viewWidth, viewHeight)
  
set aView to NSView’s alloc()’s initWithFrame:(matrixRect)
  
  
set aCount to 1
  
set bArray to current application’s NSMutableArray’s new()
  
repeat with y from 1 to rowNum
    repeat with x from 1 to colNum
      if aCount ≤ aLen then
        set j to contents of item aCount of aMatList
        
set tmpB to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(((x – 1) * aButtonCellWidth), ((aLen – aCount) div colNum) * aButtonCellHeight, aButtonCellWidth, aButtonCellHeight)))
        
        (
tmpB’s setTitle:j)
        (
tmpB’s setShowsBorderOnlyWhileMouseInside:true)
        (
tmpB’s setTag:(aCount))
        (
tmpB’s setTarget:me)
        (
tmpB’s setAction:("clicked:"))
        (
tmpB’s setButtonType:(NSButtonTypeSwitch))
        
        (
bArray’s addObject:tmpB)
        
      end if
      
      
set aCount to aCount + 1
    end repeat
  end repeat
  
  
–Select the first radio button item
  
–(tmpArray’s objectAtIndex:0)’s setState:(current application’s NSOnState)
  
set theResult to {}
  
  (
aView’s setSubviews:bArray)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
    
    
–for suppression check box ( No use for this case? )
    
if (aSupMes as string) is not equal to "" then
      its setShowsSuppressionButton:(true) –「今後このメッセージを表示しない」チェックボックスを表示
      
set suppressionB to its suppressionButton
      
suppressionB’s setTitle:(aSupMes)
    else
      its setShowsSuppressionButton:(false)
    end if
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set theResult to (tmpArray’s valueForKeyPath:"status") as list
end chooseItemByCheckBox:

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

on clicked:aParam
  set aTag to (tag of aParam) as integer
  
if aTag is not in (theResult as list) then
    set the end of theResult to aTag
  else
    set theResult to my deleteItem:aTag fromList:theResult
  end if
end clicked:

on deleteItem:anItem fromList:theList
  set theArray to NSMutableArray’s arrayWithArray:theList
  
theArray’s removeObject:anItem
  
return theArray as list
end deleteItem:fromList:

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

–Help Button Clicked Event Handler
on alertShowHelp:aNotification
  set aRes to display dialog "Do you change all checkbox state?" buttons {"All Off", "All On", "Cancel"} default button 3 with icon 1
  
set bRes to (button returned of aRes) as string
  
  
if bRes = "All Off" then
    set bLen to bArray’s |count|()
    
set theResult to {}
    
repeat with i from 0 to bLen
      ((bArray’s objectAtIndex:i)’s setState:(current application’s NSOffState))
    end repeat
    
  else if bRes = "All On" then
    set bLen to bArray’s |count|()
    
set theResult to {}
    
repeat with i from 0 to bLen
      ((bArray’s objectAtIndex:i)’s setState:(current application’s NSOnState))
      
set the end of theResult to i + 1
    end repeat
  end if
  
  
return false –trueを返すと親ウィンドウ(アラートダイアログ)がクローズする
end alertShowHelp:

★Click Here to Open This Script 

Posted in GUI list | Tagged 10.12savvy 10.13savvy 10.14savvy NSAlert NSButton NSButtonTypeSwitch NSMutableArray NSOffState NSOnState NSRunningApplication NSView | 1 Comment

アラートダイアログ上にRadio Buttonを表示 v4a

Posted on 8月 7, 2019 by Takaaki Naganoya

アラートダイアログ上にRadio Buttonを表示して項目選択するAppleScriptです。

普通にラジオボタンで項目選択できるようになりました。

表示列数を指定できるようにしておきましたが、選択項目の余りが発生すると処理に矛盾が発生するため、キリのいい(割り切れる)列数を指定してください(短時間で作った試作品なので、そこまで気合は入れていません)。

AppleScript名:アラートダイアログ上にRadio Buttonを表示 v4a
— Created 2019-08-07 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSButton : a reference to current application’s NSButton
property NSRadioButton : a reference to current application’s NSRadioButton
property NSButtonTypeRadio : a reference to current application’s NSButtonTypeRadio
property NSRunningApplication : a reference to current application’s NSRunningApplication

property theResult : 0
property returnCode : 0

set paramObj to {myMessage:"Select target Item", mySubMessage:"適切なものを以下からえらんでください", myColNum:2, matrixTitleList:{"にんじん", "ごぼう", "だいこん", "りんご", "キャベツ", "レタス", "じゃがいも", "にんじん", "小松菜", "青梗菜", "しいたけ", "舞茸"}}

–my chooseItemByRadioButton:paramObj –for Debugging
my performSelectorOnMainThread:"chooseItemByRadioButton:" withObject:(paramObj) waitUntilDone:true
return (theResult as integer)

on chooseItemByRadioButton:(paramObj)
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aMatList to (matrixTitleList of paramObj) as list
  
set aLen to length of aMatList
  
  
set colNum to (myColNum of paramObj) as integer
  
set rowNum to (aLen div colNum) + (aLen mod colNum)
  
  
set aButtonCellWidth to 150
  
set aButtonCellHeight to 24
  
  
set viewWidth to aButtonCellWidth * colNum
  
set viewHeight to aButtonCellHeight * rowNum
  
  
–define the matrix size where you’ll put the radio buttons
  
set matrixRect to current application’s NSMakeRect(0.0, 0.0, viewWidth, viewHeight)
  
set aView to NSView’s alloc()’s initWithFrame:(matrixRect)
  
  
set aCount to 1
  
set tmpArray to current application’s NSMutableArray’s new()
  
repeat with y from 1 to rowNum
    repeat with x from 1 to colNum
      if aCount ≤ aLen then
        set j to contents of item aCount of aMatList
        
set tmpB to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(((x – 1) * aButtonCellWidth), ((aLen – aCount) div colNum) * aButtonCellHeight, aButtonCellWidth, aButtonCellHeight)))
        
        (
tmpB’s setTitle:j)
        (
tmpB’s setShowsBorderOnlyWhileMouseInside:true)
        (
tmpB’s setTag:(aCount))
        (
tmpB’s setTarget:me)
        (
tmpB’s setAction:("clicked:"))
        (
tmpB’s setButtonType:(current application’s NSButtonTypeRadio))
        
        (
tmpArray’s addObject:tmpB)
        
      end if
      
      
set aCount to aCount + 1
    end repeat
  end repeat
  
  
–Select the first radio button item
  (
tmpArray’s objectAtIndex:0)’s setState:(current application’s NSOnState)
  
set theResult to 1
  
  (
aView’s setSubviews:tmpArray)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
end chooseItemByRadioButton:

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

on clicked:aParam
  set aTag to tag of aParam
  
set theResult to aTag
end clicked:

★Click Here to Open This Script 

Posted in dialog GUI list | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSButtonTypeRadio NSRadioButton NSRunningApplication NSView | Leave a comment

アラートダイアログ上にRadio Buttonを表示 v3

Posted on 8月 7, 2019 by Takaaki Naganoya

アラートダイアログ上にラジオボタン的なUIを表示して選択するAppleScriptです。

–> Downdload calImageDialog (with Library within its bundle)

本当はRadio Button的なものを作りたかったのですが、NSMatrixがmacOS 10.8で非推奨というか事実上の廃止になったことを受けて、Radio Button的なものを作ってみたのですが、割と中途半端です(見た目はスゲーいいのに)。


▲macOS 10.14+Script Editor上の動き


▲macOS 10.14+Script Debugger上の動き

一応、ボタンの画像に1月分のカレンダー画像を割り当てており、機能と見た目のバランスを取ろうとしたのですが、Radio Buttonっぽい動きにはなっていません(残念!)。

あと、1年分のカレンダー画像を作成するのに不思議なぐらい時間がかかっています。

あんな素朴なcalコマンドにmacOS 10.13から当日のハイライト表示を消すための「-h」オプションが追加されていたとは、気づきませんでした。10.14で作って10.12上で動かなかったのでcalコマンドのオプションを条件分岐で変更するように初版から修正しました。

AppleScript名:アラートダイアログ上にRadio Buttonを表示 v3
— Created 2019-08-07 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use calImage : script "calImageKit"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSMatrix : a reference to current application’s NSMatrix
property NSButton : a reference to current application’s NSButton
property NSButtonCell : a reference to current application’s NSButtonCell
property NSRadioButton : a reference to current application’s NSRadioButton
property NSRadioModeMatrix : a reference to current application’s NSRadioModeMatrix
property NSRoundedBezelStyle : a reference to current application’s NSRoundedBezelStyle
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn

property theResult : 0
property returnCode : 0

set paramObj to {myMessage:"Select target month", mySubMessage:"適切なものを以下からえらんでください", matrixTitleList:{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}}

–my chooseItemByRadioButton:paramObj–for Debugging

my performSelectorOnMainThread:"chooseItemByRadioButton:" withObject:paramObj waitUntilDone:true
return theResult

on chooseItemByRadioButton:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aMatList to (matrixTitleList of paramObj) as list
  
set aLen to length of aMatList
  
  
  
set aButtonCellWidth to 104
  
set aButtonCellHeight to 104
  
  
set colNum to 4
  
set rowNum to 3
  
  
set targYear to 2019
  
  
set viewWidth to aButtonCellWidth * colNum
  
set viewHeight to aButtonCellHeight * rowNum
  
  
–create the radio button prototype
  
set aProto to NSButtonCell’s alloc()’s init()
  
aProto’s setTitle:"Options"
  
aProto’s setButtonType:(NSRadioButton)
  
  
–define the matrix size where you’ll put the radio buttons
  
set matrixRect to current application’s NSMakeRect(0.0, 0.0, viewWidth, viewHeight)
  
set aView to NSView’s alloc()’s initWithFrame:(matrixRect)
  
  
set aCount to 1
  
set tmpArray to current application’s NSMutableArray’s new()
  
repeat with y from 1 to rowNum
    repeat with x from 1 to colNum
      set j to contents of item aCount of aMatList
      
set tmpB to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(((x – 1) * aButtonCellWidth), ((aLen – aCount) div colNum) * aButtonCellHeight, aButtonCellWidth, aButtonCellHeight)))
      
–(tmpB’s setTitle:j)
      
      
set tmpImage to makeSmallCalendarImage(targYear, aCount) of calImage
      (
tmpB’s setImage:(tmpImage))
      (
tmpB’s setShowsBorderOnlyWhileMouseInside:true)
      (
tmpB’s setTag:(aCount))
      (
tmpB’s setTarget:me)
      (
tmpB’s setAction:("clicked:"))
      (
tmpB’s setButtonType:(current application’s NSButtonTypeMomentaryPushIn))
      
      (
tmpArray’s addObject:tmpB)
      
set aCount to aCount + 1
    end repeat
  end repeat
  
  (
aView’s setSubviews:tmpArray)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
end chooseItemByRadioButton:

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

on clicked:aParam
  set aTag to tag of aParam
  
set theResult to aTag
end clicked:

★Click Here to Open This Script 

Posted in Calendar dialog GUI Image | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSAlert NSAlertSecondButtonReturn NSButton NSRoundedBezelStyle NSRunningApplication NSView | Leave a comment

アラートダイアログ上にpath control x2を表示 v2

Posted on 8月 3, 2019 by Takaaki Naganoya

アラートダイアログ上にPathcontrolを表示して、ファイルパス選択をドラッグ&ドロップで受け付けるAppleScriptの改良版です。

実行中にアピアランスのDark Mode/Light Modeへの変更が行われたときの対応を追加してみました。

実行途中でアピアランスの変更が行われると、OSが提供している部品をそのまま利用している分にはOSの管理下で色変更が行われますが、あとから色指定している部品はそのままです(↑)。上記の(↑)ように、割と違和感があるというか、実用上困る(そもそもアピアランス変更をそんな時に行う方がどうかしているとは思うのですが)ので、対処してみました。

部品はひととおり作ってあったので、組み合わせただけです。アピアランスの変更Notificationを受信する部品や、アピアランステーマを判定する部品などです。

部品の組み合わせ方にも些細なノウハウがあるので、一応やっておいたことには意義があると思っています。

AppleScript名:アラートダイアログ上にpath control x2を表示 v2
— Created 2019-08-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSTextField : a reference to current application’s NSTextField
property NSPathControl : a reference to current application’s NSPathControl
property NSUserDefaults : a reference to current application’s NSUserDefaults
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSDistributedNotificationCenter : a reference to current application’s NSDistributedNotificationCenter

property theResult : 0
property returnCode : 0
property resList : {}
property aPathControl : missing value
property bPathControl : missing value

set paramObj to {myMessage:"ファイルの入出力フォルダ選択", mySubMessage:"どれか選択してください。", fromPathMes:"移動元:", toPathMes:"移動先:"}
my performSelectorOnMainThread:"chooseTwoPath:" withObject:paramObj waitUntilDone:true

return resList
–> {fromPathRes:"/Users/me/Desktop/keyn1.png", toPathRes:"/Users/me/Desktop/scriptmenu1.png"}

on chooseTwoPath:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set fromLabel to fromPathMes of paramObj
  
set toLabel to toPathMes of paramObj
  
  
—Dark Mode Notification受信開始
  
NSDistributedNotificationCenter’s defaultCenter()’s addObserver:me selector:"darkModeChanged:" |name|:"AppleInterfaceThemeChangedNotification" object:(missing value)
  
  
— create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 600, 60))
  
  
— create two path control & text field
  
set aPathControl to NSPathControl’s alloc()’s initWithFrame:(current application’s NSMakeRect(100, 35, 700, 20))
  
set bPathControl to NSPathControl’s alloc()’s initWithFrame:(current application’s NSMakeRect(100, 0, 700, 20))
  
  
–Set path control’s bg colors
  
set {aCol, bCol} to pathControlSrtringColor() of me
  
aPathControl’s setBackgroundColor:(aCol)
  
bPathControl’s setBackgroundColor:(bCol)
  
  
  
set aHome to current application’s |NSURL|’s fileURLWithPath:(current application’s NSHomeDirectory()) –initial dir
  
aPathControl’s setURL:aHome
  
bPathControl’s setURL:aHome
  
  
set a1TF to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 35, 100, 20))
  
set a2TF to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 100, 20))
  
a1TF’s setEditable:false
  
a2TF’s setEditable:false
  
a1TF’s setStringValue:fromLabel
  
a2TF’s setStringValue:toLabel
  
a1TF’s setDrawsBackground:false
  
a2TF’s setDrawsBackground:false
  
a1TF’s setBordered:false
  
a2TF’s setBordered:false
  
  
theView’s setSubviews:{a1TF, aPathControl, a2TF, bPathControl}
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set s1Val to (aPathControl’s |URL|’s |path|()) as string
  
set s2Val to (bPathControl’s |URL|’s |path|()) as string
  
  
set resList to {fromPathRes:s1Val, toPathRes:s2Val}
  
  
–Notification受信停止
  
NSDistributedNotificationCenter’s defaultCenter()’s removeObserver:me |name|:"AppleInterfaceThemeChangedNotification" object:(missing value)
end chooseTwoPath:

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

–ダークモードの判定。ダークモード時:true、ライトモード時:falseが返る
on retLIghtOrDark()
  set curMode to (NSUserDefaults’s standardUserDefaults()’s stringForKey:"AppleInterfaceStyle") as string
  
return (curMode = "Dark") as boolean
end retLIghtOrDark

–aMaxValを最大値とする数値でNSColorを作成して返す
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–Notification handler
on darkModeChanged:(aNotification)
  set {aCol, bCol} to pathControlSrtringColor() of me
  
aPathControl’s setBackgroundColor:(aCol)
  
bPathControl’s setBackgroundColor:(bCol)
end darkModeChanged:

on pathControlSrtringColor()
  set dMode to retLIghtOrDark() of me –Dark mode:true
  
if dMode = false then
    –Light Mode
    
set aCol to (NSColor’s cyanColor())
    
set bCol to (NSColor’s yellowColor())
  else
    –Dark Mode
    
set aCol to (makeNSColorFromRGBAval(0, 96, 65, 255, 255) of me)
    
set bCol to (makeNSColorFromRGBAval(93, 92, 0, 255, 255) of me)
  end if
  
  
return {aCol, bCol}
end pathControlSrtringColor

★Click Here to Open This Script 

Posted in Color dialog GUI Noification | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSAlert NSColor NSDistributedNotificationCenter NSPathControl NSRunningApplication NSTextField NSUserDefaults NSView | Leave a comment

People Picker

Posted on 7月 11, 2019 by Takaaki Naganoya

ABPersonPickerでアドレスブックに登録のあるPerson(人)をダイアログ選択するAppleScriptです。

ずいぶんと前に作ってあったものの、活用できる機会がまったくなくて埃をかぶっていました。Alertダイアログ上に表示できないかと修正してみたものの、ABPersonPickerがWindowを要求するようで、書き換えてもうまく動かなかったために「誰か改良してくれるかもしれないし、掲載しとくかー」と、引っ張り出してきたものです。

本Scriptは人物(Person)1人を選択するものであるため、正確にいえば、Person Pickerですね。

人物の選択を行うための機能はAppleScriptには提供されていないため、一般的にはアドレスブックに登録されている全員の氏名を一括で取得してchoose from listで選択するといった話になることでしょう。

それよりは幾分マシではあるものの、使い勝手という面ではさっぱりです。アドレスブック(連絡先)でAppleScriptプラグインが(macOS 10.14で)使えなくなりましたが、このような代替案だったり、使い物にならない連作先.appの代わりにAddressBookフレームワークにアクセスしてPerson情報をしぼりこんでScriptを実行するようなプログラムを作ることになるでしょう。

連絡先(旧称アドレスブック)、カレンダー(旧称iCal)は「ただ動けばいい」ぐらいのぞんざいな作りなのが本当に残念です。


▲macOS 10.14.5(Dark Mode)上で実行したところ


▲ ABPersonPicker上でキーワードによる絞り込みもリアルタイムに行える

AppleScript名:People Picker
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "AddressBook"

property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property ABPersonPicker : a reference to current application’s ABPersonPicker
property NSRectEdgeMaxX : a reference to current application’s NSRectEdgeMaxX
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSRoundedBezelStyle : a reference to current application’s NSRoundedBezelStyle
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSMomentaryLightButton : a reference to current application’s NSMomentaryLightButton

property windisp : false
property selectedPerson : missing value

on run
  set (my selectedPerson) to missing value
  
  
my performSelectorOnMainThread:"dispPeoplePicker:" withObject:(missing value) waitUntilDone:true
  
if (my selectedPerson) = missing value then return false
  
  
set firstName to (my selectedPerson’s |First|) as string
  
set lastName to (my selectedPerson’s |Last|) as string
  
  
return {lastName, firstName}
end run

on dispPeoplePicker:aParam
  set aWidth to 300
  
set aHeight to 100
  
choosePeople(aWidth, aHeight, "Result", "OK", 180) of me
end dispPeoplePicker:

on choosePeople(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number)
  set (my windisp) to true
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth / 4, 0, aWidth / 2, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(NSMomentaryLightButton)
  
bButton’s setBezelStyle:(NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
  
–NSViewをつくる
  
set aNSV to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
aNSV’s addSubview:bButton
  
aNSV’s setNeedsDisplay:true
  
  
–NSWindowをつくる  
  
set aWin to makeWinWithView(aNSV, aWidth, aHeight, aTitle, 1.0)
  
  
–NSWindowControllerをつくる
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
  
–People Pickerをつくる
  
set anAB to ABPersonPicker’s alloc()’s init()
  
anAB’s showRelativeToRect:(current application’s NSMakeRect(0, 0, 200, 200)) ofView:aNSV preferredEdge:(NSRectEdgeMaxX)
  
anAB’s setDelegate:(me)
  
  
–NSWindowの最前面表示  
  
aWin’s makeKeyAndOrderFront:me
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
end choosePeople

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on personPicker:(aPicker) didChoosePerson:(aPerson) |property|:(aProperty) identifier:(anID)
  log {"personPicker:didChoosePerson:"}
  
log aPicker
  
log aPerson
  
log aProperty
  
log anID
  
copy aPerson to my selectedPerson
end personPicker:didChoosePerson:|property|:identifier:

on personPickerDidClose:(aPicker)
  log {"personPickerDidClose"}
  
set (my windisp) to false
end personPickerDidClose:

★Click Here to Open This Script 

Posted in dialog GUI System | Tagged 10.12savvy 10.13savvy 10.14savvy ABPersonPicker NSBackingStoreBuffered NSButton NSMomentaryLightButton NSNormalWindowLevel NSRectEdgeMaxX NSRoundedBezelStyle NSScreen NSTitledWindowMask NSView NSWindow NSWindowController | Leave a comment

アラートダイアログ上にTable Viewを表示 v4

Posted on 7月 11, 2019 by Takaaki Naganoya

アラートダイアログ上にTable Viewを表示するAppleScriptです。

データを表UIで表示する部品としては、Shane Stanleyの「Myriad Tables Lib」が定番ですが、高機能なぶんライブラリ中にFrameworkが含まれていたりして、場合によっては困ることもあります。また、見た目をカスタマイズしたい場合にも、あまりいじくれなくて困ることもあります(とくにデータの文字サイズを変更できなくて困ること多し)。

そのため、AppleScriptだけで書いた表UI表示用の部品も、たまに必要になることがあります。


▲スクリプトエディタで実行@macOS 10.14.5(左:Light Mode、右:Dark Mode)


▲Script Debuggerで実行@macOS 10.14.5(左:Light Mode、右:Dark Mode)


▲AppleScriptアプレットで実行@macOS 10.14.5(左:Light Mode、右:Dark Mode)

AppleScript名:アラートダイアログ上にTable Viewを表示 v4
— Created 2019-02-21 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSIndexSet : a reference to current application’s NSIndexSet
property NSScrollView : a reference to current application’s NSScrollView
property NSTableView : a reference to current application’s NSTableView
property NSTableColumn : a reference to current application’s NSTableColumn
property NSMutableArray : a reference to current application’s NSMutableArray
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSModalPanelWindowLevel : a reference to current application’s NSModalPanelWindowLevel
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn

property theResult : 0
property returnCode : 0
property theDataSource : {}

on run
  set (my theResult) to 0 –initialize
  
  
set paramObj to {myMessage:"項目の選択", mySubMessage:"適切なものを以下からえらんでください", aTableList:{{field1:"MacBook Air", field2:"119,800円", field3:"1.6GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)、4MB L3キャッシュ"}, {field1:"MacBook Pro 13", field2:"139,800円", field3:"1.4GHzクアッドコアIntel Core i5(Turbo Boost使用時最大3.9GHz)、128MB eDRAM"}, {field1:"MacBook Pro 15", field2:"258,800円", field3:"2.6GHz 6コアIntel Core i7(Turbo Boost使用時最大4.5GHz)、12MB共有L3キャッシュ"}, {field1:"Mac mini", field2:"122,800円", field3:"3.0GHz 6コアIntel Core i5 Turbo Boost使用時最大4.1GHz 9MB共有L3キャッシュ"}, {field1:"iMac 21.5", field2:"120,800円", field3:"2.3GHzデュアルコアIntel Core i5(Turbo Boost使用時最大3.6GHz)"}, {field1:"iMac 4K 21.5", field2:"142,800円", field3:"3.6GHzクアッドコアIntel Core i3"}, {field1:"iMac 5K 27", field2:"198,800円", field3:"3.0GHz 6コア Intel Core i5(Turbo Boost使用時最大4.1GHz)"}, {field1:"iMac Pro", field2:"558,800円", field3:"3.2GHz Intel Xeon W Turbo Boost使用時最大4.2GHz 19MBキャッシュ"}}, aSortOrder:{"field1", "field2", "field3"}}
  
  
–my chooseItemByTableView:paramObj–for debug
  
my performSelectorOnMainThread:"chooseItemByTableView:" withObject:paramObj waitUntilDone:true
  
return (my theResult)
end run

on chooseItemByTableView:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aTList to (aTableList of paramObj) as list
  
set labelSortList to (aSortOrder of paramObj) as list
  
  
set aWidth to 600
  
set aHeight to 200
  
  
set aScroll to makeTableView(aTList, aWidth, aHeight, labelSortList) of me
  
  
–Detect Dark Mode
  
set dMode to retLIghtOrDark() of me
  
if dMode = true then
    set tvCol to 1
    
set tvAlpha to 0.8
    
set bCol to 0.1
    
set bAlpha to 0.8
    
set contentCol to (NSColor’s cyanColor())
  else
    set tvCol to 0
    
set tvAlpha to 0.1
    
set bCol to 1
    
set bAlpha to 0.8
    
set contentCol to (NSColor’s blackColor())
  end if
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aScroll
    
    
set myWindow to its |window|
  end tell
  
  
myWindow’s setOpaque:(false)
  
myWindow’s setBackgroundColor:(NSColor’s colorWithCalibratedWhite:(bCol) alpha:(bAlpha))
  
myWindow’s setLevel:(NSModalPanelWindowLevel)
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode) = 1001 then error number -128
  
  
set (my theResult) to (aScroll’s documentView’s selectedRow()) + 1
end chooseItemByTableView:

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

–TableView Event Handlers
on numberOfRowsInTableView:aView
  return my theDataSource’s |count|()
end numberOfRowsInTableView:

on tableView:aView objectValueForTableColumn:aColumn row:aRow
  set aRec to (my theDataSource)’s objectAtIndex:(aRow as number)
  
set aTitle to (aColumn’s headerCell()’s title()) as string
  
set aRes to (aRec’s valueForKey:aTitle)
  
return aRes
end tableView:objectValueForTableColumn:row:

on makeTableView(aDicList, aWidth, aHeight, labelSortList)
  set aOffset to 40
  
set theDataSource to current application’s NSMutableArray’s alloc()’s init()
  
theDataSource’s addObjectsFromArray:aDicList
  
  
set aScroll to current application’s NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
  
set aView to current application’s NSTableView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
  
  
set aLen to length of labelSortList
  
  
repeat with i in labelSortList
    set j to contents of i
    
set aColumn to (current application’s NSTableColumn’s alloc()’s initWithIdentifier:j)
    (
aColumn’s setWidth:(aWidth div aLen))
    (
aColumn’s headerCell()’s setStringValue:j)
    (
aView’s addTableColumn:aColumn)
  end repeat
  
  
aView’s setDelegate:me
  
aView’s setDataSource:me
  
aView’s reloadData()
  
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
aScroll’s setVerticalLineScroll:(30.0 as real)
  
  
–1行目を選択
  
set aIndexSet to current application’s NSIndexSet’s indexSetWithIndex:0
  
aView’s selectRowIndexes:aIndexSet byExtendingSelection:false
  
  
–強制的にトップにスクロール
  
set aDBounds to aScroll’s documentView()’s |bounds|()
  
if class of aDBounds = list then
    –macOS 10.13 or later
    
set maxHeight to item 2 of item 1 of aDBounds
  else
    –macOS 10.10….10.12
    
set maxHeight to height of |size| of aDBounds
  end if
  
  
set aPT to current application’s NSMakePoint(0.0, -1 * (maxHeight as real))
  
aScroll’s documentView()’s scrollPoint:aPT
  
  
return aScroll
end makeTableView

on alertShowHelp:aNotification
  display dialog "Help Me!" buttons {"OK"} default button 1 with icon 1
  
return false –trueを返すと親ウィンドウ(アラートダイアログ)がクローズする
end alertShowHelp:

–ダークモードの判定。ダークモード時:true、ライトモード時:falseが返る。System Eventsを使っていないのは、macOS 10.14以降対策(承認を取得しなくてもいいように)
on retLIghtOrDark()
  set curMode to (current application’s NSUserDefaults’s standardUserDefaults()’s stringForKey:"AppleInterfaceStyle") as string
  
return (curMode = "Dark") as boolean
end retLIghtOrDark

★Click Here to Open This Script 

Posted in Color GUI list Record | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSAlertSecondButtonReturn NSColor NSIndexSet NSModalPanelWindowLevel NSMutableArray NSRunningApplication NSScrollView NSTableColumn NSTableView | 1 Comment

アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明_Float_SuppressionButtonつき

Posted on 7月 10, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

Xcode上でNSAlert.hを調べ、アラートダイアログに指定できる各種オプションを指定してみました。NSWindowLevelの変更は効いていないみたいですけれども。

AppleScript名:アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明_Float_SuppressionButtonつき
— Created 2019-07-09 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSFont : a reference to current application’s NSFont
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSUserDefaults : a reference to current application’s NSUserDefaults
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSModalPanelWindowLevel : a reference to current application’s NSModalPanelWindowLevel

property returnCode : 0
property supState : false

set asStr to do shell script "cal 2019"
set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:450, mesHeight:200, fontName:"Courier", fontSize:11.0, suppressionMes:"Some Option"}

–my dispTextViewWithAlertdialog:paramObj–for debug
my performSelectorOnMainThread:"dispTextViewWithAlertdialog:" withObject:paramObj waitUntilDone:true

return (my supState)

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
set aSupMes to (suppressionMes of paramObj) as string –Suppression Button Titile
  
  
–Detect Dark Mode
  
set dMode to retLIghtOrDark() of me
  
if dMode = true then
    set tvCol to 1
    
set tvAlpha to 0.8
    
set bCol to 0.1
    
set bAlpha to 0.8
    
set contentCol to (NSColor’s cyanColor())
  else
    set tvCol to 0
    
set tvAlpha to 0.1
    
set bCol to 1
    
set bAlpha to 0.5
    
set contentCol to (NSColor’s grayColor())
  end if
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:(tvAlpha)
  
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(contentCol)
  
aView’s setFont:(NSFont’s fontWithName:aFontName |size|:aFontSize)
  
  
aView’s setDrawsBackground:false
  
  
  
aView’s setBackgroundColor:aColor
  
aView’s setOpaque:(false)
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
–aScroll’s setBorderType:(current application’s NSBezelBorder)
  
–aScroll’s setBorderType:(current application’s NSGrooveBorder)
  
–aScroll’s setBorderType:(current application’s NSLineBorder)
  
aScroll’s setBorderType:(current application’s NSNoBorder)
  
  
–Ruler
  
–aScroll’s setHasHorizontalRuler:(true)
  
–aScroll’s setRulersVisible:(true)
  
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
set anImage to current application’s NSImage’s imageNamed:(current application’s NSImageNameComputer)
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setIcon:(anImage)
    
    
–for Messages
    
its setMessageText:(aMainMes)
    
its setInformativeText:(aSubMes)
    
    
–for Buttons
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
    
–Add Accessory View
    
its setAccessoryView:(aScroll)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
    
    
its setAlertStyle:0 —-0…2
    
    
its setShowsSuppressionButton:(true) –「今後このメッセージを表示しない」チェックボックスを表示
    
    
set suppressionB to its suppressionButton
    
set myWindow to its |window|
  end tell
  
  
myWindow’s setOpaque:(false)
  
myWindow’s setBackgroundColor:(NSColor’s colorWithCalibratedWhite:(bCol) alpha:(bAlpha))
  
myWindow’s setLevel:(NSModalPanelWindowLevel)
  
  
suppressionB’s setTitle:(aSupMes)
  
suppressionB’s setState:(true) —default state
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set my supState to (suppressionB’s state) as boolean
end dispTextViewWithAlertdialog:

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

on alertShowHelp:aNotification
  display dialog "Help Me!" buttons {"OK"} default button 1 with icon 1
  
return false –trueを返すと親ウィンドウ(アラートダイアログ)がクローズする
end alertShowHelp:

–ダークモードの判定。ダークモード時:true、ライトモード時:falseが返る。System Eventsを使っていないのは、macOS 10.14以降対策(承認を取得しなくてもいいように)
on retLIghtOrDark()
  set curMode to (current application’s NSUserDefaults’s standardUserDefaults()’s stringForKey:"AppleInterfaceStyle") as string
  
return (curMode = "Dark") as boolean
end retLIghtOrDark

★Click Here to Open This Script 

Posted in Color dialog Font GUI Icon Image | Tagged 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSModalPanelWindowLevel NSRunningApplication NSScrollView NSTextView NSURL NSUserDefaults | Leave a comment

アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明

Posted on 7月 8, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

# 前バージョンの「自分のソースコード」表示というのは意味不明だったので、プロセス一覧を取得してみました

ヘルプボタン(?)を付け、アラートダイアログのウィンドウ背景を半透明に設定。そのままでは配色の都合上Dark Mode/Light Modeの切り替え時に読みづらい文字なども出てきたため、モード判定を行って表示色などを変更しています。

アプレット書き出ししたときに、スクロールビューがマウスのスクロールホイールの操作に追従したスクロールを行ってくれないので、そのあたり何か追加でNSScrollViewに設定を行う必要があるのだろうかと。


▲スクリプトエディタ上で実行@macOS 10.14.5。左がLight Mode、右がDark Mode(以下同様)


▲ヘルプボタンをクリックしたところ。本当にアンカーを指定して指定のヘルプコンテンツを表示させることもできる模様。そのための基礎的な試験


▲AppleScriptアプレット書き出しして実行したところ


▲Script Debugger上で実行@macOS 10.14.5。Dark Modeに対応できていない(次バージョンで対応することでしょう)


▲Script DebuggerからAppleScript Applet (Enhanced)で書き出して実行したところ。マウスのスクロールホイールの操作を受け付けて文字がスクロールする

AppleScript名:アラートダイアログ上にTexViewを表示_ヘルプ付き_半透明
— Created 2019-07-08 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSFont : a reference to current application’s NSFont
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication

property returnCode : 0

–Get Self Source Code (a kind of joke)
set asStr to do shell script "ps -ax"
set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:400, mesHeight:200, fontName:"HiraginoSans-W3", fontSize:11.0}

–my dispTextViewWithAlertdialog:paramObj–for debug
my performSelectorOnMainThread:"dispTextViewWithAlertdialog:" withObject:paramObj waitUntilDone:true

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
  
–Detect Dark Mode
  
set dMode to retLIghtOrDark() of me
  
if dMode = true then
    set tvCol to 1
    
set tvAlpha to 0.8
    
set bCol to 0.1
    
set bAlpha to 0.8
  else
    set tvCol to 1
    
set tvAlpha to 1.0
    
set bCol to 1
    
set bAlpha to 0.7
  end if
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(NSColor’s cyanColor()) –cyanColor
  
aView’s setFont:(NSFont’s fontWithName:aFontName |size|:aFontSize)
  
set aColor to NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:(tvAlpha)
  
aView’s setBackgroundColor:aColor
  
aView’s setOpaque:(false)
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    –for Messages
    
its setMessageText:(aMainMes)
    
its setInformativeText:(aSubMes)
    
    
–for Buttons
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
    
–Add Accessory View
    
its setAccessoryView:(aScroll)
    
    
–for Help Button
    
its setShowsHelp:(true)
    
its setDelegate:(me)
    
    
set myWindow to its |window|
  end tell
  
  
myWindow’s setOpaque:(false)
  
myWindow’s setBackgroundColor:(NSColor’s colorWithCalibratedWhite:(bCol) alpha:(bAlpha))
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
end dispTextViewWithAlertdialog:

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

on alertShowHelp:aNotification
  display dialog "Help Me!" buttons {"OK"} default button 1 with icon 1
  
return false –trueを返すと親ウィンドウ(アラートダイアログ)がクローズする
end alertShowHelp:

–ダークモードの判定。ダークモード時:true、ライトモード時:falseが返る
on retLIghtOrDark()
  set curMode to (current application’s NSUserDefaults’s standardUserDefaults()’s stringForKey:"AppleInterfaceStyle") as string
  
return (curMode = "Dark") as boolean
end retLIghtOrDark

★Click Here to Open This Script 

Posted in Color dialog GUI | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSRunningApplication NSScrollView NSTextView NSURL NSView | Leave a comment

アラートダイアログ上にTextViewを表示

Posted on 7月 8, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

とくにこれといって何か表示するものを思いつかなかったので、自分自身のソースコードを取得して表示しています。スクリプトエディタやScript Debugger上で実行した場合には自分自身のソースコードをテキストビュー上で表示します。

読み取り専用のスクリプトやアプレットで実行している場合にはソースコードを取得できません。何か適宜自分で表示させたいテキストを与えてみてください。

AppleScript名:アラートダイアログ上にTexViewを表示
— Created 2019-07-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "OSAKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSFont : a reference to current application’s NSFont
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication
property OSAScript : a reference to current application’s OSAScript

property returnCode : 0

–Get Self Source Code (a kind of joke)
set mePath to path to me
set asStr to getASsourceFor(mePath) of me

set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:400, mesHeight:200, fontName:"HiraginoSans-W3", fontSize:11.0}

–my dispTextViewWithAlertdialog:paramObj–for debug
my performSelectorOnMainThread:"dispTextViewWithAlertdialog:" withObject:paramObj waitUntilDone:true

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(current application’s NSColor’s cyanColor()) –cyanColor
  
aView’s setFont:(current application’s NSFont’s fontWithName:aFontName |size|:aFontSize)
  
set aColor to current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.5
  
aView’s setBackgroundColor:aColor
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aScroll
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
end dispTextViewWithAlertdialog:

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

–指定AppleScriptファイルのソースコードを取得する(実行専用Scriptからは取得できない)
— Original Created 2014-02-23 Shane Stanley
on getASsourceFor(anAlias as {alias, string})
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set theScript to OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
  
  
if theScript is equal to missing value then
    error "Compile Error" — handle error
  else
    set sourceText to theScript’s source()
  end if
  
  
return sourceText as string
end getASsourceFor

★Click Here to Open This Script 

Posted in Color file File path Font GUI Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSRunningApplication NSScrollView NSTextView NSURL OSAScript | Leave a comment

Keynote書類のテキスト色を置換

Posted on 6月 9, 2019 by Takaaki Naganoya

最前面のKeynote書類の文字色を置換するAppleScriptです。

# 初出時にはmacOS 10.13であったため、スクリプトエディタ上からも野良Framework呼び出しができましたが、macOS 10.14以降ではSIPを解除するかScript Debugger上で実行する必要があります

Keynoteは文字色の置換をする機能が実装されていないので、個別に手で色を変更するか、あるいはスタイルを編集して一括で修正するやり方になります。

そこで、AppleScriptで色置換を行う処理を書いてみました。表の背景色を置換する処理を書いたときの部品を大幅に使いまわしています。

文字色の取得や判定は、テキストアイテムの1文字目の情報で判断しています。途中で色を変更しているような場合にはうまく検出できません(処理スピードを重視したことと、自分の利用方法の範囲ではそういう文字ごとに異なる色を指定するところまではサポートしなくてよいと考えたためです。仕事ならもうちょっと真面目に作り込むかもしれませんが、、、、)。

ポップアップメニュー中の色名の動的な推定に、オープンソースの「DBColorNames」をフレームワーク化した
「dbColNamesKit.framework」を利用しています。

–> dbColNamesKit.framework (To ~/Library/Frameworks)


▲左上の時刻部分の色を置換したい


▲本Scriptを実行した直後。最前面のKeynote書類のすべてのテキストを走査して文字色を取得する


▲取得した文字色リスト。この中から置換対象を選択する。色データから色名を動的に生成し、色IDとともに名称で個別に指定したり識別したりできる


▲変更後の色をカラーピッカーで選択


▲Keynote書類上の文字色を変更してみた

AppleScript名:Keynote書類の現在のテキスト色を置換.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/06/08
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — Yosemite (10.11) or later
use framework "Foundation"
use framework "AppKit"
use framework "dbColNamesKit" –https://github.com/daniel-beard/DBColorNames/
use scripting additions

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSMenu : a reference to current application’s NSMenu
property NSImage : a reference to current application’s NSImage
property NSIndexSet : a reference to current application’s NSIndexSet
property NSTextField : a reference to current application’s NSTextField
property NSColorWell : a reference to current application’s NSColorWell
property NSMenuItem : a reference to current application’s NSMenuItem
property NSBezierPath : a reference to current application’s NSBezierPath
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSMutableArray : a reference to current application’s NSMutableArray
property NSRunningApplication : a reference to current application’s NSRunningApplication

property returnCode : 0
property pop1ind : 0

–スライド枚数をカウント
tell application "Keynote"
  tell front document
    set sCount to count every slide
  end tell
end tell

–すべてのテキストアイテム、タイトルから色情報を取得する
set cList to {}
repeat with sNum from 1 to sCount
  set cList to cList & getEveryTextColorOfSlide(sNum) of me
end repeat

–文字色のユニーク化
set dList to makeUniqueListOf(cList) of me

set paramObj to {mainDat:dList, myTitle:"テキスト色置換", mySubTitle:"Keynoteのテキストアイテム、デフォルトアイテム(タイトル)の文字色置換", myColorRangeMax:65535}
my getPopupValues:paramObj

if pop1ind = false then return –timed out
set fromCol to (contents of item pop1ind of dList)

–カラーピッカーで置換色選択
set tCol to choose color default color fromCol

–Keynote書類中のテキストの文字色を置換
repeat with sNum from 1 to sCount
  set cList to cList & repEveryTextColorOfSlide(sNum, fromCol, tCol) of me
end repeat

–カラーポップアップメニューをウィンドウ表示
on getPopupValues:paramObj
  set ap1List to (mainDat of (paramObj as record)) as list
  
set winTitle to (myTitle of (paramObj as record)) as string
  
set subTitle to (mySubTitle of (paramObj as record)) as string
  
set aColMax to (myColorRangeMax of (paramObj as record)) as list
  
  
–Viewをつくる
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 80))
  
  
–Labelをつくる
  
set a1TF to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, 80, 20))
  
a1TF’s setEditable:false
  
a1TF’s setStringValue:"From Color:"
  
a1TF’s setDrawsBackground:false
  
a1TF’s setBordered:false
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 40, 200, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
set a1Menu to NSMenu’s alloc()’s init()
  
set aCDB to current application’s DBColorNames’s alloc()’s init()
  
  
–Popup Menuをつくる
  
set iCount to 1
  
repeat with i in ap1List
    copy i to {r1, g1, b1}
    
    
set nsCol to makeNSColorFromRGBAval(r1, g1, b1, aColMax, aColMax) of me
    
set anImage to makeRoundedNSImageWithFilledWithColor(64, 64, nsCol, 4) of me
    
    
–色名をRGB値から動的に生成(あらかじめdbNamesが持っているカラーパレットの近似色の色名を返す)
    
set aTitle to "#" & (iCount as string) & " " & (aCDB’s nameForColor:nsCol) as string
    
    
–Menu Itemを作成する
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    (
aMenuItem’s setImage:anImage)
    (
aMenuItem’s setEnabled:true)
    (
aMenuItem’s setTarget:me)
    (
a1Menu’s addItem:aMenuItem)
    
    
set iCount to iCount + 1
  end repeat
  
  
–Popup ButtonにPopup Menuを設定する
  
a1Button’s setMenu:a1Menu
  
  
–ViewにPopup Buttonとテキストラベルを入れる
  
aView’s addSubview:a1TF
  
aView’s addSubview:a1Button
  
aView’s setNeedsDisplay:true
  
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:winTitle
    
its setInformativeText:subTitle
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set s1Val to ((a1Button’s indexOfSelectedItem() as number) + 1)
  
copy s1Val to my pop1ind
end getPopupValues:

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

–Popup Action Handler
on actionHandler:sender
  set aTag to tag of sender as integer
  
set aTitle to title of sender as string
end actionHandler:

–aMaxValを最大値とする数値でNSColorを作成して返す
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–指定サイズのNSImageを作成し、指定色で塗ってNSImageで返す
on makeNSImageWithFilledWithColor(aWidth as integer, aHeight as integer, fillColor)
  set anImage to NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
—
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
—
  
anImage’s unlockFocus()
  
—
  
return anImage
end makeNSImageWithFilledWithColor

–指定サイズのNSImageを作成し、指定色で塗ってNSImageで返す、anRadiusの半径の角丸で
on makeRoundedNSImageWithFilledWithColor(aWidth as integer, aHeight as integer, fillColor, anRadius as real)
  set anImage to NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to NSBezierPath’s bezierPathWithRoundedRect:theRect xRadius:anRadius yRadius:anRadius
  
—
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
—
  
anImage’s unlockFocus()
  
  
return anImage
end makeRoundedNSImageWithFilledWithColor

–最前面のKeynote書類のすべてのスライドから、テキストアイテムとタイトルアイテムの文字色を取得
on getEveryTextColorOfSlide(sNum)
  set cList to {}
  
  
tell application "Keynote"
    tell front document
      set sMax to count every slide
      
if sMax < sNum then return false
      
      
tell slide sNum
        –すべての文字アイテムの先頭の文字の色情報を取得
        
try
          set tCount to count every text item
          
repeat with i from 1 to tCount
            set s1List to color of character 1 of object text of text item i
            
set the end of cList to s1List
          end repeat
        on error
          –set s1List to {}
        end try
        
        
–タイトルの先頭の文字の色情報を取得
        
try
          set s2List to color of character 1 of object text of default title item
          
set the end of cList to s2List
        on error
          set s2List to {}
        end try
      end tell
      
    end tell
  end tell
  
  
return cList
end getEveryTextColorOfSlide

–最前面のKeynote書類の指定番号のスライドで、テキストアイテムとタイトルアイテムの文字色を置換
on repEveryTextColorOfSlide(sNum, fromCol, toCol)
  tell application "Keynote"
    tell front document
      set sMax to count every slide
      
if sMax < sNum then return false
      
      
tell slide sNum
        –すべての文字アイテムの先頭の文字の色情報を置換
        
try
          set tCount to count every text item
          
repeat with i from 1 to tCount
            set s1List to color of character 1 of object text of text item i
            
if s1List = fromCol then
              ignoring application responses
                set color of every character of object text of text item i to toCol
              end ignoring
            end if
          end repeat
        on error
          —
        end try
        
        
–タイトルの先頭の文字の色情報を置換
        
try
          set s2List to color of character 1 of object text of default title item
          
if s2List = fromCol then
            ignoring application responses
              set color of every character of object text of default title item to toCol
            end ignoring
          end if
        on error
          set s2List to {}
        end try
      end tell
      
    end tell
  end tell
end repEveryTextColorOfSlide

–Listのユニーク化
on makeUniqueListOf(theList)
  set theSet to current application’s NSOrderedSet’s orderedSetWithArray:theList
  
return (theSet’s array()) as list
end makeUniqueListOf

★Click Here to Open This Script 

Posted in Color dialog GUI list | Tagged 10.11savvy 10.12savvy 10.13savvy Keynote NSAlert NSBezierPath NSColor NSColorWell NSImage NSIndexSet NSMenu NSMenuItem NSMutableArray NSPopUpButton NSRunningApplication NSTextField NSView | Leave a comment

Keynote書類の現在のスライド上の選択中の表の背景色を置換 v2

Posted on 5月 4, 2019 by Takaaki Naganoya

Keynoteでオープン中の最前面の書類の現在表示中のスライドに存在する選択中の表オブジェクトの背景色を置換するAppleScriptです。

–> Keynote_table_color_replace v2 Run-Only (Download Run-only script with Framework and Library)

初版ではtable 1を決め打ちで指定していましたが、選択中の表オブジェクトへの参照を取得するルーチンを組み込んで、選択中の表を処理できるように機能アップしました。

Scriptの状態で、macOS 10.12.6+Keynote v8.1上で動作確認。Appletの状態で、macOS 10.14.4/10.13.6+Keynote v9.0.1上で動作確認してあります。

本Scriptは大量のセルを持つ表を高速に色置換するために作成したものなので、時間がかかってもよくてのんびり色置換するだけでよければ、このコードの10分の1以下で書けます。

(1)セルを1つずつ塗るのではなく、複数セルを一度に塗る高速化
(2)セルの連続範囲を縦方向と横方向にセル連続区間を検出・カウントを実行。どちらか処理が早く終わる方を採用(処理前に2方向でシミュレーション)
(3)Keynoteとの間で非同期処理を行って処理高速化
(4)色選択のためにカラーポップアップメニューを、独自で作成したウィンドウ上に表示
(5)色の内容を把握しやすいように、色のRGB数値から色名をその場で生成
(6)カラーポップアップ上に表示する色プレビューを角丸で表示

といった高速化、高機能化のための実装をふんだんに投下しています。これらをすべて撤去すれば相当に記述量は少なくて済むことでしょう。

AppleScript名:Keynote書類の現在のスライド上の選択中の表の背景色を置換 v2
— Created 2019-01-29 by Takaaki Naganoya
— Modified 2019-05-04 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "dbColNamesKit" –https://github.com/daniel-beard/DBColorNames/
use Bplus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

–v1:Convert Pages version to Keynote
–v2:Prepare Selected Table

property NSView : a reference to current application’s NSView
property NSColor : a reference to current application’s NSColor
property NSArray : a reference to current application’s NSArray
property NSMenu : a reference to current application’s NSMenu
property NSImage : a reference to current application’s NSImage
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property NSWindow : a reference to current application’s NSWindow
property NSTextField : a reference to current application’s NSTextField
property NSMenuItem : a reference to current application’s NSMenuItem
property NSBezierPath : a reference to current application’s NSBezierPath
property NSPopUpButton : a reference to current application’s NSPopUpButton
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSRoundedBezelStyle : a reference to current application’s NSRoundedBezelStyle
property NSFloatingWindowLevel : a reference to current application’s NSFloatingWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSMomentaryLightButton : a reference to current application’s NSMomentaryLightButton

property windisp : true
property wController : missing value
property pop1ind : 1

–初期化
set (my windisp) to true
set (my pop1ind) to 1
load framework

–選択中のTableオブジェクトへの参照を取得する
set theTable to getSelectedTable() of me

–選択中のTableオブジェクトの塗り色をすべて取得
tell application "Keynote"
  tell theTable
    set c1List to background color of every cell
    
set aProp to properties
    
set xCount to column count of aProp
  end tell
end tell

–Convert 1D List to 2D List
set c3List to (current application’s SMSForder’s subarraysFrom:c1List groupedBy:xCount |error|:(missing value)) as list

–色データをユニーク化(重複削除)
set bList to uniquifyList(c1List) of me

–missing value(背景色なし)を除外する
set c2List to (current application’s SMSForder’s arrayByDeletingBlanksIn:(bList)) as list

–Popup Menuで置換色選択
set paramObj to {c2List, 65535, "OK", "Select Target Color", 180} –Timeout = 180 sec, Color val range = 16bit
my performSelectorOnMainThread:"getPopupValues:" withObject:(paramObj) waitUntilDone:true
if pop1ind = false then return –timed out
set fromCol to (contents of item pop1ind of c2List)

–カラーピッカーで置換色選択
set tCol to choose color default color fromCol

set d1 to current date

–実際に表の背景色を置換する
set hitList to findDataFrom2DList(fromCol, c3List) of me –データ上で当該色のセル情報を計算する

–Rangeを横スキャンと縦スキャンの2通りで試算(Two way Simulation)
set rList1 to retRangeFromPosListHorizontal(hitList) of me –横方向へのrange評価
set rList2 to retRangeFromPosListVertival(hitList) of me –縦方向へのrange評価

–Simulationの結果、要素数の少ない方(=処理時間の短い方=高速な方)を採用する
log {"Simulation", (length of rList1), (length of rList2)}
if (length of rList1) < (length of rList2) then
  copy rList1 to rangeList
else
  copy rList2 to rangeList
end if

tell application "Keynote"
  activate
  
  
tell theTable
    repeat with i in rangeList
      set j to contents of i
      
      
ignoring application responses –非同期実行モードで高速実行
        set background color of range j to tCol
      end ignoring
      
    end repeat
  end tell
  
end tell

set d2 to current date
return d2 – d1

on getSelectedTable()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          set tCount to count every table
          
if tCount = 0 then
            error "No Selected Table Objects…"
          else
            –選択セルがない場合はTable 1を全選択
            
set theTable to table 1
          end if
        end try
        
        
return theTable
      end tell
    end tell
  end tell
end getSelectedTable

–カラーポップアップメニューをウィンドウ表示
on getPopupValues:paramObj
  copy (paramObj as list) to {ap1List, aColMax, aButtonMSG, aSliderValMSG, timeOutSecs}
  
  
set (my windisp) to true
  
  
set aView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 360, 100))
  
  
–Labelをつくる
  
set a1TF to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(30, 60, 80, 20))
  
a1TF’s setEditable:false
  
a1TF’s setStringValue:"Color:"
  
a1TF’s setDrawsBackground:false
  
a1TF’s setBordered:false
  
  
–Ppopup Buttonをつくる
  
set a1Button to NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 60, 200, 20)) pullsDown:false
  
a1Button’s removeAllItems()
  
  
set a1Menu to NSMenu’s alloc()’s init()
  
set aCDB to current application’s DBColorNames’s alloc()’s init()
  
  
set iCount to 1
  
repeat with i in ap1List
    copy i to {r1, g1, b1}
    
    
set nsCol to makeNSColorFromRGBAval(r1, g1, b1, aColMax, aColMax) of me
    
set anImage to makeRoundedNSImageWithFilledWithColor(64, 64, nsCol, 4) of me
    
    
set aTitle to "#" & (iCount as string) & " " & (aCDB’s nameForColor:nsCol) as string
    
set aMenuItem to (NSMenuItem’s alloc()’s initWithTitle:aTitle action:"actionHandler:" keyEquivalent:"")
    (
aMenuItem’s setImage:anImage)
    (
aMenuItem’s setEnabled:true)
    (
a1Menu’s addItem:aMenuItem)
    
    
set iCount to iCount + 1
  end repeat
  
  
a1Button’s setMenu:a1Menu
  
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(80, 10, 140, 40)))
  
bButton’s setButtonType:(NSMomentaryLightButton)
  
bButton’s setBezelStyle:(NSRoundedBezelStyle)
  
bButton’s setTitle:aButtonMSG
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
bButton’s setKeyEquivalent:(return)
  
  
aView’s addSubview:a1TF
  
  
aView’s addSubview:a1Button
  
aView’s addSubview:bButton
  
aView’s setNeedsDisplay:true
  
  
–NSWindowControllerを作ってみた(いらない?)
  
set aWin to (my makeWinWithView(aView, 300, 100, aSliderValMSG))
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
  
wController’s showWindow:me
  
  
set aCount to timeOutSecs * 100
  
  
set hitF to false
  
repeat aCount times
    if (my windisp) = false then
      set hitF to true
      
exit repeat
    end if
    
delay 0.01
    
set aCount to aCount – 1
  end repeat
  
  
my closeWin:aWin
  
  
if hitF = true then
    set s1Val to ((a1Button’s indexOfSelectedItem() as number) + 1)
  else
    set s1Val to false
  end if
  
  
copy s1Val to my pop1ind
  
end getPopupValues:

on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Display
on makeWinWithView(aView, aWinWidth as integer, aWinHeight as integer, aTitle as string)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to NSTitledWindowMask
  
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSFloatingWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

–Popup Action Handler
on actionHandler:sender
  set aTag to tag of sender as integer
  
set aTitle to title of sender as string
end actionHandler:

–aMaxValを最大値とする数値でNSColorを作成して返す
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–指定サイズのNSImageを作成し、指定色で塗ってNSImageで返す
on makeNSImageWithFilledWithColor(aWidth as integer, aHeight as integer, fillColor)
  set anImage to NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
—
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
—
  
anImage’s unlockFocus()
  
—
  
return anImage
end makeNSImageWithFilledWithColor

–指定サイズのNSImageを作成し、指定色で塗ってNSImageで返す、anRadiusの半径の角丸で
on makeRoundedNSImageWithFilledWithColor(aWidth as integer, aHeight as integer, fillColor, anRadius as real)
  set anImage to NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight))
  
anImage’s lockFocus()
  
—
  
set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}}
  
set theNSBezierPath to NSBezierPath’s bezierPathWithRoundedRect:theRect xRadius:anRadius yRadius:anRadius
  
—
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
  
—
  
anImage’s unlockFocus()
  
  
return anImage
end makeRoundedNSImageWithFilledWithColor

on uniquifyList(aList as list)
  set aArray to NSArray’s arrayWithArray:aList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
return bArray as list
end uniquifyList

on findDataFrom2DList(anItem, aList as list)
  script spd
    property aList : {}
    
property resList : {}
  end script
  
  
set (aList of spd) to aList
  
set (resList of spd) to {}
  
  
set yCount to 1
  
  
repeat with i in (aList of spd)
    
    
set aResList to (Bplus’s indexesOfItem:anItem inList:i inverting:false) as list
    
    
set tmpList to {}
    
if aResList is not equal to {} then
      repeat with ii in aResList
        set jj to contents of ii
        
set the end of tmpList to {jj, yCount}
      end repeat
      
set (resList of spd) to (resList of spd) & tmpList
    end if
    
    
set yCount to yCount + 1
  end repeat
  
  
return (resList of spd) –return {{x, y}…..} item list (1-based)
end findDataFrom2DList

on retRangeFromPosListVertival(posList as list)
  script rangeSPD
    property posList2 : {}
  end script
  
  
–縦方向へのrange評価に都合がいいようにソート
  
set (posList2 of rangeSPD) to shellSortListAscending(posList, {1, 2}) of me
  
  
–先頭データをピックアップ
  
set firstData to first item of (posList2 of rangeSPD)
  
set (posList2 of rangeSPD) to rest of (posList2 of rangeSPD)
  
  
copy firstData to {curX1, curY1}
  
set tmpRangeStr to aNumToExcelColumn(curX1) of me & (curY1 as string) & ":"
  
  
set tmpRange to {}
  
set hitF to false
  
  
set outList to {}
  
  
repeat with i in (posList2 of rangeSPD)
    copy i to {tmpX, tmpY}
    
    
–log {"{curX1, curY1}", {curX1, curY1}}
    
–log {"{tmpX, tmpY}", {tmpX, tmpY}}
    
    
    
if (curX1 = tmpX) and (curY1 + 1 = tmpY) then
      –Y方向への連続値を拾っている最中
      
if hitF = false then
        –log "case 1a"
        
–log {"hitF", hitF}
        
set hitF to true
      else
        –log "case 1b"
        
–log {"hitF", hitF}
        
–横に連続しているブロックの途中
      end if
    else
      –直前の値と連続していない
      
if hitF = false then
        –log "case 2a"
        
–log {"hitF", hitF}
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
      else
        –log "case 2b"
        
–log {"hitF", hitF}
        
–連続ブロックの末尾を拾った
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
        
–log {"tmpRangeStr", tmpRangeStr}
      end if
    end if
    
    
copy {tmpX, tmpY} to {curX1, curY1}
  end repeat
  
  
–log {tmpRangeStr, hitF}
  
  
if (hitF = true) or (tmpRangeStr is not equal to "") then
    set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
    
set the end of outList to tmpRangeStr
  end if
  
  
return outList
end retRangeFromPosListVertival

on retRangeFromPosListHorizontal(posList as list)
  script rangeSPD
    property posList2 : {}
  end script
  
  
copy posList to (posList2 of rangeSPD)
  
  
–先頭データをピックアップ
  
set firstData to first item of (posList2 of rangeSPD)
  
set (posList2 of rangeSPD) to rest of (posList2 of rangeSPD)
  
  
copy firstData to {curX1, curY1}
  
set tmpRangeStr to aNumToExcelColumn(curX1) of me & (curY1 as string) & ":"
  
  
set tmpRange to {}
  
set hitF to false
  
  
set outList to {}
  
  
repeat with i in (posList2 of rangeSPD)
    copy i to {tmpX, tmpY}
    
    
–log {"{curX1, curY1}", {curX1, curY1}}
    
–log {"{tmpX, tmpY}", {tmpX, tmpY}}
    
    
    
if (curX1 + 1 = tmpX) and (curY1 = tmpY) then
      –X方向への連続値を拾っている最中
      
if hitF = false then
        –log "case 1a"
        
–log {"hitF", hitF}
        
set hitF to true
      else
        –log "case 1b"
        
–log {"hitF", hitF}
        
–横に連続しているブロックの途中
      end if
    else
      –直前の値と連続していない
      
if hitF = false then
        –log "case 2a"
        
–log {"hitF", hitF}
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
      else
        –log "case 2b"
        
–log {"hitF", hitF}
        
–連続ブロックの末尾を拾った
        
set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
        
set the end of outList to tmpRangeStr
        
set tmpRangeStr to aNumToExcelColumn(tmpX) of me & (tmpY as string) & ":"
        
set hitF to false
        
–log {"tmpRangeStr", tmpRangeStr}
      end if
    end if
    
    
copy {tmpX, tmpY} to {curX1, curY1}
  end repeat
  
  
–log {tmpRangeStr, hitF}
  
  
if (hitF = true) or (tmpRangeStr is not equal to "") then
    set tmpRangeStr to tmpRangeStr & aNumToExcelColumn(curX1) of me & (curY1 as string)
    
set the end of outList to tmpRangeStr
  end if
  
  
return outList
end retRangeFromPosListHorizontal

–2008/05/01 By Takaaki Naganoya
–10進数数値をExcel 2004/2008的カラム表現にエンコードするサブルーチン を使いまわし
–1〜1351までの間であれば正しいエンコーディング結果を返す
on aNumToExcelColumn(origNum as integer)
  if origNum > 1351 then
    error "エラー:Excel 2004/2008的カラム表現(A1形式)への変換ルーチンにおいて、想定範囲外(1351以上)のパラメータが指定されました"
  end if
  
  
set upperDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
set lowerDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
  
set oNum to origNum
  
set nTh to 26
  
set stringLength to 4
  
  
–数字が1桁の場合の対応
  
if origNum < 27 then
    set aRes to (item origNum of upperDigitEncTable) as string
    
return aRes
  end if
  
  
  
if origNum > 702 then
    –3桁になる場合
    
set upupNum to oNum div 676 –整数除算–上の上の桁
    
set oNum to oNum – (upupNum * 676)
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
–超つじつま合わせ処理
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upupChar to (item upupNum of upperDigitEncTable) as string
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upupChar & upChar & lowChar
    
  else
    –2桁の場合
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
–超つじつま合わせ処理
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upChar & lowChar
    
  end if
  
  
return resText
end aNumToExcelColumn

–入れ子のリストを昇順ソート
on shellSortListAscending(a, keyItem)
  return sort2DList(a, keyItem, {true}) of me
end shellSortListAscending

–入れ子のリストを降順ソート
on shellSortListDecending(a, keyItem)
  return sort2DList(a, keyItem, {false}) of me
end shellSortListDecending

–2D Listをソート
on sort2DList(aList as list, sortIndexes as list, sortOrders as list)
  
  
–index値をAS流(アイテムが1はじまり)からCocoa流(アイテムが0はじまり)に変換
  
set newIndex to {}
  
repeat with i in sortIndexes
    set j to contents of i
    
set j to j – 1
    
set the end of newIndex to j
  end repeat
  
  
–Sort TypeのListを作成(あえて外部から指定する内容でもない)
  
set sortTypes to {}
  
repeat (length of sortIndexes) times
    set the end of sortTypes to "compare:"
  end repeat
  
  
–Sort
  
set resList to (current application’s SMSForder’s subarraysIn:(aList) sortedByIndexes:newIndex ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list
  
  
return resList
end sort2DList

★Click Here to Open This Script 

Posted in Color dialog GUI | Leave a comment

アラートダイアログ上にTextField x 2を表示 v2

Posted on 5月 2, 2019 by Takaaki Naganoya

アラートダイアログに簡易UIを実装して便利なダイアログ部品を整備する計画の一環として作成した、アラートダイアログにNSTextFieldを2つ+ラベル用のfield2つを作成して、ユーザーからの数値入力を取得するAppleScriptです。

スクリプトエディタ、ScriptDebuggerの両方で実行できますが、Script Menuから実行するとダイアログが最前面に表示されません。Script Menuから実行する場合にはAppleScript書類の状態で呼び出すのではなく、AppleScriptアプレットに書き出して呼び出すのがよいでしょう。

macOS 10.14上では本Scriptの実行は明確にメインスレッド上で行うことを要求されます。Control-Comand-Rで実行してください。

AppleScript名:アラートダイアログ上にTextField x 2を表示 v2
— Created 2019-05-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSTextField : a reference to current application’s NSTextField
property NSRunningApplication : a reference to current application’s NSRunningApplication

property theResult : 0
property returnCode : 0

set paramObj to {myMessage:"Keynoteオブジェクトの2次元詰め込み", mySubMessage:"詰め込み先の矩形サイズを数値で入力してください", mes1:"幅", mes1Default:"900", mes2:"高さ", mes2Default:"500"}

set segRes to my simulateAndRetRect:paramObj
–> {a1Res:900, a2Res:500}

on simulateAndRetRect:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mes1Label to (mes1 of paramObj) as string –Text Input field 1 Label
  
set mes2Label to (mes2 of paramObj) as string –Text Input field 2 Label
  
set aTextInputString to (mes1Default of paramObj) as string –Text Input field 1 Default value
  
set bTextInputString to (mes2Default of paramObj) as string –Text Input field 2 Default value
  
  
— Create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 300, 60))
  
  
— create two input field and their labels pairs
  
–NSTextFields for Input
  
set aTextInput to makeNSTextField(100, 35, 140, 20, true, (aTextInputString), true, true) of me
  
set bTextInput to makeNSTextField(100, 0, 140, 20, true, (bTextInputString), true, true) of me
  
  
–Labels
  
set a1TF to makeNSTextField(0, 35, 100, 20, false, (mes1Label), false, false) of me
  
set a2TF to makeNSTextField(0, 0, 100, 20, false, (mes2Label), false, false) of me
  
  
theView’s setSubviews:{a1TF, aTextInput, a2TF, bTextInput}
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set s1Val to (aTextInput’s integerValue()) as integer
  
set s2Val to (bTextInput’s integerValue()) as integer
  
  
return {a1Res:s1Val, a2Res:s2Val}
end simulateAndRetRect:

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

on makeNSTextField(xPos as integer, yPos as integer, myWidth as integer, myHeight as integer, editableF as boolean, setVal as string, backgroundF as boolean, borderedF as boolean)
  set aNSString to NSTextField’s alloc()’s initWithFrame:(current application’s NSMakeRect(xPos, yPos, myWidth, myHeight))
  
aNSString’s setEditable:(editableF)
  
aNSString’s setStringValue:(setVal)
  
aNSString’s setDrawsBackground:(backgroundF)
  
aNSString’s setBordered:(borderedF)
  
return aNSString
end makeNSTextField

★Click Here to Open This Script 

Posted in GUI Text | Tagged 10.11savvy 10.12savvy 10.13savvy NSAlert NSRunningApplication NSTextField NSView | Leave a comment

順序変更可能な項目選択ダイアログ

Posted on 4月 28, 2019 by Takaaki Naganoya

順序の変更が可能な項目選択(指定)ダイアログ表示AppleScriptです。

項目を行単位でドラッグ&ドロップして順番を変更できるようになっています。この機能を自前で作ろうとすると、筆舌に尽くし難いほど大変なのでMyriad Tables Libを利用して作ってみました。

Myriad Tables Libはたいへんに多機能なライブラリですが、あえて限定された機能だけを利用してみるというのもアリでしょう。

なにげに、仕事で実際に納品するプログラムによく使っています、Myriad Tables Lib。

AppleScript名:順序変更可能な項目選択ダイアログ.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/04/28
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use framework "Foundation"
use framework "AppKit"
use scripting additions
use script "Myriad Tables Lib" version "1.0.9" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html

set aTitle to "順番を指定してください"
set aPrompt to "各行はドラッグ&ドロップで順序を変更できます"
set origData to {"iMac 5K", "MacBook Pro", "Mac mini", "MacBook Air", "MacBook", "Mac Pro", "iMac Pro"}

set selRowList to dispDroppableTableViewDialog(aTitle, aPrompt, origData) of me
–>{"Mac mini", "MacBook Air", "MacBook", "Mac Pro", "MacBook Pro", "iMac 5K", "iMac Pro"}

–順序変更可能なダイアログを表示
on dispDroppableTableViewDialog(aTitle, aPrompt, origData)
  set someData to make1DListTo2D(origData) of me
  
  
set myTable to make new table with data someData with title aTitle with prompt aPrompt initially selected rows {1} with multiple selections allowed
  
set theAccessoryView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 400, 0))
  
modify table myTable accessory view theAccessoryView with row dragging
  
  
set theResult to (display table myTable)
  
  
set selList to values returned of theResult
  
set sel2List to FlattenList(selList) of me
  
  
return sel2List
end dispDroppableTableViewDialog

–1D Listを2D Listに変換
on make1DListTo2D(aList as list)
  set outList to {}
  
repeat with i in aList
    set j to contents of i
    
set the end of outList to {j}
  end repeat
  
return outList
end make1DListTo2D

on FlattenList(aList)
  set oldDelims to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {"????"}
  
set aString to aList as text
  
set aList to text items of aString
  
set AppleScript’s text item delimiters to oldDelims
  
return aList
end FlattenList

★Click Here to Open This Script 

Posted in dialog GUI | Tagged 10.11savvy 10.12savvy 10.13savvy NSView | Leave a comment

アラートダイアログ上にsegmented controlを表示 v4

Posted on 3月 27, 2019 by Takaaki Naganoya

アラートダイアログ上にsegmented controlを複数表示して、複数選択項目を取得するAppleScriptです。

複数選択項目にpopup buttonではなくsegmented controlを使う必要性というのは、あんまりないですが………すべての選択項目が見える状態で少量の選択項目から1つを選ぶような用途には使えるのではないでしょうか。

segmented controlをそれぞれBoxに入れ、Viewにまとめ、Scroll viewに突っ込んでいますが、あまり効果があるんだかないんだか不明です。

AppleScript名:アラートダイアログ上にsegmented controlを表示 v4
— Created 2019-03-26 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
–Scroll Viewをつかってみた

property NSBox : a reference to current application’s NSBox
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSScrollView : a reference to current application’s NSScrollView
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property returnCode : 0
property returnSels : {}

set paramObj to {myMessage:"複数項目選択", mySubMessage:"どれか選択してください。", segmentMes:{{"Red1", "Blue1", "Yellow1", "Brown1", "White1", "Cyan1", "Grey1"}, {"Red2", "Blue2", "Yellow2", "Brown2", "White2", "Cyan2", "Grey2"}, {"Red3", "Blue3", "Yellow3", "Brown3", "White3", "Cyan3", "Grey3"}, {"Red4", "Blue4", "Yellow4", "Brown4", "White4", "Cyan4", "Grey4"}, {"Red5", "Blue5", "Yellow5", "Brown5", "White5", "Cyan5", "Grey5"}}, segmentTitles:{"1st Segments", "2nd Segments", "3rd Segments", "4th Segments", "5th Segments"}}

my chooseMultipleSegments:paramObj

return my returnSels
–> {1, 2, 3, 4, 5}

on chooseMultipleSegments:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set segMes2DList to segmentMes of paramObj
  
set segTitleList to segmentTitles of paramObj
  
  
set aTmpY to (length of segMes2DList) * 60
  
  
–BoX + Segmented Control をつくる
  
set segsList to {}
  
set boxLIst to {}
  
set segsCount to 0
  
set tmpMaxX to 500
  
  
set aCount to 1
  
  
repeat with i in segMes2DList
    set aSeg to makeSegmentedControlWithStartY(i, aTmpY – segsCount – 40, 500, 40) of me
    
    
set aDBounds to aSeg’s |bounds|()
    
set tmpWidth to getWidth(aDBounds) of me
    
    
set aBox to (NSBox’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aTmpY – segsCount – 60, 500, 60)))
    (
aBox’s setTitle:(item aCount of segTitleList))
    (
aBox’s addSubview:aSeg)
    
    
if tmpWidth > tmpMaxX then set tmpMaxX to tmpWidth
    
    
set the end of segsList to aSeg –選択検出用
    
set the end of boxLIst to aBox –表示用
    
    
set segsCount to segsCount + 60
    
set aCount to aCount + 1
  end repeat
  
  
— create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX, aTmpY))
  
theView’s setSubviews:boxLIst
  
  
— create a Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, tmpMaxX, aTmpY))
  
aScroll’s setDocumentView:theView
  
theView’s enclosingScrollView()’s setHasHorizontalScroller:false
  
theView’s enclosingScrollView()’s setHasVerticalScroller:false
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aScroll
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set my returnSels to {}
  
repeat with i in segsList
    set tmpSegSel to (i’s selectedSegment()) as number
    
set the end of (my returnSels) to tmpSegSel + 1
  end repeat
end chooseMultipleSegments:

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

on makeSegmentedControlWithStartY(titleList, aStartY, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(20, aHeight – 35, aWidth, aHeight – 40))
  
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControlWithStartY

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
end clickedSeg:

on getWidth(aDBounds)
  if class of aDBounds = list then
    –macOS 10.13 or later
    
return item 1 of item 1 of aDBounds
  else
    –macOS 10.10….10.12
    
return width of |size| of aDBounds
  end if
end getWidth

★Click Here to Open This Script 

Posted in GUI list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSBox NSRunningApplication NSScrollView NSSegmentedControl NSView | 1 Comment

アラートダイアログ上にBrowser+Map Viewを表示 v2

Posted on 3月 17, 2019 by Takaaki Naganoya

ダイアログ上に表示したNSBrowserで都道府県→都道府県別データを選択し、選択したデータの位置情報をMap Viewに表示するAppleScriptの改良版です。

初版掲載時のおかしな挙動を減らし、地図種別の切り替えができるようになっています。本掲載リストだけだと動作が完結しないため、ライブラリを含んだスクリプトバンドルをダウンロードして実行してください。下記リストは「参考までに」掲載しているものです。

–> Download whole Script bundle with Library

前バージョンでは、NSBrowser上でデータが存在していない箇所に空白のセルが表示され、クリックするとクラッシュするという状態でした。本バージョンでもたまに出てくるので完全ではないのですが、

 ・予想どおりデータの行数をカウントするハンドラで絞り込みを行うPredicates文の文字列に問題があった
 ・データに半角のシングルクォートが入っていて、これによってデータの絞り込みに問題が出た

という問題を解消しました。前者はこまめにstringにcastし、後者は全角文字に置き換えました。

それでもまだ問題が出るケースがあるので、まだしばらく実際に使いつつ様子見といったところでしょうか。

AppleScript名:アラートダイアログ上にBrowser+Map Viewを表示 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/03/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use scripting additions
use skLib : script "senjoNoKizunaLib"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSBrowser : a reference to current application’s NSBrowser
property MKMapView : a reference to current application’s MKMapView
property NSScrollView : a reference to current application’s NSScrollView
property NSMutableArray : a reference to current application’s NSMutableArray
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property zLevel : 17
property aMaxViewWidth : 1000
property aMaxViewHeight : 500
property theResult : 0
property returnCode : 0
property theDataSource : {}
property aSelection : {}
property aMapView : missing value
property aBrowser : missing value
property skDataList : {}

property prefList : {"北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県", "茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県", "新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県", "徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"}

if my skDataList = {} then
  set my skDataList to current application’s NSMutableArray’s arrayWithArray:(getSenjoNokizunaGameCenterDataList() of skLib)
end if

set tmpLen to length of (my skDataList as list)

set aSelection to {}

set paramObj to {myMessage:"Choose a Game Center", mySubMessage:("Choose an appropriate Game Center from list (" & tmpLen as string) & ") to play Senjo-no-Kizuna"}

my performSelectorOnMainThread:"chooseItemByBrowser:" withObject:(paramObj) waitUntilDone:true
if (my returnCode as number) = 1001 then error number -128

return my aSelection
–> {loc_id:"QIEXj9er5QSA_Y42-OjPNg", gcName:"THE 3RD PLANET ジャングルパーク鹿児島", latitude:31.5703088, longitude:130.5653137, address:"鹿児島県 鹿児島市 与次郎 1-11-1 フレスポジャングルパーク2F"}

on chooseItemByBrowser:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
  
— create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aMaxViewWidth, aMaxViewHeight))
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(410, 30, aMaxViewWidth – 410, aMaxViewHeight – 30))
  
tell aMapView
    its setMapType:(MKMapTypeStandard)
    
its setZoomEnabled:true
    
its setScrollEnabled:true
    
its setPitchEnabled:true
    
its setRotateEnabled:true
    
its setShowsCompass:true
    
its setShowsZoomControls:true
    
its setShowsScale:true
    
its setShowsUserLocation:true
    
its setDelegate:me
  end tell
  
  
— make browser view with scroll view
  
set aScrollWithTable to makeBrowserView(prefList, 400, aMaxViewHeight) of me
  
  
–Segmented Controlをつくる
  
set segTitleList to {"Map", "Satellite", "Satellite + Map"}
  
set aSeg to makeSegmentedControl(segTitleList, 410, 0, 150, 20) of me
  
  
–Compose Views in NSView
  
theView’s setSubviews:{aScrollWithTable, aMapView, aSeg}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
end chooseItemByBrowser:

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

on makeBrowserView(aList as list, aWidth as number, aHeight as number)
  set (my theDataSource) to NSMutableArray’s arrayWithArray:aList
  
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aBrowser to NSBrowser’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
aBrowser’s setDelegate:(me)
  
aBrowser’s setTarget:(me)
  
aBrowser’s setAction:"browserCellSelected:"
  
aBrowser’s setMinColumnWidth:120
  
aBrowser’s setSeparatesColumns:true
  
aBrowser’s setMaxVisibleColumns:2
  
aBrowser’s setAutohidesScroller:true
  
aBrowser’s setTakesTitleFromPreviousColumn:true
  
–aBrowser’s setBackgroundColor:(NSColor’s grayColor())
  
  
aScroll’s setDocumentView:aBrowser
  
aBrowser’s enclosingScrollView()’s setHasHorizontalScroller:true
  
aBrowser’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
return aScroll
end makeBrowserView

–NSBrowser Event Handlers
on browser:aView numberOfRowsInColumn:aColumn
  if aColumn = 0 then
    return my theDataSource’s |count|()
  else if aColumn = 1 then
    set aPath to (text 2 thru -1 of ((aView’s |path|()) as string)) as string –ここが問題だったもよう
    
set tmpArray to (my filterRecListByLabel1(skDataList, "address BEGINSWITH ’" & aPath & "’")) as list
    
return (length of tmpArray)
  else
    return 0
  end if
end browser:numberOfRowsInColumn:

on browser:aView willDisplayCell:(aCell) atRow:(rowIndex as integer) column:(colIndex as integer)
  if colIndex = 0 then
    –Prefectures
    
aCell’s setTitle:((item (rowIndex + 1) of prefList) as string)
    
aCell’s setLeaf:false
    
  else if colIndex = 1 then
    –Each Game Centers in the Prefecture
    
set aPath to text 2 thru -1 of ((aView’s |path|()) as string)
    
set tmpArray to my filterRecListByLabel1(skDataList, "address BEGINSWITH ’" & aPath & "’")
    
set tmpItem to (tmpArray’s objectAtIndex:rowIndex)
    
    
set aGameCenterName to (tmpItem’s gcName) as string
    
aCell’s setTitle:(aGameCenterName)
    
aCell’s setLeaf:true
    
  else if colIndex ≥ 2 then
    error "Wrong NSBrowser status"
  end if
end browser:willDisplayCell:atRow:column:

on browserCellSelected:aSender
  set aPath to my aBrowser’s |path|()
  
set aList to (aPath’s pathComponents()) as list
  
set aLen to length of aList
  
  
if aLen = 3 then
    –set aPref to contents of item 2 of aList
    
set aGc to contents of last item of aList
    
    
set tmpArray to my filterRecListByLabel1(skDataList, "gcName == ’" & aGc & "’")
    
–set tmpArray to my filterRecListByLabel1(skDataList, "gcName == " & aGc)
    
set tmpItem to contents of first item of (tmpArray as list)
    
    
copy tmpItem to my aSelection
    
    
set aLatitude to (latitude of tmpItem) as real
    
set aLongitude to (longitude of tmpItem) as real
    
    
tell aMapView
      set aLocation to current application’s CLLocationCoordinate2DMake(aLatitude, aLongitude)
      
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    end tell
    
  end if
end browserCellSelected:

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

–Segmented Controlをつくる
on makeSegmentedControl(titleList, startX, startY, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(startX, startY, aWidth, aHeight))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Segmented Controlのクリック時のイベントハンドラ
on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set tList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set tmpType to contents of item (aSel + 1) of tList
  
  
aMapView’s setMapType:(tmpType)
  
  
set selSeg to aSel
end clickedSeg:

★Click Here to Open This Script 

Posted in geolocation GUI list Map regexp | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy MKMapTypeHybrid MKMapTypeSatellite MKMapTypeStandard MKMapView NSAlert NSAlertSecondButtonReturn NSBrowser NSColor NSMutableArray NSRunningApplication NSScrollView NSSegmentedControl NSSegmentStyleTexturedRounded NSView | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 13.6.5 AS系のバグ、一切直らず
  • CotEditorで2つの書類の行単位での差分検出
  • Apple純正マウス、キーボードのバッテリー残量取得
  • macOS 15, Sequoia
  • ディスプレイをスリープ状態にして処理続行
  • 初心者がつまづきやすい「log」コマンド
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • メキシカンハットの描画
  • macOS 13 TTS環境の変化について
  • 新刊発売 AppleScript最新リファレンス v2.8対応
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • 指定のWordファイルをPDFに書き出す
  • 可変次元のベクトルに対応したコサイン類似度計算
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • macOS 13.6.2アップデート Cocoa-AppleScript Applet修正はなし
  • AdobeがInDesign v19.4からPOSIX pathを採用

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (437) 11.0savvy (281) 12.0savvy (201) 13.0savvy (129) 14.0savvy (77) 15.0savvy (49) CotEditor (62) Finder (50) iTunes (19) Keynote (110) NSAlert (60) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (19) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (65) Pages (51) Safari (44) Script Editor (25) 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
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • 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)
  • 未分類

アーカイブ

  • 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